σμ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.3·~50 minAdvanced

Horizontal operations and reductions

Skill positionModule 3 of 4 · Topic 3 of 4
3.3 Horizontal operations and reductions
—Lab score— / 100Total XP—Streak—
Lecture0% read

6 min readCode examples: 7

  1. 01The idea in plain words
  2. 02The smallest example: halving four lanes
  3. 03Build it up: partial sums, dot product and maximum
  4. 04Typical mistakes
  5. 05What the tasks ask

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?

01

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.

DefinitionPartial sums, one reduction

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.

02

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.

main.pyPython
# 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}
  1. 1Lane 0 meets lane 2, lane 1 meets lane 3.
  2. 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.

03

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.

main.pyPython
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
  1. 1Ordinary lane-by-lane work: no shuffles in the loop.
  2. 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.

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

main.pyPython
# 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. 1(1e16 + -1e16) + (1 + 1): nothing is lost this way round.
partial[k] = Σ x[k + j · lanes], total = partial[0] + partial[1] + ... + partial[lanes - 1] (in halving order)(1)Each lane k sums its own stripe of the array; then the lanes are added in the order of the halving steps. A different order gives a total that differs in the last digits.

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.

main.pyPython
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)
  1. 1The first register seeds the running maxima.
What the real data saysSPY daily returns, 2005-02-25 to 2026-08-21
Sum of squared returns0.7729over 5,404 returns: the dot product of the series with itself
Realised volatility18.98%sqrt(sum / 5,404 * 252), a year of 252 days
Best day+14.52%2008-10-13, the maximum a vector_max finds
Worst day-10.95%2020-03-16, a negative number: why not to start a maximum at 0
Dot product, 5,400 elements, 8 lanes (instr.)2,7089.97x fewer than scalar
Instructions for the dot product of 5,400 elements
Scalar27000
4 lanes5406
8 lanes2708
  • 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
04

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.

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

main.pyPython
# 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
A sum is not one exact number

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.

05

What the tasks ask

  • Task and functionWhat it must do
  • LaneSim.vshuffle(reg, order)A new register whose lane k is reg[order[k]]; count one vshuffle.three error checks, in order
  • LaneSim.hsum(reg)Add all lanes by halving, ending with one vextract.uses vshuffle, vadd, vextract
  • vector_dot(sim, a, b)Partial sums with vfma, one hsum at the end.the order of the additions is tested
  • vector_max(sim, a)Running maxima with vcmp_gt and vblend, one hmax at the end.works for negative numbers

Key takeaways

  • Reduce once, at the end Keep partial results per lane through the loop and add across lanes a single time afterwards; the cost is log2(lanes) steps, whatever the array length.
  • Order changes the last digits Floating-point addition is not associative, so a vector sum differs from a left-to-right sum; compare with a tolerance and fix the order if you need identical results.
  • Seed from the data Start a maximum from the first register, not from zero, or a set of negative numbers gives the wrong answer.
Quick check
A dot product of 800 elements runs on 8 lanes. Roughly how many instructions does the final hsum add to the whole run, compared with the loop?
Pick an answer.

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

Reset this topic?

Everything in lab-7-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