σμimplied vol · KKmax(S−K,0)udβρᵢⱼfat tailsPnL · drawdownyield · TdSₜ = μSₜ dt + σSₜ dWₜC = S·N(d₁) − K·e⁻ʳᵀ·N(d₂)σₚ² = wᵀΣwd₁ = [ln(S/K) + (r + σ²⁄2)T] ⁄ σ√T∂V/∂t + ½σ²S²·∂²V/∂S² + rS·∂V/∂S − rV = 0Sharpe = (Rₚ − R_f) ⁄ σₚVaR₉₉ = μ − 2.33σρ = Cov(X,Y) ⁄ σₓσᵧE[Rₚ] = Σ wᵢ·E[Rᵢ]φ(x) = e^(−x²/2) ⁄ √2πE[Rᵢ] = R_f + βᵢ(E[Rₘ] − R_f)dXₜ = θ(μ − Xₜ)dt + σ dWₜσ²ₜ = ω + α·ε²ₜ₋₁ + β·σ²ₜ₋₁C − P = S − K·e⁻ʳᵀΔ = ∂V/∂S Γ = ∂²V/∂S²p = (e^(rΔt) − d) ⁄ (u − d)rₜ = ln(Pₜ ⁄ Pₜ₋₁)E[Xₜ₊₁ | ℱₜ] = Xₜf* = (bp − q) ⁄ bz = (x − μ) ⁄ σP(N=k) = λᵏe^(−λ) ⁄ k!Θ = −∂V/∂Tν = S·φ(d₁)·√Tmin wᵀΣw s.t. wᵀμ = μ*∫Σ∂∞λ
uantCraft Academy路线图学习路线
Ctrl K
AO
+1.2k 位学习者
登录加入 ↗
路线图学习路线
AO
+1.2k 位学习者
登录
  • English
  • Français
  • Español
  • العربية
  • Português
  • Deutsch
  • 日本語
  • 中文
σμimplied vol · KKmax(S−K,0)udβρᵢⱼfat tailsPnL · drawdownyield · TdSₜ = μSₜ dt + σSₜ dWₜC = S·N(d₁) − K·e⁻ʳᵀ·N(d₂)σₚ² = wᵀΣwd₁ = [ln(S/K) + (r + σ²⁄2)T] ⁄ σ√T∂V/∂t + ½σ²S²·∂²V/∂S² + rS·∂V/∂S − rV = 0Sharpe = (Rₚ − R_f) ⁄ σₚVaR₉₉ = μ − 2.33σρ = Cov(X,Y) ⁄ σₓσᵧE[Rₚ] = Σ wᵢ·E[Rᵢ]φ(x) = e^(−x²/2) ⁄ √2πE[Rᵢ] = R_f + βᵢ(E[Rₘ] − R_f)dXₜ = θ(μ − Xₜ)dt + σ dWₜσ²ₜ = ω + α·ε²ₜ₋₁ + β·σ²ₜ₋₁C − P = S − K·e⁻ʳᵀΔ = ∂V/∂S Γ = ∂²V/∂S²p = (e^(rΔt) − d) ⁄ (u − d)rₜ = ln(Pₜ ⁄ Pₜ₋₁)E[Xₜ₊₁ | ℱₜ] = Xₜf* = (bp − q) ⁄ bz = (x − μ) ⁄ σP(N=k) = λᵏe^(−λ) ⁄ k!Θ = −∂V/∂Tν = S·φ(d₁)·√Tmin wᵀΣw s.t. wᵀμ = μ*∫Σ∂∞λ
uantCraft Academy路线图学习路线
Ctrl K
AO
+1.2k 位学习者
登录加入 ↗
路线图学习路线
AO
+1.2k 位学习者
登录
  • English
  • Français
  • Español
  • العربية
  • Português
  • Deutsch
  • 日本語
  • 中文
SIMD 学习路线›模块 4 · 可移植代码与分派›主题 4.1·~50分钟高级

可移植 SIMD:一个内核适配任意宽度

路线进度模块 4/4 · 主题 1/3
4.1 可移植 SIMD:一个内核适配任意宽度
—实验得分— / 100总 XP—连续天数—
讲解0% read

阅读约 5 分钟7 个代码示例

  1. 01用通俗的话说这个想法
  2. 02最小的例子:一个表达式,任何宽度
  3. 03逐步搭建:各种宽度下的点积
  4. 04常见错误
  5. 05任务要求

同一个点积只写一次,在 5,404 个 SPY 收益率上,2 通道要 13,514 条指令,16 通道只要 1,755 条。但只有 30 个元素时顺序反了:4 通道要 51 条,16 通道要 85 条。一个不知道自己宽度的内核,必须做对什么?

01

用通俗的话说这个想法

我们在哪里。 上一讲给 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。没有额外开销:计数与手写版本完全相同,这正是重点。抽象是免费的,机器之间唯一变化的是宽度。

02

最小的例子:一个表达式,任何宽度

下面是完整的类型。只是包装一条机器指令的方法已经替你写好;你要写的是两个运算符。看 __add__ 和 __mul__:它们先检查两个操作数是否属于同一台机器,然后恰好调用一次 LaneSim。4 通道机器的向量不能和 8 通道机器的向量相加,就像编译器拒绝混用 simd<double, 4> 和 simd<double, 8> 一样。

