σμ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 2 · Vectorizing a loop›Topic 2.2·~1 hr 10 minAdvanced

Intrinsics: writing the vector code by hand

Skill positionModule 2 of 4 · Topic 2 of 2
2.2 Intrinsics: writing the vector code by hand
—Lab score— / 100Total XP—Streak—
Lecture0% read

6 min readCode examples: 6

  1. 01The idea in plain words
  2. 02The smallest example: the fused kernel on the machine
  3. 03Build it up: rounding, names and savings
  4. 04Typical mistakes
  5. 05What the tasks ask

On 4 lanes y = alpha * x + y over 5,400 SPY returns takes 8,101 instructions with a separate multiply and add, and 6,751 when you write the fused instruction yourself. Where do you find that instruction, what is its name in C, and why does it round differently from the two-step version?

01

The idea in plain words

Where we are. The last topic showed that a compiler vectorizes a loop only when it can prove the answer stays the same, and that it stays silent when it cannot. When a loop matters and the compiler declines it, you write the vector instructions yourself. In C and C++ you do that with intrinsics, and in LaneSim you already have the same thing: every method is one instruction.

Look at the same kernel in both worlds. The C version below uses AVX2 intrinsics on 64-bit floats, four per register. Each name encodes the register width, the operation and the type, and the line _mm256_fmadd_pd(a, vx, vy) computes a * vx + vy in a single instruction. Read it next to vector_axpy, whose body you will write: vsplat is set1, vload is loadu, vstore is storeu and vfma is fmadd.

axpy.ccpp
#include <immintrin.h>// y = alpha * x + y for n doubles, n a multiple of 4. Build with -mavx2 -mfma.void axpy(double alpha, const double* x, double* y, int n) {    __m256d a = _mm256_set1_pd(alpha);1    for (int i = 0; i < n; i += 4) {        __m256d vx = _mm256_loadu_pd(x + i);        __m256d vy = _mm256_loadu_pd(y + i);        _mm256_storeu_pd(y + i, _mm256_fmadd_pd(a, vx, vy));    }2}
  1. 1Once, before the loop: vsplat in LaneSim.
  2. 2One instruction does the multiply and the add.
02

The smallest example: the fused kernel on the machine

The fused instruction is one new method. vfma(a, b, c) returns a * b + c in every lane and counts one vfma. Everything else in the kernel is a piece you already know from the topic on NumPy: splat the constant once, then load, compute and store, pass by pass. Run all three versions on 8 numbers and compare the counts.

main.pyPython
# y = 2 * x + y on 8 numbers: scalar, separate multiply and add, fusedx = [0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0]y = [1.0] * 8results = []for name, kernel in (("scalar", scalar_axpy), ("unfused", vector_axpy_unfused), ("fused", vector_axpy)):    sim = LaneSim(4)    results.append(kernel(sim, 2.0, x, y))    print(f"{name:8}{sim.total():3} instructions  {sim.counts}")print("same numbers:", all(r == results[0] for r in results), results[0])
scalar   48 instructions  {'loop': 8, 'sload': 16, 'smul': 8, 'sadd': 8, 'sstore': 8}
unfused  13 instructions  {'vsplat': 1, 'loop': 2, 'vload': 4, 'vmul': 2, 'vadd': 2, 'vstore': 2}
fused    11 instructions  {'vsplat': 1, 'loop': 2, 'vload': 4, 'vfma': 2, 'vstore': 2}
same numbers: True [2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]

The scalar version spends 48 instructions, six per element. The unfused vector version spends 13 and the fused one 11: the multiply and the add merged, so each pass loses one instruction. The three versions print the same numbers here because every result is exact; the next section shows the case where fusing changes a digit.

03

Build it up: rounding, names and savings

