Sub topic 2
How LLM generation works: prefill and decode
This chapter assumes you know what a prompt and a completion are, can read basic Python, and have a rough idea of what a GPU does. It explains the two phases of every generation request. The rest of the tutorial's tuning advice depends on this split.
Generation is a loop
A language model does not write a reply in one pass. It predicts one token at a time. A token is a piece of text, often a word or part of a word, that the model's tokenizer maps to an integer ID.
This is called autoregressive decoding. Each step does the following:
- Take all tokens so far (the prompt plus anything already generated).
- Run the model to get a score for every token in the vocabulary.
- Choose one token from those scores.
- Append it to the sequence and repeat.
The loop stops when the model emits a special end-of-sequence token or when a length limit is reached.
The following script is the loop written out by hand with Hugging Face transformers. It uses greedy selection, which always takes the highest-scoring token.
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
name = "Qwen/Qwen2.5-1.5B-Instruct"
tok = AutoTokenizer.from_pretrained(name)
model = AutoModelForCausalLM.from_pretrained(name, torch_dtype=torch.bfloat16).to("cuda")
ids = tok("The capital of France is", return_tensors="pt").input_ids.to("cuda")
with torch.no_grad():
for _ in range(10):
logits = model(ids).logits # shape: (batch, seq_len, vocab)
next_id = logits[0, -1].argmax() # score for the next position only
ids = torch.cat([ids, next_id.view(1, 1)], dim=1)
print(tok.decode(ids[0]))This loop is correct but wasteful. Every iteration feeds the whole sequence back through the model, so work done for earlier tokens is repeated. The next chapter shows how a cache removes that repetition. The cost structure of the loop is already visible here, and it leads to the two phases.
The two phases
Each request passes through two phases with very different hardware behavior.
Prefill processes the entire prompt in one forward pass. All prompt tokens are known in advance, so the GPU handles them in parallel as large matrix multiplications. At the end of prefill the model produces the first output token.
Decode produces every later token. Each step needs the token chosen in the previous step, so the steps cannot run in parallel. Each step handles one new token per request.
Why the phases behave differently
A GPU has two limits that matter here: how many arithmetic operations it can do per second (compute) and how many bytes it can read from memory per second (memory bandwidth).
| Property | Prefill | Decode |
|---|---|---|
| Tokens processed per step | Whole prompt (hundreds to thousands) | One per request |
| Parallelism inside a request | High | None across steps |
| Typical bottleneck | Compute | Memory bandwidth |
| What the user feels | Wait before the first token | Speed of the streaming text |
| Metric | Time to first token (TTFT) | Time per output token (TPOT) |
In decode, the GPU must read all of the model's weights from memory to produce a single token for a request. A 1.5B-parameter model in 16-bit precision is about 3 GB of weights. Reading 3 GB for one token means the arithmetic units sit mostly idle while they wait for data. This is why decode is called memory-bound.
In prefill, the same weight read is shared across thousands of prompt tokens, so the GPU spends its time computing. This is why prefill is called compute-bound.
Why batching changes the picture
Because a decode step is limited by reading weights, reading them once and applying them to many requests costs little more than applying them to one. If 32 requests each need one token, the weights are still read once, and the GPU produces 32 tokens for roughly the price of one.
This is the main reason serving systems group requests. Throughput, meaning total tokens per second across all users, rises sharply with batch size until compute or memory runs out. Per-request latency rises only slightly at first.
The batch cannot grow without limit. Each active request holds memory for its own state, which is the subject of the next chapter. When that memory is full, no more requests can join the batch. This is why the tutorial describes serving as bound by memory and scheduling.
Measuring the two phases yourself
You can observe the split with vLLM. Requesting a single output token makes a run almost pure prefill. Requesting many tokens adds decode time. The script below uses ignore_eos=True so each request generates exactly the number of tokens asked for.
import time
from vllm import LLM, SamplingParams
llm = LLM(
model="Qwen/Qwen2.5-1.5B-Instruct",
max_model_len=4096,
gpu_memory_utilization=0.85,
)
long_prompt = "Summarize the following text. " + "The quick brown fox jumps over the lazy dog. " * 150
def timed(max_tokens):
params = SamplingParams(temperature=0.0, max_tokens=max_tokens, ignore_eos=True)
start = time.perf_counter()
llm.generate([long_prompt], params, use_tqdm=False)
return time.perf_counter() - start
timed(1) # warm-up so one-time setup is not counted
prefill_only = timed(1)
with_decode = timed(129)
per_token = (with_decode - prefill_only) / 128
print(f"about prefill (long prompt + 1 token): {prefill_only * 1000:.0f} ms")
print(f"about per decoded token: {per_token * 1000:.1f} ms")Subtracting the one-token run from the 129-token run isolates 128 decode steps. The result is approximate, because the one-token run also includes a little scheduling overhead. On a modern GPU you should see a per-token figure of a few milliseconds, and the prefill figure should grow as you lengthen the prompt.
Consequences for how you serve
Several practical rules follow from the two-phase model.
- Long prompts raise TTFT. Prefill time grows with prompt length. A 4,000-token prompt costs far more before the first token than a 100-token prompt.
- Long outputs raise total latency. Decode time grows linearly with the number of generated tokens, because each token needs its own step.
- Prompt length and output length are different costs. A request with a long prompt and a short answer stresses prefill. A request with a short prompt and a long answer stresses decode. Benchmark with the mix your application sends.
- Prefill can interfere with decode. A large prefill occupies the GPU and can delay decode steps of other users, which shows up as stutter in streaming responses. Schedulers have to balance the two.
- Output tokens cost more than input tokens in time. This is the reason many hosted APIs price them higher.
Common mistakes
- Treating "tokens per second" as one number. Prefill speed (prompt tokens processed per second) and decode speed (output tokens per second) differ by a large factor. Report them separately.
- Confusing TTFT with total latency. A system can start answering quickly and still finish slowly if the answer is long.
- Assuming a bigger GPU always speeds up decode. Decode speed tracks memory bandwidth more than raw compute, so compare bandwidth figures when choosing hardware.
- Forgetting the stop condition. Without
max_tokensor an end-of-sequence token, a generation can run to the model's context limit.
Exercise
A chatbot returns a 20-token answer to a 3,000-token prompt, and users complain that it feels slow before any text appears. Which phase is the likely cause, and why would adding more output-length limits not help?
Show answer
Prefill is the likely cause. Processing a 3,000-token prompt takes a long time before the first token can be produced, which is the TTFT. The answer is only 20 tokens, so decode is a small part of the total, and capping output length would remove little time. Shortening the prompt, using prefix caching for shared prompt text, or faster compute would address the delay.
Exercise
Why does serving 32 requests together in a decode step cost far less than 32 times the cost of serving one?
Show answer
A decode step is limited by memory bandwidth, because the GPU must read all model weights to produce a token. Those weights are read once per step no matter how many requests are in the batch, so the extra requests add little memory traffic and use arithmetic capacity that would otherwise be idle.