One dot product, written once, costs 13,514 instructions at 2 lanes and 1,755 at 16 on the 5,404 SPY returns. But on 30 elements the order flips: 4 lanes need 51 and 16 lanes 85. What must a kernel that does not know its width get right?
The idea in plain words
Where we are. The last topic gave LaneSim gather and scatter. Every kernel since the beginning has been written against sim.lanes, but with one machine in mind, usually 4. Real code does not get to pick: the same program may run on a laptop with 4 lanes of doubles, a server with 8 and one with 16, and the compiler cannot guess which one the next machine will be. Portable SIMD is the answer, and it is the idea behind C++26 std::simd, Rust's portable SIMD (still behind a feature flag at the time of writing) and libraries such as Highway and xsimd.
The kernel never writes 4, 8 or 16. It asks the machine for its lane count, steps through the data by that amount, and does all arithmetic through operators on a vector type. The compiler or the library turns each operator into the one instruction the target has.
In LaneSim the portable type is Vec. It holds a register and remembers which machine it belongs to. x + y is one vadd, x * y one vmul, Vec.load(sim, a, i) one vload and acc.sum() one hsum. Nothing is added: the counts are exactly those of the hand-written version, which is the point. The abstraction is free, and the width is the only thing that changes between machines.
The smallest example: one expression, any width
Here is the type, in full. The methods that only wrap one machine instruction are written for you; you will write the two operators. Look at __add__ and __mul__: each checks that both operands live on the same machine, then makes exactly one call into LaneSim. A vector from a 4-lane machine cannot be added to one from an 8-lane machine, in the same way that the compiler refuses to mix simd<double, 4> and simd<double, 8>.
class Vec: """A register that remembers its machine, so a kernel can be written with + - * and never mention the lane count. This is the idea of C++26 `std::simd`, Rust's portable SIMD and libraries such as Highway: the width is a parameter of the type, not something the kernel code spells out. Every operation is still ONE instruction on the machine the vector came from. """ def __init__(self, sim, values): self.sim = sim self.values = list(values) @property def lanes(self): return self.sim.lanes @classmethod def load(cls, sim, mem, i): """The `lanes` numbers from mem[i]: one `vload`.""" return cls(sim, sim.vload(mem, i)) @classmethod def splat(cls, sim, x): """`x` in every lane: one `vsplat`.""" return cls(sim, sim.vsplat(x)) def store(self, mem, i): """Write the vector to mem[i:i + lanes]: one `vstore`.""" self.sim.vstore(mem, i, self.values) def sum(self): """Add all the lanes into one ordinary number with `hsum`.""" return self.sim.hsum(self.values) def __sub__(self, other): """Lane-wise difference as a new Vec: one `vsub`.""" return Vec(self.sim, self.sim.vsub(self.values, other.values)) def __add__(self, other): """Lane-wise sum as a new Vec: one `vadd`, on the machine both vectors share. If the two vectors come from different machines (`self.sim is not other.sim`) raise ValueError("vectors must come from the same machine") and count nothing. """ if self.sim is not other.sim: raise ValueError("vectors must come from the same machine") return Vec(self.sim, self.sim.vadd(self.values, other.values))1 def __mul__(self, other): """Lane-wise product as a new Vec: one `vmul`, on the machine both vectors share. If the two vectors come from different machines raise ValueError("vectors must come from the same machine") and count nothing. """ if self.sim is not other.sim: raise ValueError("vectors must come from the same machine") return Vec(self.sim, self.sim.vmul(self.values, other.values))
- 1One call into the machine: the abstraction adds no instructions.
# One expression, three machines: the same code, different widthsfor width in (2, 4, 8): sim = LaneSim(width) x = Vec.load(sim, [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0], 0) y = Vec.splat(sim, 10.0) z = x * y + x print(width, z.values, sim.counts)
2 [11.0, 22.0] {'vload': 1, 'vsplat': 1, 'vmul': 1, 'vadd': 1}
4 [11.0, 22.0, 33.0, 44.0] {'vload': 1, 'vsplat': 1, 'vmul': 1, 'vadd': 1}
8 [11.0, 22.0, 33.0, 44.0, 55.0, 66.0, 77.0, 88.0] {'vload': 1, 'vsplat': 1, 'vmul': 1, 'vadd': 1}Same line x * y + x, three machines, three registers of different length, and one vmul plus one vadd each time. That is what makes portable code attractive: the kernel is the same text, and the machine decides how much work each instruction does.
Build it up: the dot product at every width
Now the kernel of the lab, portable_dot. It combines three pieces from earlier topics: partial sums with one reduction at the end, a scalar tail for the leftover elements, and operators on Vec. The only place the width appears is sim.lanes, read once. The rules of the lab are strict on purpose: a literal 4 or 8 in the body, or a direct call to vadd, is flagged, because either one ties the kernel to a machine.
def portable_dot(sim, a, b): """The dot product of two arrays of ANY length, written once for ANY lane count, with `Vec` and no lane-count constants. Let `body` be the largest multiple of `sim.lanes` that fits in the length. If `body` is not 0: a `Vec.splat` of 0.0 for the partial sums, then per pass `sim.loop()`, two `Vec.load`, and `acc = acc + x * y` (a `vmul` and a `vadd`), then `acc.sum()` once. The leftover elements after `body` are added one at a time: `sim.loop()`, two `sload`, `smul` and `sadd` into the running total. Empty arrays return 0.0 and count nothing. If the arrays differ in length raise ValueError("arrays must have the same length"). Do not call `vadd`, `vmul` or `vfma` directly, and write no lane count: `sim.lanes` is the only place the width appears. """ if len(a) != len(b): raise ValueError("arrays must have the same length") lanes = sim.lanes1 body = len(a) - len(a) % lanes total = 0.0 if body: acc = Vec.splat(sim, 0.0) for i in range(0, body, lanes): sim.loop() acc = acc + Vec.load(sim, a, i) * Vec.load(sim, b, i)2 total = acc.sum() for i in range(body, len(a)): sim.loop() total = sim.sadd(total, sim.smul(sim.sload(a, i), sim.sload(b, i))) return total
- 1The width appears here and nowhere else.
- 2
+and*on Vec, not vadd and vmul.
Run the same function at every width on the same ten numbers. The answer is the same dot product, 385.0, every time. The instruction counts differ, and not in the simple way you might expect from the lane counts.
# The same kernel on ten numbers at every width: the answer, the instructions, and the scalar baseline of 50ten = [float(i) for i in range(1, 11)]for width in (2, 4, 8, 16): sim = LaneSim(width) print(f"{width:2} lanes: dot = {portable_dot(sim, ten, ten)}, {sim.total():2} instructions")1
2 lanes: dot = 385.0, 29 instructions 4 lanes: dot = 385.0, 26 instructions 8 lanes: dot = 385.0, 23 instructions 16 lanes: dot = 385.0, 50 instructions
- 116 lanes cannot fill one register from 10 numbers: everything is tail, 50 instructions.
The formula shows the trade. A wider register shrinks the first term, but it grows the reduction by one step each time the width doubles, and it can leave a longer tail (up to L - 1 elements, each costing five). For a long array the first term dominates and the widest machine wins. For a short array the tail and the fixed costs dominate, and a narrower width can win. best_width is your tool for asking the question with numbers instead of guessing.
# Which width wins, by array lengthfor n in (3, 10, 30, 100, 5404): counts = {} for width in (2, 4, 8, 16): sim = LaneSim(width) portable_dot(sim, [0.0] * n, [0.0] * n) counts[width] = sim.total() print(f"n = {n:4}: {counts} best {best_width(n, [2, 4, 8, 16])} scalar {5 * n}")1
n = 3: {2: 14, 4: 15, 8: 15, 16: 15} best (2, 14) scalar 15
n = 10: {2: 29, 4: 26, 8: 23, 16: 50} best (8, 23) scalar 50
n = 30: {2: 79, 4: 51, 8: 53, 16: 85} best (4, 51) scalar 150
n = 100: {2: 254, 4: 131, 8: 88, 16: 60} best (16, 60) scalar 500
n = 5404: {2: 13514, 4: 6761, 8: 3403, 16: 1755} best (16, 1755) scalar 27020- 1The winner is 4 at n = 30 and 8 at n = 10, not always the widest.
- Portable libraryHow the width is set
- std::simd<double, N> (C++26)A vector type with N lanes and operators.N is the machine's native width unless you choose
- std::simd::f64x4 (Rust)Fixed-width vector types, for example four doubles.you pick the width; the compiler lowers it per target
- Highway, xsimdLibraries with one source and per-target versions.the width comes from the target you build for
Typical mistakes
Hard-coding a width. A kernel that steps by 8 because "my machine has 8" silently works on the wrong data when it meets 4 lanes: it skips every second register. Nothing raises an error, because every individual instruction is valid. Run the broken version below next to the portable one on a 4-lane machine and compare the sums.
# A kernel that assumed 8 lanes, run on a 4-lane machine: it skips every second registerdef dot_for_eight(sim, a, b): acc = Vec.splat(sim, 0.0) for i in range(0, len(a), 8):1 acc = acc + Vec.load(sim, a, i) * Vec.load(sim, b, i) return acc.sum()four = LaneSim(4)ones = [1.0] * 16print(dot_for_eight(four, ones, ones), portable_dot(LaneSim(4), ones, ones))
8.0 16.0
- 1Steps by 8: loads at 0 and 8, never at 4 or 12.
Assuming the widest machine is the fastest. The table above shows 16 lanes losing on 10 and 30 elements. The fixed cost of the reduction and the longer tail eat the gain. Short arrays are common in quant code, such as one day's cross-section of a few dozen names, so a portable kernel is only half the work; picking the width by array length is the other half, and the next topic does it by CPU feature.
# Vectors from machines of different widths cannot be mixedwide = Vec.splat(LaneSim(8), 1.0)narrow = Vec.splat(LaneSim(4), 1.0)wide + narrow
ValueError: vectors must come from the same machine
In LaneSim the counts show yes. In a real compiler it is true for operators that map to one instruction; an operation the target lacks, such as a gather on a narrow instruction set, is emulated with several instructions, so a portable kernel can still hide a slow path.
What the tasks ask
- Task and functionWhat it must do
- Vec.__add__(self, other)
x + yas onevadd, after checking both vectors share a machine.callsvadd - Vec.__mul__(self, other)
x * yas onevmul, with the same machine check.callsvmul - portable_dot(sim, a, b)Dot product of any length at any width, through
Vec, with a scalar tail.no lane-count literal, no directvadd - best_width(n, widths)
(width, instructions)with the fewest instructions, each width measured by runningportable_dot.a tie goes to the wider width
portable_dot on 10 elements costs 50 instructions at 16 lanes, against 23 at 8 lanes. Where does the extra come from?Next. A portable kernel runs at any width, but the machine you actually have offers one set of instructions: perhaps AVX2 with 4 doubles, perhaps AVX-512 with 8, perhaps neither. The next topic is the last piece before the capstone. A program is built once and has to choose, when it starts, which version to run based on what the CPU says it supports, and it has to refuse politely to run an instruction the chip does not have.
Lab · what's graded
4 tasks · 100 pts- Make
x + yonevaddwithVec.__add__25 pts - Make
x * yonevmulwithVec.__mul__25 pts - Write the dot product once with
portable_dot25 pts - Pick a width with
best_width25 pts