Looking up a regime weight for each of 5,400 SPY returns takes 21,600 instructions one at a time and 5,400 with a gather, yet the gather is charged 9,450, because each lane is a separate memory access. And a vector histogram of the same returns finds only 127 collision-free registers out of 1,350. What do gather and scatter really buy you?
The idea in plain words
Where we are. The last topic collapsed a register into one number. Every load so far, though, has read neighbours: vload(a, i) fills the register from a[i] to a[i + lanes - 1]. A lot of quant data is reached through an index instead, a risk weight looked up by market regime, prices picked by a list of positions, a counter added to the bin a return falls in. That needs a gather to read and a scatter to write.
gather(mem, idx) returns [mem[idx[0]], mem[idx[1]], ...]: one number per lane from wherever the index says. scatter(mem, idx, reg) writes reg[k] to mem[idx[k]]. Both are one instruction, but each lane is its own memory access, so they cost far more than a vload of neighbours.
Think of fetching four library books. If they sit side by side on one shelf you take them in one reach, which is a vload. If they are on four different shelves, one trip puts four books in your arms but you still walk to four shelves. LaneSim records a gather as one instruction in counts, as the hardware does, and adds a second figure, cost(), that charges it one unit per lane. Use total() for "instructions issued" and cost() for the honest price.
The smallest example: a lookup
Give each return a regime number from 0 to 5 and keep a table of six risk weights. Finding the weight of every return is a lookup, out[i] = table[idx[i]]. The scalar loop spends four instructions per element: loop, an sload of the index, an sload of the table entry and an sstore. vector_lookup is written for you: it loads a register of indexes with an ordinary vload and hands it to a gather.
def vector_lookup(sim, table, idx): """out[i] = table[idx[i]] with a gather: per pass `loop`, a `vload` of the indexes, a `gather` from the table, a `vstore`.""" if len(idx) % sim.lanes: raise ValueError("length must be a multiple of the lane count") out = [0.0] * len(idx) for i in range(0, len(idx), sim.lanes): sim.loop() sim.vstore(out, i, sim.gather(table, sim.vload(idx, i)))1 return out
- 1An ordinary load fetches the indexes; the gather fetches what they point at.
# Eight regime numbers looked up in a table of six weights, scalar against 4 lanestable = [0.0, 0.5, 1.0, 1.5, 2.0, 2.5]idx = [5, 0, 3, 3, 1, 4, 2, 2]scalar = LaneSim(4)print(scalar_lookup(scalar, table, idx), scalar.total())sim = LaneSim(4)print(vector_lookup(sim, table, idx), sim.total(), sim.cost())1print(sim.counts)
[2.5, 0.0, 1.5, 1.5, 0.5, 2.0, 1.0, 1.0] 32
[2.5, 0.0, 1.5, 1.5, 0.5, 2.0, 1.0, 1.0] 8 14
{'loop': 2, 'vload': 2, 'gather': 2, 'vstore': 2}- 18 instructions issued, but the cost is 14: each gather is worth 4 units.
Read the last two lines. The vector run issues 8 instructions against 32 for the scalar loop, a promising 4x. But cost() says 14: the two gathers are charged 4 units each, so the honest speedup is 32 / 14, about 2.3. A gather is still better than four separate scalar loads, because one instruction does the bookkeeping, but it is nowhere near the 4x of vadd.
Build it up: scatter, collisions and the histogram
total() counts instructions issued, cost() charges a gather or scatter one unit per lane because each lane is a separate memory access.Now the mirror image, and the trap. Count how many returns fall in each of six regime bins: read the current counts of the bins in the register (gather), add one (vadd), write them back (scatter). It works as long as the four indexes of a register are all different. If two lanes name the same bin, both read the same old count, both add one, and both write the same new count: one increment is lost.
# Four returns, two of them in bin 1: a gather-add-scatter loses a countsim = LaneSim(4)counts = [0, 0, 0, 0, 0, 0]reg = [1, 1, 2, 3]print("conflict:", sim.vconflict(reg))sim.scatter(counts, reg, sim.vadd(sim.gather(counts, reg), sim.vsplat(1)))1print(counts, "-> bin 1 should hold 2")
conflict: True [0, 1, 1, 1, 0, 0] -> bin 1 should hold 2
- 1Both lanes wrote 1 into bin 1.
vconflict is the guard: it answers whether any two lanes of an index register hold the same index. On real CPUs the same job is done by a conflict-detection instruction in the newest AVX-512 chips, and without it you must find duplicates yourself. Here is the safe histogram, which you will write: when a register has no conflict, gather, add and scatter; when it has one, update the counts one index at a time with scalar instructions for that register only.
def vector_histogram(sim, idx, nbins): """Count how many times each bin number 0 .. nbins - 1 appears in `idx`, with gather and scatter where that is safe. Return the counts as a list of `nbins` ints. One `vsplat` of 1 first (none when `idx` is empty). Then per pass of `sim.lanes` indexes: `sim.loop()`, a `vload` of the indexes and a `vconflict` of that register. With no conflict: `gather` the counts of those bins, `vadd` the ones, `scatter` the result back. With a conflict a scatter would lose increments, so do that register one index at a time instead: for each lane an `sload` of the index, an `sload` of its count, a `sadd` of 1 and an `sstore`. Raise ValueError("nbins must be at least 1"), then ValueError("length must be a multiple of the lane count"), then ValueError("index out of range") if any index is not in range(nbins). Check in that order. """ if nbins < 1: raise ValueError("nbins must be at least 1") if len(idx) % sim.lanes: raise ValueError("length must be a multiple of the lane count") if any(j < 0 or j >= nbins for j in idx): raise ValueError("index out of range") counts = [0] * nbins if not idx: return counts ones = sim.vsplat(1) for i in range(0, len(idx), sim.lanes): sim.loop() reg = sim.vload(idx, i) if sim.vconflict(reg): for k in range(sim.lanes):1 j = sim.sload(idx, i + k) sim.sstore(counts, j, sim.sadd(sim.sload(counts, j), 1)) else: sim.scatter(counts, reg, sim.vadd(sim.gather(counts, reg), ones))2 return counts
- 1A collision: do this one register index by index.
- 2No collision: gather, add, scatter.
# Eight indexes into six bins: the first register is clean, the second has a collisionsim = LaneSim(4)print(vector_histogram(sim, [0, 1, 2, 3, 1, 1, 4, 5], 6))print(sim.counts)print(scalar_histogram(LaneSim(4), [0, 1, 2, 3, 1, 1, 4, 5], 6))
[1, 3, 1, 1, 1, 1]
{'vsplat': 1, 'loop': 2, 'vload': 2, 'vconflict': 2, 'gather': 1, 'vadd': 1, 'scatter': 1, 'sload': 8, 'sadd': 4, 'sstore': 4}
[1, 3, 1, 1, 1, 1]- AccessMemory accesses it makes
- vload(mem, i)
lanesneighbours.one wide access, cost 1 - gather(mem, idx)
lanespositions chosen by the index register.lanesaccesses, costlanes - scatter(mem, idx, reg)
laneswrites; later lanes win on a repeated index.costlanes, and collisions lose updates
Typical mistakes
Counting a gather as one cheap load. The total() of a lookup kernel looks wonderful, 5,400 instructions for 5,400 lookups on 4 lanes, and the honest figure is 9,450. Always compare cost(), not total(), when a gather or a scatter is in the loop, and be ready for it to lose against plain scalar code when the table does not fit in the cache.
# total() against cost() for the lookup of 5,400 regime numbers, on 4 and 8 lanesregimes = [(i * 7) % 6 for i in range(5400)]weights = [0.0, 0.5, 1.0, 1.5, 2.0, 2.5]for lanes in (4, 8): sim = LaneSim(lanes) vector_lookup(sim, weights, regimes) print(lanes, "lanes: issued", sim.total(), "cost", sim.cost(), "speedup", round(21600 / sim.cost(), 2))1
4 lanes: issued 5400 cost 9450 speedup 2.29 8 lanes: issued 2700 cost 7425 speedup 2.91
- 1The honest speedup is the last number, not 4 or 8.
A histogram with few bins. Six regimes means a register of four returns almost always names the same bin twice, and a register of eight must (eight indexes cannot all differ across six bins). On the SPY data only 127 of 1,350 four-lane registers are collision-free, so the vector path runs 9% of the time and the kernel is mostly the scalar fallback. The remedy is not a cleverer guard but a different layout: give each lane its own private table of counts, so lanes never collide, and add the tables together at the end.
# A gather past the end of the table. The simulator refuses; real hardware reads whatever is theresim = LaneSim(4)sim.gather(weights, [0, 1, 2, 6])
ValueError: gather index out of range
When the same few slots are hit again and again, keep one private copy of the table per lane and merge them at the end. The same idea, partial results per lane and one reduction last, made the dot product fast in the previous topic.
What the tasks ask
- Task and functionWhat it must do
- LaneSim.gather(mem, idx)A new register
[mem[idx[k]] ...]; count onegather.two error checks, in order - LaneSim.scatter(mem, idx, reg)Write
reg[k]tomem[idx[k]]in lane order; count onescatter.a refused scatter writes nothing - LaneSim.vconflict(idx)
Truewhen two lanes hold the same index; count onevconflict.any two lanes, not only neighbours - vector_histogram(sim, idx, nbins)Counts per bin, vector where safe and scalar for registers with a collision.exact instruction counts per register kind
gather is recorded in sim.counts. What does sim.cost() charge for it?Next. Every kernel in this skill was written for 4 lanes or for 8, with the lane count read from sim.lanes. The next topic turns that into a design rule. A portable kernel is written once against a lane count it does not know, and runs correctly on any width; the question it then asks is which width to use for an array of a given length, since the tail, the reduction and the alignment peel all depend on it.
Lab · what's graded
4 tasks · 100 pts- Load from arbitrary positions with
gather25 pts - Write to arbitrary positions with
scatter25 pts - Detect a collision with
vconflict25 pts - Count bins safely with
vector_histogram25 pts