σμ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.2·~55 minAdvanced

Masks and branchless code

Skill positionModule 3 of 4 · Topic 2 of 4
3.2 Masks and branchless code
—Lab score— / 100Total XP—Streak—
Lecture0% read

6 min readCode examples: 8

  1. 01The idea in plain words
  2. 02The smallest example: a payoff with an if
  3. 03Build it up: compare, blend and masked loads
  4. 04Typical mistakes
  5. 05What the tasks ask

On the 5,404 SPY returns, 50.5% of consecutive days switch between up and down, so an if on the sign of a return is a coin toss for the CPU. How can a loop that contains an if run with no jump at all, and what does the extra work cost?

01

The idea in plain words

Where we are. The last topic ended the loop with a scalar tail: a second loop that runs at scalar speed. It also left an old problem waiting. A vector instruction does the same thing in every lane, so what happens to a loop that does one thing for some elements and another for the rest? That is an if, and in quant code it is everywhere: gains only, a cap on a position, a payoff that is zero below a strike.

The answer is a mask. Instead of jumping, compute the answer for every lane, build a mask of the lanes where the condition holds, and use it to pick between the two results lane by lane. A branch is gone, and so is the cost of guessing it wrong.

DefinitionBranchless code

Compute both outcomes for every lane, build a mask of the lanes where the condition holds, and blend: take the first outcome where the mask is True and the second where it is False. Every lane does the work of both arms, and nothing jumps.

02

The smallest example: a payoff with an if

A call option pays max(price - strike, 0) at expiry: the gain above the strike, or nothing. Written with an if it is the scalar loop below. The machine gives each element a compare (scmp) and a jump (branch) on top of the load, the subtract and the store, six instructions per element, and the jump is the part that suffers when the outcome flips unpredictably.

main.pyPython
def scalar_call_payoff(sim, prices, strike):    """The scalar version of max(price - strike, 0) with an `if`: loop, sload, ssub, scmp, branch, sstore, six per element."""    out = [0.0] * len(prices)    for i in range(len(prices)):        sim.loop()        diff = sim.ssub(sim.sload(prices, i), strike)        if sim.sbranch(sim.scmp_gt(diff, 0.0)):1            sim.sstore(out, i, diff)        else:            sim.sstore(out, i, 0.0)    return out
  1. 1The compare and the jump, once per element.
main.pyPython
# Eight prices around a strike of 100, scalar with an if, then the branchless vector versionprices = [98.0, 101.5, 100.0, 103.25, 99.5, 110.0, 95.0, 104.0]sim = LaneSim(4)print(scalar_call_payoff(sim, prices, 100.0), sim.total(), sim.counts["branch"], "branches")sim = LaneSim(4)print(vector_call_payoff(sim, prices, 100.0), sim.total(), sim.counts)
[0.0, 1.5, 0.0, 3.25, 0.0, 10.0, 0.0, 4.0] 48 8 branches
[0.0, 1.5, 0.0, 3.25, 0.0, 10.0, 0.0, 4.0] 14 {'vsplat': 2, 'loop': 2, 'vload': 2, 'vsub': 2, 'vcmp': 2, 'vblend': 2, 'vstore': 2}

Same eight payoffs, 48 instructions against 14, and the vector run has no branch entry at all. How it gets there takes three small instructions: subtract the strike in every lane, compare the result with zero to get a mask, and blend the difference with zeros using that mask.

03

Build it up: compare, blend and masked loads

The two new instructions are small. vcmp_gt(a, b) returns a mask with True in each lane where a > b. vblend(mask, a, b) returns a register that takes the lane of a where the mask is True and the lane of b where it is False. Each counts as one instruction, whatever the lane count. Try them on one register of four.

main.pyPython
# Compare a register of four prices with a strike, then blend the gain with zerosim = LaneSim(4)diff = sim.vsub([98.0, 101.5, 100.0, 103.25], sim.vsplat(100.0))mask = sim.vcmp_gt(diff, sim.vsplat(0.0))1print(diff, mask)print(sim.vblend(mask, diff, sim.vsplat(0.0)))print(sim.counts)
[-2.0, 1.5, 0.0, 3.25] [False, True, False, True]
[0.0, 1.5, 0.0, 3.25]
{'vsplat': 3, 'vsub': 1, 'vcmp': 1, 'vblend': 1}
  1. 1A mask: one flag per lane.
