σμ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 4 · Portable code and dispatch›Topic 4.3·~1 hr 30 minAdvanced

Capstone: a SIMD moving average and dot product with a speedup report

Skill positionModule 4 of 4 · Topic 3 of 3
4.3 Capstone: a SIMD moving average and dot product with a speedup report
—Lab score— / 100Total XP—Streak—
Lecture0% read

7 min readCode examples: 7

  1. 01The idea in plain words
  2. 02The smallest example: from a file to returns
  3. 03Build it up: the kernels and the report
  4. 04Typical mistakes
  5. 05What the tasks ask

On the 5,404 real SPY returns a 20-day rolling mean costs 226,170 instructions the simple way, 37,730 with a running sum, and 56,575 on 4 lanes. The vector kernel is 4 times faster than the loop it was copied from and 0.67 times as fast as the best algorithm. What does an honest speedup report say, and when do 8 or 16 lanes finally win?

01

The idea in plain words

Where we are. This is the end of the chain. The first topic built the machine and added two arrays; since then you have learned how a compiler decides, how to write the instructions yourself, how to finish the tail, how to replace an if, how to reduce across lanes, how to reach scattered data, how to write one kernel for any width and how to pick a version by CPU. Here all of it works on the running example from the start of the skill: a rolling mean and a dot product over the daily returns of SPY.

DefinitionAn honest speedup

The ratio of the instructions of the best scalar algorithm you know to the instructions of the vector kernel, counted exactly, on the real data, at every width you claim. A speedup against a baseline you made slow on purpose is not a speedup.

A return here is the simple daily return, the day's close divided by the day before, minus one. A rolling mean of window w is the average of the last w returns at each day, a smoothing every desk uses. The autocorrelation at lag 1 measures whether today's return tends to repeat or reverse yesterday's, and it is a dot product of the series with a copy of itself shifted by one day, divided by the dot product of the series with itself. Two small statistics, two kernels from this skill.

r[i] = close[i] / close[i - 1] - 1, mean[j] = (r[j] + ... + r[j + w - 1]) / w, ρ₁ = Σ r[i] · r[i - 1] / Σ r[i]²(1)The three quantities of the capstone: the return series, its rolling mean of window w, and its (uncentered) lag-1 autocorrelation.
02

The smallest example: from a file to returns

The data is a plain CSV with one row per trading day, date,open,high,low,close,volume, from 2005-02-25 to 2026-08-21: 5,405 rows, hence 5,404 returns. load_returns is the first task, and it is ordinary Python with the csv module. Keep it independent of the position of the close column, so that it survives a file with the columns in another order.

main.pyPython
def load_returns(path="data/SPY.csv"):    """Read a CSV file with a header row and return the daily simple returns of its `close` column as a list of floats.    The other columns may be anything and in any order. A return is close[i] / close[i - 1] - 1, so there is one fewer return than    rows. Use the `csv` module. Raise ValueError("no close column") if the header has no `close`, then    ValueError("need at least two prices") if there are fewer than two rows below the header. Check in that order.    """    with open(path, newline="") as file:        reader = csv.DictReader(file)        if "close" not in (reader.fieldnames or []):            raise ValueError("no close column")1        closes = [float(row["close"]) for row in reader]    if len(closes) < 2:        raise ValueError("need at least two prices")    return [closes[i] / closes[i - 1] - 1 for i in range(1, len(closes))]
  1. 1Find the column by name, not by position.
main.pyPython
# 5,405 closes become 5,404 returnsreturns = load_returns()print(len(returns), [round(x, 5) for x in returns[:3]])print(round(min(returns), 4), round(max(returns), 4))
5404 [-0.00683, 0.0052, -0.00049]
-0.1095 0.1452

The worst day, -10.95%, and the best, +14.52%, are in there: 2020-03-16 and 2008-10-13. Now the first vector kernel on a toy series. Eleven numbers and a window of 3 give nine means, which on 4 lanes is two full blocks and one block with a single live lane. The counts show the pieces: shifted vloads inside the blocks, vmaskload and vmaskstore for the last one, and no scalar instruction at all.

main.pyPython
# Nine rolling means of 3 on 4 lanes: two full blocks and a masked onetoy = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0]sim = LaneSim(4)print(rolling_mean_vector(sim, toy, 3))print(sim.total(), sim.counts)
[2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]
25 {'vsplat': 1, 'loop': 3, 'vload': 6, 'vadd': 6, 'vmul': 3, 'vstore': 2, 'vmaskload': 3, 'vmaskstore': 1}
03

Build it up: the kernels and the report

The rolling mean is vectorized across the outputs, not across the window. A block of lanes neighbouring outputs needs the same w shifted views of the data: load x[j..j+lanes-1], add x[j+1..j+lanes], then x[j+2..] and so on, and scale once at the end. Every one of those loads starts one element later than the last, so none after the first is aligned; the cost of that is paid in cache lines, which LaneSim does not count but a real chip does. The last, short block uses a mask so it never reads past the data.

