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?
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.
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.
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.
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
- 1The compare and the jump, once per element.
# 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.
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.
# 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}- 1A mask: one flag per lane.
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
- 1The strike and the zeros are spread once, before the loop.
- 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.
# 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}- 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
# 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
- 15,404 is a multiple of 4, so the first kernel is enough; 8 lanes need the masked tail.
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.
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.
# 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.
# 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]
- 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.
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.
What the tasks ask
- Task and functionWhat it must do
- LaneSim.vcmp_gt(a, b)Return a mask: True where
a > b; count onevcmp.returns a new list of bools - LaneSim.vblend(mask, a, b)Take
awhere the mask is True,belsewhere; count onevblend.checks the mask first - vector_call_payoff(sim, prices, strike)
max(price - strike, 0)per price, withvcmp_gtandvblendand noif.exact counts are tested - vector_call_payoff_any(sim, prices, strike)The same for any length, finishing with
vmaskload,vmaskstoreandsim.tail_mask(...).no scalar instructions
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?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
ifwithvector_call_payoff25 pts - Handle the last register with masks in
vector_call_payoff_any25 pts