Skip to content

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.

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.

This pass needs Pass 5; its Llama-family model is the model every section here runs on.

  1. Rejection sampling and residual distributions. Afterwards you can explain why rejection sampling with a residual distribution yields exact samples from the target.
  2. Error analysis, condition numbers, and tolerance budgets. Afterwards you can explain how condition numbers and error analysis set a tolerance budget.
  3. 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.
  4. 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.
  5. Sampling and logit processors. Afterwards you can explain the order in which logit processors apply temperature, top-k, top-p, and penalties before sampling.
  6. 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.
  7. A paged KV cache in Python. Afterwards you can explain how a paged KV cache maps logical positions to physical blocks.
  8. 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.
  9. A radix prefix cache. Afterwards you can explain how the radix prefix cache matches at block granularity, locks shared prefixes, and evicts LRU leaves.
  10. 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.
  11. 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.
  12. 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.
  13. Benchmarks and perf gates. Afterwards you can explain how a benchmark controls noise and how a perf gate decides a regression.
  14. 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.

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:

  1. 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.
  2. A growable array. Afterwards you can explain how tl_vec grows geometrically and why push is amortized O(1).
  3. A Swiss table. Afterwards you can explain how the Swiss table probes with control bytes and groups.
  4. An intrusive list and an LRU. Afterwards you can explain how an intrusive list links nodes without allocation and how it builds an LRU.
  5. Heap top-k in C. Afterwards you can explain how a size-k min-heap keeps the top k in O(n log k).
  6. 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.
  7. 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.
  8. 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.
  9. Polynomial approximation and range reduction: expf in C. Afterwards you can explain how expf reduces its range and approximates the remainder with a polynomial.
  10. Low-precision conversions in C. Afterwards you can explain how the C conversions round to bf16, fp16, and fp8 and handle NaN and overflow.
  11. 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.
  12. 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.
  13. FlashAttention forward in C. Afterwards you can explain how FlashAttention’s forward tiles keys and values and keeps a running max and sum.
  14. Paged attention for decode in C. Afterwards you can explain how paged attention for decode reads keys and values through the block table.
  15. 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.
  16. 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.

Generated from path.tsv.

StageReadDone when
1Rejection 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).
2Error 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).
3FP8 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).
4Floating 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.
5Sampling 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).
6KV 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).
7Paged 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).
8Radix 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).
9Radix 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).
10Quantization: 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).
11Speculative 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).
12Constrained 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).
13Benchmarks 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).
14What 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.
15C 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).
16Growable 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).
17Swiss 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).
18Intrusive 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).
19Binary 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).
20Thread 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).
21Paged 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).
22Fast 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).
23Polynomial 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).
24Low-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).
25Cache-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).
26Softmax 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).
27FlashAttention 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).
28Paged 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).
29Fused 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).
30Elementwise 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).