σμ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.1·~45 minIntermediate

Data parallelism and vector registers

Skill positionModule 1 of 4 · Topic 1 of 2
1.1 Data parallelism and vector registers
—Lab score— / 100Total XP—Streak—
Lecture0% read

7 min readCode examples: 9

  1. 01The idea in plain words
  2. 02The smallest example: one number per instruction
  3. 03Build it up: a register, a load and an add
  4. 04Typical mistakes
  5. 05What the tasks ask

Adding two arrays of 5,400 daily SPY returns takes 27,000 instructions when the CPU handles one number at a time, and 6,750 when it adds four numbers with each instruction. Where does that factor of four come from, and what must a machine do to get it?

01

The idea in plain words

Where we are. This is the first topic of the SIMD skill, so nothing comes before it. By the end you will have built a small vector machine in Python, called LaneSim, and used it to add two arrays in a quarter of the instructions a one-number-at-a-time loop needs. Every later topic grows this same machine, so what you write here is the foundation.

A CPU works by running instructions, tiny steps such as "load a number from memory", "add two numbers" and "store the result". An ordinary (scalar) add instruction works on one pair of numbers. But a modern CPU also has wide registers that hold four or eight numbers side by side, and instructions that act on every one of them at once. Each position in such a register is a lane.

DefinitionSIMD

Single Instruction, Multiple Data: one instruction that does the same operation on every lane of a wide register at once, so one add handles four or eight numbers instead of one.

An everyday comparison: carrying eggs from the shop to your kitchen one at a time, or in a carton of four. The walk is the same and so is the effort of one trip, but the carton moves four times the eggs. A quant cares because the work that dominates many programs, a rolling mean, a dot product, a risk sum, is a loop that repeats the same arithmetic on thousands of numbers. That is exactly the shape a carton fits.

How wide are real registers? An SSE register is 128 bits wide, an AVX2 register 256 bits and an AVX-512 register 512 bits. A price stored as a 64-bit float takes 64 bits, so those registers hold 2, 4 and 8 of them; a 32-bit float is half the size, so they hold 4, 8 and 16. LaneSim uses 4 or 8 lanes, which is a 256-bit register of 64-bit or 32-bit floats. The width changes the speedup but not the idea.

We will not time anything in this skill. Wall-clock timing depends on the machine, the load and the cache, so two runs disagree. Instead LaneSim counts instructions: a speedup becomes a ratio of two integers that you can print, check and reproduce exactly. That is a model, and a later note says what it leaves out, but it keeps the idea clear.

02

The smallest example: one number per instruction

Here is the start of LaneSim, the part that is already written in your starter file. It keeps a dictionary counts that maps an instruction name to how many times it ran, and offers the scalar instructions: sload reads one number, sadd adds two, sstore writes one, and loop stands for the compare-and-jump that ends every pass of a loop.

main.py (LaneSim, scalar side)Python
class LaneSim:    """A vector machine with `lanes` lanes that counts every instruction it runs."""    def __init__(self, lanes=4):        if lanes not in (4, 8):            raise ValueError("lanes must be 4 or 8")        self.lanes = lanes        self.counts = {}1    def tick(self, op):        """Count one instruction named `op`."""        self.counts[op] = self.counts.get(op, 0) + 12    def total(self):        """The number of instructions run so far."""        return sum(self.counts.values())    # ---- the scalar side: one number per instruction ----    def loop(self):        """One compare-and-jump at the end of a loop pass."""        self.tick("loop")    def sload(self, mem, i):        self.tick("sload")        return mem[i]    def sstore(self, mem, i, x):        self.tick("sstore")        mem[i] = x    def sadd(self, x, y):        self.tick("sadd")        return x + y
  1. 1counts is where every instruction is recorded.
  2. 2tick is the only place a count goes up.

Now the baseline, scalar_add. It adds two arrays by walking through them one element at a time. Each pass does five things: one loop, two sload (one number from each array), one sadd and one sstore.

main.pyPython
# Add two arrays of 8 numbers, one element per pass, and count what the machine ransim = LaneSim(4)a = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0]b = [10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0]print(scalar_add(sim, a, b))print(sim.total(), sim.counts)1
[11.0, 22.0, 33.0, 44.0, 55.0, 66.0, 77.0, 88.0]
40 {'loop': 8, 'sload': 16, 'sadd': 8, 'sstore': 8}
  1. 18 passes x 5 instructions = 40.

Read the last line: sim.total() is 40 and sim.counts shows eight of each of the five instructions, five instructions times eight elements. The array length is the only thing that changes this number, so it grows in a straight line with the data.

03

Build it up: a register, a load and an add

The vector side needs just three new instructions, and these are the first three tasks. vload copies lanes neighbouring numbers from memory into a register, vadd adds two registers lane by lane, and vstore copies a register back into memory. Each one counts as a single instruction no matter how many lanes it moves, and that is the whole trick.

