Sub topic 2
How LLM Generation Works: Prefill and Decode
This chapter assumes basic Python, command-line use, GPU memory, and familiarity with prompts and completions.
An LLM generates text one token at a time. A token is a piece of text, such as a word, part of a word, or punctuation. Generation has two different phases: prefill and decode.
The two phases
During prefill, the model reads the complete input prompt. It processes the prompt tokens together, using parallel GPU operations. This phase produces the first next-token scores and stores attention data for the prompt.
During decode, the model repeatedly generates one new token. Each new token becomes part of the context for the next step. The model does not usually recompute the full prompt. Instead, it reuses stored attention data in a key-value cache, often called the KV cache.
Prefill is often compute-bound. The GPU performs large matrix operations over many prompt tokens. Longer prompts usually increase time to first token, or TTFT.
Decode is often limited by memory movement and scheduling. Each step handles only one new token per sequence, but it reads the model weights and the relevant KV-cache entries. Longer generated outputs require more decode steps. The time between generated tokens is called inter-token latency, or ITL.
A simple walkthrough
Suppose the prompt is:
“Explain continuous batching.”
- Tokenization converts the text into prompt tokens.
- Prefill processes all prompt tokens and builds their keys and values.
- The model produces scores for the next token.
- A sampling rule selects a token, such as “Continuous.”
- Decode processes that new token while reusing the prompt’s KV cache.
- The model selects another token and repeats until it produces a stop token or reaches the token limit.
| Phase | Input per sequence | Main work | Common limit |
|---|---|---|---|
| Prefill | Many prompt tokens | Parallel computation | Compute and prompt length |
| Decode | One new token | Cache reads and sequential steps | Memory bandwidth and latency |
The distinction matters for serving. A workload with short prompts and long answers stresses decode capacity. A workload with large documents and short answers stresses prefill capacity. A scheduler must balance both kinds of work so that one long request does not prevent other requests from making progress.
Exercise
Why does decode usually process one new token instead of recomputing the entire prompt?
Show answer
Decode reuses the prompt and earlier tokens through the KV cache, avoiding repeated computation and reducing latency.