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

Alignment and the scalar tail

Skill positionModule 3 of 4 · Topic 1 of 4
3.1 Alignment and the scalar tail
—Lab score— / 100Total XP—Streak—
Lecture0% read

6 min readCode examples: 6

  1. 01The idea in plain words
  2. 02The smallest example: two ways to get the tail wrong
  3. 03Build it up: peel, body and tail
  4. 04Typical mistakes
  5. 05What the tasks ask

The 5,404 daily SPY returns fill 675 registers of 8 lanes and leave 4 numbers over. Drop those four and the last days of your sum are missing; read past the end and you read somebody else's memory. How do you finish the job, and what does it cost?

01

The idea in plain words

Where we are. Every kernel so far refused an array whose length was not a multiple of the lane count, and the C version of the last topic simply said "n is a multiple of 4" in a comment. Real data does not oblige. This topic builds the two pieces that make a vector loop usable on any array: handling the tail, and starting from an aligned address.

DefinitionHead, body, tail

Any array splits into three parts: a short head of single elements until the address is aligned, a body of whole registers, and a short tail of single elements. Only the body runs on vector instructions.

Both ends are handled with the scalar instructions you already have, which is why the loops are slower there but still correct. The head and the tail are short, fewer than lanes elements each, so for a long array they are a tiny share of the work. For a short array they can be most of it, and that is a reason to measure before vectorizing.

02

The smallest example: two ways to get the tail wrong

Take 7 numbers on 4 lanes: one full register and 3 left over. The first mistake is to loop only over the full registers and say nothing about the rest. Nothing fails: the output has 7 slots and the last three keep their starting zeros.

main.pyPython
# Mistake 1: loop over the full registers only. The last 3 sums are simply never computeda = [float(i) for i in range(7)]b = [1.0] * 7sim = LaneSim(4)out = [0.0] * 7for i in range(0, 7 - 7 % 4, 4):1    sim.vstore(out, i, sim.vadd(sim.vload(a, i), sim.vload(b, i)))print(out)
[1.0, 2.0, 3.0, 4.0, 0.0, 0.0, 0.0]
  1. 17 - 7 % 4 is 4: only one register fits.

The second mistake is the opposite: round the loop up and load the last, partly empty register. LaneSim refuses with a ValueError. Real hardware does not: a load simply reads the next four numbers in memory, whatever they are, and may stop the program if that memory belongs to nobody. The simulator is strict on purpose so you notice.

main.pyPython
# Mistake 2: load the last, partly empty registersim = LaneSim(4)sim.vload(a, 4)
ValueError: vector load out of range
03

Build it up: peel, body and tail

Alignment first. A register of 4 numbers of 8 bytes is 32 bytes wide, and an array is aligned for it when its first element sits at a byte address that is a multiple of 32. is_aligned is that test. The array's own start is usually aligned by the allocator, but a slice such as returns[1:] starts one element, 8 bytes, later and no longer is. peel_count says how many single elements to handle until the next one is aligned.

main.pyPython
# Where an array that starts at this byte address becomes aligned for 4 lanes of 8 bytes (32 bytes wide)for address in (0, 8, 16, 24, 32, 40, 4104):    print(address, is_aligned(address, 32), peel_count(address, 4))1
0 True 0
8 False 3
16 False 2
24 False 1
32 True 0
40 False 3
4104 False 3
  1. 1The peel is 3 at address 8, 2 at 16, 1 at 24, and 0 once aligned.
n = head + body + tail, head < lanes, body % lanes = 0, tail < lanes(1)head is the peel (never more than n), body is as many of the remaining elements as fill whole registers, and tail is what is left.
  1. 1
    PeelHandle single elements from the front until the address is aligned.
  2. 2
    Run the bodyProcess whole registers, one vector pass per lanes elements.
  3. 3
    Finish the tailHandle the last few elements one at a time. Never read past the end.

split_work turns an array length and a start address into the three counts. Try the lengths of the lead: 5,404 returns starting aligned give no head, 5,400 in the body and 4 in the tail on 8 lanes, while a slice that starts 8 bytes later gives a head of 7. Then vector_add_aligned runs the three loops, and the counts show where the instructions go.

main.pyPython
# The three parts for the 5,404 returns of the lead, aligned and 8 bytes lateprint(split_work(5404, 0, 8), split_work(5404, 8, 8))for lanes, address in ((4, 0), (8, 0), (8, 8)):    sim = LaneSim(lanes)    vector_add_aligned(sim, [1.0] * 5404, [1.0] * 5404, address)    print(lanes, "lanes, address", address, sim.total(), sim.counts)
(0, 5400, 4) (7, 5392, 5)
4 lanes, address 0 6755 {'loop': 1351, 'vload': 2702, 'vadd': 1351, 'vstore': 1351}
8 lanes, address 0 3395 {'loop': 679, 'vload': 1350, 'vadd': 675, 'vstore': 675, 'sload': 8, 'sadd': 4, 'sstore': 4}
8 lanes, address 8 3430 {'loop': 686, 'sload': 24, 'sadd': 12, 'sstore': 12, 'vload': 1348, 'vadd': 674, 'vstore': 674}

