σμ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 1 · Lanes and registers›Topic 1.2·~50 minIntermediate

NumPy as SIMD: why vectorization wins

Skill positionModule 1 of 4 · Topic 2 of 2
1.2 NumPy as SIMD: why vectorization wins
—Lab score— / 100Total XP—Streak—
Lecture0% read

5 min readCode examples: 5

  1. 01The idea in plain words
  2. 02The smallest example: scale an array by 2
  3. 03Build it up: a fixed cost and a long array
  4. 04Typical mistakes
  5. 05What the tasks ask

You have written r * 2.0 on a NumPy array a thousand times. On 5,400 SPY returns the machine loop behind it runs 3.96 times fewer instructions than a one-number-at-a-time loop on 4 lanes, but on 16 numbers it is barely a win. Why does the same idea win big on long arrays and not at all on short ones?

01

The idea in plain words

Where we are. The last topic built LaneSim, a machine with 4 or 8 lanes that counts instructions, and a vector_add that beats the scalar loop by exactly the lane count. The question it left open: you already use a tool that does this, NumPy, so is it the same thing? It is, and this topic uses the machine to show why, and also why the win is not the same for every array.

A Python for loop pays twice for every element. First, the interpreter runs many small steps just to fetch the element, check that it is a number and make a new result object. Second, the machine finally performs one scalar multiply. A NumPy call such as r * 2.0 removes the first cost: one call into compiled code, which then runs a tight loop over a block of numbers laid out one after the other.

DefinitionVectorized code (NumPy sense)

Writing an operation on a whole array at once, so that a compiled loop does the repetition. That loop is also where SIMD instructions come in, because it can work on one register of numbers at a time.

Be clear about what LaneSim models here. It counts the machine instructions of the compiled loop, so it shows the second effect, the lane count. It does not model the interpreter's extra work per element, which is a separate and often larger cost that you would see only by timing. In this skill we stay with the part we can count exactly.

02

The smallest example: scale an array by 2

Start with the NumPy line and its Python-loop twin. They give the same numbers; what differs is who does the repeating. The dtype and itemsize lines tell us how wide each number is, which fixes how many fit in a 256-bit register.

main.pyPython
# The same scaling in NumPy and in a plain Python loopimport numpy as npr = np.array([0.012, -0.004, 0.007, -0.011, 0.003, 0.009, -0.006, 0.002])print((r * 2.0).tolist())1print([x * 2.0 for x in r.tolist()])print(r.dtype, r.itemsize, "bytes ->", 32 // r.itemsize, "numbers in a 256-bit register")2
[0.024, -0.008, 0.014, -0.022, 0.006, 0.018, -0.012, 0.004]
[0.024, -0.008, 0.014, -0.022, 0.006, 0.018, -0.012, 0.004]
float64 8 bytes -> 4 numbers in a 256-bit register
  1. 1One call, a compiled loop inside.
  2. 2A 64-bit float is 8 bytes: 4 fit in 256 bits.

Now the machine's version of the same job. scalar_scale is the plain loop: four instructions per element (loop, sload, smul, sstore). vector_scale is the task you will write: first a vsplat that copies the factor 2.0 into every lane of a register, then a loop of vload, vmul, vstore. The splat is needed because vmul multiplies two registers lane by lane, so the constant must sit in a register too.

main.pyPython
def vector_scale(sim, a, k):    """Return every element of `a` multiplied by `k` as a new list, using only vector instructions.    Spread `k` over all lanes once with `vsplat`, before the loop. Each pass then runs one `sim.loop()`, one `vload`, one `vmul`    and one `vstore`. For 8 elements on 4 lanes: {"vsplat": 1, "loop": 2, "vload": 2, "vmul": 2, "vstore": 2}, 9 instructions where    `scalar_scale` needs 32. An empty array returns [] and counts nothing. If the length is not a multiple of `sim.lanes` raise    ValueError("length must be a multiple of the lane count").    """    if len(a) % sim.lanes:        raise ValueError("length must be a multiple of the lane count")    if not a:        return []    factor = sim.vsplat(k)1    out = [0.0] * len(a)    for i in range(0, len(a), sim.lanes):        sim.loop()        sim.vstore(out, i, sim.vmul(sim.vload(a, i), factor))2    return out
  1. 1Once, before the loop: the factor does not change.
  2. 2Load, multiply, store: three instructions for lanes numbers.
main.pyPython
# 8 numbers on 4 lanes: the scalar loop against the vector loopdata = [0.5] * 8scalar = LaneSim(4)scalar_scale(scalar, data, 2.0)vector = LaneSim(4)vector_scale(vector, data, 2.0)print("scalar", scalar.total(), scalar.counts)print("vector", vector.total(), vector.counts)print("speedup", round(scalar.total() / vector.total(), 3))
scalar 32 {'loop': 8, 'sload': 8, 'smul': 8, 'sstore': 8}
vector 9 {'vsplat': 1, 'loop': 2, 'vload': 2, 'vmul': 2, 'vstore': 2}
speedup 3.556

Read the numbers: 32 instructions against 9, a speedup of 3.556, not 4. The extra vsplat is one instruction that the scalar loop does not have. It is paid once, so on a longer array it matters less and less.

