You have written r * 2.0 on a NumPy array a thousand times. On 5,400 SPY returns the machine loop behind it runs 3.96 times fewer instructions than a one-number-at-a-time loop on 4 lanes, but on 16 numbers it is barely a win. Why does the same idea win big on long arrays and not at all on short ones?
The idea in plain words
Where we are. The last topic built LaneSim, a machine with 4 or 8 lanes that counts instructions, and a vector_add that beats the scalar loop by exactly the lane count. The question it left open: you already use a tool that does this, NumPy, so is it the same thing? It is, and this topic uses the machine to show why, and also why the win is not the same for every array.
A Python for loop pays twice for every element. First, the interpreter runs many small steps just to fetch the element, check that it is a number and make a new result object. Second, the machine finally performs one scalar multiply. A NumPy call such as r * 2.0 removes the first cost: one call into compiled code, which then runs a tight loop over a block of numbers laid out one after the other.
Writing an operation on a whole array at once, so that a compiled loop does the repetition. That loop is also where SIMD instructions come in, because it can work on one register of numbers at a time.
Be clear about what LaneSim models here. It counts the machine instructions of the compiled loop, so it shows the second effect, the lane count. It does not model the interpreter's extra work per element, which is a separate and often larger cost that you would see only by timing. In this skill we stay with the part we can count exactly.
The smallest example: scale an array by 2
Start with the NumPy line and its Python-loop twin. They give the same numbers; what differs is who does the repeating. The dtype and itemsize lines tell us how wide each number is, which fixes how many fit in a 256-bit register.
# The same scaling in NumPy and in a plain Python loopimport numpy as npr = np.array([0.012, -0.004, 0.007, -0.011, 0.003, 0.009, -0.006, 0.002])print((r * 2.0).tolist())1print([x * 2.0 for x in r.tolist()])print(r.dtype, r.itemsize, "bytes ->", 32 // r.itemsize, "numbers in a 256-bit register")2
[0.024, -0.008, 0.014, -0.022, 0.006, 0.018, -0.012, 0.004] [0.024, -0.008, 0.014, -0.022, 0.006, 0.018, -0.012, 0.004] float64 8 bytes -> 4 numbers in a 256-bit register
- 1One call, a compiled loop inside.
- 2A 64-bit float is 8 bytes: 4 fit in 256 bits.
Now the machine's version of the same job. scalar_scale is the plain loop: four instructions per element (loop, sload, smul, sstore). vector_scale is the task you will write: first a vsplat that copies the factor 2.0 into every lane of a register, then a loop of vload, vmul, vstore. The splat is needed because vmul multiplies two registers lane by lane, so the constant must sit in a register too.
def vector_scale(sim, a, k): """Return every element of `a` multiplied by `k` as a new list, using only vector instructions. Spread `k` over all lanes once with `vsplat`, before the loop. Each pass then runs one `sim.loop()`, one `vload`, one `vmul` and one `vstore`. For 8 elements on 4 lanes: {"vsplat": 1, "loop": 2, "vload": 2, "vmul": 2, "vstore": 2}, 9 instructions where `scalar_scale` needs 32. An empty array returns [] and counts nothing. If the length is not a multiple of `sim.lanes` raise ValueError("length must be a multiple of the lane count"). """ if len(a) % sim.lanes: raise ValueError("length must be a multiple of the lane count") if not a: return [] factor = sim.vsplat(k)1 out = [0.0] * len(a) for i in range(0, len(a), sim.lanes): sim.loop() sim.vstore(out, i, sim.vmul(sim.vload(a, i), factor))2 return out
- 1Once, before the loop: the factor does not change.
- 2Load, multiply, store: three instructions for
lanesnumbers.
# 8 numbers on 4 lanes: the scalar loop against the vector loopdata = [0.5] * 8scalar = LaneSim(4)scalar_scale(scalar, data, 2.0)vector = LaneSim(4)vector_scale(vector, data, 2.0)print("scalar", scalar.total(), scalar.counts)print("vector", vector.total(), vector.counts)print("speedup", round(scalar.total() / vector.total(), 3))
scalar 32 {'loop': 8, 'sload': 8, 'smul': 8, 'sstore': 8}
vector 9 {'vsplat': 1, 'loop': 2, 'vload': 2, 'vmul': 2, 'vstore': 2}
speedup 3.556Read the numbers: 32 instructions against 9, a speedup of 3.556, not 4. The extra vsplat is one instruction that the scalar loop does not have. It is paid once, so on a longer array it matters less and less.
Build it up: a fixed cost and a long array
The vsplat is a one-off cost inside the loop machine. A NumPy call has a bigger one-off cost outside it: Python must look up the function, check the types and shapes of the arguments and allocate the output array before the first lane is touched. We model that with a number, call_cost, added to the vector side. It is a stand-in, not a measurement: 50 instructions is a round, believable size for the lesson.
lanes elements, and the fixed call_cost.For a short array the fixed cost dominates and the speedup is below 1: the plain loop wins. For a long array the per-pass term dominates and the speedup climbs toward the lane count but never reaches it. Let the machine draw the curve, and find the break-even length where the two sides meet.
# Speedup against array length on 4 lanes, with a call cost of 50 instructionsfor n in (4, 16, 64, 256, 1024, 5400): print(n, round(numpy_speedup(n, 4, 50), 3))n = 4while numpy_speedup(n, 4, 50) <= 1: n += 4print("break-even length:", n)
4 0.291 16 0.955 64 2.226 256 3.336 1024 3.81 5400 3.963 break-even length: 20
- NumPy callMachine instructions in its loop
- np.add(a, b)Which instructions does adding two arrays run?
vloadx2,vadd,vstore - np.multiply(r, 2.0)And a constant factor?one
vsplat, thenvload,vmul,vstore - for x in r: x * 2.0The Python loop?one scalar multiply per element, plus interpreter work
Typical mistakes
Vectorizing a tiny array. Four numbers do not repay a call cost of 50. The curve above shows a speedup of 0.291 at 4 values: the vector side is more than three times slower. The cure is not a different loop but a bigger batch: gather many small calls into one call over a long array.
# Four numbers, then a splat in every pass: two ways to loseprint(round(numpy_speedup(4, 4, 50), 3))sim = LaneSim(4)out = [0.0] * 8for i in range(0, 8, 4): sim.loop() sim.vstore(out, i, sim.vmul(sim.vload(data, i), sim.vsplat(2.0)))1print(sim.total(), sim.counts)
0.291
10 {'loop': 2, 'vload': 2, 'vsplat': 2, 'vmul': 2, 'vstore': 2}- 1The splat now runs in every pass: 10 instructions instead of 9.
Repeating work that never changes. The second half of that example moved the vsplat into the loop. The answer stays correct, so nothing complains, but the count rises from 9 to 10 because the same constant is rebuilt every pass. Anything that does not depend on the loop index belongs before the loop. The graded test counts exactly one vsplat.
for x in r hands you one Python number at a time, so you pay the interpreter for every element and the SIMD loop never runs. Write the whole-array expression instead.
What the tasks ask
- Task and functionWhat it must do
- LaneSim.vmul(a, b)Multiply two registers lane by lane into a new register and count one
vmul.same checks asvadd - LaneSim.vsplat(x)Return a new register with
xin every lane and count onevsplat.a fresh list every call - vector_scale(sim, a, k)Scale a whole array: one
vsplatbefore the loop, then per passloop,vload,vmul,vstore.exact counts are tested - numpy_speedup(n, lanes, call_cost)Run both scale loops on fresh machines and return scalar total / (vector total + call_cost).uses your two scale functions
Next. NumPy hides the loop behind a call. The next topic asks what happens when you write the loop yourself in a compiled language and leave the vectorizing to the compiler: which loops can it turn into vector code, and which does it refuse? You will build a small analyser for the loops it refuses and see why, on LaneSim, an overlapping read and write breaks the lane-by-lane idea.
Lab · what's graded
4 tasks · 100 pts- Multiply lane by lane with
vmul25 pts - Spread one number across the lanes with
vsplat25 pts - Scale an array with
vector_scale25 pts - Count the speedup with
numpy_speedup25 pts