σμ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 2 · Vectorizing a loop›Topic 2.1·~55 minAdvanced

Auto-vectorization: which loops a compiler can vectorize

Skill positionModule 2 of 4 · Topic 1 of 2
2.1 Auto-vectorization: which loops a compiler can vectorize
—Lab score— / 100Total XP—Streak—
Lecture0% read

6 min readCode examples: 4

  1. 01The idea in plain words
  2. 02The smallest example: a vector that is wrong
  3. 03Build it up: the distance and the verdict
  4. 04Typical mistakes
  5. 05What the tasks ask

A compiler turns a[i] = a[i] + b[i] into vector code at once, but not a[i + 1] = a[i] + b[i], though the two loops look almost the same. On 5,400 SPY returns the first costs 3,375 instructions on 8 lanes and the second 27,000. What does the compiler see that you do not?

01

The idea in plain words

Where we are. The last topic showed that NumPy is the vector idea behind a function call, with a fixed cost per call. Now you write the loop yourself in a compiled language such as C, C++, Rust or Fortran, and the compiler has to decide whether to turn it into vector code. That is auto-vectorization. The question it leaves is which loops the compiler may touch, and you will play compiler on LaneSim to find out.

DefinitionThe compiler's one rule

A vector version is allowed only if it gives exactly the same answer as the scalar loop. If the compiler cannot prove that from the code, it leaves the loop scalar.

The only thing that can break that promise in a[i + w] = a[i + r] + b[i] is a dependence between passes: a value written by one pass and read by another. A vector register runs lanes passes at once, so those passes cannot depend on each other. This is also why finance code is mixed: adding daily profit and loss to a running total (total[i + 1] = total[i] + pnl[i]) is a chain, while adding two return series element by element is not.

02

The smallest example: a vector that is wrong

scalar_loop runs a[i + w] = a[i + r] + b[i] one element per pass, on a copy of a, and defines what the answer must be. With writes at a[i + 1] and reads at a[i] it is a running total: every pass adds b[i] to what the pass before just wrote. Now force that same loop into registers of 4 lanes without thinking, and compare.

main.pyPython
# The running total, scalar: the answer every faster version must matcha = [1.0] * 9b = [1.0] * 8print(scalar_loop(LaneSim(4), a, b, 1, 0))# The same loop forced into 4-lane registers: both loads happen before the storesim = LaneSim(4)out = list(a)for i in range(0, 8, 4):    sim.vstore(out, i + 1, sim.vadd(sim.vload(out, i), sim.vload(b, i)))1print(out)
[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]
[1.0, 2.0, 2.0, 2.0, 2.0, 3.0, 2.0, 2.0, 2.0]
  1. 1Pass 1 loads a[1] before pass 0 has stored it.

The scalar run counts up 1, 2, 3 ... 9, a running total. The forced vector run gives [1, 2, 2, 2, 2, 3, 2, 2, 2]: wrong, and silently wrong, since nothing raised an error. In the scalar loop, pass 1 reads a[1] after pass 0 wrote it. In the vector version all four loads happen before the store, so lanes 1 to 3 read the old values. That is exactly the kind of difference a compiler must rule out before it may vectorize.

03

Build it up: the distance and the verdict

Count how many passes later a value is read after it was written. A pass writes a[i + w]. A later pass reads that same element when its own i + r equals it, which happens w - r passes later. That number is the dependence distance, and a single subtraction is the whole analysis for this loop shape.

distance d = w - r(1)w is where each pass writes (a[i + w]) and r where it reads (a[i + r]). The vector version is safe when d ≤ 0 or d ≥ lanes.
  1. 1
    Find the pairWhich array does the loop write, and which element of the same array does it read? Different arrays do not conflict here.
  2. 2
    SubtractDistance d = w - r: how many passes later the written value is read.
  3. 3
    Compare with the lanesIf d ≤ 0 nothing is read after being written. If d ≥ lanes, the value is written in an earlier register. Otherwise it is read inside the same register: stop.
  4. 4
    Pick the pathSafe: emit the vector loop. Unsafe: keep the scalar loop. This is what run_loop does.

Look at the four loops below and the verdicts the functions you will write give. Notice that distance 0 and a negative distance are fine for any width, distance 1 is never fine, and distance 4 splits the two machines: safe on 4 lanes, unsafe on 8.

main.pyPython
# Verdicts for four loops of the shape a[i + w] = a[i + r] + b[i]loops = [("a[i] = a[i] + b[i]", 0, 0), ("a[i + 1] = a[i] + b[i]", 1, 0), ("a[i + 4] = a[i] + b[i]", 4, 0), ("a[i] = a[i + 3] + b[i]", 0, 3)]for text, w, r in loops:    print(f"{text:24} d={dependence_distance(w, r):2}  widest={max_vector_width(w, r):2}  4 lanes={can_vectorize(w, r, 4)!s:5}  8 lanes={can_vectorize(w, r, 8)}")1
a[i] = a[i] + b[i]       d= 0  widest=16  4 lanes=True   8 lanes=True
a[i + 1] = a[i] + b[i]   d= 1  widest= 1  4 lanes=False  8 lanes=False
a[i + 4] = a[i] + b[i]   d= 4  widest= 4  4 lanes=True   8 lanes=False
a[i] = a[i + 3] + b[i]   d=-3  widest=16  4 lanes=True   8 lanes=True
  1. 1Reading ahead (d = -3) is safe: the old values are the ones the scalar loop reads too.

