Skip to content
ImagineWorld

Inference: How Generation Works

node_idnode-book_building-frontier-llm-from-scratch_chapter-27-inference-how-generation-works
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num27
chapter_titleInference: How Generation Works
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 27 — Inference: How Generation Works

Section titled “Chapter 27 — Inference: How Generation Works”

Part VII — Inference, Serving, and Evaluation

Training gets the attention, but inference is where a model spends its life and most of its total compute across millions of requests. Generating text efficiently is a distinct engineering problem from training, with its own dominant cost — the key/value cache — and its own characteristic structure. Understanding it explains why the architectural choices of Part IV (MLA above all) mattered so much, and sets up the serving systems of the next chapter. This chapter covers how a single generation actually runs.

Generation splits into two phases with opposite performance characteristics. Prefill processes the entire prompt at once: because all prompt tokens are known, they pass through the model in parallel in a single forward pass, which is compute-bound and uses the GPU efficiently. Decode then generates the response one token at a time — each new token depends on the previous one, so it is inherently sequential, and each step does very little arithmetic while reading the entire model and cache from memory. Decode is therefore memory-bound, exactly the regime Chapter 2’s roofline warned about, and it dominates the cost of long generations. Table 27.1 contrasts the two.

PhaseProcessesParallelismBottleneck
Prefillthe whole prompt at onceall prompt tokens in parallelcompute-bound
Decodeone new token per stepsequentialmemory-bound (reads weights + cache)

Table 27.1 — The two phases of inference

Figure 27.1. Inference in two phases. Prefill runs the whole prompt through the model in one parallel pass, filling the KV cache; decode then generates tokens one at a time, reading and extending the cache at every step.

The reason decode is even tractable is the KV cache introduced in Chapter 12. Each generated token must attend to all previous tokens, whose keys and values would otherwise be recomputed every step — quadratic wasted work. Instead, the keys and values of every processed token are stored and reused, so each decode step computes only the new token’s query, key, and value and attends against the cached rest. This turns per-step work from growing with sequence length into roughly constant — but at the price of memory that grows with every token, which is exactly the cost MLA was designed to slash. The generation loop, with an explicit cache, makes the two phases visible:

@torch.no_grad()
def generate(model, prompt_ids, max_new, temperature=1.0):
cache = model.new_kv_cache()
logits = model(prompt_ids, cache=cache)[:, -1]
out = [prompt_ids]
for _ in range(max_new):
probs = (logits / temperature).softmax(dim=-1)
nxt = torch.multinomial(probs, num_samples=1)
out.append(nxt)
logits = model(nxt, cache=cache)[:, -1] # DECODE: 1 token, cache reused
return torch.cat(out, dim=1)

Python — infer.py: prefill once, then decode with a reused cache

Note the shape of the work: prefill passes many tokens, decode passes exactly one per call. This is why a long prompt is cheap to ingest but a long answer is expensive to produce, and why inference systems optimize the two phases separately.

Decode’s sequential, memory-bound nature leaves the GPU’s arithmetic mostly idle — which speculative decoding exploits. A small, fast draft model proposes several tokens ahead; the large target model then verifies all of them in a single forward pass (which costs about the same as generating one token, since it is memory-bound), accepting the longest correct prefix. When the draft is usually right, several tokens are produced per expensive step. The draft can be a separate small model, or — as Chapter 13 showed — the target model’s own multi-token prediction heads, which is why DeepSeek-V3 gets a roughly 1.8× decode speed-up essentially for free. The output is provably identical to standard decoding; only the speed changes.

Code reference — vllm-project/vllm · ggerganov/llama.cpp · Leviathan et al., “Fast Inference via Speculative Decoding”

vLLM and llama.cpp implement cached generation and speculative decoding production-ready; the speculative-decoding paper proves the equivalence to exact sampling. The cache management above is, in real systems, the most heavily optimized code path in inference.

One generation is now efficient. But a deployed model serves thousands of concurrent requests, and batching them well — without wasting the memory the KV cache demands — is a systems problem of its own. That is the subject of the next chapter.

Autoregressive generation would be quadratic if every step recomputed attention over the whole prefix. The KV cache makes it linear by storing each step’s keys and values and appending to them, so step t attends a fresh query against all cached keys without recomputation:

