Adding two arrays of 5,400 daily SPY returns takes 27,000 instructions when the CPU handles one number at a time, and 6,750 when it adds four numbers with each instruction. Where does that factor of four come from, and what must a machine do to get it?
The idea in plain words
Where we are. This is the first topic of the SIMD skill, so nothing comes before it. By the end you will have built a small vector machine in Python, called LaneSim, and used it to add two arrays in a quarter of the instructions a one-number-at-a-time loop needs. Every later topic grows this same machine, so what you write here is the foundation.
A CPU works by running instructions, tiny steps such as "load a number from memory", "add two numbers" and "store the result". An ordinary (scalar) add instruction works on one pair of numbers. But a modern CPU also has wide registers that hold four or eight numbers side by side, and instructions that act on every one of them at once. Each position in such a register is a lane.
Single Instruction, Multiple Data: one instruction that does the same operation on every lane of a wide register at once, so one add handles four or eight numbers instead of one.
An everyday comparison: carrying eggs from the shop to your kitchen one at a time, or in a carton of four. The walk is the same and so is the effort of one trip, but the carton moves four times the eggs. A quant cares because the work that dominates many programs, a rolling mean, a dot product, a risk sum, is a loop that repeats the same arithmetic on thousands of numbers. That is exactly the shape a carton fits.
How wide are real registers? An SSE register is 128 bits wide, an AVX2 register 256 bits and an AVX-512 register 512 bits. A price stored as a 64-bit float takes 64 bits, so those registers hold 2, 4 and 8 of them; a 32-bit float is half the size, so they hold 4, 8 and 16. LaneSim uses 4 or 8 lanes, which is a 256-bit register of 64-bit or 32-bit floats. The width changes the speedup but not the idea.
We will not time anything in this skill. Wall-clock timing depends on the machine, the load and the cache, so two runs disagree. Instead LaneSim counts instructions: a speedup becomes a ratio of two integers that you can print, check and reproduce exactly. That is a model, and a later note says what it leaves out, but it keeps the idea clear.
The smallest example: one number per instruction
Here is the start of LaneSim, the part that is already written in your starter file. It keeps a dictionary counts that maps an instruction name to how many times it ran, and offers the scalar instructions: sload reads one number, sadd adds two, sstore writes one, and loop stands for the compare-and-jump that ends every pass of a loop.
class LaneSim: """A vector machine with `lanes` lanes that counts every instruction it runs.""" def __init__(self, lanes=4): if lanes not in (4, 8): raise ValueError("lanes must be 4 or 8") self.lanes = lanes self.counts = {}1 def tick(self, op): """Count one instruction named `op`.""" self.counts[op] = self.counts.get(op, 0) + 12 def total(self): """The number of instructions run so far.""" return sum(self.counts.values()) # ---- the scalar side: one number per instruction ---- def loop(self): """One compare-and-jump at the end of a loop pass.""" self.tick("loop") def sload(self, mem, i): self.tick("sload") return mem[i] def sstore(self, mem, i, x): self.tick("sstore") mem[i] = x def sadd(self, x, y): self.tick("sadd") return x + y
- 1
countsis where every instruction is recorded. - 2
tickis the only place a count goes up.
Now the baseline, scalar_add. It adds two arrays by walking through them one element at a time. Each pass does five things: one loop, two sload (one number from each array), one sadd and one sstore.
# Add two arrays of 8 numbers, one element per pass, and count what the machine ransim = LaneSim(4)a = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0]b = [10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0]print(scalar_add(sim, a, b))print(sim.total(), sim.counts)1
[11.0, 22.0, 33.0, 44.0, 55.0, 66.0, 77.0, 88.0]
40 {'loop': 8, 'sload': 16, 'sadd': 8, 'sstore': 8}- 18 passes x 5 instructions = 40.
Read the last line: sim.total() is 40 and sim.counts shows eight of each of the five instructions, five instructions times eight elements. The array length is the only thing that changes this number, so it grows in a straight line with the data.
Build it up: a register, a load and an add
The vector side needs just three new instructions, and these are the first three tasks. vload copies lanes neighbouring numbers from memory into a register, vadd adds two registers lane by lane, and vstore copies a register back into memory. Each one counts as a single instruction no matter how many lanes it moves, and that is the whole trick.
# ---- the vector side: `lanes` numbers per instruction ----def vload(self, mem, i):1 """Load `lanes` consecutive numbers starting at index `i` into a register (a new list): one `vload`. If they do not all fit (i < 0 or i + lanes > len(mem)) raise ValueError("vector load out of range") and count nothing. """ if i < 0 or i + self.lanes > len(mem): raise ValueError("vector load out of range") self.tick("vload") return list(mem[i:i + self.lanes])def vstore(self, mem, i, reg):2 """Write the register `reg` into `mem[i:i + lanes]`: one `vstore`. Returns nothing. If `reg` does not have exactly `lanes` numbers raise ValueError("register must have one number per lane"); if the lanes do not all fit in `mem` raise ValueError("vector store out of range"). Nothing is counted or written when it raises. """ if len(reg) != self.lanes: raise ValueError("register must have one number per lane") if i < 0 or i + self.lanes > len(mem): raise ValueError("vector store out of range") self.tick("vstore") mem[i:i + self.lanes] = regdef vadd(self, a, b): """Add two registers lane by lane and return the result as a new list: one `vadd`. If either register does not have exactly `lanes` numbers raise ValueError("register must have one number per lane"). """ if len(a) != self.lanes or len(b) != self.lanes: raise ValueError("register must have one number per lane") self.tick("vadd") return [x + y for x, y in zip(a, b)]
- 1A register is a plain list with one number per lane.
- 2
vstorereturns nothing: it changes memory.
- 1Load
vload(a, i)fills a register witha[i]toa[i + lanes - 1]: one instruction. - 2Add
vadd(x, y)adds the two registers lane by lane: one instruction for all lanes. - 3Store
vstore(out, i, r)writes the register intoout[i]toout[i + lanes - 1]: one instruction. - 4Move on by one registerThe loop index jumps by
lanes, not by 1, andloopcounts one pass.
Try the three instructions on their own first. Load four numbers from each array, add the two registers and look at the counts. Notice that the registers r1, r2 and r3 are ordinary lists: printing them shows the four lanes.
# One register from each array, added in a single instructionsim = LaneSim(4)r1 = sim.vload(a, 0)r2 = sim.vload(b, 0)1r3 = sim.vadd(r1, r2)print(r1, r2, r3)print(sim.counts)
[1.0, 2.0, 3.0, 4.0] [10.0, 20.0, 30.0, 40.0] [11.0, 22.0, 33.0, 44.0]
{'vload': 2, 'vadd': 1}- 1Three instructions moved or added 12 numbers.
Now put the three together in a loop. vector_add is task four. It walks through the arrays lanes elements at a time and, in each pass, runs one loop, two vload, one vadd and one vstore. Look at how few lines it needs, and at the two checks at the top that the topic on alignment and the scalar tail will remove.
def vector_add(sim, a, b): """Return the lane-by-lane sum of the arrays `a` and `b` as a new list, using only vector instructions. Each pass handles `sim.lanes` elements: one `sim.loop()`, two `vload`, one `vadd`, one `vstore`. For 8 elements on 4 lanes that is two passes: {"loop": 2, "vload": 4, "vadd": 2, "vstore": 2}, 10 instructions where `scalar_add` needs 40. If the arrays differ in length raise ValueError("arrays must have the same length"); if the length is not a multiple of `sim.lanes` raise ValueError("length must be a multiple of the lane count") (topic 5 handles the leftover elements). """ if len(a) != len(b): raise ValueError("arrays must have the same length") if len(a) % sim.lanes: raise ValueError("length must be a multiple of the lane count") out = [0.0] * len(a)2 for i in range(0, len(a), sim.lanes):1 sim.loop() total = sim.vadd(sim.vload(a, i), sim.vload(b, i)) sim.vstore(out, i, total) return out
- 1Step by
lanes, not by 1. - 2Results go to a new list, so the inputs stay untouched.
# The same sum with 4 lanes and with 8 lanesfor lanes in (4, 8): sim = LaneSim(lanes) print(lanes, vector_add(sim, a, b) == scalar_add(LaneSim(lanes), a, b), sim.total(), sim.counts)
4 True 10 {'loop': 2, 'vload': 4, 'vadd': 2, 'vstore': 2}
8 True 5 {'loop': 1, 'vload': 2, 'vadd': 1, 'vstore': 1}Same answer, fewer instructions: 10 with 4 lanes and 5 with 8 lanes, against 40 for the scalar loop. The speedup in instructions is exactly the number of lanes, because each vector pass does the work of lanes scalar passes for the same five instructions.
The counts depend only on how many elements there are, never on their values. So we can check the numbers in the lead with any array of the right length: 5,400 returns, here all equal because the value does not matter.
# 5,400 returns: the scalar loop against 4 and 8 lanesreturns = [0.001] * 5400scalar = LaneSim(4)scalar_add(scalar, returns, returns)print("scalar", scalar.total())for lanes in (4, 8): sim = LaneSim(lanes) vector_add(sim, returns, returns) print(lanes, "lanes", sim.total(), "speedup", scalar.total() / sim.total())1
scalar 27000 4 lanes 6750 speedup 4.0 8 lanes 3375 speedup 8.0
- 1The ratio is exactly the lane count.
Real chips run some wide instructions slower than narrow ones, and memory can be the limit. So a real 4-lane speedup is usually below 4x. The simulator shows the ceiling the idea can reach.
Typical mistakes
An array whose length is not a multiple of the lanes. A register is always full, so there is no way to load 3 numbers into 4 lanes. Seven elements on 4 lanes leave a leftover, and vector_add refuses it with an error. Reading that message is the whole fix for now: pass a length that fits. The topic on alignment and the scalar tail shows what to do with the leftover.
# Seven elements do not fill two registers of 4 lanessim = LaneSim(4)vector_add(sim, a[:7], b[:7])
ValueError: length must be a multiple of the lane count
Treating a register as a window onto memory. vload copies. If you change r1 afterwards, a does not change; only vstore writes memory. Forgetting the vstore is the quiet version of the same mistake: the sums are computed, counted and then thrown away, and the output list is still full of zeros.
# Changing a register does not change memory; only vstore doessim = LaneSim(4)r = sim.vload(a, 0)r[0] = 99.01print(a[:4], r)out = [0.0] * 4sim.vstore(out, 0, r)print(out)
[1.0, 2.0, 3.0, 4.0] [99.0, 2.0, 3.0, 4.0] [99.0, 2.0, 3.0, 4.0]
- 1This edits the register, not
a.
The speedup is only honest if the vector loop pays for its loads, stores and loop passes too. If you skip a tick, the ratio looks better than it is, and the graded tests compare your counts exactly.
What the tasks ask
- Task and functionWhat it must do
- LaneSim.vload(mem, i)Copy
lanesnumbers frommeminto a new register and count onevload.raises if it does not fit - LaneSim.vstore(mem, i, reg)Write a register into memory and count one
vstore; return nothing.a failing store writes nothing - LaneSim.vadd(a, b)Add two registers lane by lane into a new register and count one
vadd.inputs are not changed - vector_add(sim, a, b)Add two whole arrays with only vector instructions: per pass one
loop, twovload, avaddand avstore.exact counts are tested
Next. You now have a machine whose instructions you can count, and a loop that beats the scalar one by exactly the number of lanes. The next topic asks why a familiar tool, NumPy, is fast: it is the same idea. You will extend LaneSim with multiplication and a way to spread one number across all lanes, and count how the speedup depends on the length of the array.
Lab · what's graded
4 tasks · 100 pts- Load a register with
vload25 pts - Write it back with
vstore25 pts - Add lane by lane with
vadd25 pts - Add two arrays with
vector_add25 pts