σμimplied vol · KKmax(S−K,0)udβρᵢⱼfat tailsPnL · drawdownyield · TdSₜ = μSₜ dt + σSₜ dWₜC = S·N(d₁) − K·e⁻ʳᵀ·N(d₂)σₚ² = wᵀΣwd₁ = [ln(S/K) + (r + σ²⁄2)T] ⁄ σ√T∂V/∂t + ½σ²S²·∂²V/∂S² + rS·∂V/∂S − rV = 0Sharpe = (Rₚ − R_f) ⁄ σₚVaR₉₉ = μ − 2.33σρ = Cov(X,Y) ⁄ σₓσᵧE[Rₚ] = Σ wᵢ·E[Rᵢ]φ(x) = e^(−x²/2) ⁄ √2πE[Rᵢ] = R_f + βᵢ(E[Rₘ] − R_f)dXₜ = θ(μ − Xₜ)dt + σ dWₜσ²ₜ = ω + α·ε²ₜ₋₁ + β·σ²ₜ₋₁C − P = S − K·e⁻ʳᵀΔ = ∂V/∂S Γ = ∂²V/∂S²p = (e^(rΔt) − d) ⁄ (u − d)rₜ = ln(Pₜ ⁄ Pₜ₋₁)E[Xₜ₊₁ | ℱₜ] = Xₜf* = (bp − q) ⁄ bz = (x − μ) ⁄ σP(N=k) = λᵏe^(−λ) ⁄ k!Θ = −∂V/∂Tν = S·φ(d₁)·√Tmin wᵀΣw s.t. wᵀμ = μ*∫Σ∂∞λ
uantCraft AcademyRoadmapsSkills
Ctrl K
AO
+1.2k Learners
LoginJoin ↗
RoadmapsSkills
AO
+1.2k Learners
Login
  • English
  • Français
  • Español
  • العربية
  • Português
  • Deutsch
  • 日本語
  • 中文
σμimplied vol · KKmax(S−K,0)udβρᵢⱼfat tailsPnL · drawdownyield · TdSₜ = μSₜ dt + σSₜ dWₜC = S·N(d₁) − K·e⁻ʳᵀ·N(d₂)σₚ² = wᵀΣwd₁ = [ln(S/K) + (r + σ²⁄2)T] ⁄ σ√T∂V/∂t + ½σ²S²·∂²V/∂S² + rS·∂V/∂S − rV = 0Sharpe = (Rₚ − R_f) ⁄ σₚVaR₉₉ = μ − 2.33σρ = Cov(X,Y) ⁄ σₓσᵧE[Rₚ] = Σ wᵢ·E[Rᵢ]φ(x) = e^(−x²/2) ⁄ √2πE[Rᵢ] = R_f + βᵢ(E[Rₘ] − R_f)dXₜ = θ(μ − Xₜ)dt + σ dWₜσ²ₜ = ω + α·ε²ₜ₋₁ + β·σ²ₜ₋₁C − P = S − K·e⁻ʳᵀΔ = ∂V/∂S Γ = ∂²V/∂S²p = (e^(rΔt) − d) ⁄ (u − d)rₜ = ln(Pₜ ⁄ Pₜ₋₁)E[Xₜ₊₁ | ℱₜ] = Xₜf* = (bp − q) ⁄ bz = (x − μ) ⁄ σP(N=k) = λᵏe^(−λ) ⁄ k!Θ = −∂V/∂Tν = S·φ(d₁)·√Tmin wᵀΣw s.t. wᵀμ = μ*∫Σ∂∞λ
uantCraft AcademyRoadmapsSkills
Ctrl K
AO
+1.2k Learners
LoginJoin ↗
RoadmapsSkills
AO
+1.2k Learners
Login
  • English
  • Français
  • Español
  • العربية
  • Português
  • Deutsch
  • 日本語
  • 中文
SIMD skill›Module 3 · Tails, masks and reductions›Topic 3.4·~45 minAdvanced

Gather and scatter

Skill positionModule 3 of 4 · Topic 4 of 4
3.4 Gather and scatter
—Lab score— / 100Total XP—Streak—
Lecture0% read

6 min readCode examples: 7

  1. 01The idea in plain words
  2. 02The smallest example: a lookup
  3. 03Build it up: scatter, collisions and the histogram
  4. 04Typical mistakes
  5. 05What the tasks ask

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?

01

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.

DefinitionGather and scatter

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.

02

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.

main.pyPython
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
  1. 1An ordinary load fetches the indexes; the gather fetches what they point at.
main.pyPython
# 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}
  1. 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.

03

Build it up: scatter, collisions and the histogram

cost = Σ count(op) × weight(op), weight(gather) = weight(scatter) = lanes, weight(any other op) = 1(1)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.

main.pyPython
# 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
  1. 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.

main.pyPython
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
  1. 1A collision: do this one register index by index.
  2. 2No collision: gather, add, scatter.
main.pyPython
# 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]
What the real data says5,400 SPY returns sorted into 6 regimes by size
Regime lookup, scalar (instr.)21,6004 per element
Gather, 4 lanes: issued (instr.)5,400looks like 4.0x
Gather, 4 lanes: cost() (cost)9,4502.29x
Gather, 8 lanes: cost() (cost)7,4252.91x
Collision-free registers, 4 lanes127of 1,350 (9.4%)
Collision-free registers, 8 lanes0of 675: 8 lanes cannot fit in 6 bins
Cost of the regime lookup on 5,400 returns
Scalar21600
4 lanes, cost()9450
8 lanes, cost()7425
  • AccessMemory accesses it makes
  • vload(mem, i)lanes neighbours.one wide access, cost 1
  • gather(mem, idx)lanes positions chosen by the index register.lanes accesses, cost lanes
  • scatter(mem, idx, reg)lanes writes; later lanes win on a repeated index.cost lanes, and collisions lose updates
04

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.

main.pyPython
# 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
  1. 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.

main.pyPython
# 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
Fix the layout, not the guard

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.

05

What the tasks ask

  • Task and functionWhat it must do
  • LaneSim.gather(mem, idx)A new register [mem[idx[k]] ...]; count one gather.two error checks, in order
  • LaneSim.scatter(mem, idx, reg)Write reg[k] to mem[idx[k]] in lane order; count one scatter.a refused scatter writes nothing
  • LaneSim.vconflict(idx)True when two lanes hold the same index; count one vconflict.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

Key takeaways

  • Gather and scatter reach any position One instruction reads or writes one number per lane at positions an index register names, which makes table lookups and histograms vectorizable at all.
  • They cost per lane A gather or scatter makes a memory access per lane, so compare cost() rather than the number of instructions issued; expect gains of 2 to 3x, not the lane count.
  • Collisions lose updates If two lanes name the same slot, a scatter keeps only one write; check with vconflict and fall back to scalar, or give each lane a private table.
Quick check
On 8 lanes, one gather is recorded in sim.counts. What does sim.cost() charge for it?
Pick an answer.

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
Explorer · lab-8-1
▾ lab-8-1
…
bash · in-browser
learner@quantcraft:~/lab-8-1$
Python not loaded yetPythonLn 1, Col 1Spaces: 4UTF-8

Reset this topic?

Everything in lab-8-1 goes back to the starter files and the terminal is cleared. Your current solution will be lost — this can't be undone.

Will be reset
  • main.py → starter code
  • Terminal history and test output
  • Unsubmitted changes
Will be kept
  • Best lab score
  • Your XP and streak
  • Lecture progress and notes