How LLM inference works, prefill, decode and the KV cache
Every serving trick in this track, from PagedAttention to speculative decoding to prompt caching, is a response to one simple fact: a language model generates text one token at a time, and each new token needs to look back at every token before it. If you understand the two phases of a request (prefill and decode) and the data structure that connects them (the KV cache), the rest of inference engineering stops feeling like magic and starts feeling like plumbing.
Why it matters
When people first deploy a model they usually think in terms of "requests per second", the way they would for a web API. That mental model breaks quickly. Two requests with the same prompt length can cost wildly different amounts depending on how many tokens they generate. A GPU that looks 30 percent utilised can still be the bottleneck. Latency has two separate components that users feel differently: the wait before the first word appears, and the speed at which words stream after that.
All of that falls out of the prefill and decode split. Once you see it, you can reason about:
- why time to first token (TTFT) grows with prompt length while time per output token (TPOT) grows with batch size and context length,
- why GPU memory, not compute, is usually what limits how many users you can serve at once,
- why caching a shared system prompt saves real money and real latency,
- why smaller "draft" models and quantization speed things up at all.
How it works
A decoder-only transformer takes a sequence of token ids and, for each position, produces a probability distribution over the next token. Inside every layer, attention computes three projections for each token: a query (Q), a key (K) and a value (V). A token's output depends on its own query compared against the keys of every earlier token, weighted by their values.
Here is the key observation: once a token has been processed, its K and V vectors never change. So instead of recomputing them for every new token, the engine stores them. That store is the KV cache.
A request then runs in two phases.
Prefill. The engine takes the whole prompt (system prompt, chat history, retrieved documents, user message) and runs it through the model in one big parallel pass. Every prompt token's K and V get written into the cache, and the final position produces the first output token. Because thousands of tokens are processed together, this phase does a lot of matrix multiplication per byte of weights loaded. It is compute bound: faster tensor cores make it faster.
Decode. Now the model produces one token per step. Each step feeds only the newest token in, computes its Q, K and V, appends K and V to the cache, attends over the entire cache, and samples the next token. The model weights have to be read from GPU memory on every step, but only a handful of tokens' worth of arithmetic is done with them. This phase is memory-bandwidth bound: the speed limit is how fast the GPU can stream weights and KV cache out of HBM.
Rendering diagram…
A rough rule of thumb I use at the whiteboard: for a single stream, an upper bound on decode speed is
tokens_per_second ≈ memory_bandwidth / bytes_read_per_step
bytes_read_per_step ≈ weight_bytes + kv_cache_bytes_for_this_sequence
That is why decode speed barely changes when you buy a GPU with more FLOPs but the same memory bandwidth, and why shrinking weights with quantization helps decode so much. It is also why batching works: if you are already paying to stream the weights once per step, you can serve 32 sequences with that same read and only pay extra for their individual KV caches.
Sizing the KV cache
The cache grows linearly with tokens. Per token it costs:
kv_bytes_per_token = 2 (K and V) × num_layers × num_kv_heads × head_dim × bytes_per_element
For a model with 32 layers, 8 KV heads (grouped-query attention) and head dimension 128 stored in FP16 (2 bytes), that is 2 × 32 × 8 × 128 × 2 = 131,072 bytes, or 128 KiB per token. A single 32k-token conversation therefore needs about 4 GiB of cache on top of the weights. Multiply by concurrent users and you see why memory is the scarce resource. The GPU sizing doc works through this in detail.
Reference architecture
In a real server, many requests are in flight at once and a scheduler decides, every step, which ones get GPU time. New requests need prefill; existing ones need decode. Modern engines mix them in the same step (continuous batching, often with chunked prefill so a giant prompt does not stall everyone else's decode).
Rendering diagram…
Larger deployments go one step further and run prefill and decode on different GPU pools, shipping the KV cache between them (disaggregated serving). That is covered in the serving engines doc.
Code
You do not need a serving engine to see the two phases. With Hugging Face Transformers you can run them by hand and watch the cache grow.
import time, torch
from transformers import AutoModelForCausalLM, AutoTokenizer
model_id = "Qwen/Qwen2.5-0.5B-Instruct"
tok = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.float16).to("cuda")
ids = tok("Explain the KV cache in one sentence.", return_tensors="pt").input_ids.to("cuda")
with torch.no_grad():
t0 = time.perf_counter()
out = model(ids, use_cache=True) # prefill: whole prompt at once
past = out.past_key_values
next_id = out.logits[:, -1].argmax(-1, keepdim=True)
print(f"prefill {ids.shape[1]} tokens: {time.perf_counter() - t0:.3f}s")
generated = [next_id]
t1 = time.perf_counter()
for _ in range(64): # decode: one token per step
out = model(next_id, past_key_values=past, use_cache=True)
past = out.past_key_values
next_id = out.logits[:, -1].argmax(-1, keepdim=True)
generated.append(next_id)
print(f"decode 64 tokens: {time.perf_counter() - t1:.3f}s")
print(tok.decode(torch.cat(generated, dim=1)[0]))
Try doubling the prompt length and doubling the number of generated tokens separately. You will see prefill time respond to the first and decode time respond to the second, which is the whole story of this doc in two numbers.
Trade-offs and pitfalls
- Batching trades per-user speed for throughput. Bigger decode batches raise total tokens per second but each user's stream gets a little slower, and every sequence's KV cache competes for the same memory.
- Long prompts hurt everyone, not just their owner. A 100k-token prefill can monopolise the GPU for a noticeable time. Chunked prefill exists precisely to interleave it with other users' decode steps.
- Output length is the hidden cost driver. Decode steps are sequential, so a request that generates 2,000 tokens occupies a batch slot for 2,000 steps. Setting sensible
max_tokensis a capacity decision, not just a cost one. - Attention cost grows with context. Each decode step attends over the whole cache, so very long contexts slow down decode too, even though the weight reads are constant.
- GQA and MQA matter. Models with fewer KV heads than query heads have much smaller caches. When comparing models for serving, check
num_key_value_headsin the config, not just parameter count.
Checklist
- I can explain why prefill is compute bound and decode is memory-bandwidth bound.
- I measure TTFT and TPOT separately rather than one "latency" number.
- I can compute KV bytes per token from a model's config.json.
- I set
max_tokensdeliberately for each endpoint. - I know whether my engine uses chunked prefill and continuous batching.
- I check the number of KV heads when choosing a model to self-host.
Further reading
- Efficient Memory Management for Large Language Model Serving with PagedAttention (vLLM paper)
- Transformer inference arithmetic, kipply's blog
- GQA: Training Generalized Multi-Query Transformer Models
- DistServe: disaggregating prefill and decoding
- vLLM production metrics (TTFT and inter-token latency)