同一个程序只构建一次,SPY 点积在带 AVX-512 的 CPU 上要 3,403 条指令,带 AVX2 的要 6,761 条,只有 SSE2 的要 13,514 条,什么都没有的要 27,020 条。而在一块没有它所针对的任何特性的芯片上,它不是跑得慢,而是直接停下。程序怎样知道自己运行在哪台机器上,又绝不能做什么?
用通俗的话说这个想法
我们在哪里。 可移植内核能在任何宽度上运行,best_width 也告诉了我们对给定长度哪种宽度最便宜。但只有 CPU 具备相应指令,这个宽度才可用。程序只构建一次、发布出去,就会落到笔记本、云服务器和老旧的构建机上。解决办法是运行时分派:问问 CPU 支持什么,然后选它能运行的最佳版本。
为热点函数保留多个版本,每个针对一个指令集级别。启动时读取 CPU 的特性标志,算出它能运行的最佳级别,此后一直调用那个版本。始终保留一个什么都不需要的普通版本。
在 Linux 上,CPU 把自己的特性列在 /proc/cpuinfo 的 flags 一行里;在 C 和 C++ 中,类似 __builtin_cpu_supports("avx2") 的调用给出同样的答案;NumPy 在导入时会自己做这件事并选择匹配的 SIMD 代码,numpy.show_config() 会报告它发现了什么。不管来源是什么,程序最终拿到的都是一组标志名,你的工作就是把这组标志转换成一个级别。
最小的例子:从标志行到级别
本技能的内容可以用四个级别概括:avx512(8 个 double 通道)、avx2(4 个)、sse2(2 个)和 scalar(1 个)。表 REQUIRES 写明了每个级别需要什么。有一个细节比看上去更重要:融合内核需要 fma,它是与 avx2 分开的标志。有 avx2 却没有 fma 的 CPU 无法运行 AVX2 版本,因此要降一级。
# The instruction-set levels, best first; what each one needs from the CPU; how many 64-bit lanes each one has.LEVEL_ORDER = ["avx512", "avx2", "sse2", "scalar"]REQUIRES = {"avx512": {"avx512f", "fma"}, "avx2": {"avx2", "fma"}, "sse2": {"sse2"}, "scalar": set()}1LANES = {"avx512": 8, "avx2": 4, "sse2": 2, "scalar": 1}class IllegalInstruction(Exception): """What a CPU does when it is asked to run an instruction it does not have."""def require(level, features): """Check that a CPU with these `features` can run code built for `level`; raise IllegalInstruction if it cannot.""" missing = REQUIRES[level] - set(features) if missing: raise IllegalInstruction(f"{level} needs {', '.join(sorted(missing))}")
- 1
avx2还需要fma:融合内核要用它。
# A shortened flags line, as /proc/cpuinfo prints it, turned into a set and then a levelline = "flags\t\t: fpu vme sse sse2 ssse3 sse4_2 popcnt avx fma avx2 bmi2"features = parse_features(line)print(sorted(features & {"sse2", "avx", "fma", "avx2", "avx512f"}))print(best_level(features))for name, flags in (("old server", "sse sse2"), ("avx2 but no fma", "sse2 avx avx2"), ("laptop", "sse2 avx avx2 fma"), ("new server", "sse2 avx2 fma avx512f")): print(f"{name:16}", best_level(parse_features(flags)))
['avx', 'avx2', 'fma', 'sse2'] avx2 old server sse2 avx2 but no fma sse2 laptop avx2 new server avx512
读最后四行。笔记本得到 avx2,新服务器得到 avx512,有 avx2 但没有 fma 的 CPU 停在 sse2。还要注意,即使第五台机器一个已知标志也没有,也依然会得到答案 scalar,因为最后一个级别什么都不要求:分派器必须始终有一个可以落脚的底线。
逐步搭建:决定一次,然后调用
读取标志、比较集合很便宜但并不免费,而热点内核每秒可能被调用成千上万次。因此真正的分派器只在第一次调用时决定一次,记住选中的函数,之后每次调用都直接进入它。make_dispatcher 就是这个模式。它返回一个把选择保存在内部的函数,还带有两个你可以检查的计数:resolved 表示做了几次选择,level 表示选了哪个。
def make_dispatcher(kernels, features): """Return a function `dispatch(*args)` that picks the right kernel ONCE and then calls it on every call. `kernels` maps a level name to a function. On the first call of `dispatch`, find the first level in LEVEL_ORDER that the CPU can run (its REQUIRES are among `features`) AND that has a kernel, remember it, and call that kernel with the arguments; every later call goes straight to the remembered kernel without deciding again. Give `dispatch` two attributes: `resolved`, the number of times a choice was made (0 before the first successful call, then always 1), and `level`, the chosen level (None before the first successful call). If no level qualifies raise ValueError("no kernel for this CPU") from the call, leave `resolved` at 0 and `level` at None. """ chosen = [] def dispatch(*args): if not chosen:1 have = set(features) for level in LEVEL_ORDER: if REQUIRES[level] <= have and level in kernels: chosen.append(kernels[level]) dispatch.level = level dispatch.resolved += 1 break else: raise ValueError("no kernel for this CPU") return chosen[0](*args)2 dispatch.resolved = 0 dispatch.level = None return dispatch
- 1只有第一次调用会进来。
- 2每次调用(包括第一次)都在这里结束。
# One dispatcher on a laptop-like CPU, called a thousand timeskernels = {"scalar": lambda x: ("plain", x), "avx2": lambda x: ("avx2", x)}call = make_dispatcher(kernels, parse_features("sse2 avx avx2 fma"))print(call.resolved, call.level)results = [call(i) for i in range(1000)]print(results[0], results[-1], "decisions:", call.resolved, "level:", call.level)
0 None
('avx2', 0) ('avx2', 999) decisions: 1 level: avx2第一次调用之前什么都没有决定(resolved 为 0,level 为 None);一千次调用之后恰好只做了一次决定。分派器还会选择有内核的最佳级别:CPU 有 avx2,但可用的只有 scalar 和 sse2 版本时,它就用 sse2。只要下面还有可用的版本,缺少某个版本就不算错误。
- 1读取标志
parse_features把 CPU 的文本变成小写名称的集合。 - 2选择级别
best_level返回第一个所有要求都满足的级别。 - 3匹配内核
make_dispatcher选取同时拥有对应版本的最佳级别。 - 4记住并调用选择被保存下来,所以之后的每次调用都是直接调用。
run_dot 把这些部件用在你已有的内核上。它读取一组标志,取得级别,在合适宽度的机器上运行 scalar_dot 或 portable_dot,返回级别、数值和花费的指令数。把同样的十个数放在四种不同的 CPU 上试试,看看分派带来了什么。
# The same dot product of ten numbers on four different CPUsten = [float(i) for i in range(1, 11)]for name, flags in (("nothing", ""), ("sse2", "sse2"), ("avx2", "sse2 avx2 fma"), ("avx512", "sse2 avx2 fma avx512f")): have = parse_features(flags) if flags else set() print(f"{name:8}", run_dot(have, ten, ten))1
nothing ('scalar', 385.0, 50)
sse2 ('sse2', 385.0, 29)
avx2 ('avx2', 385.0, 26)
avx512 ('avx512', 385.0, 23)- 1(级别,点积,指令数):结果从不改变,改变的是代价。
- 分派方式在哪里做出选择
- __builtin_cpu_supports("avx2")在 C 或 C++ 中,调用某个变体之前做的显式检查。分派器由你来写
- target_clones, ifunc编译器和加载器构建各个版本,并在程序加载时选择一个。自动,每个函数一次
- Highway, NumPy库自带各个变体,并在启动时选择一个。你只需调用函数
常见错误
不检查就调用指令。 到处假定有 AVX2 的构建,在开发者的笔记本上能跑,却会在第一台较旧的服务器上崩溃。在 LaneSim 里,这种崩溃的替身是 require:当 CPU 缺少该级别所需的东西时,它抛出 IllegalInstruction。真实硬件上没有可捕获的异常,进程会被直接杀死,这正是此类 bug 在生产环境里代价高昂的原因。
# Asking an old CPU to run the avx2 buildold = parse_features("sse sse2")for level in ("sse2", "avx2"): try: require(level, old) print(level, "can run") except IllegalInstruction as error: print("illegal instruction:", error)
sse2 can run illegal instruction: avx2 needs avx2, fma
没有底线。 内核只有 avx2 和 avx512 的分派器,在较旧的 CPU 上无物可运行。此时 make_dispatcher 会抛出带有“no kernel for this CPU”的 ValueError,这是一次带信息的干净失败,远好于非法指令。解决办法是,凡是要分派的函数都带上一个 scalar 版本,即使你认为永远用不到。
# A dispatcher with no scalar version on a CPU that has neither avx2 nor avx512fragile = make_dispatcher({"avx2": lambda x: x, "avx512": lambda x: x}, parse_features("sse2"))fragile(1)
ValueError: no kernel for this CPU
CPU 可能具备某项特性,但操作系统或虚拟机并未启用它;宽寄存器还要求操作系统在上下文切换时保存它们。生产级库除了检查标志,也会检查操作系统的支持。要在程序真正运行的机器上读取标志,而不是在构建机上。
由于 best_level 和 make_dispatcher 把特性集合作为参数,你可以给它们传一个虚构的 CPU。一个依次尝试 ""、"sse2"、"sse2 avx2 fma" 等的测试,无需拥有这些硬件就能覆盖每条路径。而在内部自己读取真实 CPU 的分派器就没法这样测试。
任务要求
- 任务与函数要做什么
- parse_features(text)
/proc/cpuinfo一行或普通列表中的小写标志集合。没有标志时抛出ValueError - best_level(features)
LEVEL_ORDER中第一个REQUIRES全部满足的级别。scalar始终是底线 - make_dispatcher(kernels, features)第一次调用时只选择一次、记住选择,并暴露
resolved和level的函数。没有合适的就抛出ValueError - run_dot(features, a, b)使用
best_level和合适宽度下的正确内核,返回(level, value, instructions)。指令数会被精确检验
sse2 avx avx2,没有 fma。按表 REQUIRES,best_level 返回哪个级别?下一讲。 所有部件都齐了。结业项目把它们汇总到同一个任务中:在真实的 SPY 收益率上做移动平均和点积,用可移植类型写成适用于任何宽度,处理好尾部,推迟归约,并根据 CPU 能运行什么来选择版本。最后给出一份诚实统计指令数的加速报告:在 5,404 个真实收益率上,对每种宽度比较向量内核与标量内核。
实验:评分内容
4 个任务 · 100 分- 用
parse_features读取 CPU 标志25 分 - 用
best_level选出最佳级别25 分 - 用
make_dispatcher只决定一次25 分 - 用
run_dot在拿到的 CPU 上运行25 分