Skip to content

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.

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.

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.

  1. 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.
  2. 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.
  3. 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.
  4. A radix prefix cache: block-granular prefix matching over a radix tree in Rust, with locks that pin running requests and LRU leaf eviction.
  5. 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.
  6. 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.
  7. 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.
  8. 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.