σμ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 AcademyRoadmapsSkills
Ctrl K
AO
+1.2k Learners
LoginJoin ↗
RoadmapsSkills
AO
+1.2k Learners
Login
  • 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 AcademyRoadmapsSkills
Ctrl K
AO
+1.2k Learners
LoginJoin ↗
RoadmapsSkills
AO
+1.2k Learners
Login
  • English
  • Français
  • Español
  • العربية
  • Português
  • Deutsch
  • 日本語
  • 中文
SIMD skill›Module 4 · Portable code and dispatch›Topic 4.2·~50 minAdvanced

Runtime dispatch by CPU feature

Skill positionModule 4 of 4 · Topic 2 of 3
4.2 Runtime dispatch by CPU feature
—Lab score— / 100Total XP—Streak—
Lecture0% read

6 min readCode examples: 7

  1. 01The idea in plain words
  2. 02The smallest example: a flags line to a level
  3. 03Build it up: decide once, then call
  4. 04Typical mistakes
  5. 05What the tasks ask

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?

01

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.

DefinitionDispatch

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.

02

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.

main.pyPython
# 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. 1avx2 also needs fma: the fused kernels use it.
main.pyPython
# 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.

03

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.

main.pyPython
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. 1Only the first call goes in here.
  2. 2Every call, including the first, ends here.
main.pyPython
# 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

Before 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.

  1. 1
    Read the flagsparse_features turns the CPU's text into a set of lower-case names.
  2. 2
    Pick the levelbest_level returns the first level whose requirements are all present.
  3. 3
    Match a kernelmake_dispatcher takes the best level that also has a version built for it.
  4. 4
    Remember 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.

main.pyPython
# 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. 1(level, dot product, instructions): the answer never changes, the cost does.
What the real data says5,404 SPY returns, dot product with itself, by CPU level
scalar (nothing) (instr.)27,020the floor every machine can run
sse2 (2 lanes) (instr.)13,5142.0x
avx2 (4 lanes) (instr.)6,7614.0x
avx512 (8 lanes) (instr.)3,4037.9x
Instructions by CPU level
scalar27020
sse213514
avx26761
avx5123403
  • 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
04

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.

main.pyPython
# 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.

main.pyPython
# 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
A flag is not a promise

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.

Test every level on one 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.

05

What the tasks ask

  • Task and functionWhat it must do
  • parse_features(text)The set of lower-case flags in a /proc/cpuinfo line or a plain list.ValueError when no flag is left
  • best_level(features)The first level in LEVEL_ORDER whose REQUIRES are all present.scalar is always the floor
  • make_dispatcher(kernels, features)A function that chooses once on its first call, remembers the choice, and exposes resolved and level.ValueError when nothing qualifies
  • run_dot(features, a, b)(level, value, instructions) using best_level and the right kernel on the right width.exact instruction counts are tested

Key takeaways

  • Ask the CPU, then choose Read the feature flags where the program runs and map them to the best level whose requirements are all present; a missing flag, such as fma next to avx2, drops a level.
  • Decide once, keep a floor A dispatcher resolves on its first call and then calls directly, and it always ships a scalar version, because a missing kernel is a clean error and an illegal instruction is a crash.
  • Take the CPU as a parameter Passing the feature set in, instead of reading it inside, lets one test run every level on one machine.
Quick check
A CPU reports the flags sse2 avx avx2 and no fma. Which level does best_level return, given the table REQUIRES?
Pick an answer.

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
Explorer · lab-10-1
▾ lab-10-1
…
bash · in-browser
learner@quantcraft:~/lab-10-1$
Python not loaded yetPythonLn 1, Col 1Spaces: 4UTF-8

Reset this topic?

Everything in lab-10-1 goes back to the starter files and the terminal is cleared. Your current solution will be lost — this can't be undone.

Will be reset
  • main.py → starter code
  • Terminal history and test output
  • Unsubmitted changes
Will be kept
  • Best lab score
  • Your XP and streak
  • Lecture progress and notes