A floating-point multiply rounds its result to the nearest representable number, and so does the add that follows: two roundings. A fused multiply-add computes a * b + c as if with unlimited precision and rounds once at the end. Usually the difference is invisible, but not always, and a quant who reconciles a risk number between two machines needs to know why the last digits disagree. To make vfma behave like the hardware, compute each lane exactly with Fraction and call float() once.

main.pyPython
# One rounding or two: 0.1 * 3 is 0.30000000000000004 once roundedproduct = 0.1 * 3.0sim = LaneSim(4)print("two roundings:", [x * y + z for x, y, z in zip([0.1] * 4, [3.0] * 4, [-product] * 4)])print("one rounding: ", sim.vfma([0.1] * 4, [3.0] * 4, [-product] * 4))1print(sim.counts)
two roundings: [0.0, 0.0, 0.0, 0.0]
one rounding:  [-2.7755575615628914e-17, -2.7755575615628914e-17, -2.7755575615628914e-17, -2.7755575615628914e-17]
{'vfma': 1}
  1. 1The fused result keeps the part of the product that rounding threw away.

Subtracting the rounded product from the exact one leaves a tiny remainder, about -2.8e-17, which the two-step version loses completely. Neither answer is a bug. The point is that a fused kernel and an unfused one can differ in the last bits, so a test that compares them should use a tolerance. The graded tests of this lab compare against the exact, once-rounded value.

_mm256_fmadd_pd = _mm256 · _fmadd · _pd (width · operation · type)(1)Width: none for 128 bits, 256 or 512 otherwise. Operation: add, sub, mul, fmadd, loadu, storeu, set1. Type: ps for packed 32-bit floats, pd for packed 64-bit floats.

A name like this is a small table lookup, and that is what intrinsic_name does. Print the names of all seven instructions at three widths and two types and you will see why a codebase full of intrinsics reads like a dialect of its own: the width and the type are part of every name, so changing from doubles to floats means changing every call.

main.pyPython
# The names of the seven instructions at three widths, for 64-bit floatsfor op in INTRINSIC_OPS:    print(f"{op:7}", [intrinsic_name(op, bits, "f64") for bits in (128, 256, 512)])print(register_bits(4, "f64"), register_bits(4, "f32"), register_bits(8, "f32"))1
vadd    ['_mm_add_pd', '_mm256_add_pd', '_mm512_add_pd']
vsub    ['_mm_sub_pd', '_mm256_sub_pd', '_mm512_sub_pd']
vmul    ['_mm_mul_pd', '_mm256_mul_pd', '_mm512_mul_pd']
vfma    ['_mm_fmadd_pd', '_mm256_fmadd_pd', '_mm512_fmadd_pd']
vload   ['_mm_loadu_pd', '_mm256_loadu_pd', '_mm512_loadu_pd']
vstore  ['_mm_storeu_pd', '_mm256_storeu_pd', '_mm512_storeu_pd']
vsplat  ['_mm_set1_pd', '_mm256_set1_pd', '_mm512_set1_pd']
256 128 256
  1. 14 lanes of 32-bit floats fill only 128 bits; 8 lanes fill 256.
  • LaneSim instructionC intrinsic on 256 bits, 64-bit floats
  • vload(mem, i)Which call loads four doubles from any address?_mm256_loadu_pd
  • vsplat(x)And the one that copies a number into every lane?_mm256_set1_pd
  • vmul(a, b), vadd(a, b)Separate multiply and add?_mm256_mul_pd_mm256_add_pd
  • vfma(a, b, c)The fused one, which needs the FMA feature flag?_mm256_fmadd_pd
What the real data says5,400 SPY returns, y = alpha * x + y on 4 lanes
Scalar (instr.)32,4006 per element
Multiply, then add (instr.)8,1014.0x fewer than scalar
Fused (instr.)6,7514.8x fewer than scalar
Saved by fusing (instr.)1,350one per pass
Instructions for y = alpha * x + y
Scalar32400
Multiply, then add8101
Fused6751
main.pyPython
# The saving at the length of the leadprint(instruction_saving(5400, 4))scalar = LaneSim(4)scalar_axpy(scalar, 1.0, [0.0] * 5400, [0.0] * 5400)print(scalar.total(), round(scalar.total() / 6751, 2))
{'unfused': 8101, 'fused': 6751, 'saved': 1350}
32400 4.8
A fair baseline

