σμ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 学习路线›模块 3 · 尾部、掩码与归约›主题 3.4·~45分钟高级

聚集与分散(gather 与 scatter)

路线进度模块 3/4 · 主题 4/4
3.4 聚集与分散(gather 与 scatter)
—实验得分— / 100总 XP—连续天数—
讲解0% read

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

  1. 01用通俗的话说这个想法
  2. 02最小的例子:查表
  3. 03逐步搭建:scatter、冲突与直方图
  4. 04常见错误
  5. 05任务要求

为 5,400 个 SPY 收益率各查一次市场状态权重,逐个做需要 21,600 条指令,用 gather 只要 5,400 条,但 gather 按每个通道一次内存访问计价,算作 9,450。而对同样这些收益率做向量直方图,1,350 个寄存器里只有 127 个没有冲突。gather 和 scatter 到底买到了什么?

01

用通俗的话说这个想法

我们在哪里。 上一讲把一个寄存器归约成一个数。但到目前为止的加载读的都是相邻元素:vload(a, i) 用 a[i] 到 a[i + lanes - 1] 填满寄存器。许多量化数据要通过下标来取:按市场状态查的风险权重、用位置列表挑出的价格、累加到收益率所属分箱的计数器。读取需要gather,写入需要scatter。

定义gather 与 scatter

gather(mem, idx) 返回 [mem[idx[0]], mem[idx[1]], ...]:每个通道从下标所指的地方取一个数。scatter(mem, idx, reg) 把 reg[k] 写入 mem[idx[k]]。两者都是一条指令,但每个通道都是独立的内存访问,因此代价远高于读取相邻元素的 vload。

想象去图书馆取四本书。如果它们并排放在同一个书架上,一伸手就拿全了,这就是 vload。如果它们在四个不同的书架上,一趟能把四本抱在怀里,但你仍然要走到四个书架。LaneSim 像硬件一样把一次 gather 记作 counts 里的一条指令,并增加第二个数字 cost(),按每个通道一个单位计价。用 total() 表示“发出的指令数”,用 cost() 表示老实的价格。

02

最小的例子:查表

给每个收益率一个 0 到 5 的市场状态编号,并保存一张含六个风险权重的表。查出每个收益率的权重就是查表,out[i] = table[idx[i]]。标量循环每个元素花四条指令:loop、一次下标的 sload、一次表项的 sload 和一次 sstore。vector_lookup 已经替你写好:它用普通的 vload 加载一个下标寄存器,再交给 gather。

main.pyPython
def vector_lookup(sim, table, idx):    """out[i] = table[idx[i]] with a gather: per pass `loop`, a `vload` of the indexes, a `gather` from the table, a `vstore`."""    if len(idx) % sim.lanes:        raise ValueError("length must be a multiple of the lane count")    out = [0.0] * len(idx)    for i in range(0, len(idx), sim.lanes):        sim.loop()        sim.vstore(out, i, sim.gather(table, sim.vload(idx, i)))1    return out
  1. 1普通加载取下标,gather 取它们所指的内容。
main.pyPython
# Eight regime numbers looked up in a table of six weights, scalar against 4 lanestable = [0.0, 0.5, 1.0, 1.5, 2.0, 2.5]idx = [5, 0, 3, 3, 1, 4, 2, 2]scalar = LaneSim(4)print(scalar_lookup(scalar, table, idx), scalar.total())sim = LaneSim(4)print(vector_lookup(sim, table, idx), sim.total(), sim.cost())1print(sim.counts)
[2.5, 0.0, 1.5, 1.5, 0.5, 2.0, 1.0, 1.0] 32
[2.5, 0.0, 1.5, 1.5, 0.5, 2.0, 1.0, 1.0] 8 14
{'loop': 2, 'vload': 2, 'gather': 2, 'vstore': 2}
  1. 1发出 8 条指令,但代价是 14:每个 gather 值 4 个单位。

看最后两行。向量运行发出 8 条指令,标量循环是 32 条,看起来是 4 倍的好成绩。但 cost() 说是 14:两次 gather 各按 4 个单位计价,所以老实的加速比是 32 / 14,约 2.3。gather 仍然好过四次分开的标量加载,因为一条指令就管了账,但它离 vadd 的 4 倍还差得很远。

03

逐步搭建:scatter、冲突与直方图

cost = Σ count(op) × weight(op), weight(gather) = weight(scatter) = lanes, weight(any other op) = 1(1)total() 统计发出的指令数,cost() 把每次 gather 或 scatter 按每通道一个单位计价,因为每个通道都是独立的内存访问。