class KVCache:
def __init__(self):
self.k, self.v = None, None
def update(self, k_new, v_new):
self.k = k_new if self.k is None else torch.cat([self.k, k_new], 1)
self.v = v_new if self.v is None else torch.cat([self.v, v_new], 1)
return self.k, self.v
# decoding step t attends its new query against ALL cached k, v;
# cost per token is O(t), not O(t^2) — and the cache is the memory cost
# that MLA (Chapter 12) and the compression of Chapter 41 fight to reduce

Python — the KV cache that makes generation fast

Generation is bottlenecked by one forward pass per token. Speculative decoding (Chapter 28) breaks that: a cheap draft proposes several tokens and the large model verifies them all in a single parallel pass, accepting the longest agreeing prefix:

draft = small_model.generate(prefix, k=4) # cheap guesses
logits = big_model(prefix + draft) # ONE parallel verification pass
accepted = 0
for i, tok in enumerate(draft): # accept while they agree
if sample(logits[i]) == tok:
accepted += 1
else:
break
# emit the accepted tokens plus one correction; the MTP heads of
# Chapter 13 can BE the draft — how GLM-5.2 (Chapter 44) speeds decoding

Python — speculative decoding: draft cheaply, verify in parallel

27.6 Decoding Strategies: Temperature, Top-k, and Nucleus

Section titled “27.6 Decoding Strategies: Temperature, Top-k, and Nucleus”

The model emits a probability distribution over the vocabulary at every step; how you draw a token from it shapes the output’s character. Greedy decoding (always the argmax) is deterministic but prone to dull repetition. Temperature rescales the logits before the softmax — below one sharpens the distribution toward its peak, above one flattens it. Top-k keeps only the k most probable tokens; nucleus (top-p) keeps the smallest set whose probability sums past p, adapting the candidate pool to the distribution’s shape:

def sample(logits, temperature=0.8, top_p=0.95):
logits = logits / temperature
probs = F.softmax(logits, dim=-1)
sorted_p, idx = torch.sort(probs, descending=True)
cdf = torch.cumsum(sorted_p, dim=-1)
keep = cdf - sorted_p < top_p # the nucleus
sorted_p = sorted_p * keep
sorted_p = sorted_p / sorted_p.sum()
return idx[torch.multinomial(sorted_p, 1)]

Python — infer/sample.py: temperature + nucleus sampling

The choice is task-dependent and consequential. Reasoning, mathematics, and code want a low temperature (often 0–0.3): there is usually one right continuation, and creativity is a liability — which is why the reasoning models of Chapter 25 are evaluated near-greedy. Open-ended writing wants a higher temperature and a nucleus around 0.9–0.95, where the model can surprise without going incoherent. Nucleus sampling is generally preferred over a fixed top-k because it widens the pool when the model is uncertain and narrows it when the model is confident, rather than imposing the same cutoff on both.

27.7 Worked Example: KV-Cache Memory at Long Context

Section titled “27.7 Worked Example: KV-Cache Memory at Long Context”

Section 27.2 introduced the KV cache; at long context its size is the dominant cost of inference, and it is the single number that motivates much of Part IV. The cache holds, for every layer and every past token, one key and one value vector. For standard multi-head attention the arithmetic is unforgiving:

SchemeStored per token / layerTotal at 128K
MHA (64 heads × 128 dim)2 × 64 × 128 × 2 B~335 GB
MLA (512-dim latent)~(512 + 64) × 2 B~12 GB

Table 27.1 — KV-cache memory at 128K tokens (80-layer model, BF16, batch 1)

The full-attention cache — about 335 gigabytes — does not fit on any single accelerator; it would not fit on eight. Multi-Head Latent Attention (Chapter 12) stores a single compressed latent per token per layer instead of one vector per head, cutting the same cache to roughly twelve gigabytes — an almost thirty-fold reduction that is the difference between a 128K context being serviceable and being impossible. This is the concrete payoff of MLA, and alongside paged attention (Section 28.3) and KV

quantization it is why frontier models can offer the long contexts they advertise.

At long context, the cache is the cost Weights are fixed; the KV cache grows linearly with tokens and batch. Past a few tens of thousands of tokens it dominates inference memory, which is why every long-context model attacks it — MLA to shrink it, paging to stop wasting it, quantization to compress it.