blend(mask, a, b)[lane] = a[lane] if mask[lane] else b[lane](1)The mask decides lane by lane which register the result comes from. Both a and b were fully computed first; blend only chooses.
main.pyPython
def vector_call_payoff(sim, prices, strike):    """Return max(price - strike, 0) for every price as a new list, with no branch: a call option's payoff at expiry.    Spread `strike` and 0.0 over all lanes once each with `vsplat` (two `vsplat`), then per pass: `sim.loop()`, `vload`, `vsub` of the    strike, `vcmp_gt` of the difference against zero, `vblend` to keep the difference where it is positive and 0.0 elsewhere, `vstore`.    For 8 prices on 4 lanes: {"vsplat": 2, "loop": 2, "vload": 2, "vsub": 2, "vcmp": 2, "vblend": 2, "vstore": 2}, 14 instructions.    An empty list returns [] and counts nothing; a length that is not a multiple of `sim.lanes` raises    ValueError("length must be a multiple of the lane count").    """    if len(prices) % sim.lanes:        raise ValueError("length must be a multiple of the lane count")    if not prices:        return []    strikes = sim.vsplat(strike)1    zeros = sim.vsplat(0.0)    out = [0.0] * len(prices)    for i in range(0, len(prices), sim.lanes):        sim.loop()        diff = sim.vsub(sim.vload(prices, i), strikes)2        sim.vstore(out, i, sim.vblend(sim.vcmp_gt(diff, zeros), diff, zeros))    return out
  1. 1The strike and the zeros are spread once, before the loop.
  2. 2Mask, blend, store: no jump.

Masks also solve the problem the last topic left. For a length that is not a multiple of the lane count, build a mask that is True for the live lanes of the last register. A masked load reads only those lanes and fills the others with zero, and a masked store writes only those lanes back. Nothing past the end is read or written, and there is no scalar tail loop.

main.pyPython
# Seven prices on 4 lanes: one full register and a masked one with 3 live lanessim = LaneSim(4)seven = [98.0, 101.5, 100.0, 103.25, 99.5, 110.0, 95.0]mask = sim.tail_mask(3)print(mask, sim.vmaskload(seven, 4, mask))1sim = LaneSim(4)print(vector_call_payoff_any(sim, seven, 100.0), sim.counts)
[True, True, True, False] [99.5, 110.0, 95.0, 0.0]
[0.0, 1.5, 0.0, 3.25, 0.0, 10.0, 0.0] {'vsplat': 2, 'loop': 2, 'vload': 1, 'vsub': 2, 'vcmp': 2, 'vblend': 2, 'vstore': 1, 'vmaskload': 1, 'vmaskstore': 1}
  1. 1The dead lane is 0.0 and was never read from memory.
  • InstructionWhat it does
  • vcmp_gt(a, b)Which lanes have a greater than b?returns a mask, no jump
  • vblend(mask, a, b)Take a where the mask is True, b elsewhere.computes both arms first
  • vmaskload(mem, i, mask)Load only the live lanes, zero elsewhere.never reads past the end
  • vmaskstore(mem, i, reg, mask)Write only the live lanes back.leaves the other memory alone
What the real data saysSPY daily returns, 2005-02-25 to 2026-08-21
Up days2,96454.8% of 5,404 returns
Sign changes day to day2,72950.5% of 5,403 pairs: a predictor that repeats the last outcome is wrong that often
Days above +1%72113.3%: the payoff above a 1% strike is mostly zero
Scalar `if`, 5,404 returns (instr.)32,4246 per element, 5,404 branches
Branchless, 8 lanes, masked tail (instr.)4,0587.99x fewer, no branches
Instructions for 5,404 payoffs
Scalar with `if`32424
4 lanes8108
8 lanes + masked tail4058
main.pyPython
# The totals in the panel: 5,404 payoffs, scalar against two vector machinesn = 5404big = [100.0 + (i % 7) for i in range(n)]scalar = LaneSim(4)scalar_call_payoff(scalar, big, 102.0)print("scalar", scalar.total(), "with", scalar.counts["branch"], "branches")for lanes, kernel in ((4, vector_call_payoff), (8, vector_call_payoff_any)):    sim = LaneSim(lanes)    kernel(sim, big, 102.0)1    print(lanes, "lanes", sim.total(), round(scalar.total() / sim.total(), 2))
scalar 32424 with 5404 branches
4 lanes 8108 4.0
8 lanes 4058 7.99
  1. 15,404 is a multiple of 4, so the first kernel is enough; 8 lanes need the masked tail.
The cost of a mispredicted branch