再看镜像操作,以及陷阱。统计有多少收益率落入六个市场状态分箱中的每一个:把寄存器里这些分箱的当前计数读出来(gather),加一(vadd),再写回去(scatter)。只要一个寄存器里的四个下标互不相同,这样就没问题。如果两个通道指向同一个分箱,它们读到同一个旧计数,各自加一,又写回同一个新计数:丢了一次累加。

main.pyPython
# Four returns, two of them in bin 1: a gather-add-scatter loses a countsim = LaneSim(4)counts = [0, 0, 0, 0, 0, 0]reg = [1, 1, 2, 3]print("conflict:", sim.vconflict(reg))sim.scatter(counts, reg, sim.vadd(sim.gather(counts, reg), sim.vsplat(1)))1print(counts, "-> bin 1 should hold 2")
conflict: True
[0, 1, 1, 1, 0, 0] -> bin 1 should hold 2
  1. 1两个通道都往分箱 1 写了 1。

vconflict 是守卫:它回答下标寄存器中是否有两个通道持有相同的下标。在真实 CPU 上,最新的 AVX-512 芯片有专门的冲突检测指令来做这件事;没有它,就得自己去找重复项。下面就是你要写的安全直方图:寄存器没有冲突时,gather、加法、scatter;有冲突时,只对这个寄存器改用标量指令,一个下标一个下标地更新计数。

main.pyPython
def vector_histogram(sim, idx, nbins):    """Count how many times each bin number 0 .. nbins - 1 appears in `idx`, with gather and scatter where that is safe.    Return the counts as a list of `nbins` ints. One `vsplat` of 1 first (none when `idx` is empty). Then per pass of `sim.lanes`    indexes: `sim.loop()`, a `vload` of the indexes and a `vconflict` of that register. With no conflict: `gather` the counts of those    bins, `vadd` the ones, `scatter` the result back. With a conflict a scatter would lose increments, so do that register    one index at a time instead: for each lane an `sload` of the index, an `sload` of its count, a `sadd` of 1 and an `sstore`.    Raise ValueError("nbins must be at least 1"), then ValueError("length must be a multiple of the lane count"), then    ValueError("index out of range") if any index is not in range(nbins). Check in that order.    """    if nbins < 1:        raise ValueError("nbins must be at least 1")    if len(idx) % sim.lanes:        raise ValueError("length must be a multiple of the lane count")    if any(j < 0 or j >= nbins for j in idx):        raise ValueError("index out of range")    counts = [0] * nbins    if not idx:        return counts    ones = sim.vsplat(1)    for i in range(0, len(idx), sim.lanes):        sim.loop()        reg = sim.vload(idx, i)        if sim.vconflict(reg):            for k in range(sim.lanes):1                j = sim.sload(idx, i + k)                sim.sstore(counts, j, sim.sadd(sim.sload(counts, j), 1))        else:            sim.scatter(counts, reg, sim.vadd(sim.gather(counts, reg), ones))2    return counts
  1. 1有冲突:这个寄存器改成逐个下标处理。
  2. 2无冲突:gather、加法、scatter。
main.pyPython
# Eight indexes into six bins: the first register is clean, the second has a collisionsim = LaneSim(4)print(vector_histogram(sim, [0, 1, 2, 3, 1, 1, 4, 5], 6))print(sim.counts)print(scalar_histogram(LaneSim(4), [0, 1, 2, 3, 1, 1, 4, 5], 6))
[1, 3, 1, 1, 1, 1]
{'vsplat': 1, 'loop': 2, 'vload': 2, 'vconflict': 2, 'gather': 1, 'vadd': 1, 'scatter': 1, 'sload': 8, 'sadd': 4, 'sstore': 4}
[1, 3, 1, 1, 1, 1]
真实数据怎么说5,400 个 SPY 收益率按大小分入 6 个状态
状态查表,标量 (指令)21,600每元素 4 条
gather,4 通道:发出 (指令)5,400看似 4.0 倍
gather,4 通道:cost() (代价)9,4502.29 倍
gather,8 通道:cost() (代价)7,4252.91 倍
无冲突寄存器,4 通道127共 1,350 个(9.4%)
无冲突寄存器,8 通道0共 675 个:8 个通道装不进 6 个分箱
5,400 个收益率状态查表的代价
标量21600
4 通道,cost()9450
8 通道,cost()7425
  • 访问产生的内存访问
  • vload(mem, i)lanes 个相邻元素。一次宽访问,代价 1
  • gather(mem, idx)由下标寄存器选定的 lanes 个位置。lanes 次访问,代价 lanes
  • scatter(mem, idx, reg)lanes 次写入;下标重复时后面的通道胜出。代价 lanes,冲突会丢失更新
