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?
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.
#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}
- 1Once, before the loop:
vsplatin LaneSim. - 2One instruction does the multiply and the add.
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.
# 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.
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.
# 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}- 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.
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.
# 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
- 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
# 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.8Real 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.
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.
# 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.
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.
What the tasks ask
- Task and functionWhat it must do
- LaneSim.vfma(a, b, c)Return
a * b + cper lane, rounded once, and count onevfma.usesFraction - vector_axpy(sim, alpha, x, y)The kernel with one
vsplat, then per passloop, 2vload,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
_mm256_add_ps(a, b) and the data is double (64-bit floats). What is wrong?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 + ywithvector_axpy25 pts - Build the C name with
intrinsic_name25 pts - Count what fusing saves with
instruction_saving25 pts