Inference
You’ll learn how autoregressive generation works: predict one token, append it, and repeat. You’ll also see why inference is sequential, how the KV cache avoids repeated work, why Q is not cached, and how sampling choices shape the output.
You’ve seen how a transformer trains: all positions in parallel, teacher forcing, cross-entropy loss. But at inference time, there’s no ground truth. The model is on its own, generating one token at a time.
Autoregressive Generation
The model generates text by repeating a simple loop:
| Step | Action |
|---|---|
| 1 | Run forward pass on the current sequence |
| 2 | Get probability distribution over the vocabulary for the next token |
| 3 | Pick a token from that distribution |
| 4 | Append it to the sequence |
| 5 | Repeat until done (or max length) |
This is the opposite of training. During training, the model processes all positions in parallel because the full sequence is available. During generation, each new token depends on the previous one, so the model must run sequentially. Position 5 can’t be generated until position 4 exists.
This sequential nature is why LLMs feel slow when generating long responses: each token requires a full forward pass through every layer. A 96-layer model must run all 96 layers just to produce one word.
KV Cache: Why Generation Gets Faster
There’s something wasteful about the loop above: every time we generate a new token, we re-run the forward pass on the entire sequence, including recomputing K and V for tokens we’ve already processed. But those tokens haven’t changed!
The insight: K and V for token depend only on token ‘s embedding and the weight matrices. Once computed, they’re fixed forever. Only the new token needs fresh K and V.
The KV cache stores previous tokens’ K and V vectors so they don’t need to be recomputed:
Generate "The": Compute K₁,V₁ → cache them → predict "cat"
Generate "cat": Compute K₂,V₂ → cache them → reuse K₁,V₁ → predict "sat"
Generate "sat": Compute K₃,V₃ → cache them → reuse K₁,V₁,K₂,V₂ → predict ...
Without the KV cache, generating the 100th token requires recomputing K and V for all 99 previous tokens. With the cache, we compute K and V for just the new token and concatenate with the cached values.
Why not cache Q too? The new token’s Q is what we actually need: it’s the “question” that searches over all cached keys to find relevant context. There’s nothing to reuse, because the query comes from the token we’re currently processing.
The trade-off is memory. GPT-3 175B with a 2K context window needs ~9 GB of KV cache per request in FP16 (96 layers × 2,048 tokens × 2 vectors × 12,288 dims × 2 bytes). This is why techniques like GQA (which shrink K and V by sharing them across query heads) are so important for serving real users.
Sampling Strategies
The forward pass produces a probability distribution over the entire vocabulary. How we pick a token from that distribution dramatically affects the output quality. Clear the 3 sampling puzzles below:
| Strategy | How It Works | Tradeoff |
|---|---|---|
| Greedy | Always pick the highest probability token | Deterministic but repetitive |
| Temperature | Divide logits by T before softmax | Low T = focused, high T = diverse |
| Top-k | Only consider the top k tokens | Removes low-probability nonsense |
| Top-p (nucleus) | Consider tokens until cumulative probability reaches p | Adapts to distribution shape |
Why top-p is often better than top-k: Top-k always keeps exactly k tokens, regardless of how the probability is distributed. If the model is very confident (one token at 95%), top-k=10 still keeps 9 unlikely tokens. Top-p adapts: it would keep just 1-2 tokens when the model is confident and more when it’s uncertain.
The Inference Pipeline
Putting it all together, here’s what happens when you send a prompt to an LLM:
| Step | Action |
|---|---|
| 1 | User types a prompt |
| 2 | Tokenize the prompt |
| 3 | Prefill: forward pass through all layers on the full prompt (parallel, compute-bound) |
| 4 | Cache all K and V vectors from the prefill |
| 5 | Sample the first generated token from the output distribution |
| 6 | Decode: forward pass for just the new token, reusing cached K/V (sequential, memory-bound) |
| 7 | Repeat steps 5-6 until done |
| 8 | Detokenize back to text and return |
The prefill phase is fast (processes the full prompt in parallel, like training). The decode phase is slow (one token at a time, bottlenecked by reading the KV cache from memory). This is why “time to first token” (TTFT) and “tokens per second” are reported as separate metrics.
Quick Summary
| Aspect | Training | Inference |
|---|---|---|
| Direction | Forward + backward pass | Forward only |
| Parallelism | All positions in parallel | One token at a time |
| Input | Ground truth tokens (teacher forcing) | Model’s own predictions |
| Output | Loss and gradients | Next token probability |
| Speed | Slow (backprop is expensive) | Fast per token (with KV cache) |
| Hardware | Many GPUs for weeks | Fewer GPUs, real-time (large models still need multiple GPUs) |
- I can explain why inference is sequential (autoregressive) even though training is parallel
- I know what the KV cache stores and why it speeds up generation
- I can explain why Q is not cached but K and V are
- I understand the difference between prefill (parallel, compute-bound) and decode (sequential, memory-bound)
- I know the difference between greedy decoding, temperature sampling, top-k, and top-p
Next: End-to-End Walkthrough
You understand the architecture, training, and generation. Time to watch it all happen with real numbers: every matrix multiply, every dot product, every softmax, traced through a complete forward pass. End-to-End Walkthrough →