在 5,404 个真实 SPY 收益率上,20 日移动平均用简单方法要 226,170 条指令,用滚动求和要 37,730 条,在 4 通道上要 56,575 条。向量内核比它所改写自的循环快 4 倍,却只有最佳算法速度的 0.67 倍。诚实的加速报告会怎么说?8 通道或 16 通道什么时候才终于获胜?
用通俗的话说这个想法
我们在哪里。 这是整条链的终点。第一讲搭出了机器并加了两个数组;此后你学会了编译器如何判断、如何亲手写指令、如何处理尾部、如何替换 if、如何跨通道归约、如何访问分散的数据、如何为任意宽度写一个内核,以及如何按 CPU 选择版本。在这里,所有这些都用在技能开头就一直贯穿的例子上:对 SPY 日收益率做移动平均和点积。
你所知的最佳标量算法的指令数,与向量内核的指令数之比,在真实数据上、对你宣称的每种宽度精确计数。相对于一个被你故意拖慢的基线得到的加速,不叫加速。
这里的收益率是简单日收益率:当天收盘价除以前一天收盘价,再减一。窗口为 w 的移动平均是每一天最近 w 个收益率的平均值,是每个交易台都在用的平滑。滞后 1 的自相关衡量今天的收益率倾向于重复还是反转昨天的收益率,它是序列与其平移一天后的副本的点积,除以序列与自身的点积。两个小统计量,对应本技能的两个内核。
最小的例子:从文件到收益率
数据是一个普通的 CSV,每个交易日一行,列为 date,open,high,low,close,volume,从 2005-02-25 到 2026-08-21:共 5,405 行,因此有 5,404 个收益率。load_returns 是第一个任务,用 csv 模块写的普通 Python 即可。不要依赖 close 列的位置,这样即使文件的列顺序不同也能正常工作。
def load_returns(path="data/SPY.csv"): """Read a CSV file with a header row and return the daily simple returns of its `close` column as a list of floats. The other columns may be anything and in any order. A return is close[i] / close[i - 1] - 1, so there is one fewer return than rows. Use the `csv` module. Raise ValueError("no close column") if the header has no `close`, then ValueError("need at least two prices") if there are fewer than two rows below the header. Check in that order. """ with open(path, newline="") as file: reader = csv.DictReader(file) if "close" not in (reader.fieldnames or []): raise ValueError("no close column")1 closes = [float(row["close"]) for row in reader] if len(closes) < 2: raise ValueError("need at least two prices") return [closes[i] / closes[i - 1] - 1 for i in range(1, len(closes))]
- 1按名字而不是位置查找列。
# 5,405 closes become 5,404 returnsreturns = load_returns()print(len(returns), [round(x, 5) for x in returns[:3]])print(round(min(returns), 4), round(max(returns), 4))
5404 [-0.00683, 0.0052, -0.00049] -0.1095 0.1452
最差的一天 -10.95% 和最好的一天 +14.52% 都在其中:2020-03-16 和 2008-10-13。现在在一个玩具序列上运行第一个向量内核。十一个数、窗口为 3,得到九个均值,在 4 通道上就是两个满块和一个只有一个有效通道的块。计数显示各个部件:块内错位的 vload,最后一块的 vmaskload 和 vmaskstore,没有任何标量指令。
# Nine rolling means of 3 on 4 lanes: two full blocks and a masked onetoy = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0]sim = LaneSim(4)print(rolling_mean_vector(sim, toy, 3))print(sim.total(), sim.counts)
[2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]
25 {'vsplat': 1, 'loop': 3, 'vload': 6, 'vadd': 6, 'vmul': 3, 'vstore': 2, 'vmaskload': 3, 'vmaskstore': 1}逐步搭建:内核与报告
移动平均是沿着输出向量化的,而不是沿着窗口。一个包含 lanes 个相邻输出的块需要数据的同样 w 个错位视图:加载 x[j..j+lanes-1],加上 x[j+1..j+lanes],再加 x[j+2..],依此类推,最后统一缩放一次。这些加载每次都比上一次晚开始一个元素,所以第一个之后都不对齐;其代价体现在缓存行上,LaneSim 不统计这个,真实芯片会统计。最后一个较短的块使用掩码,因此永远不会读到数据之外。
def rolling_mean_vector(sim, x, window): """The rolling mean with `lanes` outputs per pass: out[j] = (x[j] + ... + x[j + window - 1]) * (1.0 / window), summed left to right. One `vsplat` of 1.0 / window first. An output block starting at j is: `sim.loop()`, `acc = vload(x, j)`, then for k = 1 .. window - 1 `acc = vadd(acc, vload(x, j + k))`, then `vmul(acc, factor)` and a `vstore` into the output. The loads are shifted by one element each time, so most are not aligned. If the number of outputs is not a multiple of `sim.lanes`, the last block has only `live` real outputs: do it with `sim.tail_mask(live)`, using `vmaskload` for every load and a `vmaskstore` at the end, never a scalar loop. A window of 1 needs no `vadd`. If window < 1 raise ValueError("window must be at least 1"); if window > len(x) raise ValueError("window is longer than the data"). Check in that order. """ if window < 1: raise ValueError("window must be at least 1") if window > len(x): raise ValueError("window is longer than the data") outputs = len(x) - window + 1 factor = sim.vsplat(1.0 / window) out = [0.0] * outputs full = outputs - outputs % sim.lanes1 for j in range(0, full, sim.lanes): sim.loop() acc = sim.vload(x, j) for k in range(1, window): acc = sim.vadd(acc, sim.vload(x, j + k)) sim.vstore(out, j, sim.vmul(acc, factor)) if full < outputs:2 mask = sim.tail_mask(outputs - full) sim.loop() acc = sim.vmaskload(x, full, mask) for k in range(1, window): acc = sim.vadd(acc, sim.vmaskload(x, full + k, mask)) sim.vmaskstore(out, full, sim.vmul(acc, factor), mask) return out
- 1错位加载:每次晚一个元素。
- 2最后一块:用掩码,没有标量尾部。
现在是这份报告要回答的问题。简单的标量循环每个输出要加 w 个数,所以每个输出花 2w + 2 条指令。滚动求和是加上进入窗口的数、减去离开窗口的数,因此无论 w 多大,每个输出都是 7 条。向量内核每个含 lanes 个输出的块花 2w + 2 条,所以每个输出的代价是 (2w + 2) / lanes。只有当 (2w + 2) / lanes < 7 时,它才能赢过滚动求和。
speedup_report 会运行全部五个内核(简单循环、滚动求和、向量均值、标量点积和可移植点积),并把计数按每种宽度放成一行。看 mean_speedup 这一列:它用两种标量算法中较便宜的那个除以向量版本。在真实序列上试五种窗口,看看获胜者如何变化。
# Speedup against the BEST scalar algorithm, by window and width, on the 5,404 real returnsprint("window 4 lanes 8 lanes 16 lanes (simple loop / vector, for comparison)")for window in (2, 5, 10, 20, 60): rows = speedup_report(returns, window, [4, 8, 16]) honest = " ".join(f"{row['mean_speedup']:8.2f}" for row in rows) naive = " ".join(f"{row['mean_scalar'] / row['mean_vector']:5.2f}" for row in rows) print(f"{window:5} {honest} ({naive})")1
window 4 lanes 8 lanes 16 lanes (simple loop / vector, for comparison)
2 4.00 7.99 15.98 ( 4.00 7.99 15.98)
5 2.33 4.67 9.32 ( 4.00 8.00 15.97)
10 1.27 2.54 5.08 ( 4.00 7.99 15.96)
20 0.67 1.33 2.67 ( 4.00 7.99 15.98)
60 0.23 0.46 0.92 ( 4.00 7.99 15.95)- 1相对于简单循环,每种宽度都像是赢家;相对于最佳标量,窗口 60 即便 16 通道也输。
任务中点积的那一半不需要这样小心,因为点积没有更聪明的标量算法:每个元素都必须相乘再相加。它的加速几乎恰好等于通道数。autocorrelation 调用两次 portable_dot,一次算滞后乘积,一次算序列的能量,然后相除。
# Autocorrelation of the real returns at several lags, and what it costs on 8 lanesfor lag in (1, 2, 3, 5, 10): sim = LaneSim(8) print(lag, round(autocorrelation(sim, returns, lag), 4), sim.total(), "instructions")1print("scalar for the same two dot products:", 5 * (len(returns) - 1) + 5 * len(returns))
1 -0.1021 6801 instructions 2 -0.0121 6796 instructions 3 0.007 6791 instructions 5 -0.0121 6816 instructions 10 0.0007 6791 instructions scalar for the same two dot products: 54035
- 1滞后 1 约为 -0.10:上涨日之后倾向于出现下跌日,但很微弱。
- 内核每个输出(每个元素)的指令数
- rolling_mean_scalar每个输出都对整个窗口求和。2w + 2
- rolling_mean_running加上进入的数,减去离开的数。7
- rolling_mean_vector每个块为
lanes个输出对窗口求和。(2w + 2) / lanes - portable_dot不存在更聪明的标量算法。5 / lanes
常见错误
拿慢基线去汇报加速比。 只引用一行的第一个数字,20 日窗口就像大获全胜:4 通道 4.0 倍,8 通道 8.0 倍。完整的一行却说明,最佳标量算法比 4 通道还快。读代码的评审者几分钟就能找到更便宜的基线,受损的是报告里的所有其他数字。要像 mean_speedup 那样使用诚实的那一列。
只相信一个窗口。 盈亏平衡窗口随通道数增大(4、8、16 通道分别为 13、27、55),所以只选一个 w 无法描述这个内核。上面的表才是你要的报告:多个窗口、每种宽度,并且能看到曲线穿过 1 的那个点。使用 5 和 10 窗口的交易台与使用 60 的交易台,需要同一份代码给出不同的答案。
# The last digits depend on the width: the same lag-1 autocorrelation on four machinesfor lanes in (2, 4, 8, 16): print(lanes, repr(autocorrelation(LaneSim(lanes), returns, 1)))
2 -0.10207994414042755 4 -0.10207994414042723 8 -0.10207994414042747 16 -0.10207994414042743
用 == 比较向量与标量的结果。 上面四行在大约 15 位上一致,只在最后一位不同,因为每种宽度对同样的数以不同顺序求和。移动平均是例外:rolling_mean_vector 对每个窗口从左到右求和,与 rolling_mean_scalar 完全一样,所以两者连最后一位都一致。在决定怎么测试之前,要先弄清你的哪些内核改变了加法顺序。
本报告统计的是指令数。在真实芯片上,移动平均的错位加载会跨越缓存行,宽指令可能更慢,内存也可能是瓶颈。计数告诉你哪个内核有可能获胜、交叉点在哪里;最终要在目标机器上用真实数据,用秒表来裁决。
任务要求
- 任务与函数要做什么
- load_returns(path)按列名取出 CSV 文件
close列的简单收益率。按顺序两项错误检查 - rolling_mean_vector(sim, x, window)每块
lanes个输出,从左到右求和,最后一块用掩码。没有标量指令 - autocorrelation(sim, r, lag)
dot(r[lag:], r[:-lag]) / dot(r, r),两个点积都用portable_dot。按顺序三项错误检查 - speedup_report(returns, window, widths)每种宽度一行,含五个内核的计数和诚实的加速比。运行所有内核,标量的只运行一次
mean_speedup 大约是多少?接下来去哪里。 你从零开始搭建、统计并论证了一台向量机。在真实硬件上,同样的思想表现为 C++ 内部函数和自动向量化报告、std::simd 和 Highway,而数字会有所不同:内存、缓存行和宽指令的代价都会参与进来。等 C++ 技能上线后,它关于内部函数和自动向量化的主题会正好接上第 3 讲和第 4 讲停下的地方,缓存局部性技能则覆盖了这个模拟器有意略去的内存一侧。
实验:评分内容
4 个任务 · 100 分- 用
load_returns读取价格25 分 - 用
rolling_mean_vector向量化移动平均25 分 - 用
autocorrelation度量滞后25 分 - 用
speedup_report给出诚实的加速报告25 分