Summing the same 5,400 SPY returns gives 2.496325973347371 left to right, 2.4963259733473677 on 4 lanes and 2.4963259733473686 on 8: three different answers from one set of numbers. Why does adding across lanes change the digits, and why does it still cost only a handful of instructions?
The idea in plain words
Where we are. Masks let each lane make its own choice, but every result so far stayed in its own lane. A lot of quant arithmetic ends in one number: a sum of squared returns, a dot product of two return series, the largest drawdown. That is a reduction, and it asks the one thing a vector register is bad at: moving numbers between lanes.
The way out is to delay it. Do not add across lanes inside the loop. Keep a register of partial sums, one per lane, add into it pass after pass, which is ordinary lane-by-lane work, and collapse its lanes into one number a single time after the loop. The collapse costs a few instructions and does not depend on the array length, so on a long array it is invisible.
Each lane adds up its own share of the array, lanes apart. After the loop the lanes are combined into one number by halving: add the far half onto the near half, then the far quarter onto the near quarter, until one lane is left.
The smallest example: halving four lanes
Two small instructions make it possible. vshuffle(reg, order) builds a new register whose lane k is reg[order[k]]: it moves lanes around, one instruction. vextract(reg) hands one lane out as an ordinary number. With them hsum adds [r0, r1, r2, r3] in two steps: shuffle so each lane meets the lane two places on, add; shuffle so each lane meets its neighbour, add; the answer is in lane 0.
# Adding the four lanes of one register: two halving steps and one extractsim = LaneSim(4)reg = [1.0, 2.0, 3.0, 4.0]step1 = sim.vadd(reg, sim.vshuffle(reg, [2, 3, 0, 1]))1step2 = sim.vadd(step1, sim.vshuffle(step1, [1, 0, 3, 2]))2print(step1, step2, sim.vextract(step2, 0))print(sim.counts)sim = LaneSim(4)print(sim.hsum(reg), sim.counts)
[4.0, 6.0, 4.0, 6.0] [10.0, 10.0, 10.0, 10.0] 10.0
{'vshuffle': 2, 'vadd': 2, 'vextract': 1}
10.0 {'vshuffle': 2, 'vadd': 2, 'vextract': 1}- 1Lane 0 meets lane 2, lane 1 meets lane 3.
- 2Now lane 0 meets lane 1: the total lands in lane 0.
Five instructions, two halving steps, for four lanes. Eight lanes need three steps and seven instructions: the cost grows with the logarithm of the lane count, not with the array. That is why a reduction at the end is cheap, and why a reduction inside the loop would not be.
Build it up: partial sums, dot product and maximum
vector_sum is the pattern in its plainest form, and it is written for you. A vsplat of zero makes the register of partial sums; each pass loads a register and adds it in (vadd); hsum finishes. Lane k ends up with a[k] + a[k + lanes] + a[k + 2 * lanes] + ...: its own stripe of the array.
def vector_sum(sim, a): """The sum of an array: keep a register of partial sums, one per lane, and add across the lanes only once at the end. One `vsplat` of 0.0, then per pass `sim.loop()`, one `vload` and one `vadd` into the register, then `hsum` of the register. """ if len(a) % sim.lanes: raise ValueError("length must be a multiple of the lane count") if not a: return 0.0 partial = sim.vsplat(0.0) for i in range(0, len(a), sim.lanes): sim.loop() partial = sim.vadd(partial, sim.vload(a, i))1 return sim.hsum(partial)2
- 1Ordinary lane-by-lane work: no shuffles in the loop.
- 2The one reduction, after the loop.
The dot product is the same pattern with one change, and it is your task: instead of adding a loaded register, add the lane-wise product of two loaded registers. The fused multiply-add from the topic on intrinsics does both at once, partial = vfma(x, y, partial), so a pass is loop, two vload and one vfma. The scalar loop spends five instructions per element where this one spends about one.
# A dot product of an array of 5,400 numbers with itself: scalar against 4 and 8 lanesdata = [0.5] * 5400scalar = LaneSim(4)scalar_dot(scalar, data, data)print("scalar", scalar.total())for lanes in (4, 8): sim = LaneSim(lanes) value = vector_dot(sim, data, data)1 print(lanes, "lanes", sim.total(), sim.counts["vshuffle"], "shuffles", round(scalar.total() / sim.total(), 2), value)
scalar 27000 4 lanes 5406 2 shuffles 4.99 1350.0 8 lanes 2708 3 shuffles 9.97 1350.0
- 1Only 2 or 3 shuffles in the whole run: the reduction is a rounding error in the count.
The order of the additions matters, and this is the part that surprises people. Floating-point addition is not associative: (a + b) + c and a + (b + c) can differ in the last digits because each add rounds. A left-to-right loop adds in one order, 4 lanes in a second, 8 lanes in a third, so the three sums of the lead differ. None is "the" right answer; a compensated sum such as math.fsum is closest to the true value. The tests of this lab therefore compare your result with the exact order a vector machine adds in.
# Same four numbers, two orders, two answers. The exact sum is 2.0values = [1e16, 1.0, -1e16, 1.0]left_to_right = 0.0for x in values: left_to_right += xsim = LaneSim(4)print(left_to_right, sim.hsum(values))1
1.0 2.0
- 1(1e16 + -1e16) + (1 + 1): nothing is lost this way round.
A maximum is a reduction too, and it reuses the previous topic: keep a register of running maxima, update it with a compare and a blend, and finish with hmax, the same halving walk as hsum with vcmp_gt and vblend in place of vadd. The first register can seed the running maxima directly, which also avoids the trap of starting from zero when every number is negative.
def vector_max(sim, a): """The largest number in an array, with a register of running maxima and one `hmax` at the end. The first pass is `sim.loop()` and a `vload` that becomes the running register. Each later pass is `sim.loop()`, a `vload`, a `vcmp_gt` of the new register against the running one and a `vblend` that keeps the larger lane. Then `hmax` of the register. Raise ValueError("array must not be empty") for an empty array, then ValueError("length must be a multiple of the lane count"). """ if not a: raise ValueError("array must not be empty") if len(a) % sim.lanes: raise ValueError("length must be a multiple of the lane count") best = None for i in range(0, len(a), sim.lanes): sim.loop() x = sim.vload(a, i) best = x if best is None else sim.vblend(sim.vcmp_gt(x, best), x, best)1 return sim.hmax(best)
- 1The first register seeds the running maxima.
vector_max finds- OperationCost of the across-lane step
- hsum(reg)Add all the lanes into one number.log2(lanes) shuffles and adds, 1 extract
- hmax(reg)The largest of the lanes.log2(lanes) shuffles, compares, blends, 1 extract
- reduce inside the loopCollapse the lanes in every pass.the same cost, paid n / lanes times
Typical mistakes
Reducing inside the loop. It is correct and it is the first thing most people write, because it matches the scalar code: add the product of each pair of lanes into a running total. Every pass then pays for a full halving walk. Count it with the code below and compare with the 5,406 of vector_dot.
# Reducing across the lanes in every pass: right answer, far more instructionssim = LaneSim(4)total = 0.0for i in range(0, 5400, 4): sim.loop() total += sim.hsum(sim.vfma(sim.vload(data, i), sim.vload(data, i), sim.vsplat(0.0)))1print(total, sim.total(), "against 5406")
1350.0 13500 against 5406
- 1A full hsum, with its shuffles, in every pass.
Starting a maximum from zero. A running maximum that begins at 0.0 can never go below zero, so the largest of a set of negative numbers comes out as 0.0 instead of the real answer. Seed it from the data, as vector_max does. The worst SPY day, -10.95%, is exactly the kind of number this bug hides.
# The maximum of eight negative days, started from zero and started from the datalosses = [-0.0457, -0.0912, -0.1095, -0.0231, -0.0388, -0.0643, -0.0715, -0.0254]sim = LaneSim(4)wrong = sim.vsplat(0.0)for i in range(0, 8, 4): x = sim.vload(losses, i) wrong = sim.vblend(sim.vcmp_gt(x, wrong), x, wrong)print(sim.hmax(wrong), vector_max(LaneSim(4), losses))
0.0 -0.0231
Two correct programs that add in different orders can disagree in the last digits, so never compare sums with ==. Test with a tolerance, and when a result must be reproducible across machines, fix the order, as hsum does.
What the tasks ask
- Task and functionWhat it must do
- LaneSim.vshuffle(reg, order)A new register whose lane
kisreg[order[k]]; count onevshuffle.three error checks, in order - LaneSim.hsum(reg)Add all lanes by halving, ending with one
vextract.usesvshuffle,vadd,vextract - vector_dot(sim, a, b)Partial sums with
vfma, onehsumat the end.the order of the additions is tested - vector_max(sim, a)Running maxima with
vcmp_gtandvblend, onehmaxat the end.works for negative numbers
hsum add to the whole run, compared with the loop?Next. Every load so far read consecutive numbers: vload(a, i) takes a[i] to a[i + lanes - 1]. Real quant data is often indexed, a table of risk weights looked up by regime, or prices picked out by an index list. The next topic adds the instruction for that, gather, and its mirror, scatter, and counts what they cost, because a gather is far from one cheap load.
Lab · what's graded
4 tasks · 100 pts- Move lanes around with
vshuffle25 pts - Add across lanes with
hsum25 pts - Write the dot product
vector_dot25 pts - Find the largest value with
vector_max25 pts