The same program, built once, runs the SPY dot product in 3,403 instructions on a CPU with AVX-512, 6,761 with AVX2, 13,514 with only SSE2 and 27,020 with nothing. And on a chip that has none of the features it was built for, it does not run slowly: it stops. How does a program find out which machine it is on, and what must it never do?
The idea in plain words
Where we are. A portable kernel runs at any width, and best_width told us which width is cheapest for a given length. But a width is only available if the CPU has the instructions behind it. You build a program once, ship it, and it lands on a laptop, a cloud server and an old build machine. The fix is runtime dispatch: ask the CPU what it supports and pick the best version it can run.
Keep several versions of a hot function, each built for one instruction-set level. At start-up read the CPU's feature flags, work out the best level it can run, and call that version from then on. Always keep a plain version that needs nothing.
On Linux a CPU lists its features in the flags line of /proc/cpuinfo; in C and C++ a call such as __builtin_cpu_supports("avx2") gives the same answer; NumPy does this itself when it is imported and picks its SIMD code to match, and numpy.show_config() reports what it found. Whatever the source, the program ends up with a set of flag names, and your job is to turn that set into a level.
The smallest example: a flags line to a level
Four levels cover this skill's story: avx512 (8 lanes of doubles), avx2 (4), sse2 (2) and scalar (1). The table REQUIRES says what each needs. One detail matters more than it looks: the fused kernels need fma, which is a separate flag from avx2. A CPU with avx2 and no fma cannot run the AVX2 build, so it drops a level.
# 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
avx2also needsfma: the fused kernels use it.
# 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
Read the last four lines. A laptop gets avx2, a new server avx512, and the CPU with avx2 but no fma is held at sse2. Notice too that a fifth machine with no known flags at all still gets an answer, scalar, because the last level asks for nothing: the dispatcher must always have a floor to fall to.
Build it up: decide once, then call
Reading flags and comparing sets is cheap but not free, and a hot kernel may be called thousands of times a second. So a real dispatcher decides once, on the first call, remembers the chosen function, and every later call goes straight to it. make_dispatcher is that pattern. It returns a function that carries its choice inside it, together with two counters you can inspect: resolved, how many times a choice was made, and level, which one.
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
- 1Only the first call goes in here.
- 2Every call, including the first, ends here.
# 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: avx2Before the first call nothing is decided (resolved is 0, level is None); after a thousand calls exactly one decision was made. The dispatcher also picks the best level that has a kernel: ask for avx2 on a CPU that has it but with only a scalar and an sse2 version available, and it uses sse2. A missing version is not an error as long as something below it exists.
- 1Read the flags
parse_featuresturns the CPU's text into a set of lower-case names. - 2Pick the level
best_levelreturns the first level whose requirements are all present. - 3Match a kernel
make_dispatchertakes the best level that also has a version built for it. - 4Remember and callThe choice is kept, so every later call is a direct call.
run_dot puts the pieces to work on the kernel you already have. It reads a feature set, takes the level, and runs scalar_dot or portable_dot on a machine of the right width, returning the level, the value and the instructions spent. Try the same ten numbers on four different CPUs and see what the dispatch buys.
# 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(level, dot product, instructions): the answer never changes, the cost does.
- Way to dispatchWhere the choice is made
- __builtin_cpu_supports("avx2")An explicit check in C or C++, before calling a variant.you write the dispatcher
- target_clones, ifuncThe compiler and the loader build the versions and pick one when the program loads.automatic, once per function
- Highway, NumPyA library carries the variants and picks one at start-up.you only call the function
Typical mistakes
Calling an instruction without checking. A build that assumes AVX2 everywhere works on the developer's laptop and dies on the first older server. In LaneSim the stand-in for that death is require, which raises IllegalInstruction when a CPU lacks something the level needs. On real hardware there is no exception to catch: the process is killed, which is what makes this bug so costly in production.
# 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
Having no floor. A dispatcher whose kernels are only avx2 and avx512 has nothing to run on an older CPU. make_dispatcher raises ValueError with "no kernel for this CPU" when that happens, which is a clean failure with a message, far better than an illegal instruction. The cure is to ship a scalar version of everything you dispatch, even if you expect never to need it.
# 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
The CPU may have a feature that the operating system or a virtual machine has not enabled, and wide registers also need the OS to save them on a context switch. Production libraries check the OS support as well as the flag. Read the flags where the program actually runs, not on your build machine.
Because best_level and make_dispatcher take the feature set as an argument, you can feed them a made-up CPU. A test that tries "", "sse2", "sse2 avx2 fma" and the rest exercises every path without owning the hardware. A dispatcher that reads the real CPU inside itself cannot be tested this way.
What the tasks ask
- Task and functionWhat it must do
- parse_features(text)The set of lower-case flags in a
/proc/cpuinfoline or a plain list.ValueErrorwhen no flag is left - best_level(features)The first level in
LEVEL_ORDERwhoseREQUIRESare all present.scalaris always the floor - make_dispatcher(kernels, features)A function that chooses once on its first call, remembers the choice, and exposes
resolvedandlevel.ValueErrorwhen nothing qualifies - run_dot(features, a, b)
(level, value, instructions)usingbest_leveland the right kernel on the right width.exact instruction counts are tested
sse2 avx avx2 and no fma. Which level does best_level return, given the table REQUIRES?Next. That is every piece. The capstone puts them together on one job: a rolling mean and a dot product over real SPY returns, written for any width with the portable type, with the tail handled, the reduction deferred and the version chosen by what the CPU can run. It finishes with a speedup report that counts instructions honestly: the vector kernel against the scalar one at every width, on 5,404 real returns.
Lab · what's graded
4 tasks · 100 pts- Read the CPU's flags with
parse_features25 pts - Choose the best level with
best_level25 pts - Decide once with
make_dispatcher25 pts - Run on whatever CPU you get with
run_dot25 pts