Why bother with the head at all? Because of the cache. Memory moves in 64-byte lines, and a 32-byte load that starts 8 bytes past a multiple of 32 will, every other time, cover the end of one line and the start of the next. Such a split load is served as two accesses, so it costs more. line_crossings counts them, with and without the peel.

main.pyPython
# Loads that straddle a 64-byte cache line over 5,400 elements: misaligned, then after peeling 3print(line_crossings(8, 5400, 4), "of", 5400 // 4)print(line_crossings(8 + 3 * 8, 5400, 4), "of", 5400 // 4)
675 of 1350
0 of 1350
What the real data says5,404 SPY returns, adding two copies
Scalar (instr.)27,0205 per element
4 lanes, 0 tail (instr.)6,7555,404 is a multiple of 4
8 lanes, tail of 4 (instr.)3,39520 of them are the tail
8 lanes, slice +8 bytes (instr.)3,430head of 7 and tail of 5
Instructions on 8 lanes by start address
Aligned start3395
Start 8 bytes late3430
Scalar27020
  • Way to deal with the tailCost and catch
  • scalar tail loopFinish the last few elements one at a time.always correct, at most lanes - 1 slow passes
  • pad the arrayAllocate a multiple of lanes and fill the extra slots with zeros.no tail loop, but you own the padding
  • masked load and storeLoad and store only the live lanes of the last register.the next topic: masks
  • overlap the last vectorRedo a full register that ends at the last element, overlapping the one before.only safe when recomputing a value is harmless
04

Typical mistakes

Losing the tail without an error. Mistake 1 in the second section never raised anything, and in a real sum the missing days simply make the result slightly wrong. A test that always uses a length divisible by the lane count will never catch it. This lab's tests draw random lengths for that reason: write your own tests with lengths one less and one more than a multiple of the width.

Assuming a slice is aligned. returns[1:] in NumPy is a view that starts one element, 8 bytes, into the buffer, so a kernel that assumed an aligned start now has a head of 3 on 4 lanes. If your kernel uses loads that require alignment, a slice makes it fail or crash; with unaligned loads it still works, but pays for the split loads shown above.

main.pyPython
# A slice that starts one element (8 bytes) later needs a headfor start in (0, 1, 2, 3, 4):    print("starts at element", start, "-> peel", peel_count(start * 8, 4))
starts at element 0 -> peel 0
starts at element 1 -> peel 3
starts at element 2 -> peel 2
starts at element 3 -> peel 1
starts at element 4 -> peel 0
Pad when you own the buffer

If you allocate the array yourself, round its length up to a multiple of the width and fill the extra slots with a neutral value such as 0. Then the body covers everything and there is no tail loop to write or to get wrong.

05

What the tasks ask

  • Task and functionWhat it must return
  • is_aligned(address, width_bytes)True when the address is a multiple of the width.two error checks, in order
  • peel_count(address, lanes, itemsize=8)Single elements to handle before the address is aligned, from 0 to lanes - 1.address 8 on 4 lanes: 3
  • split_work(n, address, lanes)(head, body, tail) adding up to n, using peel_count.calls peel_count
  • vector_add_aligned(sim, a, b, address=0)The sum for any length: scalar head, vector body, scalar tail, with exact counts.uses split_work

Key takeaways

  • Every array has three parts A head to reach alignment, a body of whole registers and a tail; only the body is vector work, and the ends use scalar instructions.
  • Never read past the end A partly empty register reads memory that is not yours; the simulator refuses it, hardware does not, and a missing tail fails silently.
  • Alignment is a cost, not a rule Unaligned loads work but straddle cache lines; peeling a few elements to start aligned removes the split loads.
Quick check
An array of 5,405 doubles starts at byte address 8, and the machine has 4 lanes of 8 bytes. What does split_work give?
Pick an answer.

Next. The scalar tail works, but it is a second loop to write and it runs slower than the body. The next topic shows a better tool for the same problem and for another one that has been waiting: the if inside a loop. A mask says which lanes of a register are live, so the last partial register can be loaded and stored with only its live lanes, and a branch such as "keep the return only if it is positive" becomes arithmetic with no jump.

Lab · what's graded

4 tasks · 100 pts
  • Test an address with is_aligned25 pts
  • Count the elements to peel with peel_count25 pts
  • Split the array with split_work25 pts
  • Add any two arrays with vector_add_aligned25 pts
Explorer · lab-5-1
▾ lab-5-1
…
bash · in-browser
learner@quantcraft:~/lab-5-1$
Python not loaded yetPythonLn 1, Col 1Spaces: 4UTF-8

Reset this topic?

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