在 5,404 个 SPY 收益率中,有 50.5% 的相邻交易日在涨跌之间切换,所以对收益率符号做 if 判断,对 CPU 来说就像抛硬币。含有 if 的循环怎样才能完全不跳转地运行?额外的工作要付出什么代价?
用通俗的话说这个想法
我们在哪里。 上一讲用一个标量尾部结束循环:那是一个以标量速度运行的第二个循环。它也留下了一个老问题。向量指令在每个通道做同样的事,那么对一部分元素做一件事、对其余元素做另一件事的循环会怎样?那就是 if,它在量化代码里无处不在:只保留收益、给仓位设上限、行权价以下为零的收益。
答案是掩码。不要跳转,而是对每个通道都算出答案,建一个标记条件成立通道的掩码,再用它逐通道在两个结果之间挑选。分支不见了,猜错分支的代价也随之消失。
对每个通道都算出两种结果,构建标记条件成立通道的掩码,再做混合:掩码为 True 的位置取第一种结果,为 False 的位置取第二种。每个通道都做了两个分支的工作,而且没有任何跳转。
最小的例子:带 if 的收益
看涨期权到期时支付 max(价格 - 行权价, 0):行权价之上的收益,或者什么也没有。用 if 写出来就是下面的标量循环。机器除了加载、减法和存储之外,还要为每个元素做一次比较(scmp)和一次跳转(branch),每个元素共六条指令,而当结果不可预测地翻转时,吃亏的就是这个跳转。
def scalar_call_payoff(sim, prices, strike): """The scalar version of max(price - strike, 0) with an `if`: loop, sload, ssub, scmp, branch, sstore, six per element.""" out = [0.0] * len(prices) for i in range(len(prices)): sim.loop() diff = sim.ssub(sim.sload(prices, i), strike) if sim.sbranch(sim.scmp_gt(diff, 0.0)):1 sim.sstore(out, i, diff) else: sim.sstore(out, i, 0.0) return out
- 1每个元素一次比较和一次跳转。
# Eight prices around a strike of 100, scalar with an if, then the branchless vector versionprices = [98.0, 101.5, 100.0, 103.25, 99.5, 110.0, 95.0, 104.0]sim = LaneSim(4)print(scalar_call_payoff(sim, prices, 100.0), sim.total(), sim.counts["branch"], "branches")sim = LaneSim(4)print(vector_call_payoff(sim, prices, 100.0), sim.total(), sim.counts)
[0.0, 1.5, 0.0, 3.25, 0.0, 10.0, 0.0, 4.0] 48 8 branches
[0.0, 1.5, 0.0, 3.25, 0.0, 10.0, 0.0, 4.0] 14 {'vsplat': 2, 'loop': 2, 'vload': 2, 'vsub': 2, 'vcmp': 2, 'vblend': 2, 'vstore': 2}八个收益相同,指令是 48 对 14,而且向量运行里根本没有 branch 这一项。做到这一点只需三条小指令:在每个通道减去行权价,把结果与零比较得到掩码,再用该掩码把差值与零混合。
逐步搭建:比较、混合与带掩码的加载
两条新指令都很小。vcmp_gt(a, b) 返回一个掩码,在 a > b 的通道上为 True。vblend(mask, a, b) 返回一个寄存器,掩码为 True 的通道取 a,为 False 的通道取 b。无论多少个通道,每条都只算一条指令。在一个 4 通道寄存器上试试。
# Compare a register of four prices with a strike, then blend the gain with zerosim = LaneSim(4)diff = sim.vsub([98.0, 101.5, 100.0, 103.25], sim.vsplat(100.0))mask = sim.vcmp_gt(diff, sim.vsplat(0.0))1print(diff, mask)print(sim.vblend(mask, diff, sim.vsplat(0.0)))print(sim.counts)
[-2.0, 1.5, 0.0, 3.25] [False, True, False, True]
[0.0, 1.5, 0.0, 3.25]
{'vsplat': 3, 'vsub': 1, 'vcmp': 1, 'vblend': 1}- 1掩码:每个通道一个标志。
def vector_call_payoff(sim, prices, strike): """Return max(price - strike, 0) for every price as a new list, with no branch: a call option's payoff at expiry. Spread `strike` and 0.0 over all lanes once each with `vsplat` (two `vsplat`), then per pass: `sim.loop()`, `vload`, `vsub` of the strike, `vcmp_gt` of the difference against zero, `vblend` to keep the difference where it is positive and 0.0 elsewhere, `vstore`. For 8 prices on 4 lanes: {"vsplat": 2, "loop": 2, "vload": 2, "vsub": 2, "vcmp": 2, "vblend": 2, "vstore": 2}, 14 instructions. An empty list returns [] and counts nothing; a length that is not a multiple of `sim.lanes` raises ValueError("length must be a multiple of the lane count"). """ if len(prices) % sim.lanes: raise ValueError("length must be a multiple of the lane count") if not prices: return [] strikes = sim.vsplat(strike)1 zeros = sim.vsplat(0.0) out = [0.0] * len(prices) for i in range(0, len(prices), sim.lanes): sim.loop() diff = sim.vsub(sim.vload(prices, i), strikes)2 sim.vstore(out, i, sim.vblend(sim.vcmp_gt(diff, zeros), diff, zeros)) return out
- 1行权价和零在循环前各铺一次。
- 2掩码、混合、存储:没有跳转。
掩码也解决了上一讲遗留的问题。当长度不是通道数的整数倍时,为最后一个寄存器的有效通道构造一个为 True 的掩码。带掩码的加载只读这些通道并把其余通道填 0,带掩码的存储只写回这些通道。末尾之外的内容既不读也不写,也不需要标量尾部循环。
# Seven prices on 4 lanes: one full register and a masked one with 3 live lanessim = LaneSim(4)seven = [98.0, 101.5, 100.0, 103.25, 99.5, 110.0, 95.0]mask = sim.tail_mask(3)print(mask, sim.vmaskload(seven, 4, mask))1sim = LaneSim(4)print(vector_call_payoff_any(sim, seven, 100.0), sim.counts)
[True, True, True, False] [99.5, 110.0, 95.0, 0.0]
[0.0, 1.5, 0.0, 3.25, 0.0, 10.0, 0.0] {'vsplat': 2, 'loop': 2, 'vload': 1, 'vsub': 2, 'vcmp': 2, 'vblend': 2, 'vstore': 1, 'vmaskload': 1, 'vmaskstore': 1}- 1无效通道为 0.0,从未从内存读取。
- 指令作用
- vcmp_gt(a, b)哪些通道上 a 大于 b?返回掩码,没有跳转
- vblend(mask, a, b)掩码为 True 处取 a,其余取 b。先算出两个分支
- vmaskload(mem, i, mask)只加载有效通道,其余为零。绝不越过末尾读取
- vmaskstore(mem, i, reg, mask)只写回有效通道。不动其余内存
# The totals in the panel: 5,404 payoffs, scalar against two vector machinesn = 5404big = [100.0 + (i % 7) for i in range(n)]scalar = LaneSim(4)scalar_call_payoff(scalar, big, 102.0)print("scalar", scalar.total(), "with", scalar.counts["branch"], "branches")for lanes, kernel in ((4, vector_call_payoff), (8, vector_call_payoff_any)): sim = LaneSim(lanes) kernel(sim, big, 102.0)1 print(lanes, "lanes", sim.total(), round(scalar.total() / sim.total(), 2))
scalar 32424 with 5404 branches 4 lanes 8108 4.0 8 lanes 4058 7.99
- 15,404 是 4 的倍数,第一个内核就够;8 通道需要掩码尾部。
分支预测器会猜测跳转的方向。猜错会丢弃已经开始执行的指令,在当前的内核上通常要损失 15 到 20 个周期。LaneSim 把一次分支只算一条指令,所以对这类数据去掉分支的真实收益比表中所示更大。
常见错误
把掩码当成单个的是或否。 掩码是由四个标志组成的列表。在 Python 里任何非空列表都算真,所以即使每个标志都是 False,if mask: 也会进入分支。掩码应当传给 vblend,绝不能交给 if。
# A list of four False flags is still "true" for an ifsim = LaneSim(4)none_live = sim.vcmp_gt([1.0, 1.0, 1.0, 1.0], [2.0, 2.0, 2.0, 2.0])print(none_live, "-> any:", any(none_live))if none_live: print("the if was taken anyway")
[False, False, False, False] -> any: False the if was taken anyway
以为被掩码屏蔽的通道会被跳过。 两个分支在每个通道都会执行,混合只负责选择保留哪个结果。被掩码丢弃的通道仍然被计算过,带掩码加载的无效通道里是 0.0,对它做减法得到的是没有意义的数。这个数不会进入内存,因为带掩码的存储不碰该通道,但在被丢弃之前,它可能触发除零之类的浮点错误。要确保被丢弃的分支可以安全地计算。
# A dead lane of a masked load is zero; the masked store leaves memory alone theresim = LaneSim(4)mask = sim.tail_mask(3)reg = sim.vmaskload(seven, 4, mask)diff = sim.vsub(reg, sim.vsplat(100.0))1print(reg, diff)out = [-1.0] * 7sim.vmaskstore(out, 4, diff, mask)print(out)
[99.5, 110.0, 95.0, 0.0] [-0.5, 10.0, -5.0, -100.0] [-1.0, -1.0, -1.0, -1.0, -0.5, 10.0, -5.0]
- 1无效通道显示 -100.0,这个数没有意义。
以为无分支版本总是更快。 向量循环对每个元素都做了两个分支的工作。当某个分支代价高昂而且很少被执行时,一个可预测的、会跳过它的 if 可能比到处都计算它更快。这里两个分支只是一次减法和一个零,所以混合大获全胜;如果分支很重,结论可能改变,可靠的判断方法是计数或测量。
vcmp_gt 是严格比较:恰好为零的差值不大于零,所以会走零的那一支。这里与 max(x, 0) 一致,因为两个分支都给出 0.0;但对于“保留不低于 1% 的收益率”这类其他规则,选“大于”还是“不低于”会决定哪些天被计入。
任务要求
- 任务与函数要做什么
- LaneSim.vcmp_gt(a, b)返回掩码:
a > b处为 True;计一次vcmp。返回新的布尔列表 - LaneSim.vblend(mask, a, b)掩码为 True 处取
a,其余取b;计一次vblend。先检查掩码 - vector_call_payoff(sim, prices, strike)每个价格的
max(价格 - 行权价, 0),用vcmp_gt和vblend,不用if。计数会被精确检验 - vector_call_payoff_any(sim, prices, strike)适用于任意长度,最后用
vmaskload、vmaskstore和sim.tail_mask(...)收尾。没有标量指令
vblend,每个寄存器 4 个通道里恰好有 两个 True。每个寄存器另外两个通道花了多少工作量?下一讲。 掩码决定保留哪些通道,但到目前为止每个结果都还留在自己的通道里。下一讲把一个寄存器归约成一个数:逐通道乘积之和就是点积,是协方差或投资组合方差的核心。跨通道求和是向量寄存器唯一不擅长的事,所以你要用重排和加法来构建它,看看改变求和顺序为什么会改变最后几位数字,并把部分和保存在一个寄存器里直到最后。
实验:评分内容
4 个任务 · 100 分- 用
vcmp_gt逐通道比较25 分 - 用
vblend逐通道挑选25 分 - 用
vector_call_payoff替换if25 分 - 在
vector_call_payoff_any中用掩码处理最后一个寄存器25 分