main.py (inside LaneSim)Python
# ---- the vector side: `lanes` numbers per instruction ----def vload(self, mem, i):1    """Load `lanes` consecutive numbers starting at index `i` into a register (a new list): one `vload`.    If they do not all fit (i < 0 or i + lanes > len(mem)) raise ValueError("vector load out of range") and count nothing.    """    if i < 0 or i + self.lanes > len(mem):        raise ValueError("vector load out of range")    self.tick("vload")    return list(mem[i:i + self.lanes])def vstore(self, mem, i, reg):2    """Write the register `reg` into `mem[i:i + lanes]`: one `vstore`. Returns nothing.    If `reg` does not have exactly `lanes` numbers raise ValueError("register must have one number per lane"); if the lanes do    not all fit in `mem` raise ValueError("vector store out of range"). Nothing is counted or written when it raises.    """    if len(reg) != self.lanes:        raise ValueError("register must have one number per lane")    if i < 0 or i + self.lanes > len(mem):        raise ValueError("vector store out of range")    self.tick("vstore")    mem[i:i + self.lanes] = regdef vadd(self, a, b):    """Add two registers lane by lane and return the result as a new list: one `vadd`.    If either register does not have exactly `lanes` numbers raise ValueError("register must have one number per lane").    """    if len(a) != self.lanes or len(b) != self.lanes:        raise ValueError("register must have one number per lane")    self.tick("vadd")    return [x + y for x, y in zip(a, b)]
  1. 1A register is a plain list with one number per lane.
  2. 2vstore returns nothing: it changes memory.
  1. 1
    Loadvload(a, i) fills a register with a[i] to a[i + lanes - 1]: one instruction.
  2. 2
    Addvadd(x, y) adds the two registers lane by lane: one instruction for all lanes.
  3. 3
    Storevstore(out, i, r) writes the register into out[i] to out[i + lanes - 1]: one instruction.
  4. 4
    Move on by one registerThe loop index jumps by lanes, not by 1, and loop counts one pass.

Try the three instructions on their own first. Load four numbers from each array, add the two registers and look at the counts. Notice that the registers r1, r2 and r3 are ordinary lists: printing them shows the four lanes.

main.pyPython
# One register from each array, added in a single instructionsim = LaneSim(4)r1 = sim.vload(a, 0)r2 = sim.vload(b, 0)1r3 = sim.vadd(r1, r2)print(r1, r2, r3)print(sim.counts)
[1.0, 2.0, 3.0, 4.0] [10.0, 20.0, 30.0, 40.0] [11.0, 22.0, 33.0, 44.0]
{'vload': 2, 'vadd': 1}
  1. 1Three instructions moved or added 12 numbers.

Now put the three together in a loop. vector_add is task four. It walks through the arrays lanes elements at a time and, in each pass, runs one loop, two vload, one vadd and one vstore. Look at how few lines it needs, and at the two checks at the top that the topic on alignment and the scalar tail will remove.

main.pyPython
def vector_add(sim, a, b):    """Return the lane-by-lane sum of the arrays `a` and `b` as a new list, using only vector instructions.    Each pass handles `sim.lanes` elements: one `sim.loop()`, two `vload`, one `vadd`, one `vstore`. For 8 elements on 4 lanes    that is two passes: {"loop": 2, "vload": 4, "vadd": 2, "vstore": 2}, 10 instructions where `scalar_add` needs 40.    If the arrays differ in length raise ValueError("arrays must have the same length"); if the length is not a multiple of    `sim.lanes` raise ValueError("length must be a multiple of the lane count") (topic 5 handles the leftover elements).    """    if len(a) != len(b):        raise ValueError("arrays must have the same length")    if len(a) % sim.lanes:        raise ValueError("length must be a multiple of the lane count")    out = [0.0] * len(a)2    for i in range(0, len(a), sim.lanes):1        sim.loop()        total = sim.vadd(sim.vload(a, i), sim.vload(b, i))        sim.vstore(out, i, total)    return out
  1. 1Step by lanes, not by 1.
  2. 2Results go to a new list, so the inputs stay untouched.
main.pyPython
# The same sum with 4 lanes and with 8 lanesfor lanes in (4, 8):    sim = LaneSim(lanes)    print(lanes, vector_add(sim, a, b) == scalar_add(LaneSim(lanes), a, b), sim.total(), sim.counts)
4 True 10 {'loop': 2, 'vload': 4, 'vadd': 2, 'vstore': 2}
8 True 5 {'loop': 1, 'vload': 2, 'vadd': 1, 'vstore': 1}

Same answer, fewer instructions: 10 with 4 lanes and 5 with 8 lanes, against 40 for the scalar loop. The speedup in instructions is exactly the number of lanes, because each vector pass does the work of lanes scalar passes for the same five instructions.