Before sampling became standard, the dominant decoding method was beam search, which keeps the b most probable partial sequences at each step and expands them, aiming to find the single highest-likelihood completion. It still rules tasks with one correct output — machine translation, speech recognition — but for open-ended generation it fell out of favor for a revealing reason:

beams = [(0.0, start)]
for _ in range(max_len):
cand = []
for lp, seq in beams:
for tok, tlp in top_tokens(model(seq)):
cand.append((lp + tlp, seq + [tok]))
beams = sorted(cand, reverse=True)[:b] # prune to top b

Python — infer/beam.py: keep the b best partial sequences

The trouble is that the most probable sequence is often the most generic one. Maximizing likelihood drives beam search toward safe, repetitive, low-information text — the bland average of what the model has seen — which is exactly wrong for writing, dialogue, or brainstorming where surprise is the point. Sampling with temperature and nucleus filtering (Section 27.6) deliberately trades a little probability for diversity, and produces text that reads as alive rather than hedged. The rule that emerged is clean: beam search or greedy decoding for tasks with a single correct answer, sampling for open-ended generation — and reasoning models (Chapter 25) sit at the greedy end precisely because their task, underneath the prose, has a right answer.

Most likely is not most interesting Beam search finds the highest-probability sequence, which for open-ended generation is usually the dulllest. Sampling sacrifices a little likelihood for the diversity hat makes text engaging — which is why it won everywhere except tasks with one correct output.

27.9 Constrained Decoding: Grammars and JSON

Section titled “27.9 Constrained Decoding: Grammars and JSON”

Many applications need the model’s output to obey a structure — valid JSON, a fixed schema, a programming-language grammar — and hoping the model simply remembers to comply is fragile. Constrained decoding makes compliance a guarantee rather than a hope by masking the logits at every step so that only tokens which keep the output well-formed can be sampled:

allowed = grammar.allowed_tokens(state) # valid next tokens
logits[~allowed] = float("-inf") # forbid the rest
next_id = sample(logits) # choose among valid only
state = grammar.advance(state, next_id) # update the parser state

Python — infer/constrained.py: mask logits to a grammar

A grammar or finite-state machine tracks what is legal given what has been emitted so far — after an opening brace, only a key or a closing brace is valid; after a key, only a colon — and at each step the mask forbids every token that would break the structure. Because invalid tokens are assigned negative infinity before sampling, the model cannot produce malformed output, no matter how it was prompted; the structure is enforced by construction rather than learned by hope. This is what lets language models serve reliably as components in larger systems (Chapter 36), emitting JSON an API can parse or function calls an agent can execute (Section 39.5), and it is a clean example of constraining a probabilistic model into deterministic guarantees where an application demands them.

Enforce structure, do not hope for it Constrained decoding masks out every token that would break a grammar, so valid JSON or a well-formed function call is guaranteed regardless of the prompt. It is how a stochastic model becomes a dependable system component.

The KV cache (Section 27.2) is the memory that grows with context length, and at long sequences it dominates — often exceeding the weights themselves. Multi-Head Latent Attention (Chapter 12) attacks this by compressing what is stored, but there is a second, orthogonal lever: quantize the cache entries themselves. The keys and values, normally held in 16-bit precision, can instead be stored in INT8 or even INT4, halving or quartering the cache’s memory footprint.

The trade is the familiar one from Chapter 26, now applied to the cache rather than the weights: lower precision means a small loss of accuracy in the attention computation, in exchange for a large memory saving. Because it operates on a different quantity, KV-cache quantization composes with the other techniques — you can run a weight-quantized model (Section 26.7) with MLA’s compressed cache (Section 12.7) and additionally quantize that cache, stacking the savings. Its practical value is in what the freed memory buys: a longer maximum context, or a larger batch size (Section 28.2) and thus higher throughput, from the same hardware. For deployments pushing context length or serving many concurrent long-context requests, quantizing the cache is one of the most direct ways to fit more on each GPU, and it slots cleanly alongside the compression and paging strategies the serving chapters describe.

Quantize the cache, not just the weights The KV cache can be stored in INT8 or INT4, shrinking the memory that grows with context at a small accuracy cost. It composes with MLA and weight quantization — stacking savings to fit longer contexts or bigger batches on the same GPU.