Writing kernels: reductions, softmax, tiled matmul, fusion, FlashAttention

Writing CUDA kernels by hand, from a naive kernel to a tiled, coalesced, vectorised one, and the patterns a transformer is built from: reductions, scans, row norms, fusion, a 4-bit decode GEMV and FlashAttention, each written, tested and measured. Measured on an Apple M1 Pro GPU and compiled for NVIDIA GPUs without one; every number says which. A child of Topic: cuda-and-gpu-programming. Data as of October 2026. Reading: 34 min, plus 15 in closed details.

The idea in one screen

A kernel is fast when every byte it fetches from slow memory is used as many times as possible while it sits on chip. Each optimisation step of every kernel on this page (coalescing, tiles in shared memory, tiles in registers, wider loads, fusion) either moves fewer bytes per useful operation, or stops a result from making a round trip through global memory.

The matmul ladder: each rung asks slower memory for fewer bytes per multiply-add

Fig. 1 draws C = AB as a cube: C on the floor, A and B on the walls, the depth k of the dot products rising up them (a 256 × 256 corner of each). Each step is one rung of Simon Boehm's float32 worklog, rewritten in CUDA here (src/cuda/kernels/m_ladder.cu, his tile sizes): what one warp or block reads from global memory, what it keeps in shared memory, what one thread holds in registers, and on the right the global bytes each fused multiply-add (FMA) costs.

  1. 1. Naive. One thread per output of C. The 32 lanes of a warp take 32 rows of C in one column, so at every k they read A from 32 different rows: 32 separate 32-byte sectors for 128 useful bytes. Each FMA asks for 8 bytes and moves 33.global 33 bytes per FMA moved (8 asked) · shared 0 · 32 registers · A6000 309.0 GFLOP/s (1.3% of cuBLAS) · M1 Pro 229.20 ms
  2. 2. Coalesced. The same code with the two thread indices swapped: a warp now takes 32 columns of one row, reads one shared A value and 32 neighbouring B values, one 128-byte line: 8 bytes asked per FMA, 5 moved, 6.6 times fewer, close to the 6.4 times Boehm measured. Identical instructions; only the addresses differ.global 5 bytes per FMA moved (8 asked) · shared 0 · 32 registers · A6000 1,986.5 GFLOP/s (8.5%) · M1 Pro 47.53 ms
  3. 3. Shared-memory tiles. A block loads a 32 × 32 tile of A and of B into shared memory once, and every thread reads it 32 times. Global traffic falls to 0.25 bytes per FMA, but each FMA reads 8 bytes from shared memory, the new limit.global 0.25 · shared 8 bytes per FMA · 32 registers · A6000 2,980.3 GFLOP/s (12.8%) · M1 Pro 36.48 ms
  4. 4. 1D thread tile. Each thread computes 8 outputs of one column: one B value, held in a register, feeds 8 FMAs. Shared reads fall to 4.5 bytes per FMA, and the 64 × 64 block tile (K step 8) halves global traffic again. Not in the M1 lab.global 0.125 · shared 4.5 bytes per FMA · 44 registers · A6000 8,474.7 GFLOP/s (36.5%)
  5. 5. 2D thread tile. Each thread computes an 8 × 8 block of C as outer products: 8 A and 8 B values in registers feed 64 FMAs. Shared reads 1 byte per FMA, global 0.0625 (128 × 128 block tile). The price is registers: 158 per thread.global 0.0625 · shared 1 byte per FMA · 158 registers · A6000 15,971.7 GFLOP/s (68.7%) · M1 Pro 10.52 ms
  6. 6. Vectorised. The same traffic in fewer instructions (float4, 16 bytes per load, the larger dots): A is transposed as it is stored, so both register fragments load as LDS.128. Fewer registers let two blocks fit per SM instead of one. On the M1 the 8 × 8 version ran slower than 4 × 4.global 0.0625 · shared 1 byte per FMA · 127 registers · A6000 18,237.3 GFLOP/s (78.4%) · M1 Pro 13.43 ms
  7. 7. Beyond: warp tiles, autotuning, tensor cores. Boehm adds a warp-level tile and autotunes the sizes: 93.7% of cuBLAS. Production matmuls use tensor-core instructions instead of the FMA block. On the M1, its 8 × 8 matrix instructions (Kernel lab M7) take 5.10 ms against MLX’s 4.24 ms.A6000 21,779.3 GFLOP/s (93.7%) · M1 Pro 5.10 ms

Bytes per FMA are derived from the code as written, before caches (src/ladder.py; global traffic counted in 32-byte sectors per warp load); A6000 GFLOP/s are Boehm's published table (kernel 10 for rung 7); registers are compiled for sm_90a; M1 Pro times are the topic root's Kernel lab, measured on Apple M1 Pro GPU, n = 2,048, its nearest rung. Global traffic falls 528 times from rung 1 to rung 6. Rung 7's drawn warp tile is illustrative.

You need: threads, warps (32 threads issuing together), blocks, shared memory and barriers (__syncthreads()) from the programming model page; coalescing, bank conflicts and registers as hardware from the memory hierarchy page; and the ridge point (FLOPs per byte above which a kernel is compute-bound) from Performance math. The topic root is Topic: cuda-and-gpu-programming.

Reuse
how many FMAs each loaded value feeds while it sits in shared memory or a register.
Tile
the block of a matrix one block (block tile) or one thread (thread tile) works on, kept on chip.
Reduction, scan
many numbers into one; running totals (prefix sums).
Shuffle
a register value passed directly between lanes of a warp, no shared memory, no barrier.
Fusion, epilogue, prologue
doing two operations in one kernel; an operation applied to a matmul's output while still in registers, or to its input as it is loaded.
Online softmax
a running max and sum that rescale when a larger value arrives, so partial results merge exactly.
Split-KV (Flash-Decoding)
decode attention split over chunks of the keys, merged at the end.
What is real on this page
There is no NVIDIA GPU here. Timings are measured on Apple M1 Pro GPU, a real SIMT GPU whose SIMD-groups of 32 threads, threadgroups and threadgroup memory are a warp, a block and shared memory under other names: Metal kernels through MLX 0.32.3, each checked against float64 before timing, 3 runs of 7 trials, median shown, the machine's load recorded (the laptop was shared; Kernel bench (M1) shows the spread). NVIDIA behaviour is compiled output (CUDA 13.4.2, the same kernels in CUDA C++ for sm_80, sm_90a and sm_120, no GPU; Compiled for NVIDIA) and published papers; arithmetic on these is derived, with its formula. The shape of each M1 result transfers; the absolute speeds do not.
The patterns in one table, and the method used for each (reference)
PatternIn a transformerWhat limits itThe trickHere
Tiled matmulevery linear layer, QKT and PVarithmetic, if every loaded value is reused enoughtiles in shared memory, then in registers, then tensor cores1
Reducerow max and sum in softmax, norms, the loss, gradient normsbytes read; then the cost of combining partial resultseach thread sums many values in a register; a warp combines 32 with shuffles; one partial per block2
ScanMoE token routing offsets, top-p sampling, ragged batches, cumsumeach output depends on every earlier inputscan tiles in parallel, then add each tile's offset; CUB does it in one pass3
Row normalisesoftmax, LayerNorm, RMSNormbytes; and numerics (overflow, cancellation)one block per row, the row kept in registers; online or Welford statistics4
Fusebias + activation, residual + norm, dequantise + GEMVthe round trip of an intermediate through global memoryapply the cheap operation while the data is still on chip5, 6
AttentionattentionN × N intermediates; then the exponentials; then idle SMstiles plus online softmax (FlashAttention), then scheduling7