main.pyPython
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. 1对机器的一次调用:抽象不会增加指令。
main.pyPython
# 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。这就是可移植代码的吸引力:内核是同一份文本,每条指令做多少活由机器决定。

03

逐步搭建:各种宽度下的点积

现在是实验的内核 portable_dot。它综合了之前几讲的三个部件:只在最后归约一次的部分和、处理剩余元素的标量尾部,以及 Vec 上的运算符。宽度只出现在读取一次的 sim.lanes 里。实验的规则故意很严:函数体里出现字面量 4 或 8,或者直接调用 vadd,都会被标记,因为它们都把内核绑定到了某台机器。

main.pyPython
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. 1宽度只在这里出现。
  2. 2用 Vec 的 + 和 *,而不是 vadd 和 vmul。

在同样的十个数上,用每种宽度运行同一个函数。每次得到的都是同一个点积 385.0。指令数各不相同,而且不是你按通道数简单推想的那样。

main.pyPython
# 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
  1. 116 个通道用 10 个数填不满一个寄存器:全是尾部,50 条指令。
instructions(n, L) = 5 · ⌊n / L⌋ + 2 · log2(L) + 2 + 5 · (n mod L) (when ⌊n / L⌋ ≥ 1)(1)第一项是向量主体,接下来两项是起始的 splat 和末尾的归约,最后一项是每元素 5 条指令的标量尾部。当 n < L 时没有主体和归约,代价是 5 · n。

这个公式展示了权衡。更宽的寄存器会缩小第一项,但宽度每翻一倍归约就多一步,还可能留下更长的尾部(最多 L - 1 个元素,每个五条指令)。数组很长时,第一项占主导,最宽的机器获胜;数组很短时,尾部和固定开销占主导,较窄的宽度反而可能获胜。best_width 就是让你用数字而不是猜测来回答这个问题的工具。

main.pyPython
# 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
  1. 1n = 30 时 4 通道最优,n = 10 时 8 通道最优,并非总是最宽的。
真实数据怎么说5,404 个 SPY 收益率,与自身的点积,同一个内核
标量 (指令)27,020每元素 5 条
2 通道 (指令)13,5142.0 倍
4 通道 (指令)6,7614.0 倍
8 通道 (指令)3,4037.9 倍;尾部 4 个数
16 通道 (指令)1,75515.4 倍;尾部 12 个数
各宽度的指令数
标量27020
2 通道13514
4 通道6761
8 通道3403
16 通道1755
  • 可移植库宽度如何确定
  • std::simd<double, N> (C++26)带运算符的 N 通道向量类型。不指定时 N 为机器的原生宽度
  • std::simd::f64x4 (Rust)固定宽度的向量类型,例如四个 double。宽度由你选,编译器按目标下沉
  • Highway, xsimd同一份源码、按目标生成不同版本的库。宽度来自你构建的目标
04

常见错误

把宽度写死。 因为“我的机器是 8 通道”就按 8 步进的内核,遇到 4 通道机器时会悄悄地在错误的数据上工作:每隔一个寄存器就跳过一个。没有任何报错,因为单看每条指令都是合法的。在 4 通道机器上,把下面这个有问题的版本和可移植版本并排运行,比较两个和。

main.pyPython
# 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. 1步长为 8:在 0 和 8 处加载,从不在 4 或 12 处加载。

以为最宽的机器一定最快。 上面的表显示,在 10 个和 30 个元素时 16 通道反而输了。归约的固定开销和更长的尾部吃掉了收益。短数组在量化代码里很常见,比如一天里几十只股票的横截面,所以可移植内核只完成了一半的工作;按数组长度选宽度是另一半,下一讲则是按 CPU 特性来选。

main.pyPython
# 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)会用多条指令来模拟,所以可移植内核仍可能藏着一条慢路径。

05

任务要求

  • 任务与函数要做什么
  • 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 测得。平局时取更宽的

要点

  • 宽度是一个参数 可移植内核只读取一次通道数,按它步进,并通过向量类型的运算符做算术,因此同一份源码在 2、4、8 或 16 通道上都能正确运行。
  • 不要写死宽度 字面量 4 或 8 在另一台机器上会悄悄跳过或重复数据;因为每条指令都合法,所以不会报错。
  • 最宽不一定最好 归约和尾部是随宽度增长的固定开销,所以对短数组,较窄的宽度可能执行更少的指令;用 best_width 来测量。
快速检查
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 分
资源管理器 · lab-9-1
▾ lab-9-1
…
bash · 浏览器内
learner@quantcraft:~/lab-9-1$
Python 尚未加载PythonLn 1, Col 1Spaces: 4UTF-8

要重置此主题吗?

lab-9-1 中的所有内容将恢复为初始文件,终端也会被清空。你当前的解答将丢失,且无法撤销。

将被重置
  • main.py → 初始代码
  • 终端历史与测试输出
  • 未提交的更改
将被保留
  • 实验最高得分
  • 你的 XP 与连续天数
  • 讲解进度与笔记