B.8 Pass 6: Inference and Kernels
A model that matches Hugging Face is correct, but a correct model decoded naively is slow: without a cache, every new token recomputes attention over the whole prefix. This pass builds the Python inference stack that makes decoding fast without changing its output: samplers and logit processors, the KV cache with incremental decoding, a paged cache and a radix prefix cache, quantized weights, speculative decoding, and constrained decoding that guarantees every document parses and validates.
Concepts from other sections (31)
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.
- Logit processor: a step that rewrites the logits (a penalty, temperature, or filter) before the softmax. Read more: 21.1 Sampling and logit processors
- KV cache: per-layer storage of past keys and values, so each decode step processes only the new token. Read more: 21.2 The KV cache, incremental decoding, and generate
- Prefix cache: a map from token prefixes of past prompts to the KV blocks already computed for them. Read more: 21.4 A radix prefix cache
- Speculative decoding: drafting several tokens cheaply and verifying them with one target forward pass, keeping the longest acceptable prefix. Read more: 23.9 Speculative decoding in the engine
- Constrained decoding: masking, at every step, every token that would take the output outside an allowed language. Read more: 23.10 Tool calls and constrained decoding
- 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
- Block pool: one slab of fixed-size KV blocks handed out by id. Read more: 21.8 A paged KV block pool in C
- Tolerance budget: a test allowance that sums every deliberate perturbation and the rounding bound, and nothing else. Read more: 15.3 Error analysis, condition numbers, and tolerance budgets in Mathematics
- Rejection sampling: drawing from a proposal and accepting each draw with a probability chosen so that accepted draws follow the target . Read more: 13.7 Rejection sampling and residual distributions in Mathematics
- Residual distribution: , the normalized mass that acceptance leaves missing from . Read more: 13.7 Rejection sampling and residual distributions in Mathematics
- Condition number: how much the exact answer of a problem moves relative to a change in its input. Read more: 15.3 Error analysis, condition numbers, and tolerance budgets in Mathematics
- E4M3: an fp8 format with 4 exponent and 3 mantissa bits, largest finite value 448. Read more: 21.5 Quantization: int8, int4 groups, fp8, and the KV cache
- E5M2: an 8-bit float with 5 exponent bits (bias 15) and 2 fraction bits, IEEE-style infinities and NaNs, largest finite value 57344. Read more: 15.4 FP8 and microscaling formats in Mathematics
- MXFP4: blocks of 32 FP4 E2M1 codes sharing one power-of-two E8M0 scale. Read more: 21.5 Quantization: int8, int4 groups, fp8, and the KV cache
- E8M0: an 8-bit unsigned power-of-two scale with bias 127, used as the shared scale of an MX block. Read more: 15.4 FP8 and microscaling formats in Mathematics
- Top-p (nucleus): the smallest set of most likely tokens whose mass reaches , including the crossing token. Read more: 21.1 Sampling and logit processors
- paged KV cache: a cache stored as fixed-size blocks anywhere in a pool, with a per-sequence table mapping logical blocks to physical ones. Read more: 22.6 Paged attention for decode in C
- Radix tree: a trie whose single-child chains are merged into labelled edges. Read more: 15.7 A radix tree over token ids in Programming and Algorithms
- LRU (least recently used): an eviction policy that reclaims the element whose last use is oldest. Read more: 15.3 An intrusive list and an LRU in Programming and Algorithms
- Perf gate: a check that fails a change when head is slower than base by more than the budget. Read more: 3.4 Benchmarks and perf gates in Software Engineering
- amortized O(1): constant average cost per operation over a long sequence, as with geometric growth. Read more: 1.3 C: memory, pointers, structs, headers, and the C11 toolchain in Programming and Algorithms
- Control byte: one byte per slot holding EMPTY, DELETED, or the key’s 7-bit fingerprint. Read more: 15.2 A Swiss table in Programming and Algorithms
- Intrusive list: a linked list whose link fields live inside the elements, so linking needs no allocation. Read more: 15.3 An intrusive list and an LRU in Programming and Algorithms
- Magic constant:
0x5F3759DF, the offset that turns the bit-pattern logarithm into a first guess for within 3.44%. Read more: 15.5 Fixed-point iteration and fast inverse square root in C in Mathematics - BF16: a 16-bit float with float32’s sign and exponent and 7 mantissa bits; the top half of a rounded float32. Read more: 6.7 Safetensors for every dtype, atomic checkpoints, and the token stream
- fp16: a 16-bit format with 5 exponent bits and 10 mantissa bits; finer precision but a maximum of 65504 and a smallest subnormal of . Read more: 17.1 Mixed precision, loss scaling, gradient accumulation, and activation checkpointing
- block table: a request’s list of the physical KV blocks holding its tokens, used by attention to read the paged cache. Read more: 20.6 Inside an Inference Engine: How vLLM and SGLang Run a Model
- 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
- RMSNorm: divides a vector by its root mean square plus eps (inside the root) and multiplies by a learned gain; no mean subtraction, no bias. Read more: 13.1 Pre-LN and RMSNorm
- RoPE: rotary position embedding, which rotates queries and keys by position to encode relative position. Read more: 5.3 Model landscape and lifecycle
The rule that runs through the pass is that every optimization must be invisible in the output. Each one is checked against the no-cache greedy tokens, and that definition of correctness is what the Rust engine of Pass 7 inherits. A second half, entirely optional, writes the runtime pieces and kernels in standalone C: an arena allocator, data structures, a thread pool, a paged block pool, numerical approximations, a tiled matmul, softmax, flash and paged attention, and fused quantized matmul. Nothing later depends on them.
Learning objectives
- Explain how error analysis and tolerance budgets decide when two numerical results are equal enough.
- Explain how the KV cache makes decoding linear in length and how the paged and radix caches share memory.
- Explain how quantization formats trade accuracy for memory and how that trade is measured.
- Explain why speculative decoding never changes the greedy output and how constrained decoding masks tokens.
Before you begin
Section titled “Before you begin”This pass needs Pass 5; its Llama-family model is the model every section here runs on.
In this pass
Section titled “In this pass”- Rejection sampling and residual distributions. Afterwards you can explain why rejection sampling with a residual distribution yields exact samples from the target.
- Error analysis, condition numbers, and tolerance budgets. Afterwards you can explain how condition numbers and error analysis set a tolerance budget.
- FP8 and microscaling formats. Afterwards you can explain the FP8 E4M3 and E5M2 formats and how MXFP4 and MXFP8 share an E8M0 scale per block.
- Problem set B: condition numbers, error bounds, Newton, polynomial approximation, and low precision. Afterwards you can work every problem in the set and explain each answer.
- Sampling and logit processors. Afterwards you can explain the order in which logit processors apply temperature, top-k, top-p, and penalties before sampling.
- The KV cache, incremental decoding, and generate. Afterwards you can explain how the KV cache makes decode incremental and how the UTF-8 detokenizer emits only complete characters.
- A paged KV cache in Python. Afterwards you can explain how a paged KV cache maps logical positions to physical blocks.
- A radix tree over token ids. Afterwards you can explain how the radix tree over token ids splits edges and how the index-linked LRU leaf list picks evictions.
- A radix prefix cache. Afterwards you can explain how the radix prefix cache matches at block granularity, locks shared prefixes, and evicts LRU leaves.
- Quantization: int8, int4 groups, fp8, and the KV cache. Afterwards you can explain how int8, packed int4 group, and fp8 quantization scale weights and how KV quantization works.
- Speculative decoding: n-gram, prompt-lookup, and model drafts. Afterwards you can explain why speculative decoding with n-gram, prompt-lookup, and model drafts preserves the target distribution.
- Constrained decoding: from regex to token masks. Afterwards you can trace how a regex becomes a DFA and then per-token masks, and how the JSON-schema subset compiles to one.
- Benchmarks and perf gates. Afterwards you can explain how a benchmark controls noise and how a perf gate decides a regression.
- What the System Does After Pass 6. Afterwards you can explain why the Python inference stack matches no-cache output token for token with every optimization on.
Optional depth: standalone C
Section titled “Optional depth: standalone C”These sections write runtime utilities, data structures, and kernels in C. Each compiles its own test binary, and numerical parity is checked against vectors emitted by the corresponding Python solution:
- C runtime support and an arena allocator with marks. Afterwards you can explain how the arena allocator hands out aligned memory and how marks free in bulk.
- A growable array. Afterwards you can explain how tl_vec grows geometrically and why push is amortized O(1).
- A Swiss table. Afterwards you can explain how the Swiss table probes with control bytes and groups.
- An intrusive list and an LRU. Afterwards you can explain how an intrusive list links nodes without allocation and how it builds an LRU.
- Heap top-k in C. Afterwards you can explain how a size-k min-heap keeps the top k in O(n log k).
- Thread pool and tl_parallel_for. Afterwards you can explain how the thread pool splits a range in tl_parallel_for and waits for every chunk.
- A paged KV block pool in C. Afterwards you can explain the paged KV block pool’s format v1 and how blocks are allocated, shared, and freed.
- Fixed-point iteration and fast inverse square root in C. Afterwards you can explain why the fast inverse square root’s magic constant gives a good first guess and how a Newton step refines it.
- Polynomial approximation and range reduction: expf in C. Afterwards you can explain how expf reduces its range and approximates the remainder with a polynomial.
- Low-precision conversions in C. Afterwards you can explain how the C conversions round to bf16, fp16, and fp8 and handle NaN and overflow.
- Cache-blocked, packed, batch-invariant matmul in C. Afterwards you can explain how cache blocking and packing speed up the C matmul and why a fixed reduction order makes it batch-invariant.
- Softmax in C: three-pass and online two-pass. Afterwards you can explain how the online two-pass softmax rescales its running sum to save a pass.
- FlashAttention forward in C. Afterwards you can explain how FlashAttention’s forward tiles keys and values and keeps a running max and sum.
- Paged attention for decode in C. Afterwards you can explain how paged attention for decode reads keys and values through the block table.
- Fused int4 and int8 dequantize-matmul in C. Afterwards you can explain how the fused int4 and int8 dequantize-matmul unpacks and scales weights inside the inner loop.
- Elementwise kernels in C: RMSNorm, RoPE, SiLU-mul, embedding, add, argmax. Afterwards you can explain each C elementwise kernel (RMSNorm, RoPE, SiLU-mul, embedding, add, argmax) and the numerics it must match.
The stages are also in this pass’s manifest, path.tsv. Pass 7 moves inference into the Rust engine and puts a production platform around it.
Stages
Section titled “Stages”Generated from path.tsv.
| Stage | Read | Done when |
|---|---|---|
| 1 | Rejection sampling and residual distributions 13.7 Rejection sampling and residual distributions | You can explain why rejection sampling with a residual distribution yields exact samples from the target (M07.6). |
| 2 | Error analysis, condition numbers, tolerance budgets 15.3 Error analysis, condition numbers, and tolerance budgets | You can explain how condition numbers and error analysis set a tolerance budget (M09.3). |
| 3 | FP8 E4M3/E5M2, MXFP4/MXFP8 with E8M0 scales 15.4 FP8 and microscaling formats | You can explain the FP8 E4M3 and E5M2 formats and how MXFP4 and MXFP8 share an E8M0 scale per block (M09.4). |
| 4 | Floating point problem set, part b: condition numbers, error bounds, Newton, polynomial approximation, low precision 15.9 Problem set B: condition numbers, error bounds, Newton, polynomial approximation, and low precision | You can work every S-M09b problem and explain each answer. |
| 5 | Sampling and logit processors 21.1 Sampling and logit processors | You can explain the order in which logit processors apply temperature, top-k, top-p, and penalties before sampling (L8.1). |
| 6 | KV cache, incremental decode, incremental UTF-8 detokenizer, generate 21.2 The KV cache, incremental decoding, and generate | You can explain how the KV cache makes decode incremental and how the UTF-8 detokenizer emits only complete characters (L8.2). |
| 7 | Paged KV cache in Python 21.3 A paged KV cache in Python | You can explain how a paged KV cache maps logical positions to physical blocks (L8.3). |
| 8 | Radix tree over token ids with index-linked LRU leaf list 15.7 A radix tree over token ids | You can explain how the radix tree over token ids splits edges and how the index-linked LRU leaf list picks evictions (ds.07). |
| 9 | Radix prefix cache (block-granular, LRU leaf eviction, locks) 21.4 A radix prefix cache | You can explain how the radix prefix cache matches at block granularity, locks shared prefixes, and evicts LRU leaves (L8.4). |
| 10 | Quantization: int8, int4 group (packed), fp8, KV quant 21.5 Quantization: int8, int4 groups, fp8, and the KV cache | You can explain how int8, packed int4 group, and fp8 quantization scale weights and how KV quantization works (L8.5). |
| 11 | Speculative decoding: n-gram, prompt-lookup, and model drafts 21.6 Speculative decoding: n-gram, prompt-lookup, and model drafts | You can explain why speculative decoding with n-gram, prompt-lookup, and model drafts preserves the target distribution (L8.6). |
| 12 | Constrained decoding: regex to DFA to token masks, JSON-schema subset 21.7 Constrained decoding: from regex to token masks | You can trace how a regex becomes a DFA and then per-token masks, and how the JSON-schema subset compiles to one (L8.7). |
| 13 | Benchmarks and perf gates (R7) 3.4 Benchmarks and perf gates | You can explain how a benchmark controls noise and how a perf gate decides a regression (craft.06). |
| 14 | What the system does after Pass 6 B.8.1 What the System Does After Pass 6 | You can explain why the Python inference stack matches no-cache output token for token with every optimization on. |
| 15 | C runtime support and arena allocator with marks (optional) 22.1 C runtime support and an arena allocator with marks | You can explain how the arena allocator hands out aligned memory and how marks free in bulk (rt.02). |
| 16 | Growable array tl_vec (type-erased, optional C) 15.1 A growable array | You can explain how tl_vec grows geometrically and why push is amortized O(1) (ds.01). |
| 17 | Swiss table tl_map (u64 to u64, optional C) 15.2 A Swiss table | You can explain how the Swiss table probes with control bytes and groups (ds.02). |
| 18 | Intrusive list + LRU (optional C) 15.3 An intrusive list and an LRU | You can explain how an intrusive list links nodes without allocation and how it builds an LRU (ds.03). |
| 19 | Binary heap top-k in C (optional) 15.4 Heap top-k in C | You can explain how a size-k min-heap keeps the top k in O(n log k) (ds.04). |
| 20 | Thread pool and tl_parallel_for (optional C) 22.2 Thread pool and tl_parallel_for | You can explain how the thread pool splits a range in tl_parallel_for and waits for every chunk (rt.03). |
| 21 | Paged KV block pool (format v1, optional C) 21.8 A paged KV block pool in C | You can explain the paged KV block pool’s format v1 and how blocks are allocated, shared, and freed (rt.04). |
| 22 | Fast inverse square root in standalone C (optional) 15.5 Fixed-point iteration and fast inverse square root in C | You can explain why the fast inverse square root’s magic constant gives a good first guess and how a Newton step refines it (M09.5). |
| 23 | Polynomial approximation and range reduction: expf in C (optional) 15.6 Polynomial approximation and range reduction: expf in C | You can explain how expf reduces its range and approximates the remainder with a polynomial (M09.6). |
| 24 | Low-precision conversions in standalone C (optional) 15.7 Low-precision conversions in C | You can explain how the C conversions round to bf16, fp16, and fp8 and handle NaN and overflow (M09.7). |
| 25 | Cache-blocked, packed, batch-invariant matmul in C (optional) 22.3 Cache-blocked, packed, batch-invariant matmul in C | You can explain how cache blocking and packing speed up the C matmul and why a fixed reduction order makes it batch-invariant (L9.1). |
| 26 | Softmax in C: three-pass and online two-pass 22.4 Softmax in C: three-pass and online two-pass | You can explain how the online two-pass softmax rescales its running sum to save a pass (L9.2). |
| 27 | FlashAttention forward in C 22.5 FlashAttention forward in C | You can explain how FlashAttention’s forward tiles keys and values and keeps a running max and sum (L9.3). |
| 28 | Paged attention for decode in C 22.6 Paged attention for decode in C | You can explain how paged attention for decode reads keys and values through the block table (L9.4). |
| 29 | Fused int4 and int8 dequantize-matmul in C 22.7 Fused int4 and int8 dequantize-matmul in C | You can explain how the fused int4 and int8 dequantize-matmul unpacks and scales weights inside the inner loop (L9.5). |
| 30 | Elementwise kernels in C: RMSNorm, RoPE, SiLU-mul, embedding, add, argmax 22.8 Elementwise kernels in C: RMSNorm, RoPE, SiLU-mul, embedding, add, argmax | You can explain each C elementwise kernel (RMSNorm, RoPE, SiLU-mul, embedding, add, argmax) and the numerics it must match (L9.6). |