04

常见错误

把 gather 当成一次便宜的加载。 查表内核的 total() 看起来很漂亮:4 通道上 5,400 次查找只要 5,400 条指令,而老实的数字是 9,450。循环里有 gather 或 scatter 时,要比较 cost() 而不是 total();当表装不进缓存时,还要做好它输给简单标量代码的准备。

main.pyPython
# total() against cost() for the lookup of 5,400 regime numbers, on 4 and 8 lanesregimes = [(i * 7) % 6 for i in range(5400)]weights = [0.0, 0.5, 1.0, 1.5, 2.0, 2.5]for lanes in (4, 8):    sim = LaneSim(lanes)    vector_lookup(sim, weights, regimes)    print(lanes, "lanes: issued", sim.total(), "cost", sim.cost(), "speedup", round(21600 / sim.cost(), 2))1
4 lanes: issued 5400 cost 9450 speedup 2.29
8 lanes: issued 2700 cost 7425 speedup 2.91
  1. 1老实的加速比是最后一个数,而不是 4 或 8。

分箱很少的直方图。 六个状态意味着,一个含四个收益率的寄存器几乎总会两次指向同一个分箱,而含八个收益率的寄存器则必然如此(八个下标不可能在六个分箱里全不相同)。在 SPY 数据上,1,350 个四通道寄存器中只有 127 个没有冲突,所以向量路径只在 9% 的时候运行,内核大部分时间走的是标量退路。补救办法不是更聪明的守卫,而是换一种布局:给每个通道一张自己的私有计数表,让通道之间永不冲突,最后再把这些表加起来。

main.pyPython
# A gather past the end of the table. The simulator refuses; real hardware reads whatever is theresim = LaneSim(4)sim.gather(weights, [0, 1, 2, 6])
ValueError: gather index out of range
改布局,而不是改守卫

当总是那几个槽位被反复访问时,给每个通道保留一份私有的表,最后再合并。这和上一讲让点积变快的是同一个思路:每个通道各存部分结果,最后只归约一次。

05

任务要求

  • 任务与函数要做什么
  • LaneSim.gather(mem, idx)新寄存器 [mem[idx[k]] ...];计一次 gather。按顺序两项错误检查
  • LaneSim.scatter(mem, idx, reg)按通道顺序把 reg[k] 写入 mem[idx[k]];计一次 scatter。被拒绝的 scatter 不写任何东西
  • LaneSim.vconflict(idx)两个通道下标相同时为 True;计一次 vconflict。任意两个通道,不只是相邻的
  • vector_histogram(sim, idx, nbins)每个分箱的计数:安全时用向量,有冲突的寄存器用标量。按寄存器类型精确计数

要点

  • gather 与 scatter 可到达任意位置 一条指令按下标寄存器给出的位置,每个通道读或写一个数,这使得查表和直方图能够向量化。
  • 按通道计价 gather 或 scatter 每个通道做一次内存访问,所以要比较 cost() 而不是发出的指令数;预期收益是 2 到 3 倍,而不是通道数倍。
  • 冲突会丢失更新 若两个通道指向同一个槽位,scatter 只保留一次写入;用 vconflict 检查并退回标量,或给每个通道一张私有表。
快速检查
在 8 通道上,sim.counts 里记录了一次 gather。sim.cost() 为它计多少?
请选择一个答案。

下一讲。 本技能里的每个内核都是为 4 通道或 8 通道写的,通道数从 sim.lanes 读取。下一讲把它变成一条设计规则。可移植的内核只需针对一个它不知道的通道数写一次,就能在任何宽度上正确运行;这时要问的是:对给定长度的数组该用哪种宽度,因为尾部、归约和对齐剥离都取决于它。

实验:评分内容

4 个任务 · 100 分
  • 用 gather 从任意位置加载25 分
  • 用 scatter 写入任意位置25 分
  • 用 vconflict 检测冲突25 分
  • 用 vector_histogram 安全地统计分箱25 分
资源管理器 · lab-8-1
▾ lab-8-1
…
bash · 浏览器内
learner@quantcraft:~/lab-8-1$
Python 尚未加载PythonLn 1, Col 1Spaces: 4UTF-8

要重置此主题吗?

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

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