main.pyPython
def rolling_mean_vector(sim, x, window):    """The rolling mean with `lanes` outputs per pass: out[j] = (x[j] + ... + x[j + window - 1]) * (1.0 / window), summed left to right.    One `vsplat` of 1.0 / window first. An output block starting at j is: `sim.loop()`, `acc = vload(x, j)`, then for k = 1 .. window - 1    `acc = vadd(acc, vload(x, j + k))`, then `vmul(acc, factor)` and a `vstore` into the output. The loads are shifted by one    element each time, so most are not aligned. If the number of outputs is not a multiple of `sim.lanes`, the last block has only    `live` real outputs: do it with `sim.tail_mask(live)`, using `vmaskload` for every load and a `vmaskstore` at the end, never a    scalar loop. A window of 1 needs no `vadd`.    If window < 1 raise ValueError("window must be at least 1"); if window > len(x) raise ValueError("window is longer than the data").    Check in that order.    """    if window < 1:        raise ValueError("window must be at least 1")    if window > len(x):        raise ValueError("window is longer than the data")    outputs = len(x) - window + 1    factor = sim.vsplat(1.0 / window)    out = [0.0] * outputs    full = outputs - outputs % sim.lanes1    for j in range(0, full, sim.lanes):        sim.loop()        acc = sim.vload(x, j)        for k in range(1, window):            acc = sim.vadd(acc, sim.vload(x, j + k))        sim.vstore(out, j, sim.vmul(acc, factor))    if full < outputs:2        mask = sim.tail_mask(outputs - full)        sim.loop()        acc = sim.vmaskload(x, full, mask)        for k in range(1, window):            acc = sim.vadd(acc, sim.vmaskload(x, full + k, mask))        sim.vmaskstore(out, full, sim.vmul(acc, factor), mask)    return out
  1. 1Shifted loads: one element later each time.
  2. 2The last block: masks, no scalar tail.

Now the question the report exists to answer. The simple scalar loop adds w numbers for every output, so it costs 2w + 2 instructions per output. A running sum adds the number that enters the window and subtracts the one that leaves, so it costs 7 per output whatever w is. The vector kernel does 2w + 2 per block of lanes outputs, so its cost per output is (2w + 2) / lanes. It beats the running sum only when (2w + 2) / lanes < 7.

vector beats running sum ⇔ (2w + 2) / lanes < 7 ⇔ w < (7 · lanes - 2) / 2(2)For 4 lanes the window must be under 13; for 8 lanes under 27; for 16 lanes under 55. Past that, the O(n) algorithm wins however wide the machine.

speedup_report runs all five kernels (the simple loop, the running sum, the vector mean, the scalar dot and the portable dot) and puts the counts in one row per width. Read the column mean_speedup: it divides the cheaper of the two scalar algorithms by the vector one. Try five windows on the real series and watch the winner change.

main.pyPython
# Speedup against the BEST scalar algorithm, by window and width, on the 5,404 real returnsprint("window   4 lanes   8 lanes  16 lanes   (simple loop / vector, for comparison)")for window in (2, 5, 10, 20, 60):    rows = speedup_report(returns, window, [4, 8, 16])    honest = "  ".join(f"{row['mean_speedup']:8.2f}" for row in rows)    naive = "  ".join(f"{row['mean_scalar'] / row['mean_vector']:5.2f}" for row in rows)    print(f"{window:5}  {honest}     ({naive})")1
window   4 lanes   8 lanes  16 lanes   (simple loop / vector, for comparison)
    2      4.00      7.99     15.98     ( 4.00   7.99  15.98)
    5      2.33      4.67      9.32     ( 4.00   8.00  15.97)
   10      1.27      2.54      5.08     ( 4.00   7.99  15.96)
   20      0.67      1.33      2.67     ( 4.00   7.99  15.98)
   60      0.23      0.46      0.92     ( 4.00   7.99  15.95)
  1. 1Against the simple loop every width looks like a win. Against the best scalar, a window of 60 loses even at 16 lanes.

The dot product half of the job needs no such care, because there is no cleverer scalar algorithm for a dot product: every element must be multiplied and added. It speeds up almost exactly with the lane count. autocorrelation calls portable_dot twice, once for the lag product and once for the energy of the series, and divides.

main.pyPython
# Autocorrelation of the real returns at several lags, and what it costs on 8 lanesfor lag in (1, 2, 3, 5, 10):    sim = LaneSim(8)    print(lag, round(autocorrelation(sim, returns, lag), 4), sim.total(), "instructions")1print("scalar for the same two dot products:", 5 * (len(returns) - 1) + 5 * len(returns))
1 -0.1021 6801 instructions
2 -0.0121 6796 instructions
3 0.007 6791 instructions
5 -0.0121 6816 instructions
10 0.0007 6791 instructions
scalar for the same two dot products: 54035
  1. 1About -0.10 at lag 1: a day up tends to be followed by a down day, weakly.