Now run_loop, the compiler's decision as code: ask can_vectorize, then emit the vector loop or the scalar one. Run it on all four loops over the 5,400 returns from the lead on both machine widths and read the instruction totals.

main.pyPython
# Instruction totals over 5,400 elements, on both machine widthsn = 5400for text, w, r in loops:    totals = []    for lanes in (4, 8):        sim = LaneSim(lanes)        run_loop(sim, [1.0] * (n + max(w, r)), [1.0] * n, w, r)        totals.append(sim.total())    print(f"{text:24} 4 lanes={totals[0]:6}  8 lanes={totals[1]:6}")
a[i] = a[i] + b[i]       4 lanes=  6750  8 lanes=  3375
a[i + 1] = a[i] + b[i]   4 lanes= 27000  8 lanes= 27000
a[i + 4] = a[i] + b[i]   4 lanes=  6750  8 lanes= 27000
a[i] = a[i + 3] + b[i]   4 lanes=  6750  8 lanes=  3375
What the real data says5,400 SPY returns, run_loop on 8 lanes
In place, d = 0 (instr.)3,3758x fewer
Running total, d = 1 (instr.)27,000no gain
Lag 4, d = 4 (instr.)27,000safe on 4 lanes only
Instructions on 8 lanes
d = 0 (in place)3375
d = -3 (reads ahead)3375
d = 4 (lag 4)27000
d = 1 (running total)27000
  • What the compiler checksVerdict if it fails
  • a[i + 1] = a[i] + b[i]Is a value read within the same register it was written in?stays scalar
  • p[i] = q[i] + r[i]Could the pointers p and q point at overlapping memory?runtime overlap check, or stays scalar
  • if (x[i] < 0) break;Can the loop stop early, before the register is full?stays scalar
  • a[i] = f(b[i])Does it call a function the compiler cannot see into?fine if it is inlined or has a vector version
Ask the compiler why

Compilers can report each loop they did or did not vectorize, and often the reason. In GCC the flag is -fopt-info-vec-missed, in Clang -Rpass-missed=loop-vectorize; the exact wording depends on the version.

04

Typical mistakes

Believing a loop is parallel because it looks simple. Smoothing recurrences are the classic case in quant code. An exponential moving average, ema[i + 1] = alpha * x[i] + (1 - alpha) * ema[i], reads what the previous pass wrote, so its distance is 1 and it stays scalar whatever the compiler. The cure is to change the algorithm, not the flags, and later topics show how to restructure such loops.

Code that vectorizes on your laptop and not on the server. A lag-4 loop (d = 4) is safe on 4 lanes and unsafe on 8. The same source vectorizes on one machine and silently stays scalar on a wider one, so a speedup measured on one chip does not carry over. The output below is the lag-4 row of the data panel, on both widths.

main.pyPython
# The lag-4 loop on both widths: the answer is the same, the cost is nota4, b4 = [1.0] * 20, [1.0] * 16for lanes in (4, 8):    sim = LaneSim(lanes)    result = run_loop(sim, a4, b4, 4, 0)    print(lanes, "lanes:", sim.total(), "instructions, vectorized:", can_vectorize(4, 0, lanes))1print(result == scalar_loop(LaneSim(8), a4, b4, 4, 0))
4 lanes: 20 instructions, vectorized: True
8 lanes: 80 instructions, vectorized: False
True
  1. 1Same answer; 8 lanes fall back to the scalar loop.

Expecting a warning. The compiler says nothing when it keeps a loop scalar. A slow loop with no message is the normal outcome, which is why the report flags above matter. In the simulator the quiet cost shows up as the larger count; in a real build you only see it if you ask.

A promise you cannot check

Hints such as restrict or #pragma omp simd tell the compiler to trust you that passes are independent. If you are wrong, it vectorizes anyway and the answer silently changes, as in the forced run above.

05

What the tasks ask

  • Task and functionWhat it must return
  • dependence_distance(w, r)w - r: how many passes later a written value is read.one subtraction
  • max_vector_width(w, r, cap=16)The widest power-of-two vector that keeps the answer, from the distance.calls dependence_distance
  • can_vectorize(w, r, lanes)True when lanes lanes are safe, checked against a real run of the loop.calls max_vector_width
  • run_loop(sim, a, b, w, r)The scalar loop's answer, computed on the vector path when safe and on the scalar path otherwise.exact counts are tested

Key takeaways

  • One rule: same answer A compiler vectorizes only when it can prove the vector loop gives the scalar loop's exact answer.
  • Distance decides w - r at most 0 or at least the lane count is safe; anything in between, such as a running total at 1, is not.
  • Silence is not safety A refused loop stays scalar without a word, and a lag-4 loop can vectorize on one chip and not another, so ask for the report.
Quick check
Which of these loops can a compiler vectorize on 8 lanes?
Pick an answer.

Next. When the compiler refuses a loop, or vectorizes it badly, you can write the vector code yourself. The next topic does that with intrinsics: each LaneSim instruction becomes a function you call by name, you meet a fused multiply-add that does two operations in one instruction, and you will see how a name like _mm256_add_pd is built from the register width and the type of the numbers.

Lab · what's graded

4 tasks · 100 pts
  • Measure the gap with dependence_distance25 pts
  • Find the widest safe vector with max_vector_width25 pts
  • Give the verdict with can_vectorize25 pts
  • Choose the path in run_loop25 pts
Explorer · lab-3-1
▾ lab-3-1
…
bash · in-browser
learner@quantcraft:~/lab-3-1$
Python not loaded yetPythonLn 1, Col 1Spaces: 4UTF-8

Reset this topic?

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