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.
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.
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.
| Pattern | In a transformer | What limits it | The trick | Here |
|---|---|---|---|---|
| Tiled matmul | every linear layer, QKT and PV | arithmetic, if every loaded value is reused enough | tiles in shared memory, then in registers, then tensor cores | 1 |
| Reduce | row max and sum in softmax, norms, the loss, gradient norms | bytes read; then the cost of combining partial results | each thread sums many values in a register; a warp combines 32 with shuffles; one partial per block | 2 |
| Scan | MoE token routing offsets, top-p sampling, ragged batches, cumsum | each output depends on every earlier input | scan tiles in parallel, then add each tile's offset; CUB does it in one pass | 3 |
| Row normalise | softmax, LayerNorm, RMSNorm | bytes; and numerics (overflow, cancellation) | one block per row, the row kept in registers; online or Welford statistics | 4 |
| Fuse | bias + activation, residual + norm, dequantise + GEMV | the round trip of an intermediate through global memory | apply the cheap operation while the data is still on chip | 5, 6 |
| Attention | attention | N × N intermediates; then the exponentials; then idle SMs | tiles plus online softmax (FlashAttention), then scheduling | 7 |
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.
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:
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 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.
| Rung | global bytes per FMA | shared bytes per FMA | A6000 GFLOP/s (% of cuBLAS) | M1 Pro |
|---|---|---|---|---|
| 1 Naive | 33 (8 asked) | 0 | 309.0 (1.3%) | M1 naive, uncoalesced: 229.20 ms |
| 2 Coalesced | 5 (8 asked) | 0 | 1,986.5 (8.5%) | M2 naive, coalesced: 47.53 ms |
| 3 Shared-memory tiles | 0.25 | 8 | 2,980.3 (12.8%) | M4 tiled 32x32: 36.48 ms |
| 4 1D thread tile | 0.125 | 4.5 | 8,474.7 (36.5%) | no matching rung |
| 5 2D thread tile | 0.0625 | 1 | 15,971.7 (68.7%) | M5 4x4 outputs per thread (registers): 10.52 ms |
| 6 Vectorised | 0.0625 | 1 | 18,237.3 (78.4%) | M6 8x8 per thread + float4: 13.43 ms |
| 7 Warp tile, autotuned | n/a | n/a | 21,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.
| Rung | Change | regs | FFMA | shared loads | FFMA per shared load |
|---|---|---|---|---|---|
| k1 naive | one thread per output; threadIdx.x walks rows | 32 | 29 | 0 | n/a |
| k2 coalesced | threadIdx.x walks columns | 32 | 29 | 0 | n/a |
| k3 shared tiles | 32 × 32 tiles of A and B in shared memory | 32 | 32 | 48 | 0.7 |
| k4 1D thread tile | each thread 8 outputs of one column | 44 | 64 | 40 | 1.6 |
| k5 2D thread tile | each thread an 8 × 8 block, outer products | 158 | 512 | 64 | 8.0 |
| k6 vectorised | A transposed into shared memory, float4 everywhere | 127 | 512 | 64 | 8.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).
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.
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:
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.
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.
mx.sum (1.04 ms). Even the worst kernel reads memory at more than half the copy speed.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.
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.
tid % (2s) == 0 add. Most lanes of every warp sit idle while the warp still issues.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().
*_sync shuffles, or __syncwarp() between shared-memory steps. Old tutorials (and old kernels) still contain the volatile trick.__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_90aFour 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).
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).Floating-point addition is not associative: (a + b) + c can differ from a + (b + c) in the last bits.
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).
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:
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.
224 floats, median of 3 runs, measured on Apple M1 Pro GPU.
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.
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.
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.
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.
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: 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.
| Row mean | two-pass | E[x²] − E[x]² | Welford |
|---|---|---|---|
| 0 | 6.8e-07 | 7.3e-07 | 9.1e-07 |
| 30 | 5.7e-06 | 5.4e-04 | 4.1e-06 |
| 300 | 6.0e-05 | 6.5e-02 | 6.5e-05 |
| 3,000 | 6.3e-04 | 1,653 | 6.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.
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:
Welford matters when the row is streamed once from memory, as in a long row or a fused kernel that cannot keep it.
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).
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.
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:
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).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.
K = 1,024, 4,096 × 4,096 outputs, float32; median of 3 runs, measured on Apple M1 Pro GPU.
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).
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,024 | ms |
|---|---|
MLX: mx.fast.rms_norm, then its matmul | 8.40 |
| ours, separate: RMSNorm kernel, then our matmul | 10.15 |
| ours, fused, first attempt (16 KB staging tile) | 15.03 |
| ours, fused, epilogue in registers | 10.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.
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.
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).
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.
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).
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:
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 (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:
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.
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.
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.
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).
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.
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 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.
setmaxnreg moves registers from producers to consumers.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.
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.
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.
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.
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.
| dtype | rtol | atol |
|---|---|---|
| float32 | 1.3e-6 | 1e-5 |
| float16 | 1e-3 | 1e-5 |
| bfloat16 | 0.016 | 1e-5 |
| float64 | 1e-7 | 1e-7 |
Owner: Profiling, benchmarking and correctness, section 5.
exp above about 88.7 in float32).__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.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).src/cuda/ with nvcc in a container, read ptxas -v and the SASS, and predict which will be fastest (compiler stack page).torch.compile.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).
Every timing quoted on this page, with its spread, the machine's load, the derived rate and the kernel source that was timed. All measured on Apple M1 Pro GPU (16-core GPU, MLX 0.32.3, custom Metal kernels through mx.fast.metal_kernel), each kernel first checked against a float64 NumPy reference at the measured size. Each case: 2 warm-up calls, then 7 trials of enough calls to last about 60 ms; the bar is the median of the three runs' medians, the thin line the fastest and slowest of all 21 trials. Times include MLX's per-call launch-and-wait overhead (about 0.2 ms).
What transfers to NVIDIA: which variant wins and by roughly what factor when the limit is the same (bytes, launches, idle cores); what does not: absolute times (an H100 has about 20 times this GPU's memory bandwidth), and anything that depends on Apple's memory system, threadgroup memory size (32 KB per threadgroup) or the 8 × 8 matrix instructions. Reproduce: src/run_all.sh (needs a Python with MLX; see src/README.md).
The page's CUDA kernels (the reduction ladder, CUB's block reduce and scan, Boehm's matmul ladder rewritten, and the 4-bit GEMV) compiled with CUDA 13.4.2 for three GPUs, without a GPU, in the kb-gpu-lab:1 container the topic root built: sm_80 (A100), sm_90a (H100) and sm_120 (RTX 5090). Registers, shared memory and spills come from ptxas -v; instruction counts from cuobjdump -sass. All compiled, nothing run. Counts are static (how often an instruction appears in the binary; a loop body counts once).
FFMA: fused multiply-add (float32). LDS / LDS.128: shared-memory loads, 4 or 16 bytes per lane. LDG: global loads. STS: shared stores. BAR: barriers (__syncthreads). SHFL: warp shuffles. I2F: integer-to-float conversions. "FFMA per LDS" is the reuse ratio of Reading section 1: multiply-adds per shared-memory load instruction. Blocks per SM from registers alone use NVIDIA's allocation rules as reproduced by the topic root's GPU simulator (registers per warp rounded up to 256, 64K per SM, at most 64 warps on sm_80 and sm_90a, 48 on sm_120) derived; shared memory and the block's other limits can lower it.
Toolkit: . Commands: src/cuda/compile_all.sh; statistics: src/cuda/sass_stats.py (raw SASS dumps are regenerated, not committed).
Every link opens in a new tab; times are reading or watching estimates. Links checked 2026-10-05.
Every timing with its spread, load, rate and the exact kernel source.
Registers, shared memory and instruction mix of every CUDA kernel for A100, H100 and RTX 5090.
The root: the map of the topic, every optimisation lever with the page that owns it, and the five ways to get a kernel compared. Its Kernel lab ran the softmax and matmul ladders whose numbers this page now teaches from (section 1 and section 4) and still measures the fused softmax-matmul and attention kernels; its GPU simulator and Compiler explorer tabs show divergence, occupancy and real SASS.
Threads, warps, blocks, launches, synchronisation and occupancy from zero.
Coalescing, shared memory and swizzles, registers and spills, asynchronous copies, the roofline from the programmer's side.
The same kernels written per block instead of per thread; how the Triton compiler lays them out.
cuBLAS and cuBLASLt epilogues, CUTLASS and CuTe, mma, wgmma, TMA and tcgen05: the rungs beyond section 1's ladder.
Nsight Systems and Compute, honest timing, numerical checks: the method of every section here.
PTX, SASS, NVRTC, torch.compile and the Triton it generates.
Launch overhead and CUDA graphs, the fixed cost that limited section 6's GEMV.
The algorithm run on a real input (Run the kernel), its IO proof, and FA-1 to FA-4 (Then and now).
The chips themselves: SMs, tensor cores, special-function units, memory, the roofline these kernels sit on.
Floating point, rounding and summation error: why sections 2 and 4 behave as they do.
llama.cpp and ggml-cuda, where dequantising GEMV kernels like section 6's live.
Paged attention, decode kernels and batching on the serving side.
torch.compile, custom operators and where a kernel plugs into PyTorch.
The canonical worked example, ten kernels from 1.3% to 93.7% of cuBLAS on an RTX A6000 (December 2022). Read it, then reproduce it.
The sequel: vectorisation, double buffering and autotuning, beating cuBLAS SGEMM on an RTX 4090 by the author's account.
The seven-step reduction deck (2007). Read rung 5 with the Volta correction of section 2 in mind.
Hwu, Kirk and El Hajj: chapter 6 (tiled matmul), chapters 10 and 11 (reduction, scan), later chapters for patterns.
Harris, Sengupta and Owens: Hillis-Steele, Blelloch, bank-conflict padding.
The algorithm inside CUB's DeviceScan (NVIDIA, 2016).
Block- and device-wide reduce, scan, sort and histogram you call instead of writing; source at NVIDIA/cccl.
Work partitioning; Hopper asynchrony and FP8; Blackwell's asymmetric scaling. Code: Dao-AILab/flash-attention.
Split-KV decode explained with animations (Dao, Haziza, Massa, Sizov, 2023).
The two kernels of the path's last steps, as reference solutions.
Frantar et al., 2024: 4-bit weight kernels that keep the speedup up to batch 16 to 32.
Lecture 8 (CUDA performance checklist), lecture 12 (FlashAttention), and guest lectures by kernel authors.
The four sanitizer tools of section 8; the epilogue options of section 5.
Built from the old Notion page "Writing kernels: the practical track" (saved in src/live.md; every claim accounted for in src/coverage.json), October 2026. Measurements on an Apple M1 Pro GPU; NVIDIA results compiled, not run.