One method for all of them: write the reference first (float64 NumPy or PyTorch) and a test with a tolerance chosen for the data type (section 8); write the obvious kernel, make it pass, and measure it against a ceiling (for a memory-bound kernel, the time a plain copy of the same bytes takes; for a compute-bound one, the peak arithmetic rate): the gap is what is left to win. Then find what limits it (a profiler on NVIDIA, see the profiling page; here, counting bytes and reading the compiled instructions), remove that limit, re-test, re-measure. Stop when you reach the ceiling or the library.

1. The matmul ladder: what each rung buys

C = AB for n × n matrices does 2n3 operations on 3n2 numbers, so each number loaded could be used n times: a question of reuse. Boehm's worklog (December 2022) climbs from 309 to 21,779 GFLOP/s on an RTX A6000, 1.3% to 93.7% of cuBLAS, in ten kernels published. Read Fig. 1 as three moves, one per level of memory:

  • Coalesce (rung 2). The code of rungs 1 and 2 differs only in which thread index walks rows, and compiles to the same instructions compiled (counts in the closed table below). Coalescing, worth 6.4 times on Boehm's A6000, is invisible in the code: only the addresses the 32 lanes touch at once differ. A profiler's sectors-per-request metric finds it (memory hierarchy page, section 1).
  • Tile into shared memory, then into registers (rungs 3 to 5). The ratio that rises is FFMA per shared load: 0.7 for plain tiles, 1.6 with a column of 8 outputs per thread, 8 with an 8 × 8 block per thread, because each shared value read into a register feeds 8 multiply-adds. Shared-memory bandwidth, not global, limits rungs 3 and 4.
  • Vectorise (rung 6). nvcc already vectorised rung 5's shared loads (32 of its 64 are LDS.128). The explicit float4 code bought fewer instructions around them (1,047 down to 731: less address arithmetic, 16 STG instead of 64) and fewer registers (158 down to 127).

Registers decide how many blocks fit. With NVIDIA's allocation rules (registers per warp rounded up to 256, 64K per SM, as reproduced by the root's GPU simulator), 158 registers allow 12 warps per SM, one block of 8 warps; 127 allow 16 warps, two blocks derived: one computes while the other waits at its barrier.

Beyond the CUDA-core ladder. After Boehm's last rungs, the final shape, block tile, then warp tile, then thread tile, is CUTLASS's. Real training matmuls use tensor-core instructions (mma.sync, wgmma, tcgen05; libraries and tensor cores page) and load the next tile while computing this one (memory hierarchy page, section 6). The rule that does not change: count FLOPs per byte at each level of the hierarchy, and make it larger. And, as the M1 shows (the 32 × 32 tile slower than 16 × 16, 36.48 against 26.90 ms), the best tile sizes differ from GPU to GPU, which is why every serious matmul library autotunes, and each rung's fix comes from profiling the previous one, not from a recipe.

The compiled table, Boehm's numbers and the inner loops (depth)

The hero's numbers, rung by rung. Bytes per FMA derived (src/ladder.py); A6000 published (Boehm, kernel 10 for rung 7); M1 Pro measured, the root's Kernel lab, n = 2,048, its nearest rung.

Rungglobal bytes per FMAshared bytes per FMAA6000 GFLOP/s (% of cuBLAS)M1 Pro
1 Naive33 (8 asked)0309.0 (1.3%)M1 naive, uncoalesced: 229.20 ms
2 Coalesced5 (8 asked)01,986.5 (8.5%)M2 naive, coalesced: 47.53 ms
3 Shared-memory tiles0.2582,980.3 (12.8%)M4 tiled 32x32: 36.48 ms
4 1D thread tile0.1254.58,474.7 (36.5%)no matching rung
5 2D thread tile0.0625115,971.7 (68.7%)M5 4x4 outputs per thread (registers): 10.52 ms
6 Vectorised0.0625118,237.3 (78.4%)M6 8x8 per thread + float4: 13.43 ms
7 Warp tile, autotunedn/an/a21,779.3 (93.7%)M7 8x8 matrix instructions + threadgroup tiles: 5.10 ms

The lab's other matmul cases: M3 tiled 16x16 in threadgroup memory 26.90 ms, M7a 8x8 matrix instructions, from device memory 5.54 ms, M7nu M7 with loops not unrolled 174.96 ms, MLX library A @ B 4.24 ms. Rung 2 moves 6.6 times fewer bytes than rung 1 by this count (33 / 5), against the 6.4 times Boehm measured; from rung 1 to rung 6 global traffic falls 528 times.

Nothing here ran on an NVIDIA GPU; it is all compiled (CUDA 13.4.2, sm_90a = H100, counts are static: how often an instruction appears in the binary, not how often it runs). Rungs 1 and 2 compile to the same instructions: 185 each for sm_90a, 29 FFMA, 58 global loads; 187 each for sm_80; for sm_120 the compiler unrolled them differently, 136 and 163, with the same loads per multiply-add.

RungChangeregsFFMAshared loadsFFMA per shared load
k1 naiveone thread per output; threadIdx.x walks rows32290n/a
k2 coalescedthreadIdx.x walks columns32290n/a
k3 shared tiles32 × 32 tiles of A and B in shared memory3232480.7
k4 1D thread tileeach thread 8 outputs of one column4464401.6
k5 2D thread tileeach thread an 8 × 8 block, outer products158512648.0
k6 vectorisedA transposed into shared memory, float4 everywhere127512648.0

FFMA = fused multiply-add; shared loads = LDS plus LDS.128 instructions. The Compiled for NVIDIA tab has the same table for sm_80 and sm_120 and every opcode family; the source is src/cuda/kernels/m_ladder.cu.

Boehm's summary table published (kernels 7 and 8, two bank-conflict experiments, are not in it): naive 309.0 GFLOP/s (1.3%), global memory coalescing 1,986.5 (8.5%), shared memory blocking 2,980.3 (12.8%), 1D blocktiling 8,474.7 (36.5%), 2D blocktiling 15,971.7 (68.7%), vectorized mem access 18,237.3 (78.4%), autotuning 19,721.0 (84.8%), warptiling 21,779.3 (93.7%), cuBLAS 23,249.6 (RTX A6000, 4,092 × 4,092, float32).

Correction to the old page
The old page gave kernel 6 as 81% and kernel 9 as 94% of cuBLAS; the worklog's own table says 78.4% and 84.8% (93.7% is kernel 10, warp tiling). It also said "expect higher absolute FLOPs but the same ratios on a 5090": there is no NVIDIA GPU here to check that, so the ratios are compared with the M1 (the root's Kernel lab) and the binaries with three NVIDIA targets instead.

The inner loop of rungs 5 and 6, as compiled. The .reuse flags are the compiler marking an operand it can keep in the register-file cache for the next FFMA.

k5, sm_90a
k6, sm_90a

2. Reductions: many numbers into one