A branch predictor guesses which way a jump will go. A wrong guess throws away the instructions already started, typically 15 to 20 cycles on current cores. LaneSim counts a branch as one instruction, so the real gain of going branchless on data like this is larger than the table shows.

04

Typical mistakes

Treating a mask as if it were a single yes or no. A mask is a list of four flags. In Python any non-empty list counts as true, so if mask: takes the branch even when every flag is False. The mask has to go into vblend, never into an if.

main.pyPython
# A list of four False flags is still "true" for an ifsim = LaneSim(4)none_live = sim.vcmp_gt([1.0, 1.0, 1.0, 1.0], [2.0, 2.0, 2.0, 2.0])print(none_live, "-> any:", any(none_live))if none_live:    print("the if was taken anyway")
[False, False, False, False] -> any: False
the if was taken anyway

Thinking a masked-off lane is skipped. Both arms run in every lane; the blend only chooses which result survives. A lane that the mask discards has still been computed, and a dead lane of a masked load holds 0.0, so a subtraction on it produces a meaningless number. That number never reaches memory because the masked store leaves the lane alone, but it can trip a floating-point error such as a division by zero before it is thrown away. Make sure the discarded arm is safe to compute.

main.pyPython
# A dead lane of a masked load is zero; the masked store leaves memory alone theresim = LaneSim(4)mask = sim.tail_mask(3)reg = sim.vmaskload(seven, 4, mask)diff = sim.vsub(reg, sim.vsplat(100.0))1print(reg, diff)out = [-1.0] * 7sim.vmaskstore(out, 4, diff, mask)print(out)
[99.5, 110.0, 95.0, 0.0] [-0.5, 10.0, -5.0, -100.0]
[-1.0, -1.0, -1.0, -1.0, -0.5, 10.0, -5.0]
  1. 1The dead lane shows -100.0, a number that means nothing.

Believing a branchless version is always faster. The vector loop does the work of both arms for every element. When one arm is expensive and rarely taken, a predictable if that skips it can beat computing it everywhere. Here both arms are one subtraction and a zero, so the blend wins by a wide margin; with a heavy arm the answer can change, and the reliable way to know is to count or measure.

Compare against zero with care

vcmp_gt is strict: a difference of exactly zero is not greater than zero, so it goes to the zeros arm. That matches max(x, 0) here because both arms give 0.0, but for another rule such as "keep returns of at least 1%" the choice between greater than and at least decides which days count.

05

What the tasks ask

  • Task and functionWhat it must do
  • LaneSim.vcmp_gt(a, b)Return a mask: True where a > b; count one vcmp.returns a new list of bools
  • LaneSim.vblend(mask, a, b)Take a where the mask is True, b elsewhere; count one vblend.checks the mask first
  • vector_call_payoff(sim, prices, strike)max(price - strike, 0) per price, with vcmp_gt and vblend and no if.exact counts are tested
  • vector_call_payoff_any(sim, prices, strike)The same for any length, finishing with vmaskload, vmaskstore and sim.tail_mask(...).no scalar instructions

Key takeaways

  • An if becomes a mask and a blend Compute both arms in every lane, build a mask with a compare, and blend: no jump, no misprediction.
  • Both arms always run A masked-off lane is computed and then discarded, so the discarded arm must be safe to compute, and a heavy arm can make branchless code lose.
  • Masks finish the loop too A tail mask with a masked load and store handles the last partial register with no scalar loop and no read past the end.
Quick check
Eight prices go through vblend with a mask that has exactly two True flags among four lanes in each register. How much work did the other two lanes of each register cost?
Pick an answer.

Next. Masks decide which lanes to keep, but every result so far has stayed in its own lane. The next topic collapses a register into one number: the sum of a lane-wise product is a dot product, the heart of a covariance or a portfolio variance. Adding across lanes is the one thing a vector register is bad at, so you will build it from shuffles and adds, see why summing in a different order changes the last digits, and keep a register of partial sums until the very end.

Lab · what's graded

4 tasks · 100 pts
  • Compare lane by lane with vcmp_gt25 pts
  • Pick lane by lane with vblend25 pts
  • Replace the if with vector_call_payoff25 pts
  • Handle the last register with masks in vector_call_payoff_any25 pts
Explorer · lab-6-1
▾ lab-6-1
…
bash · in-browser
learner@quantcraft:~/lab-6-1$
Python not loaded yetPythonLn 1, Col 1Spaces: 4UTF-8

Reset this topic?

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