Inference

Two-panel comic: 'Training' shows five robots at school desks all writing at once with open answer keys, captioned 'All at once, with the answers'; 'Inference' shows a single robot alone on stage at a typewriter with 'The cat sat' typed, a thought bubble spinning between 'on? in? with? under?', a long scroll trailing off the stage, captioned 'One word at a time, no answer key'
What You’ll Learn

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:

StepAction
1Run forward pass on the current sequence
2Get probability distribution over the vocabulary for the next token
3Pick a token from that distribution
4Append it to the sequence
5Repeat 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 ii depend only on token ii‘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.

Fill in the Blanks
During generation, the KV cache stores the and vectors from previous tokens so they don't need to be recomputed. The vector is not cached because it comes from the new token being processed.
Fill in every blank, then check your answer.

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:

Level 1 · Near-Greedy Decoding Drag the Temperature slider left until the top token (“mat”) reaches 90%+ probability.
0.1 (greedy) 3.0 (flat)
off (0) 10
0.10 off (1.0)
Next token after “The cat sat on the ___” 10 / 10 candidates active
mat
37.8%
floor
25.3%
bed
12.6%
couch
6.9%
table
5.1%
ground
4.2%
rug
3.1%
roof
2.1%
grass
1.7%
chair
1.3%
StrategyHow It WorksTradeoff
GreedyAlways pick the highest probability tokenDeterministic but repetitive
TemperatureDivide logits by T before softmaxLow T = focused, high T = diverse
Top-kOnly consider the top k tokensRemoves low-probability nonsense
Top-p (nucleus)Consider tokens until cumulative probability reaches pAdapts 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.

Quick Check
What happens to sampling as temperature approaches 0?
Your turn
Choose an answer to check your understanding.

The Inference Pipeline

Putting it all together, here’s what happens when you send a prompt to an LLM:

StepAction
1User types a prompt
2Tokenize the prompt
3Prefill: forward pass through all layers on the full prompt (parallel, compute-bound)
4Cache all K and V vectors from the prefill
5Sample the first generated token from the output distribution
6Decode: forward pass for just the new token, reusing cached K/V (sequential, memory-bound)
7Repeat steps 5-6 until done
8Detokenize 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

AspectTrainingInference
DirectionForward + backward passForward only
ParallelismAll positions in parallelOne token at a time
InputGround truth tokens (teacher forcing)Model’s own predictions
OutputLoss and gradientsNext token probability
SpeedSlow (backprop is expensive)Fast per token (with KV cache)
HardwareMany GPUs for weeksFewer GPUs, real-time (large models still need multiple GPUs)

Learning Checklist
  • 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 →