Chapter 21: Implementing Inference
By the end of the previous chapter you have a Llama-family model that reproduces a real checkpoint’s logits. This chapter turns those logits into text and defines reference algorithms for sampling, caches, and decoding. Small-batch dense decode often depends on memory bandwidth; actual bottlenecks vary with batch, context, architecture, and device. Exact greedy output, equality in distribution, and finite-precision numerical agreement are distinct contracts. The Python/Rust reference sampler has a deliberately strict replay contract; production engines need their own batch-invariance and reproducibility checks.
Concepts from other sections (25)
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.
- logits: unnormalized log-scores that softmax turns into probabilities; here the table stores . Read more: 6.1 Byte bigram: counts, logits, safetensors v0
- Replay contract: the inputs, environment, and equality criterion promised for reproducing an execution. Read more: 20.13 Batch invariance and numerical reproducibility
- 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
- Min-p: a filter that keeps tokens with probability at least times the top token’s. Read more: 21.1 Sampling and logit processors
- Cumulative distribution function (CDF): , defined for every random variable, discrete or continuous; it rises from 0 to 1, and for a continuous variable its derivative is the density. Read more: Chapter 13: Probability and Statistics in Mathematics
- Byte-level: the base alphabet is the 256 bytes (through the byte map), so every text encodes and there is no unknown token. Read more: 7.2 Byte-level BPE
- 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
- Block table: a sequence’s list of block ids in position order. Read more: 21.3 A paged KV cache in Python
- Reference count: the number of sequences holding a block; it returns to the pool at 0. Read more: 21.3 A paged KV cache in Python
- Copy on write: giving a writer a private copy of a shared block before writing into it. Read more: 21.3 A paged KV cache in Python
- Radix tree: a trie whose chains are compressed into labelled edges. 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
- Token mask: the set of tokens whose bytes keep the DFA alive from the current state, plus EOS in accepting states. Read more: 21.7 Constrained decoding: from regex to token masks
- tie rule: the fixed backtrace preference (diagonal, deletion, insertion) that makes the S, D, I split deterministic. Read more: 15.5 Multimodal eval metrics: WER, CER, VQA, captions, zero-shot
- Reference counting: memory management in which each object counts the references to it and is freed when the count drops to zero; CPython uses it, backed by a cycle-detecting garbage collector for objects that refer to each other. Read more: Chapter 22: Python in Programming and Algorithms
- 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
- Error budget: the per-output bound a quantized layer must stay within. Read more: 21.5 Quantization: int8, int4 groups, fp8, and the KV cache
- Committed length: the minimum fill count over layers, from which positions and masks are computed. Read more: 21.2 The KV cache, incremental decoding, and generate
- 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
- Symmetric quantization: codes with and no zero point. Read more: 21.5 Quantization: int8, int4 groups, fp8, and the KV cache
- Perplexity: , the geometric mean of ; the effective number of choices per token. Read more: 17.2 Perplexity, bits per byte, NLL accumulator in Mathematics
- NFA: a finite automaton that may be in several states at once, with -edges that consume nothing. Read more: 21.7 Constrained decoding: from regex to token masks
- Block pool: one slab of fixed-size KV blocks handed out by id. Read more: 21.8 A paged KV block pool in C
- Chained block hash: FNV-1a over the parent block’s hash and the block’s token ids, naming the whole prefix. Read more: 21.8 A paged KV block pool in C
The arc runs from the single token to the whole serving-ready toolkit. It starts with the sampler, specified to the bit: penalties, temperature, top-k, top-p, min-p, an f64 softmax, one uniform draw, and the inverse CDF, so Python and Rust agree. It then caches keys and values so each step processes one token, and streams byte-level text without half characters. The middle of the chapter is about memory: paging the KV cache into fixed-size blocks with a block table per sequence, sharing prefixes by reference count and copy on write, finding shared prefixes across requests with a radix tree, and shrinking weights and the cache with quantization. The chapter ends with two ways to change what each pass produces: speculative decoding, which drafts several tokens cheaply and verifies them in one pass without changing the output, and constrained decoding, which compiles a regex or JSON schema into token masks so invalid output is impossible.
Learning objectives
- Implement a bit-exact sampling pipeline and explain why its order, sums, and tie rules matter.
- Build a KV cache whose output equals full recomputation, with rollback and an incremental UTF-8 detokenizer.
- Explain paging, reference counting, copy on write, and prefix caching for the KV cache.
- Quantize weights and KV to int8, int4, fp8, and MXFP4 with a derived error budget.
- Prove that speculative decoding preserves the target distribution, and compile a regex or JSON schema subset into token masks.
Before you begin
Section titled “Before you begin”You should have the Llama-family model of the modern block, in particular GQA attention and the Llama-family model. Three sections of Mathematics are used just in time: rejection sampling and residual distributions for speculative decoding, error analysis and tolerance budgets and FP8 and microscaling formats for quantization, with the floating-point problem set, part b for practice. The optional C sections rely on the structures in systems data structures from Programming and Algorithms: the growable array, the Swiss table, the intrusive LRU, and the radix tree.
In this chapter
Section titled “In this chapter”- Sampling and logit processors: the eleven-step sampling pipeline of
spec/sampling.md, with penalties, filters, and a single uniform draw, written so Python and Rust emit the same token. - The KV cache, incremental decoding, and generate: an exact KV cache with committed length and rollback, the generate loop, an incremental UTF-8 detokenizer, and safe streaming around stop strings.
- A paged KV cache in Python: an optional section that stores the cache in fixed-size blocks with block tables, reference counts, and copy on write, matching the contiguous cache exactly.
- A radix prefix cache: block-granular prefix matching over a radix tree in Rust, with locks that pin running requests and LRU leaf eviction.
- Quantization: int8, int4 groups, fp8, and the KV cache: symmetric quantization schemes in the kernel’s byte layout, each with a derived error budget and a measured perplexity cost.
- Speculative decoding: n-gram, prompt-lookup, and model drafts, verified in one target pass with rules that keep greedy output identical and sampled output exactly distributed.
- Constrained decoding: from regex to token masks: regex to NFA to canonical DFA to token masks, and a JSON schema subset compiled to a regex for tool calls.
- A paged KV block pool in C: an optional C block pool with free, used, and cached states, chained block hashes, an LRU, and a checksummed export format.
Further reading
Section titled “Further reading”- Kwon et al., Efficient Memory Management for LLM Serving with PagedAttention (the vLLM block manager); Zheng et al., SGLang (RadixAttention); llama.cpp (
llama_batch). - Leviathan, Kalman, and Matias, Fast Inference from Transformers via Speculative Decoding; Willard and Louf, Efficient Guided Generation for LLMs.