What the real data saysSPY daily returns, 2005-02-25 to 2026-08-21, window 20
Simple scalar loop (instr.)226,17042 per output
Running sum (best scalar) (instr.)37,7307 per output: the number to beat
Vector, 4 lanes (instr.)56,5754.0x the simple loop, 0.67x the best
Vector, 8 lanes (instr.)28,3091.33x the best scalar
Vector, 16 lanes (instr.)14,1552.67x the best scalar
Lag-1 autocorrelation-0.102dot product: 7.94x on 8 lanes
Instructions for the 20-day rolling mean
Simple loop226170
4 lanes56575
Running sum37730
8 lanes28309
16 lanes14155
  • KernelInstructions per output (per element)
  • rolling_mean_scalarSums the whole window for every output.2w + 2
  • rolling_mean_runningAdds the entering number, subtracts the leaving one.7
  • rolling_mean_vectorSums the window for lanes outputs per block.(2w + 2) / lanes
  • portable_dotNo cleverer scalar algorithm exists.5 / lanes
04

Typical mistakes

Reporting a speedup against the slow baseline. Quote only the first number of a row and the 20-day window looks like a triumph: 4.0x on 4 lanes, 8.0x on 8. The full row says the best scalar algorithm is faster than 4 lanes. Reviewers who read the code find the cheaper baseline in minutes, and the damage is to every other number in the report. Use the honest column, as mean_speedup does.

Trusting one window. The break-even window grows with the lane count (13, 27 and 55 for 4, 8 and 16 lanes), so one choice of w cannot describe the kernel. The table above is the report you want: several windows, every width, and a visible point where the line crosses 1. A desk that uses windows of 5 and 10 and a desk that uses 60 need different answers from the same code.

main.pyPython
# The last digits depend on the width: the same lag-1 autocorrelation on four machinesfor lanes in (2, 4, 8, 16):    print(lanes, repr(autocorrelation(LaneSim(lanes), returns, 1)))
2 -0.10207994414042755
4 -0.10207994414042723
8 -0.10207994414042747
16 -0.10207994414042743

Comparing vector and scalar results with ==. The four lines above agree to about 15 digits and differ in the last one, because each width adds the same numbers in a different order. The rolling mean is the exception: rolling_mean_vector sums each window left to right, exactly as rolling_mean_scalar does, so those two agree to the last digit. Know which of your kernels reorder the additions before choosing how to test them.

Counts are not time

This report counts instructions. On a real chip the shifted loads of the rolling mean straddle cache lines, wide instructions can run slower, and memory may be the limit. A count tells you which kernel can win and where the crossover sits; a stopwatch on the target machine, with the real data, decides.

05

What the tasks ask

  • Task and functionWhat it must do
  • load_returns(path)The simple returns of the close column of a CSV file, by column name.two error checks, in order
  • rolling_mean_vector(sim, x, window)lanes outputs per block, summed left to right, with a masked last block.no scalar instruction at all
  • autocorrelation(sim, r, lag)dot(r[lag:], r[:-lag]) / dot(r, r) with portable_dot for both.three error checks, in order
  • speedup_report(returns, window, widths)One row per width with the counts of all five kernels and the honest speedups.runs every kernel; scalar ones once

Key takeaways

  • Count against the best baseline A speedup means the best scalar algorithm over the vector kernel, exact counts, real data, every width you claim; against a deliberately slow loop it proves nothing.
  • Algorithms beat lanes A running sum costs 7 per output whatever the window, so a window past (7 · lanes - 2) / 2 loses to it at any width; sometimes the right fix is a better scalar algorithm.
  • Everything in the skill, once The capstone used the machine, shifted loads, masks for the tail, partial sums with one reduction, a portable type and a report that counts exactly.
Quick check
On 4 lanes, a window of 20 costs (2 · 20 + 2) / 4 = 10.5 instructions per output with the vector kernel. The running sum costs 7. Roughly what does mean_speedup say?
Pick an answer.

Where to go from here. You have built, counted and argued for a vector machine from nothing. On real hardware the same ideas appear as C++ intrinsics and auto-vectorization reports, std::simd and Highway, and the numbers will differ: memory, cache lines and wide-instruction costs all enter. When the C++ skill is live, its topics on intrinsics and auto-vectorization will pick up exactly where topics 3 and 4 left off, and the cache-locality skill covers the memory side that this simulator deliberately left out.

Lab · what's graded

4 tasks · 100 pts
  • Read the prices with load_returns25 pts
  • Vectorize the moving average with rolling_mean_vector25 pts
  • Measure the lag with autocorrelation25 pts
  • Report the honest speedup with speedup_report25 pts
Explorer · lab-11-1
▾ lab-11-1
▾ data
…
bash · in-browser
learner@quantcraft:~/lab-11-1$
Python not loaded yetPythonLn 1, Col 1Spaces: 4UTF-8

Reset this topic?

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