为 5,400 个 SPY 收益率各查一次市场状态权重,逐个做需要 21,600 条指令,用 gather 只要 5,400 条,但 gather 按每个通道一次内存访问计价,算作 9,450。而对同样这些收益率做向量直方图,1,350 个寄存器里只有 127 个没有冲突。gather 和 scatter 到底买到了什么?
用通俗的话说这个想法
我们在哪里。 上一讲把一个寄存器归约成一个数。但到目前为止的加载读的都是相邻元素:vload(a, i) 用 a[i] 到 a[i + lanes - 1] 填满寄存器。许多量化数据要通过下标来取:按市场状态查的风险权重、用位置列表挑出的价格、累加到收益率所属分箱的计数器。读取需要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() 表示老实的价格。
最小的例子:查表
给每个收益率一个 0 到 5 的市场状态编号,并保存一张含六个风险权重的表。查出每个收益率的权重就是查表,out[i] = table[idx[i]]。标量循环每个元素花四条指令:loop、一次下标的 sload、一次表项的 sload 和一次 sstore。vector_lookup 已经替你写好:它用普通的 vload 加载一个下标寄存器,再交给 gather。
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普通加载取下标,gather 取它们所指的内容。
# 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发出 8 条指令,但代价是 14:每个 gather 值 4 个单位。
看最后两行。向量运行发出 8 条指令,标量循环是 32 条,看起来是 4 倍的好成绩。但 cost() 说是 14:两次 gather 各按 4 个单位计价,所以老实的加速比是 32 / 14,约 2.3。gather 仍然好过四次分开的标量加载,因为一条指令就管了账,但它离 vadd 的 4 倍还差得很远。
逐步搭建:scatter、冲突与直方图
total() 统计发出的指令数,cost() 把每次 gather 或 scatter 按每通道一个单位计价,因为每个通道都是独立的内存访问。再看镜像操作,以及陷阱。统计有多少收益率落入六个市场状态分箱中的每一个:把寄存器里这些分箱的当前计数读出来(gather),加一(vadd),再写回去(scatter)。只要一个寄存器里的四个下标互不相同,这样就没问题。如果两个通道指向同一个分箱,它们读到同一个旧计数,各自加一,又写回同一个新计数:丢了一次累加。
# 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。
vconflict 是守卫:它回答下标寄存器中是否有两个通道持有相同的下标。在真实 CPU 上,最新的 AVX-512 芯片有专门的冲突检测指令来做这件事;没有它,就得自己去找重复项。下面就是你要写的安全直方图:寄存器没有冲突时,gather、加法、scatter;有冲突时,只对这个寄存器改用标量指令,一个下标一个下标地更新计数。
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有冲突:这个寄存器改成逐个下标处理。
- 2无冲突:gather、加法、scatter。
# 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]- 访问产生的内存访问
- vload(mem, i)
lanes个相邻元素。一次宽访问,代价 1 - gather(mem, idx)由下标寄存器选定的
lanes个位置。lanes次访问,代价lanes - scatter(mem, idx, reg)
lanes次写入;下标重复时后面的通道胜出。代价lanes,冲突会丢失更新
常见错误
把 gather 当成一次便宜的加载。 查表内核的 total() 看起来很漂亮:4 通道上 5,400 次查找只要 5,400 条指令,而老实的数字是 9,450。循环里有 gather 或 scatter 时,要比较 cost() 而不是 total();当表装不进缓存时,还要做好它输给简单标量代码的准备。
# 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老实的加速比是最后一个数,而不是 4 或 8。
分箱很少的直方图。 六个状态意味着,一个含四个收益率的寄存器几乎总会两次指向同一个分箱,而含八个收益率的寄存器则必然如此(八个下标不可能在六个分箱里全不相同)。在 SPY 数据上,1,350 个四通道寄存器中只有 127 个没有冲突,所以向量路径只在 9% 的时候运行,内核大部分时间走的是标量退路。补救办法不是更聪明的守卫,而是换一种布局:给每个通道一张自己的私有计数表,让通道之间永不冲突,最后再把这些表加起来。
# 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
当总是那几个槽位被反复访问时,给每个通道保留一份私有的表,最后再合并。这和上一讲让点积变快的是同一个思路:每个通道各存部分结果,最后只归约一次。
任务要求
- 任务与函数要做什么
- 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)每个分箱的计数:安全时用向量,有冲突的寄存器用标量。按寄存器类型精确计数
sim.counts 里记录了一次 gather。sim.cost() 为它计多少?下一讲。 本技能里的每个内核都是为 4 通道或 8 通道写的,通道数从 sim.lanes 读取。下一讲把它变成一条设计规则。可移植的内核只需针对一个它不知道的通道数写一次,就能在任何宽度上正确运行;这时要问的是:对给定长度的数组该用哪种宽度,因为尾部、归约和对齐剥离都取决于它。
实验:评分内容
4 个任务 · 100 分- 用
gather从任意位置加载25 分 - 用
scatter写入任意位置25 分 - 用
vconflict检测冲突25 分 - 用
vector_histogram安全地统计分箱25 分