Sum 225 (33.5 million) floats. On a GPU thousands of threads each sum a part, and combining the parts is where every difficulty lives: threads in different blocks cannot see each other's shared memory or wait for each other inside one launch. The answer is a tree: half the threads each add two numbers, then a quarter add two partial sums; after log2(256) = 8 steps one thread holds the block's total, and a second, tiny launch (or an atomic add) combines the block totals.

Mark Harris's Optimizing Parallel Reduction in CUDA (NVIDIA, 2007) is the classic ladder: seven kernels for summing 4M integers on a G80, each fixing one problem, from 2.083 to 62.671 GB/s, 30.04 times faster, and 73 GB/s on 32M elements against the G80's 86.4 GB/s peak published. Its first three rungs differ only in which threads add which elements; Fig. 2 plays them, and the warp shuffle, on the same 16 numbers:

  1. The input. 16 values in shared memory, 4 warps of 4 lanes (the colours), banks b0 to b3. Harris rung 1, interleaved: at stride s, threads whose index is a multiple of 2s add.
  2. Stride 1. Multiples of 2 add the value 1 to their right: 8 additions, but all 4 warps issue, so 8 lanes idle (orange lamps). A barrier (dashed red line) follows every shared-memory step.
  3. Stride 2. Multiples of 4 add the value 2 to their right: 4 additions; all 4 warps still issue, 12 lanes idle.
  4. Stride 4. Multiples of 8: 2 additions, 2 warps issue, 6 lanes idle.
  5. Stride 8. Thread 0 adds element 8 and the sum, 48, is in element 0. In all: 15 additions, 29 idle lanes, 4 barriers. Whole warps issue for one working lane (divergence: lanes of one warp taking different branches run one after the other).

A toy GPU: warps of 4 lanes and 4 banks (real: 32 of each); dots flow from the value a thread reads to the one it writes, one row per step, front to back. Counts checked against src/tree_model.py; the two scans of section 3 run on the same toy in Fig. 3.

All six on the same input, totals (table)

Additions: useful adds. Active lanes: lane-steps doing work. Idle lanes: lanes of issued warps with nothing to do. Barriers: __syncthreads() after each shared-memory step. Shared-memory transactions: per warp and per access (read source, read destination, write destination), the largest number of distinct addresses in one bank, summed; a value above the number of warp requests means bank conflicts. The reductions end with the sum, 48, in element 0; Hillis-Steele with the inclusive scan; Blelloch with the exclusive scan.

We re-ran the ladder in Metal on 225 floats measured on Apple M1 Pro GPU. Harris's last rung was 30 times his first; predict ours.

On the M1 Pro, R6 (grid-stride, vector loads, SIMD sums) against R1 (interleaved, divergent):

Why the ladder flattened. The G80 of 2007 had little on-chip cache and slow integer arithmetic, so index arithmetic, idle lanes and barriers cost more than the memory traffic. A modern GPU has far more arithmetic per byte (a higher ridge point), so a reduction is limited by reading the input almost however clumsily it combines; the remaining gap is R1 to R3's 8 barriers per 256 values. The lesson that survives: do most of the work in registers, one value per element, and make the tree as small as possible (a grid-stride loop: a fixed grid where each thread sums many elements in a register first). That is what every production reduction does.

The whole reduction ladder spans less than 2 times on the M1 Pro

Median of 3 runs; the thin line spans the fastest and slowest of all 21 trials. Each time includes MLX's per-call launch-and-wait overhead, about 0.2 ms by the topic root (its section 1), so the kernels are faster than shown and their differences larger in proportion.

Harris's seven rungs by name (depth)
1 Interleaved, divergentAt step s, threads with tid % (2s) == 0 add. Most lanes of every warp sit idle while the warp still issues.
2 Strided indexThread t works on element 2st: active threads are now contiguous, but their addresses are strided, so several lanes hit the same shared-memory bank (shared memory is split into 32 banks).
3 Sequential addressingHalve the range each step: thread t adds element t + s. Contiguous threads, contiguous addresses.
4 First add during loadHalf the blocks; each thread loads two values and adds them on the way in, so no thread starts idle.
5 Last warp unrolledThe last 32 values are summed by one warp. Harris did it with "warp-synchronous" shared memory; today you use shuffles (below).
6, 7 Unrolled, many per threadTemplates remove loop overhead; then the grid-stride loop, so the tree runs once per thread block, not once per 512 elements.

Inside a warp: shuffles

A shuffle moves a register value from one lane of a warp to another. Five sum 32 values; compiled for sm_90a compiled it is exactly five shuffle-and-add pairs, and the mask 0xffffffff says all 32 lanes take part.

Since Volta (2017) the lanes of a warp are not guaranteed to run in lockstep, so old "warp-synchronous" code that reads other lanes' shared-memory writes without a barrier is a bug: use the *_sync shuffles or __syncwarp().

Correction to old habits: why "warp-synchronous" code broke (depth)
Harris's rung 5 relied on the 32 lanes of a warp executing in lockstep, reading each other's shared-memory writes with no barrier. Since Volta (2017), lanes of a warp can be scheduled independently, and NVIDIA's Volta tuning guide says plainly: "Assumptions that code is executed in lockstep or that reads/writes from separate threads are visible across a warp without synchronization are invalid." Use the *_sync shuffles, or __syncwarp() between shared-memory steps. Old tutorials (and old kernels) still contain the volatile trick.

Five shuffles sum a warp: five SHFL and FADD pairs in the binary

The source
__device__ float warp_sum(float v) {
  for (int o = 16; o > 0; o >>= 1)
    v += __shfl_down_sync(0xffffffffu, v, o);   // add the value held by lane (lane + o)
  return v;                                     // lane 0 holds the sum of all 32
}
As compiled for sm_90a

Combining blocks