Real CPUs also have a scalar fused multiply-add. Our scalar loop does not, so the 4.8x above is 4x from the lanes plus a bonus from fusing. Compared with a scalar loop that fuses too, the gain would be 4x.

04

Typical mistakes

Handing a plain number to a vector instruction. In C a type error stops the build; in LaneSim an exception does. vfma wants three registers, lists with one number per lane. A bare 2.0 is not even a list, and [2.0] is a list with the wrong number of lanes. The constant must go through vsplat first.

main.pyPython
# vfma wants registers, not a plain numbersim = LaneSim(4)r = sim.vload(x, 0)for bad in (2.0, [2.0]):    try:        sim.vfma(r, bad, r)    except Exception as error:        print(type(error).__name__ + ":", error)
TypeError: object of type 'float' has no len()
ValueError: register must have one number per lane

Mixing up width and type. A register of four 32-bit floats is only 128 bits, so _mm256_add_ps would take eight of them, not four, and _mm256_add_pd would misread the same memory as doubles. The compiler may accept both calls, since both are valid names, so the width and the type are yours to keep consistent. The register_bits line in the names example above is the check to make before choosing a prefix.

Writing an instruction the chip does not have. An intrinsic is tied to a CPU family. _mm256_fmadd_pd needs the FMA feature on top of AVX2, and a binary built with -mfma stops with an illegal-instruction error on an older machine. That is the problem the topic on runtime dispatch solves: choosing the version by what the CPU reports.

Do not compare fused results with ==

A test that checks a fused kernel against the unfused one with exact equality can fail by one bit for no bug at all. Compare with a tolerance, or against an exact reference as the lab does.

05

What the tasks ask

  • Task and functionWhat it must do
  • LaneSim.vfma(a, b, c)Return a * b + c per lane, rounded once, and count one vfma.uses Fraction
  • vector_axpy(sim, alpha, x, y)The kernel with one vsplat, then per pass loop, 2 vload, vfma, vstore.exact counts are tested
  • intrinsic_name(op, bits, dtype)The C name, from the instruction, the width and the type.three error checks, in order
  • instruction_saving(n, lanes)What fusing saves, measured by running both kernels on fresh machines.uses both kernels

Key takeaways

  • An intrinsic is an instruction Each call maps to one machine instruction, so you control exactly what runs, and the count in LaneSim is the count in the binary.
  • Fusing saves instructions and changes rounding A fused multiply-add rounds once, so it saves one instruction per pass and can differ from the two-step result in the last bits.
  • Names carry width and type _mm256_fmadd_pd says 256 bits, fused multiply-add, doubles; keep width and type consistent, and remember the chip must have the instruction.
Quick check
You write _mm256_add_ps(a, b) and the data is double (64-bit floats). What is wrong?
Pick an answer.

Next. Every kernel so far needed an array length that is a multiple of the lane count. Real arrays are not that polite: 5,404 returns on 4 lanes leave nothing over, but 5,405 leave one. The next topic deals with the leftover elements, the scalar tail, and with a second question the intrinsics raise: what it costs when a load starts at an address that is not a multiple of the register width.

Lab · what's graded

4 tasks · 100 pts
  • Multiply and add in one step with vfma25 pts
  • Write the kernel y = alpha * x + y with vector_axpy25 pts
  • Build the C name with intrinsic_name25 pts
  • Count what fusing saves with instruction_saving25 pts
Explorer · lab-4-1
▾ lab-4-1
…
bash · in-browser
learner@quantcraft:~/lab-4-1$
Python not loaded yetPythonLn 1, Col 1Spaces: 4UTF-8

Reset this topic?

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