同一个点积只写一次,在 5,404 个 SPY 收益率上,2 通道要 13,514 条指令,16 通道只要 1,755 条。但只有 30 个元素时顺序反了:4 通道要 51 条,16 通道要 85 条。一个不知道自己宽度的内核,必须做对什么?
用通俗的话说这个想法
我们在哪里。 上一讲给 LaneSim 加上了 gather 和 scatter。从一开始每个内核都是针对 sim.lanes 写的,但脑子里想的是某一台机器,通常是 4 通道。真实代码没法选:同一个程序可能跑在 4 个 double 通道的笔记本上,也可能跑在 8 通道或 16 通道的服务器上,编译器猜不出下一台机器是哪种。可移植 SIMD就是答案,它也是 C++26 std::simd、Rust 的可移植 SIMD(撰写本文时仍在特性开关之后),以及 Highway、xsimd 等库背后的思想。
内核从不写 4、8 或 16。它向机器询问通道数,按这个步长遍历数据,所有算术都通过向量类型的运算符完成。编译器或库把每个运算符变成目标机器拥有的那条指令。
在 LaneSim 里,可移植类型是 Vec。它持有一个寄存器,并记得自己属于哪台机器。x + y 是一次 vadd,x * y 是一次 vmul,Vec.load(sim, a, i) 是一次 vload,acc.sum() 是一次 hsum。没有额外开销:计数与手写版本完全相同,这正是重点。抽象是免费的,机器之间唯一变化的是宽度。
最小的例子:一个表达式,任何宽度
下面是完整的类型。只是包装一条机器指令的方法已经替你写好;你要写的是两个运算符。看 __add__ 和 __mul__:它们先检查两个操作数是否属于同一台机器,然后恰好调用一次 LaneSim。4 通道机器的向量不能和 8 通道机器的向量相加,就像编译器拒绝混用 simd<double, 4> 和 simd<double, 8> 一样。
class Vec: """A register that remembers its machine, so a kernel can be written with + - * and never mention the lane count. This is the idea of C++26 `std::simd`, Rust's portable SIMD and libraries such as Highway: the width is a parameter of the type, not something the kernel code spells out. Every operation is still ONE instruction on the machine the vector came from. """ def __init__(self, sim, values): self.sim = sim self.values = list(values) @property def lanes(self): return self.sim.lanes @classmethod def load(cls, sim, mem, i): """The `lanes` numbers from mem[i]: one `vload`.""" return cls(sim, sim.vload(mem, i)) @classmethod def splat(cls, sim, x): """`x` in every lane: one `vsplat`.""" return cls(sim, sim.vsplat(x)) def store(self, mem, i): """Write the vector to mem[i:i + lanes]: one `vstore`.""" self.sim.vstore(mem, i, self.values) def sum(self): """Add all the lanes into one ordinary number with `hsum`.""" return self.sim.hsum(self.values) def __sub__(self, other): """Lane-wise difference as a new Vec: one `vsub`.""" return Vec(self.sim, self.sim.vsub(self.values, other.values)) def __add__(self, other): """Lane-wise sum as a new Vec: one `vadd`, on the machine both vectors share. If the two vectors come from different machines (`self.sim is not other.sim`) raise ValueError("vectors must come from the same machine") and count nothing. """ if self.sim is not other.sim: raise ValueError("vectors must come from the same machine") return Vec(self.sim, self.sim.vadd(self.values, other.values))1 def __mul__(self, other): """Lane-wise product as a new Vec: one `vmul`, on the machine both vectors share. If the two vectors come from different machines raise ValueError("vectors must come from the same machine") and count nothing. """ if self.sim is not other.sim: raise ValueError("vectors must come from the same machine") return Vec(self.sim, self.sim.vmul(self.values, other.values))
- 1对机器的一次调用:抽象不会增加指令。
# One expression, three machines: the same code, different widthsfor width in (2, 4, 8): sim = LaneSim(width) x = Vec.load(sim, [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0], 0) y = Vec.splat(sim, 10.0) z = x * y + x print(width, z.values, sim.counts)
2 [11.0, 22.0] {'vload': 1, 'vsplat': 1, 'vmul': 1, 'vadd': 1}
4 [11.0, 22.0, 33.0, 44.0] {'vload': 1, 'vsplat': 1, 'vmul': 1, 'vadd': 1}
8 [11.0, 22.0, 33.0, 44.0, 55.0, 66.0, 77.0, 88.0] {'vload': 1, 'vsplat': 1, 'vmul': 1, 'vadd': 1}同一行 x * y + x,三台机器,三个长度不同的寄存器,每次都是一次 vmul 加一次 vadd。这就是可移植代码的吸引力:内核是同一份文本,每条指令做多少活由机器决定。
逐步搭建:各种宽度下的点积
现在是实验的内核 portable_dot。它综合了之前几讲的三个部件:只在最后归约一次的部分和、处理剩余元素的标量尾部,以及 Vec 上的运算符。宽度只出现在读取一次的 sim.lanes 里。实验的规则故意很严:函数体里出现字面量 4 或 8,或者直接调用 vadd,都会被标记,因为它们都把内核绑定到了某台机器。
def portable_dot(sim, a, b): """The dot product of two arrays of ANY length, written once for ANY lane count, with `Vec` and no lane-count constants. Let `body` be the largest multiple of `sim.lanes` that fits in the length. If `body` is not 0: a `Vec.splat` of 0.0 for the partial sums, then per pass `sim.loop()`, two `Vec.load`, and `acc = acc + x * y` (a `vmul` and a `vadd`), then `acc.sum()` once. The leftover elements after `body` are added one at a time: `sim.loop()`, two `sload`, `smul` and `sadd` into the running total. Empty arrays return 0.0 and count nothing. If the arrays differ in length raise ValueError("arrays must have the same length"). Do not call `vadd`, `vmul` or `vfma` directly, and write no lane count: `sim.lanes` is the only place the width appears. """ if len(a) != len(b): raise ValueError("arrays must have the same length") lanes = sim.lanes1 body = len(a) - len(a) % lanes total = 0.0 if body: acc = Vec.splat(sim, 0.0) for i in range(0, body, lanes): sim.loop() acc = acc + Vec.load(sim, a, i) * Vec.load(sim, b, i)2 total = acc.sum() for i in range(body, len(a)): sim.loop() total = sim.sadd(total, sim.smul(sim.sload(a, i), sim.sload(b, i))) return total
- 1宽度只在这里出现。
- 2用 Vec 的
+和*,而不是 vadd 和 vmul。
在同样的十个数上,用每种宽度运行同一个函数。每次得到的都是同一个点积 385.0。指令数各不相同,而且不是你按通道数简单推想的那样。
# The same kernel on ten numbers at every width: the answer, the instructions, and the scalar baseline of 50ten = [float(i) for i in range(1, 11)]for width in (2, 4, 8, 16): sim = LaneSim(width) print(f"{width:2} lanes: dot = {portable_dot(sim, ten, ten)}, {sim.total():2} instructions")1
2 lanes: dot = 385.0, 29 instructions 4 lanes: dot = 385.0, 26 instructions 8 lanes: dot = 385.0, 23 instructions 16 lanes: dot = 385.0, 50 instructions
- 116 个通道用 10 个数填不满一个寄存器:全是尾部,50 条指令。
这个公式展示了权衡。更宽的寄存器会缩小第一项,但宽度每翻一倍归约就多一步,还可能留下更长的尾部(最多 L - 1 个元素,每个五条指令)。数组很长时,第一项占主导,最宽的机器获胜;数组很短时,尾部和固定开销占主导,较窄的宽度反而可能获胜。best_width 就是让你用数字而不是猜测来回答这个问题的工具。
# Which width wins, by array lengthfor n in (3, 10, 30, 100, 5404): counts = {} for width in (2, 4, 8, 16): sim = LaneSim(width) portable_dot(sim, [0.0] * n, [0.0] * n) counts[width] = sim.total() print(f"n = {n:4}: {counts} best {best_width(n, [2, 4, 8, 16])} scalar {5 * n}")1
n = 3: {2: 14, 4: 15, 8: 15, 16: 15} best (2, 14) scalar 15
n = 10: {2: 29, 4: 26, 8: 23, 16: 50} best (8, 23) scalar 50
n = 30: {2: 79, 4: 51, 8: 53, 16: 85} best (4, 51) scalar 150
n = 100: {2: 254, 4: 131, 8: 88, 16: 60} best (16, 60) scalar 500
n = 5404: {2: 13514, 4: 6761, 8: 3403, 16: 1755} best (16, 1755) scalar 27020- 1n = 30 时 4 通道最优,n = 10 时 8 通道最优,并非总是最宽的。
- 可移植库宽度如何确定
- std::simd<double, N> (C++26)带运算符的 N 通道向量类型。不指定时 N 为机器的原生宽度
- std::simd::f64x4 (Rust)固定宽度的向量类型,例如四个 double。宽度由你选,编译器按目标下沉
- Highway, xsimd同一份源码、按目标生成不同版本的库。宽度来自你构建的目标
常见错误
把宽度写死。 因为“我的机器是 8 通道”就按 8 步进的内核,遇到 4 通道机器时会悄悄地在错误的数据上工作:每隔一个寄存器就跳过一个。没有任何报错,因为单看每条指令都是合法的。在 4 通道机器上,把下面这个有问题的版本和可移植版本并排运行,比较两个和。
# A kernel that assumed 8 lanes, run on a 4-lane machine: it skips every second registerdef dot_for_eight(sim, a, b): acc = Vec.splat(sim, 0.0) for i in range(0, len(a), 8):1 acc = acc + Vec.load(sim, a, i) * Vec.load(sim, b, i) return acc.sum()four = LaneSim(4)ones = [1.0] * 16print(dot_for_eight(four, ones, ones), portable_dot(LaneSim(4), ones, ones))
8.0 16.0
- 1步长为 8:在 0 和 8 处加载,从不在 4 或 12 处加载。
以为最宽的机器一定最快。 上面的表显示,在 10 个和 30 个元素时 16 通道反而输了。归约的固定开销和更长的尾部吃掉了收益。短数组在量化代码里很常见,比如一天里几十只股票的横截面,所以可移植内核只完成了一半的工作;按数组长度选宽度是另一半,下一讲则是按 CPU 特性来选。
# Vectors from machines of different widths cannot be mixedwide = Vec.splat(LaneSim(8), 1.0)narrow = Vec.splat(LaneSim(4), 1.0)wide + narrow
ValueError: vectors must come from the same machine
在 LaneSim 里,计数说明是免费的。在真实编译器里,对于能映射到一条指令的运算符确实如此;目标机器没有的操作(比如窄指令集上的 gather)会用多条指令来模拟,所以可移植内核仍可能藏着一条慢路径。
任务要求
- 任务与函数要做什么
- Vec.__add__(self, other)确认两个向量属于同一台机器后,把
x + y作为一次vadd。调用vadd - Vec.__mul__(self, other)把
x * y作为一次vmul,做同样的机器检查。调用vmul - portable_dot(sim, a, b)任意长度、任意宽度的点积,通过
Vec完成,并带标量尾部。不含通道数字面量,也不直接调用vadd - best_width(n, widths)指令数最少的
(width, instructions),每个宽度都通过运行portable_dot测得。平局时取更宽的
portable_dot 处理 10 个元素,16 通道要 50 条指令,8 通道只要 23 条。多出来的部分从哪里来?下一讲。 可移植内核能在任何宽度上运行,但你手头实际的机器只提供一套指令:可能是带 4 个 double 的 AVX2,可能是带 8 个的 AVX-512,也可能两者都没有。下一讲是项目前的最后一块拼图。程序只构建一次,启动时必须根据 CPU 报告自己支持什么来选择运行哪个版本,并且要礼貌地拒绝执行芯片没有的指令。
实验:评分内容
4 个任务 · 100 分- 用
Vec.__add__让x + y成为一次vadd25 分 - 用
Vec.__mul__让x * y成为一次vmul25 分 - 用
portable_dot只写一次点积25 分 - 用
best_width选择宽度25 分