Four ways to turn one partial per block into one number: (1) a second, small launch (R1 to R6 above); (2) every block does an atomic add into one output (A1: one launch, 1.05 ms); (3) the last block to finish, detected with an atomic counter, reduces all partials (PyTorch's choice); (4) a cooperative launch, where grid.sync() makes every block wait for all others (all blocks resident at once, which limits the grid).

What PyTorch does, and a correction to the old page (depth)
PyTorch's Reduce.cuh keeps a global buffer and a semaphore per output when a reduction spans blocks (source excerpt in src/inputs/pytorch_extracts.txt, PyTorch main at commit 8d1d972, read 2026-10-05). The old page said "in library code use CUB (cub::BlockReduce, cub::DeviceReduce), which is what PyTorch does". For sums, PyTorch does not: torch.sum on CUDA calls its own gpu_reduce_kernel (ReduceSumProdKernel.cu). It does use CUB for a one-dimensional cumsum (section 3). CUB is still the right thing to call in your own CUDA code: cub::BlockReduce compiles to the same five shuffles per warp (Compiled for NVIDIA).

The order of additions changes the answer

Floating-point addition is not associative: (a + b) + c can differ from a + (b + c) in the last bits.

The 225 inputs are uniform in [0, 1), so the exact sum is about 16.8 million. Add them one by one into a single float32 accumulator, in order. What comes out?

Atomics make the order, and so the bits, change from run to run. We ran the atomic kernel A1 30 times on the same input in each of the 3 runs: it gave 7, 6, 8 distinct results (from 16,777,702 to 16,777,718), because the blocks arrive in a different order each time; the two-launch tree gave one result every time measured on Apple M1 Pro GPU. Hence torch.use_deterministic_algorithms(True), "identical" training runs that drift apart, and tests with a tolerance rather than bit for bit (section 8).

3. Scan: running totals

An inclusive scan (prefix sum) turns x0, x1, x2, ... into x0, x0+x1, x0+x1+x2, ...; an exclusive scan shifts it by one and starts at 0. Every output depends on every earlier input, yet it is everywhere in model code: a mixture-of-experts layer scans per-expert token counts into offsets in a packed buffer; top-p sampling scans sorted probabilities; sequence packing scans lengths into offsets; torch.cumsum is a scan. Two parallel algorithms (GPU Gems 3, chapter 39, Harris, Sengupta and Owens), both run in Fig. 3 on Fig. 2's toy:

Hillis and Steele

Step k: every element adds the one 2k places to its left: log2(n) steps, but O(n log n) additions: for n = 224, 386 million adds against 16.8 million for a loop derived, Σk<24(n − 2k). Fine inside a warp.

Blelloch (work-efficient)

An up-sweep builds a reduction tree, a down-sweep pushes prefixes back down: "approximately 2 × (n − 1) adds and n − 1 swaps", 33.6 million for n = 224 derived, but twice the steps.
  1. The input. The same 16 values. Inclusive scan, Hillis and Steele: log2(16) = 4 steps, every element busy.
  2. Offset 1. Every element adds the one 1 to its left, reading from the previous copy (a double buffer): 15 additions.
  3. Offset 2. Every element adds the one 2 to its left: 14 additions.
  4. Offset 4. Every element adds the one 4 to its left: 12 additions.
  5. Offset 8. 8 more additions and the row is the inclusive scan, ending at the total, 48. In all 49 additions where a loop needs 15: the price of every lane busy at every step.

On a real GPU neither runs across the whole array. Inside a warp a scan is five shuffles (__shfl_up_sync; Metal's simd_prefix_exclusive_sum); across a block, warps exchange totals through shared memory; across blocks is hard, because block 7 needs the total of blocks 0 to 6. Reduce, then scan takes three launches: each block sums its tile; one block scans the tile sums into offsets; each block scans its tile again and adds its offset. Input read twice, output written once: 3 passes over memory, against 2 for a copy. Decoupled look-back does it in one pass (cub::DeviceScan; below; not run here).

On 224 floats measured on Apple M1 Pro GPU, Hillis and Steele over the whole array (24 launches, each reading and writing everything) takes 18.81 ms; the three-launch scan 1.41 ms, 13.4 times faster and 1.41 times a plain copy (1.00 ms), close to the 3 : 2 ratio of passes that counting bytes predicts. MLX's library mx.cumsum took 7.78 ms on the same input, 5.5 times slower than our 40 lines (code in Kernel bench (M1)): libraries are not always at the ceiling; the copy time tells you.

The three-launch scan runs at 1.41 times a copy; MLX's cumsum is 5.5 times slower than it

224 floats, median of 3 runs, measured on Apple M1 Pro GPU.

Decoupled look-back, and what PyTorch calls (depth)

Decoupled look-back (Merrill and Garland, NVIDIA, 2016) scans in one launch: each block publishes its own total as soon as it has it, and its inclusive prefix once it knows it; a block that needs its offset looks back at its predecessors' published values, summing totals until it meets a published prefix. It "requires only ~2n data movement" and its throughput "approaches that of copy operations" published. It relies on earlier blocks making progress while later ones wait, a guarantee Metal does not document, so we did not run it here.

In PyTorch, a one-dimensional torch.cumsum on CUDA calls cub::inclusive_scan, and a separate inclusive_deterministic_scan for floating-point types when deterministic algorithms are requested (ScanUtils.cuh, read 2026-10-05): the default single-pass scan can add in an order that depends on timing, for the same reason as the atomic sum of section 2.

4. Row normalisation: softmax, LayerNorm, RMSNorm

Softmax, LayerNorm and RMSNorm all compute one or two statistics of each row (a reduction), then rewrite every element with them. A transformer row is one token, a few thousand numbers, so the standard layout is one block per row, each thread keeping its share in registers between the statistics and the rewrite: read once, written once. Arithmetic is a handful of operations per element; the speed is set by bytes.

The softmax ladder: one change matters

One thread per row (S1) takes 177.14 ms: neighbouring threads read addresses a whole row (16 KB) apart. One threadgroup per row, neighbouring threads on neighbouring elements (S2), takes 3.54 ms, 50 times faster, at 92% of copy speed. SIMD-group reductions, float4 loads, the online softmax (two passes) and the row held in registers (one pass, S6, 3.27 ms) together are worth about 8%; the five-kernel eager version takes 13.08 ms (10.09 under mx.compile). S2 reads each row three times yet runs near copy speed, most likely because a 16 KB row is still in cache when re-read unconfirmed, not profiled. The idea to carry forward is the online softmax (Milakov and Gimelshein, 2018): keep a running maximum m and a running sum d of ex − m; when a larger value arrives, rescale the sum you have.

m′ = max(m, xi)    d′ = d · em − m′ + exi − m′
merge (ma, da) with (mb, db): m = max(ma, mb),   d = da ema − m + db emb − m

The second line makes it parallel: any two partial results, from two lanes, warps or tiles, combine exactly, in any order. Any reduction more than a sum needs such a merge; FlashAttention (section 7) is built on this one.

One threadgroup per row instead of one thread is worth 50 times; every later rung stays within 13% of a plain copy

The topic root's Kernel lab, 16,384 rows of 4,096 float32 (256 MiB in, 256 MiB out), median of 3 runs, measured on Apple M1 Pro GPU; data copied to src/inputs/root_kernel_lab_matmul.json. A plain copy of the same bytes at the lab's 164.7 GB/s takes 3.26 ms derived, 512 MiB / 164.7 GB/s.

LayerNorm: the variance is a numerical trap

LayerNorm: y = (x − μ) / √(σ2 + ε) · γ + β. The tempting one-pass variance, σ2 = E[x2] − E[x]2, subtracts two large, nearly equal numbers when the mean is large compared with the spread, and float32 keeps about 7 significant digits.

Rows of 4,096 float32 values with standard deviation 1 and mean 3,000. Our kernel computes the variance as E[x2] − E[x]2. How wrong is the normalised output (largest error against float64)?
Row meantwo-passE[x²] − E[x]²Welford
06.8e-077.3e-079.1e-07
305.7e-065.4e-044.1e-06
3006.0e-056.5e-026.5e-05
3,0006.3e-041,6536.0e-04

Largest absolute error against float64, 256 rows of 4,096, standard deviation 1, γ near 1. The good methods' error grows with the mean because the float32 input carries about 7 digits: at mean 3,000 each value is already rounded to 0.0002.

When the row fits in registers, two passes are as cheap as one and simpler.

Timings of the three LayerNorm kernels, and Welford's algorithm (depth)

All three kernels took 1.74 to 1.77 ms on 8,192 rows of 4,096 (154 GB/s counting one read and one write), against 1.87 ms for MLX's mx.fast.layer_norm and 9.87 ms for the same formula as seven separate MLX operations (6.79 ms under mx.compile) measured on Apple M1 Pro GPU.

Welford's algorithm keeps a count n, a mean and M2 (the sum of squared deviations), updating them per value; partial results merge with the pairwise formula of Chan, Golub and LeVeque (the parallel algorithm, summarised), which has exactly the shape of the online-softmax merge:

δ = μb − μa,   n = na + nb,   μ = μa + δ nb/n,   M2 = M2a + M2b + δ2 nanb/n
μ, M2
mean and sum of squared deviations of each part; variance = M2 / n

Welford matters when the row is streamed once from memory, as in a long row or a fused kernel that cannot keep it.

RMSNorm, fused with the residual add

RMSNorm drops the mean: y = x / √(mean(x2) + ε) · γ. In a pre-norm block it follows a residual add, h = x + r, and h is needed twice: normalised for the next layer, raw as the next residual. Count the passes first:

So at best 5 : 4 = 1.25 times faster derived. Measured: 4.03 ms for MLX's add then mx.fast.rms_norm (4.09 ms under mx.compile, which did not fuse them), 3.35 ms fused, 1.20 times measured on Apple M1 Pro GPU. Production engines ship exactly this kernel: vLLM declares fused_add_rms_norm(input, residual, weight, epsilon) next to its plain rms_norm (csrc/ops.h, read 2026-10-05).

Fusing the add into the norm saves one pass over the activations: 5 become 4

5. Fusion: keep it on chip

Two kernels in a row hand their intermediate over through global memory; a fused kernel does both while it is in registers or shared memory. Fusion pays when that round trip is a large part of the time, which gives three rules: chains of memory-bound operations (elementwise, norms) fuse to nearly the cost of one (the RMSNorm above); a cheap operation applied to a matmul's output while still in registers (an epilogue) or to its input as it is loaded (a prologue) removes one round trip of that matrix; and fusing work into a compute-bound loop can lose, because the loop was not waiting for memory.

Epilogue: matmul, bias, GELU

y = GELU(xW + b) for 4,096 tokens, 4,096 outputs, K = 1,024 or 256 inputs, float32. Unfused, the matmul writes C (64 MiB) and a second kernel reads it back: 134 MB of extra traffic, about 0.9 ms at this GPU's copy speed derived. Our fused kernel is the Kernel lab's fastest matmul (8 × 8 matrix instructions, 64 × 64 tile per threadgroup) plus the epilogue. Fig. 5 follows the unfused pair and three attempts at fusing, K = 1,024 measured on Apple M1 Pro GPU:

  1. Unfused, kernel 1. The matmul reads x and W, accumulates each tile in registers and writes C, 64 MiB, to global memory.
  2. Unfused, kernel 2. A second kernel reads C back, adds b, applies GELU, writes y. Together 10.71 ms; C's round trip alone is 134 MB.
  3. Fused 1: stage the whole tile in shared memory, then apply the epilogue: 13.76 ms, slower than not fusing. The 16 KB staging buffer tripled threadgroup memory (8 KB to 24 KB), so fewer threadgroups fit on each GPU core for the whole matmul: the occupancy cliff the hardware topic measured on this GPU (GPU architecture). Shared memory is not free.
  4. Fused 2: apply it to the accumulator registers directly, then store. Each lane of a SIMD-group holds 2 of the 64 values of every 8 × 8 accumulator, fixed by the hardware; we read the mapping from MLX's own kernels (steel/gemm/mma.h, get_coord). With the accurate precise::tanh: 11.40 ms, still slower. In a separate kernel GELU's arithmetic hid behind memory traffic; inside the matmul it adds to a compute-bound kernel's time (on NVIDIA: -use_fast_math or intrinsics such as __expf; check the error you accept).
  5. Fused 3: the same, with fast::tanh (it differs from the precise version by at most 5 × 10−7, a side experiment in src/m1/out/side_experiments.txt): 10.07 ms against 9.92 ms for the matmul alone. The epilogue costs 0.16 ms and saves 0.64 ms against the unfused pair; at K = 256, where the saved bytes weigh more, 3.45 becomes 2.86 ms.

MLX's eager version (matmul, add and four elementwise GELU kernels) took 17.47 ms and 9.24 ms under mx.compile, which fuses the elementwise chain into one kernel after MLX's (faster) matmul. So compare a fused kernel against the compiled framework, not eager mode: our epilogue looked 1.7× faster than eager and was 0.92× of compiled MLX.

The fused epilogue costs 0.16 ms over the matmul alone, and compiled MLX is faster still

K = 1,024, 4,096 × 4,096 outputs, float32; median of 3 runs, measured on Apple M1 Pro GPU.

Where epilogues live in NVIDIA's libraries, CUTLASS and Triton (depth)

On NVIDIA you rarely write this epilogue yourself: cuBLASLt takes it as a parameter (CUBLASLT_EPILOGUE_GELU_BIAS, "apply Bias and then GELU transform", plus _AUX variants that also save GELU's input for the backward pass and DGELU for the backward itself; cublasLt.h in CUDA 13.4.2, excerpt in src/inputs/), and CUTLASS composes epilogues as trees of operations on the accumulator fragments (its epilogue visitor trees), exactly what attempt 3 does by hand; in Triton you write the epilogue as ordinary code after the tl.dot loop (Triton and Gluon page). Fusing two compute-bound matmuls into one kernel rarely pays: the tensor cores are already busy, and holding both operands raises register pressure.

A prologue that lost. Folding RMSNorm into the next matmul (10.44 ms) was slower than running it separately (10.15 ms, K = 1,024): the extra shared-memory reads landed in the compute-bound inner loop, the third rule (details below).

Prologue: RMSNorm folded into the next matmul, and why it lost (depth)

rmsnorm(x)W = diag(1/rms(x)) · x · (diag(γ)W). Fold γ into W offline; the matmul loads every element of x anyway, so it can accumulate each row's sum of squares as the tiles go by and scale each output row by 1/rms(x) in the epilogue: the normalised x is never written. Did it pay measured on Apple M1 Pro GPU?

K = 1,024ms
MLX: mx.fast.rms_norm, then its matmul8.40
ours, separate: RMSNorm kernel, then our matmul10.15
ours, fused, first attempt (16 KB staging tile)15.03
ours, fused, epilogue in registers10.44

No. The separate RMSNorm kernel moves only 32 MB and costs about 0.2 ms; the fused version adds shared-memory reads of every A tile to the matmul's inner loop, which is the bottleneck, and loses more than it saves (at K = 256 too: 2.72 separate, 2.83 fused). That is the third rule. Production kernels that fuse a norm into a GEMM (say to quantise activations to FP8 on the way in) do it where the GEMM is memory-bound, at small batch. Every case, with code, K = 256 numbers and spreads, is in the Kernel bench (M1) tab.

6. Decode: a matrix times one vector, with 4-bit weights

Generating one token for one user, every linear layer multiplies its weights by a single vector: a GEMV. Each weight is read once and used once, so the time is weight bytes over memory bandwidth, and only fewer bytes go faster: hence 4-bit decode weights. The GPU cannot multiply 4-bit codes; they must be dequantised (code × scale + bias, per group). As a separate kernel that writes a full 16-bit copy of the matrix and reads it back, three times the bytes you hoped to save; inside the GEMV, in registers, only the 4-bit bytes cross the memory bus.

One MLP projection of Llama 3 8B, 14,336 × 4,096, in MLX's 4-bit format (groups of 64 weights, a float16 scale and bias each): 117.4 MB in float16, 33.0 MB in 4 bits, 0.5625 bytes per weight, 3.56 times fewer derived, 0.5 + 4/64.

  • Dequantise, then GEMV: 1.84 ms, twice the float16 GEMV (1.02 ms ours, 0.94 ms MLX): the worst of both.
  • Fused, one thread per row: 2.70 ms. Neighbouring threads read addresses a row (2 KB) apart: rung 1 again.
  • Fused, one SIMD-group (warp) per row, lane l reading 4-byte words l, l + 32, ...: 0.46 ms, 2.2 times the float16 GEMV. A further rung with 16-byte loads did not help (0.46 ms); MLX's mx.quantized_matmul took a median 0.67 ms with a best of 0.39 ms, noisy on a shared machine.

Why 2.2 times, not 3.56? Merely reading the codes takes 0.38 ms. Fitting time = t0 + bytes / bandwidth through it and the float16 GEMV gives 139 GB/s and a fixed 0.17 ms per call derived, the launch-and-wait overhead the root measured; it predicts 0.41 ms for the fused kernel's bytes. So the fused kernel runs at the memory system's speed, and the fixed launch cost keeps a 33 MB kernel from a 3.56× win. A decode step launches hundreds of such kernels, which is why engines capture them in CUDA graphs (streams and graphs page).

Fused into the GEMV, 4-bit weights run at 2.2 times float16; dequantising first is the worst of both

measured on Apple M1 Pro GPU. Every kernel checked against a float64 product with the same dequantised weights. The last bar only reads the 4-bit codes (a sum over them), for scale.

What the NVIDIA compiler makes of the unpacking, and batches beyond one token (depth)

The same kernel in CUDA (src/cuda/kernels/g_dequant_gemv.cu, compiled) shows, per 4-byte word, a LOP3 (mask) and SHF (shift) per code and an I2FP (integer to float) per code, before the FFMA. It also shows a flaw we did not see in the source: the eight float16 activations per word are fetched with eight separate 2-byte loads (LDG.E.U16). Production kernels avoid both costs: they load activations in 16-byte vectors, and convert codes to half precision with bit tricks (PRMT and LOP3 on packed pairs) instead of one conversion per code.


With a batch of b tokens each weight is used b times, and the kernel turns into a matmul whose arithmetic eventually catches up with the saved bytes. Marlin (Frantar et al., 2024) is a 4-bit-weight, 16-bit-activation kernel designed to keep the full win as long as possible: "batchsizes up to 16-32 can be supported with close to maximum (4×) quantization speedup", and up to 2.8 times end to end inside vLLM published. The quantisation formats themselves (GPTQ, AWQ, GGUF k-quants) are the quantization and precision page's and C++: reading llama.cpp, section 10's; on this toy, 4 bits moved the output by up to 8.5% of its largest value against float16 weights measured (random weights, round-to-nearest, no calibration).

7. FlashAttention, step by step

FlashAttention is sections 1, 2, 4 and 5 composed: it tiles Q, K and V, computes each tile of scores S = QKT on chip, folds it into the output with the online-softmax merge of section 4, and never writes the N × N matrices S and P to memory. The FlashAttention paper page runs it on a real input (Run the kernel) and follows FA-1 to FA-4 (Then and now); the topic root's Kernel lab builds a FlashAttention-style Metal kernel. Here: what changed in each version and why, measured where the M1 can show it. First the algorithm, in Fig. 6, on a toy small enough to see every number:

  1. Everything starts in global memory. Q, K and V of one head. Standard attention would write S = QKT and P = softmax(S), both N × N, there too (the dashed square). Here one block of 4 query rows meets N = 16 keys in 4 tiles of 4, head dimension d = 4.
  2. Load the Q tile once. The block's 4 query rows stay on chip for the whole loop; each starts with m = −∞, ℓ = 0 and O = 0.
  3. Tile 1. K and V tile 1 come up. S = QKT/√d for this tile (the 4 × 4 bars); each row's running maximum m and sum ℓ = Σ es − m start from it, and O = PV for the tile, unnormalised.
  4. Tile 2: a larger score arrives. Rows 1 and 2 meet a score above their maximum (highlighted): m rises, so ℓ and O are first multiplied by emold − mnew < 1, then this tile's terms are added. Rows 3 and 4 add without rescaling.
  5. Tile 3. Only row 4's maximum rises; the merge is the same for every tile, so tile order does not matter.
  6. Tile 4. Rows 1 and 2 rise again. Each row's (m, ℓ, O) now covers all 16 keys, and no tile of S or P ever left the chip.
  7. Normalise once, write once. O is divided by ℓ (FA-2's first change, below) and written with L = m + log ℓ for the backward pass. The result equals softmax(QKT/√d)V in one piece, to rounding (the page's checks recompute it). Global traffic: Q, K and V read once, O written once, not S and P's N2 values per head.

An illustrative toy: Q, K and V drawn from a seeded generator and computed in the page (window.WKFT); bar heights are the real values of that toy. Orange m, teal ℓ, purple O.

FlashAttention-2: three changes

FlashAttention-2 (Dao, July 2023) starts from one number: an A100 does "312 TFLOPs/s of FP16/BF16 matmul, but only 19.5 TFLOPs/s of non-matmul FP32", so every non-matmul operation (the exponentials, the rescaling, the max) costs 16 matmul FLOPs published. It reports about 2× over FA-1 and 50 to 73% of A100 peak, from three changes:

  1. Fewer non-matmul operations. Keep the output unnormalised and divide by the running sum once, at the end; store one number per row for the backward pass, the logsumexp L = m + log ℓ, instead of m and ℓ. The Kernel lab's kernel already does this.
  2. Parallelise over the sequence, not only batch × heads. FA-1 gave each (batch, head) pair one thread block looping over all query blocks; with long sequences and small batches, batch × heads is below an A100's 108 SMs and most of the GPU idles. FA-2 gives each query block its own thread block. The same switch on one kernel, 4 heads, d = 64:

At N = 8,192 the FA-1 grid takes 214.54 ms and the FA-2 grid 30.62 ms, 7.0 times faster (2.24 TFLOP/s): four threadgroups cannot fill sixteen cores, and a filled core needs several to hide memory latency.

One threadgroup per query block instead of per head: 7 times faster at N = 8,192

Log scale. "FA-1 grid": one threadgroup per head, 4 in all, for a GPU with 16 cores; "FA-2 grid": one per 64 query rows and head, 512 at N = 8,192. Same kernel, same arithmetic, measured on Apple M1 Pro GPU.

Split-K exchanges partial results through shared memory; split-Q never does

One block: 64 query rows, 64 keys and values per loop step (head dimension 128), 4 warps. Values per loop iteration from the tile shapes, derived: split-Q reads 4 times more K and V from shared memory but never exchanges partial results. Which costs more depends on bandwidths the model does not have; FlashAttention-2 reports that removing the exchange gave a speedup (FA-2, section 3.3). Checked against src/fa_model.py.

  1. Split Q across warps, not K. Inside one thread block of 4 warps, FA-1 split the K and V tile between warps ("split-K"): "all warps need to write their intermediate results out to shared memory, synchronize, then add up"; FA-2 splits Q, each warp owning its rows, with "no need for communication between warps". One loop iteration both ways:
  1. Split K (FA-1), one loop iteration. Load a K and V tile, compute scores, softmax, multiply by V.
  2. Load. The K and V tiles (64 keys, d = 128) are copied from global into shared memory; every warp waits at a barrier.
  3. Scores, by key slice. Each warp multiplies all 64 query rows by its quarter of the keys (16): every warp holds a slice of every row of S.
  4. Exchange the maxima. A row's maximum spans all four warps: each writes its 64 partial maxima to shared memory, waits, and reads the other three.
  5. Partial outputs. Each warp multiplies its slice of P (64 × 16) by its quarter of V: a partial O for every row (64 × 128) and a partial row sum.
  6. Exchange the outputs. The four partial outputs of 64 × 128, plus row sums, go through shared memory behind a second barrier and are added up.

Causal masks: skip, do not mask

In a decoder, query i attends only to keys j ≤ i. Masking still computes the forbidden scores; tiles wholly above the diagonal can be skipped instead. FA-2 reports "around 1.7-1.8× speedup compared to attention without the causal mask" published. With 64-row query blocks and 32-key tiles the work falls to (B + 1) / 2B of the tiles (B = N / 64), an ideal 1.98× at N = 8,192 derived. Measured: masking only 30.42 ms (the same as no mask), skipping 16.98 ms, 1.79× measured on Apple M1 Pro GPU. Not quite 2×: blocks near the diagonal (more work) and far from it (less) now take very different times, so the last threadgroups run alone. MLX's own causal attention took 12.66 ms. FlashAttention-3's code answers the imbalance with "longest-processing-time-first scheduling: the longest remaining tile is assigned to the first SM that's free" (hopper/tile_scheduler.hpp, read 2026-10-05).

FlashAttention-3: the exponentials become the bottleneck

On an H100 the tensor cores outran everything around them. FlashAttention-3 (Shah et al., July 2024) gives the H100 SXM5 "989 TFLOPS for FP16 matmul versus 3.9 TFLOPS for special functions" (the units that compute exponentials), a ratio of 254 published. Each score costs 4d matmul FLOPs and one exponential, so for d = 128 the exponentials take (1 / 3.9) / (512 / 989) = 50% of the matmul time derived, the paper's "exponential can take 50% of the cycle compared to matmul". Run in sequence, the tensor cores idle a third of the time. FA-3 overlaps them with Hopper's asynchronous hardware: ping-pong between two warpgroups (one's softmax runs while the other's GEMMs use the tensor cores) and pipelining inside one (the next tile's QKT starts before this tile's softmax ends). Predict which keeps the tensor cores busier, then pick a schedule: each opens on its finished time line; the scrubber replays it.

On the real H100, ping-pong and pipelining are worth about 16% over neither (570 to 661 TFLOPS, FA-3's ablation below) published; the M1 has no asynchronous matrix units to measure it.

Overlapping softmax with the GEMMs keeps the tensor cores busy

0.5: H100, d = 128 (FA-3). About 1.0: tensor cores twice as fast, exponentials not (the Blackwell case FA-4 describes).

A list-scheduling model, derived and checked against src/fa_model.py: each iteration is GEMM0 (S = QKT), softmax, GEMM1 (O += PV); 8 iterations (one warpgroup does 8, two do 4 each); GEMMs one unit, softmax r × 2 units; one tensor-core pipe, one exponential pipe; program order. It ignores loads (TMA producers hide them in FA-3), register limits and rescaling, and it is greedy: at a ratio of 1.0 both techniques do worse than ping-pong alone, a reminder that FA-3's instruction order is tuned by hand.

FA-3's measured numbers and other machinery, FlashAttention-4 on Blackwell, and the backward pass (depth)

FA-3's measured numbers published: ping-pong takes the FP16 forward "from approximately 570 TFLOPS to 620-640 TFLOPS" (head dimension 128, sequence 8,192); the ablation gives 661 TFLOPS with everything, 582 without the pipelining, 570 without warp specialisation (sequence 8,448 in that table). Headline: FP16 up to 740 TFLOPs/s, 75% of peak; FP8 close to 1.2 PFLOPs/s.

  • Warp specialisation: producer warps only issue TMA copies (the tensor memory accelerator, which moves whole tiles from global to shared memory by itself), consumer warpgroups (4 warps each) only compute, and setmaxnreg moves registers from producers to consumers.
  • FP8: block-wise scales and "incoherent processing" (multiply Q and K by a random orthogonal Hadamard-based matrix, which spreads outliers) for "2.6× lower numerical error compared to per-tensor quantization".

FlashAttention-4. On a B200 the tensor cores doubled again while "other functional units (shared memory bandwidth, exponential units) scale more slowly or remain unchanged". FlashAttention-4 (Zadouri et al., 2026) answers with fully asynchronous MMA pipelines and larger tiles, exponentials partly computed in software on the FMA units, "conditional softmax rescaling" (skip the rescale when the running maximum barely moves), and tensor memory plus the 2-CTA MMA mode in the backward pass; up to 1,613 TFLOPs/s on B200 in BF16 (71%), 1.3× over cuDNN 9.13 published, written in the CuTe DSL in Python. Every generation is the same algorithm re-scheduled around whichever unit became the bottleneck.

The backward pass never stored P; it recomputes it tile by tile from Q, K and the saved logsumexp L: P = exp(S − L). FA-2's algorithm first computes D = rowsum(dO ∘ O) (one number per row), then per tile: dV += PT dO; dP = dO VT; dS = P ∘ (dP − D); dQ += dS K; dK += dST Q. It is parallelised over blocks of keys ("each worker takes care of a block of columns"), so several thread blocks add into the same rows of dQ, which FA-2 does "using atomic adds", the non-determinism of section 2 again published. Recomputing S costs about one more QKT; storing P would cost N2 numbers per head.

Decode: split the keys

Generating a token has one query per head against a long KV cache, so a FlashAttention grid over (batch, head, query block) has only batch × heads blocks: "with a batch size of 1, FlashAttention will use less than 1% of the GPU" (published, Flash-Decoding, Dao, Haziza, Massa and Sizov, October 2023). Flash-Decoding splits the keys into chunks, runs the online softmax on each in parallel, and merges the chunks' (m, ℓ, partial output) with the section-4 rescaling in a tiny second kernel; it reports up to 8× faster generation for CodeLlama-34B at 64K context. Ours: 8 heads, d = 128, float16 cache, one query measured on Apple M1 Pro GPU.

At 65,536 tokens (268 MB of K and V), one threadgroup per head takes 3.85 ms; the best split (S = 4) 1.73 ms, 2.2×, the same as MLX's own (1.73 ms). A surprise: S = 8 took 6.05 ms, slower than no split. With 65,536 keys per head, the 8 chunks of each head start exactly 2 MiB apart; with 512 more keys (66,048) the same kernel takes 1.82 ms at S = 8 against 5.22 at 65,536, three runs each. Likely cause: concurrent reads spaced by a power of two land on the same memory channel or bank, since controllers pick a channel from address bits; we did not establish the M1's mapping, so this is a hypothesis unconfirmed. The lesson: sweep the split size and the problem size, because a cliff can sit at the exact power of two everyone benchmarks. Paged KV caches, GQA and serving-side scheduling: inference and serving.

Splitting the keys helps until S = 4; at exactly 65,536 keys, S = 8 falls off a cliff

8. Testing a kernel against a reference

A fast wrong kernel is worse than a slow right one, and GPU bugs hide: at one size, in one run of a hundred, or only after another kernel ran. Every kernel here went through one harness before timing: compare with a float64 NumPy reference, fail if the largest error exceeds a tolerance. It still let one bug through.

A kernel that wrote nothing passed the test
Our first standalone RMSNorm kernel computed its loop count as C / 4 / 256, 0 for rows of 256 floats: it wrote nothing. The check passed, error 4 × 10−6 (log line in src/m1/out/side_experiments.txt). Its output buffer was, most likely, memory MLX's allocator had just freed after the library's own RMSNorm of the same shape, still holding the right answer. Two cheap defences: poison the output (fill it with NaN before the kernel runs, or fresh memory; our harness now empties MLX's buffer cache before every check) and run the reference after, not before, the kernel under test. The fixed kernel then passed for the right reason. The topic root's Kernel lab kept a second lesson: a too-weak barrier (simdgroup_barrier where a threadgroup barrier was needed) gave 1 to 5 wrong rows of 4,096 at random, and every small test passed. Test at the real size, and repeat.

Choosing the tolerance. assert_close's per-dtype defaults fit one rounding, not a sum of thousands of terms (_comparison.py, read 2026-10-05; the formula and table are owned by section 5 of Profiling, benchmarking and correctness). A practical rule: compute the reference in float64, measure the error of a trusted implementation in your precision against it, and require your kernel's error to be within a small factor of that. Our float32 matmuls erred by up to 8 × 10−6 against float64, like MLX's; the 4-bit GEMV by 9 × 10−4 against the same dequantised weights, and by far more (section 6) against unquantised ones, a different question (does quantisation hurt the model?) for a different test (evaluation).

Tools. On NVIDIA, compute-sanitizer's initcheck would have caught our RMSNorm bug, and racecheck a missing barrier (below). Honest timing (warm-up, medians, L2 flushing, CUDA events) is that page's section 2; its section 5 workbench shows why a reordered sum or an atomic changes the last digits.

The four sanitizer tools, PyTorch's default tolerances, and inputs that break kernels (depth)

compute-sanitizer (shipped with the toolkit) has four tools, from its own help text (CUDA 13.4.2): memcheck ("Memory access checking", the default: out-of-bounds and misaligned accesses), racecheck ("Shared memory hazard checking": a missing __syncthreads()), synccheck ("Synchronization checking": a barrier only some threads reach) and initcheck ("Global memory initialization checking": reading memory nobody wrote, which would have caught our RMSNorm bug). They slow a kernel by large factors, so run them on small inputs in CI.

dtypertolatol
float321.3e-61e-5
float161e-31e-5
bfloat160.0161e-5
float641e-71e-7

Owner: Profiling, benchmarking and correctness, section 5.

  • Sizes that are not a multiple of the tile (4,097 columns, 1 row, 0 rows): the bounds checks. Every kernel on this page assumes multiples of its tile; a production kernel must not.
  • Large offsets: rows with mean 3,000 (section 4), logits of 104 (softmax without the max subtraction overflows exp above about 88.7 in float32).
  • Masks: a row whose keys are all masked gives max = −∞, then exp(−∞ − (−∞)) = NaN. Decide what the kernel should return (zeros, or NaN to flag it) and test it. Our causal kernel never meets such a row because key 0 is always visible; a padding mask breaks that.
  • Real distributions: real activations have outliers (a few channels 100 times larger than the rest); random normal inputs hide quantisation and overflow problems.
  • Repeated runs: run 10 to 30 times and compare the outputs with each other, which finds races and non-deterministic atomics (section 2).

Depth: rehearsal and a path to practise

Interview questions, with short answers (optional)
Why is a reduction memory-bound, and what is its ceiling?
One add per 4-byte element is far below any GPU's ridge point; the ceiling is the time to read the input once. On the M1 the first rung read at 83 GB/s and the last at 133 GB/s, against about 143 GB/s for a plain read measured by the hardware topic's Roofline lab.
Write a warp sum. Why the mask argument?
Five __shfl_down_sync(0xffffffff, v, o) for o = 16, 8, 4, 2, 1. The mask names the lanes that participate and must all reach the call; it exists because lanes are scheduled independently since Volta.
Hillis-Steele or Blelloch?
Hillis-Steele: log n steps, O(n log n) adds, fine inside a warp. Blelloch: O(n) adds, 2 log n steps, good for large arrays in shared memory. Across the GPU, a tiled scan with decoupled look-back reads and writes each element once (CUB).
Walk a naive matmul up to a register-tiled one. What does each step buy?
Coalesce (lanes on neighbouring columns: 8 bytes asked per FMA, 5 moved instead of 33); tile into shared memory (global traffic 32 times lower, shared reads now the limit); tile into registers (each shared value feeds 8, then 64 FMAs); vectorise (fewer instructions and registers, so more blocks per SM). Then warp tiles, autotuning and tensor cores (section 1).
A 4-bit GEMV is only 2× faster than float16, not 4×. Why might that be?
Fixed launch overhead dominates small kernels (0.17 ms here), dequantisation instructions or scalar activation loads can make it instruction-bound, and scales and biases add bytes (0.5625 bytes per weight here). Measure the read of the bytes alone first.
When does fusion not help?
When the intermediate's round trip is a small share of the time (compute-bound kernels), when it raises register or shared-memory use and cuts occupancy, or when the compiler already fused it.
A path through it, without an NVIDIA GPU at home (optional)
Correction to the old page
The old page's project ladder was written "for the dual-5090 box"; there is no NVIDIA GPU here. The same ladder, rewritten for a Mac and rented GPU hours:
  1. On the Mac: run this page's Metal kernels (src/m1/, MLX), change one thing, re-measure. Then write softmax and a sum in Triton and check them with TRITON_INTERPRET=1 (Triton and Gluon page).
  2. Compile CUDA without a GPU: build the kernels in src/cuda/ with nvcc in a container, read ptxas -v and the SASS, and predict which will be fastest (compiler stack page).
  3. Rent one H100 for a day (on-demand at about $3.99 per GPU-hour on Lambda, 2026-10-05): reproduce Boehm's ladder through kernel 6 with Nsight Compute open, then the reduction ladder; keep a table of GFLOP/s or GB/s and the profiler's bottleneck per rung.
  4. A fusion that the compiler does not do (residual + RMSNorm + FP8 quantisation, or dequantise + GEMV for a format you use), benchmarked against torch.compile.
  5. A minimal FlashAttention forward in Triton (the official fused-attention tutorial is the reference), checked against F.scaled_dot_product_attention; then a causal version that skips tiles; then a split-KV decode kernel.

The same kernels in Rust. The old page described cuda-oxide, NVIDIA's rustc backend that compiles #[kernel] functions to PTX with the same thread, warp and block model; the 2026-09-21 tech news carries the verified details (NVIDIA blog, September 2026: early alpha, no performance benchmarks published).