speedup = scalar instructions / vector instructions = 5n / (5n / lanes) = lanes(1)n is the number of elements (a multiple of lanes). Both loops spend 5 instructions per pass; the vector loop makes n / lanes passes and the scalar loop makes n.

The counts depend only on how many elements there are, never on their values. So we can check the numbers in the lead with any array of the right length: 5,400 returns, here all equal because the value does not matter.

main.pyPython
# 5,400 returns: the scalar loop against 4 and 8 lanesreturns = [0.001] * 5400scalar = LaneSim(4)scalar_add(scalar, returns, returns)print("scalar", scalar.total())for lanes in (4, 8):    sim = LaneSim(lanes)    vector_add(sim, returns, returns)    print(lanes, "lanes", sim.total(), "speedup", scalar.total() / sim.total())1
scalar 27000
4 lanes 6750 speedup 4.0
8 lanes 3375 speedup 8.0
  1. 1The ratio is exactly the lane count.
What the real data saysSPY daily returns, 2005-02-25 to 2026-08-21
Daily returns5,4045,405 closing prices give 5,404 returns
Used (multiple of 8)5,400the last 4 returns wait for the tail topic
Scalar, 5 per element (instr.)27,000
4 lanes (instr.)6,7504.0x fewer
8 lanes (instr.)3,3758.0x fewer
Instructions to add two copies of the series
Scalar27000
4 lanes6750
8 lanes3375
A count is not a stopwatch

Real chips run some wide instructions slower than narrow ones, and memory can be the limit. So a real 4-lane speedup is usually below 4x. The simulator shows the ceiling the idea can reach.

04

Typical mistakes

An array whose length is not a multiple of the lanes. A register is always full, so there is no way to load 3 numbers into 4 lanes. Seven elements on 4 lanes leave a leftover, and vector_add refuses it with an error. Reading that message is the whole fix for now: pass a length that fits. The topic on alignment and the scalar tail shows what to do with the leftover.

main.pyPython
# Seven elements do not fill two registers of 4 lanessim = LaneSim(4)vector_add(sim, a[:7], b[:7])
ValueError: length must be a multiple of the lane count

Treating a register as a window onto memory. vload copies. If you change r1 afterwards, a does not change; only vstore writes memory. Forgetting the vstore is the quiet version of the same mistake: the sums are computed, counted and then thrown away, and the output list is still full of zeros.

main.pyPython
# Changing a register does not change memory; only vstore doessim = LaneSim(4)r = sim.vload(a, 0)r[0] = 99.01print(a[:4], r)out = [0.0] * 4sim.vstore(out, 0, r)print(out)
[1.0, 2.0, 3.0, 4.0] [99.0, 2.0, 3.0, 4.0]
[99.0, 2.0, 3.0, 4.0]
  1. 1This edits the register, not a.
Count every instruction

The speedup is only honest if the vector loop pays for its loads, stores and loop passes too. If you skip a tick, the ratio looks better than it is, and the graded tests compare your counts exactly.

05

What the tasks ask

  • Task and functionWhat it must do
  • LaneSim.vload(mem, i)Copy lanes numbers from mem into a new register and count one vload.raises if it does not fit
  • LaneSim.vstore(mem, i, reg)Write a register into memory and count one vstore; return nothing.a failing store writes nothing
  • LaneSim.vadd(a, b)Add two registers lane by lane into a new register and count one vadd.inputs are not changed
  • vector_add(sim, a, b)Add two whole arrays with only vector instructions: per pass one loop, two vload, a vadd and a vstore.exact counts are tested

Key takeaways

  • One instruction, many numbers A vector register holds one number per lane, and one instruction works on every lane at once.
  • Count instructions, not seconds A speedup in this skill is a ratio of two instruction counts, exact and repeatable.
  • Load, operate, store Every vector loop is vload, an operation, vstore, stepping by the lane count, and it wins by exactly the number of lanes.
Quick check
A loop adds two arrays of 1,000 numbers (a multiple of 8). With 8 lanes, how many instructions does the vector version run, if each pass costs 5 and the scalar version costs 5 per element?
Pick an answer.

Next. You now have a machine whose instructions you can count, and a loop that beats the scalar one by exactly the number of lanes. The next topic asks why a familiar tool, NumPy, is fast: it is the same idea. You will extend LaneSim with multiplication and a way to spread one number across all lanes, and count how the speedup depends on the length of the array.

Lab · what's graded

4 tasks · 100 pts
  • Load a register with vload25 pts
  • Write it back with vstore25 pts
  • Add lane by lane with vadd25 pts
  • Add two arrays with vector_add25 pts
Explorer · lab-1-1
▾ lab-1-1
…
bash · in-browser
learner@quantcraft:~/lab-1-1$
Python not loaded yetPythonLn 1, Col 1Spaces: 4UTF-8

Reset this topic?

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