03

Build it up: a fixed cost and a long array

The vsplat is a one-off cost inside the loop machine. A NumPy call has a bigger one-off cost outside it: Python must look up the function, check the types and shapes of the arguments and allocate the output array before the first lane is touched. We model that with a number, call_cost, added to the vector side. It is a stand-in, not a measurement: 50 instructions is a round, believable size for the lesson.

speedup(n) = 4n / (1 + 4n / lanes + call_cost)(1)The scalar scale loop costs 4 instructions per element; the vector side costs one vsplat, 4 instructions per pass of lanes elements, and the fixed call_cost.

For a short array the fixed cost dominates and the speedup is below 1: the plain loop wins. For a long array the per-pass term dominates and the speedup climbs toward the lane count but never reaches it. Let the machine draw the curve, and find the break-even length where the two sides meet.

main.pyPython
# Speedup against array length on 4 lanes, with a call cost of 50 instructionsfor n in (4, 16, 64, 256, 1024, 5400):    print(n, round(numpy_speedup(n, 4, 50), 3))n = 4while numpy_speedup(n, 4, 50) <= 1:    n += 4print("break-even length:", n)
4 0.291
16 0.955
64 2.226
256 3.336
1024 3.81
5400 3.963
break-even length: 20
What the real data saysSPY daily returns, 4 lanes, call cost 50
5,400 returns3.963xthe whole series: nearly 4
1 trading year, 252 returns3.327xalready well above 3
16 returns0.955xslower than the plain loop
Speedup against array length
4 values0.291
16 values0.955
64 values2.226
1,024 values3.81
5,400 values3.963
  • NumPy callMachine instructions in its loop
  • np.add(a, b)Which instructions does adding two arrays run?vload x2, vadd, vstore
  • np.multiply(r, 2.0)And a constant factor?one vsplat, then vload, vmul, vstore
  • for x in r: x * 2.0The Python loop?one scalar multiply per element, plus interpreter work
04

Typical mistakes

Vectorizing a tiny array. Four numbers do not repay a call cost of 50. The curve above shows a speedup of 0.291 at 4 values: the vector side is more than three times slower. The cure is not a different loop but a bigger batch: gather many small calls into one call over a long array.

main.pyPython
# Four numbers, then a splat in every pass: two ways to loseprint(round(numpy_speedup(4, 4, 50), 3))sim = LaneSim(4)out = [0.0] * 8for i in range(0, 8, 4):    sim.loop()    sim.vstore(out, i, sim.vmul(sim.vload(data, i), sim.vsplat(2.0)))1print(sim.total(), sim.counts)
0.291
10 {'loop': 2, 'vload': 2, 'vsplat': 2, 'vmul': 2, 'vstore': 2}
  1. 1The splat now runs in every pass: 10 instructions instead of 9.

Repeating work that never changes. The second half of that example moved the vsplat into the loop. The answer stays correct, so nothing complains, but the count rises from 9 to 10 because the same constant is rebuilt every pass. Anything that does not depend on the loop index belongs before the loop. The graded test counts exactly one vsplat.

Do not loop over a NumPy array in Python

for x in r hands you one Python number at a time, so you pay the interpreter for every element and the SIMD loop never runs. Write the whole-array expression instead.

05

What the tasks ask

  • Task and functionWhat it must do
  • LaneSim.vmul(a, b)Multiply two registers lane by lane into a new register and count one vmul.same checks as vadd
  • LaneSim.vsplat(x)Return a new register with x in every lane and count one vsplat.a fresh list every call
  • vector_scale(sim, a, k)Scale a whole array: one vsplat before the loop, then per pass loop, vload, vmul, vstore.exact counts are tested
  • numpy_speedup(n, lanes, call_cost)Run both scale loops on fresh machines and return scalar total / (vector total + call_cost).uses your two scale functions

Key takeaways

  • NumPy is the same idea A whole-array call runs a compiled loop of vload, an operation and vstore, which is where the lanes come from.
  • Hoist what never changes Spread a constant once with vsplat before the loop; doing it in every pass wastes instructions without changing the answer.
  • Length decides the win A fixed cost per call makes short arrays lose and long arrays approach the lane count, so batch your work.
Quick check
A NumPy call costs 100 instructions before its loop starts, on 4 lanes, scaling an array with 4 instructions per element on the plain side. Which array length makes the two sides equal in the simplest estimate, ignoring the vsplat?
Pick an answer.

Next. NumPy hides the loop behind a call. The next topic asks what happens when you write the loop yourself in a compiled language and leave the vectorizing to the compiler: which loops can it turn into vector code, and which does it refuse? You will build a small analyser for the loops it refuses and see why, on LaneSim, an overlapping read and write breaks the lane-by-lane idea.

Lab · what's graded

4 tasks · 100 pts
  • Multiply lane by lane with vmul25 pts
  • Spread one number across the lanes with vsplat25 pts
  • Scale an array with vector_scale25 pts
  • Count the speedup with numpy_speedup25 pts
Explorer · lab-2-1
▾ lab-2-1
…
bash · in-browser
learner@quantcraft:~/lab-2-1$
Python not loaded yetPythonLn 1, Col 1Spaces: 4UTF-8

Reset this topic?

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