Chapter 22: Kernels and Numerical Performance
Up to this point every forward pass in the book has run through numpy, and the arithmetic has been someone else’s problem. This chapter takes it back. You will write, in plain C11, the kernels a transformer actually spends its time in: matrix multiplication, softmax, attention for prefill and for paged decode, quantized matmul, and the small elementwise operations between them. Along the way you will see why fast kernels are mostly about memory rather than arithmetic, and how to make them fast without letting the answer change with the batch size, the chunking of a prompt, or the number of threads.
Concepts from other sections (13)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- Arena (bump) allocator: an allocator that serves requests by advancing an offset and frees all allocations at once. Read more: 18.8 Arena allocator in Programming and Algorithms
- Thread pool: a fixed set of long-lived worker threads that execute tasks taken from a shared queue. Read more: 18.7 Thread pool in Programming and Algorithms
- fixed partition: ranges determined by and alone, never by the thread count. Read more: 22.2 Thread pool and tl_parallel_for
- roofline: the bound on a loop’s speed from peak compute , memory bandwidth , and arithmetic intensity . Read more: 22.3 Cache-blocked, packed, batch-invariant matmul in C
- batch invariance: the property that a kernel’s output bits do not depend on how the work was split or scheduled. Read more: 22.2 Thread pool and tl_parallel_for
- FlashAttention: attention computed tile by tile with an online softmax, so the score matrix is never stored. Read more: 22.5 FlashAttention forward in C
- elementwise kernel: a kernel that reads each element once and does constant work with it, so it is bound by memory bandwidth. Read more: 22.8 Elementwise kernels in C: RMSNorm, RoPE, SiLU-mul, embedding, add, argmax
- online softmax: computing the maximum and the normalizer in one read by rescaling the running sum whenever the maximum grows. Read more: 22.4 Softmax in C: three-pass and online two-pass
- micro-kernel: the innermost loop that computes an tile of partial sums in registers. Read more: 22.3 Cache-blocked, packed, batch-invariant matmul in C
- Grouped-query attention (GQA): query heads share key/value heads, each serving a contiguous group of query heads. Read more: 13.5 Grouped-Query Attention with a Cache Hook, Windows, and Sinks
- absolute position: , the position of a query row in the whole sequence rather than in the current call. Read more: 22.5 FlashAttention forward in C
- chunk invariance: the property that a row’s output bits do not depend on how the prompt was split into calls. Read more: 22.5 FlashAttention forward in C
- decode step: one forward pass with a single new query per sequence, at the newest position. Read more: 22.6 Paged attention for decode in C
The chapter is optional. Its C units compile into standalone test programs, and nothing here is loaded by Python or linked into the Rust engine, which keeps its own independent implementations; cross-language agreement is checked through checked-in files and process protocols. The arc runs from infrastructure to kernels. It opens with the support layer every C unit reports through and an arena allocator for scratch memory, then a thread pool whose fixed partition makes parallel results bitwise reproducible. With those in hand, the tiled matmul introduces the roofline, packing, and batch invariance; the softmax section derives the online update; FlashAttention and paged attention build on that update; and the quantized matmul and elementwise kernels complete the set.
Learning objectives
- Build allocation and threading infrastructure for kernels that never allocate in the steady state and never change bits with the thread count.
- Explain kernel performance with the roofline model, and use blocking, packing, and quantization to move a kernel toward its bound.
- Derive the online softmax and apply it to tiled and paged attention without ever storing the score matrix.
- Make every kernel batch-invariant by fixing its reduction order, and explain which common optimizations break that property.
- Handle the edge cases (masked rows, NaN, empty contexts, bad tables, misaligned views) that separate a correct kernel from a plausible one.
Before you begin
Section titled “Before you begin”You should be comfortable with C pointers, structs, headers, and the C11 toolchain, as covered in C: memory, pointers, structs, headers, and the C11 toolchain in Programming and Algorithms. The kernels implement operations you have already met in Python: scaled dot-product attention, the modern block’s RMSNorm, RoPE, and GQA, the paged KV cache, and quantization. Several numerical helpers come from Mathematics, notably stable softmax, tl_expf, and the low-precision conversions.
The build rules are in c/ABI.md. c/Makefile produces a static archive for local C use, the test harness compiles each C unit into a standalone test executable, and SANITIZE=1 enables AddressSanitizer and UndefinedBehaviorSanitizer. The concurrency tests are also meant to run under ThreadSanitizer.
In this chapter
Section titled “In this chapter”- C runtime support and an arena allocator with marks. The status, error, and allocator-hook layer every C unit uses, and a bump allocator with nested marks that makes zero allocator calls once warmed up.
- Thread pool and tl_parallel_for. A sleeping pool with one atomic counter and a fixed partition, so parallel kernels give the same bits on any number of threads, and nested calls, concurrent callers, and shutdown are all safe.
- Cache-blocked, packed, batch-invariant matmul in C. Goto’s loop nest with packing and a register micro-kernel, 10 to 20 times faster than the triple loop, with a fixed reduction order that makes each row independent of the batch.
- Softmax in C: three-pass and online two-pass. Overflow-free softmax, the online update with its invariant, and the exact handling of masked rows and NaN.
- FlashAttention forward in C. Tiled attention that never stores the score matrix, with GQA, causal and window masks at absolute positions, sinks, and bitwise chunk invariance.
- Paged attention for decode in C. One decode step over a block-table cache in f16, allocating nothing and matching FlashAttention bit for bit.
- Fused int4 and int8 dequantize-matmul in C. Matmul straight from packed 4-bit and 8-bit weights, about 3.9 times faster than float32 at decode, with eight lanes that stay batch-invariant.
- Elementwise kernels in C: RMSNorm, RoPE, SiLU-mul, embedding, add, argmax. Six small operations and the one detail in each that silently changes a model’s output.