Two jobs hiding inside one request
In Level 1 you watched one request turn into tokens, one at a time. Look at a request's timeline on a GPU and you see two phases that behave very differently:
- Prefill. The model reads your whole prompt in one forward pass. Every prompt token is processed in parallel, so 4,000 tokens of RAG context become a few big matrix multiplications. This phase is compute-bound: the GPU's maths units are the limit.
- Decode. The model produces the reply one token per forward pass, because token n+1 depends on token n. Each step does very little maths, but it still has to read every weight of the model from GPU memory. This phase is memory-bandwidth-bound.
Think of a chef with a walk-in fridge. Prefill is cooking a banquet: they fetch every ingredient once and use each one for hundreds of plates. Decode is making one plate at a time, with a fresh trip into the fridge for every plate. The walking, not the cooking, sets the pace.
Why decode is starved for bandwidth: the numbers
Take Qwen2.5-7B-Instruct (7.61B parameters, Apache-2.0). In BF16 each parameter takes 2 bytes:
params = 7.61e9
weight_bytes = params * 2 # BF16 = 2 bytes per parameter
print(weight_bytes / 1e9) # ~15.2 GB to read for every decode step
# Rough work: ~2 FLOPs (one multiply, one add) per parameter per token
flops_per_token = 2 * params # ~15.2 GFLOP
# H100 SXM datasheet: 3.35 TB/s HBM bandwidth, ~989 TFLOPS dense BF16
bw, compute = 3.35e12, 989e12
print(compute / bw) # ~295 FLOPs the GPU *could* do per byte it reads
At batch size 1, decode does about 1 FLOP per byte (2 FLOPs per 2-byte weight). The GPU can do roughly 295. So more than 99% of its maths capacity sits idle while it waits on memory. Prefill on a 2,000-token prompt reuses each weight 2,000 times, which is far more work per byte, so the maths units become the limit.
Your decode speed ceiling
If every decode step reads all the weights once, then:
max tokens/s ≈ memory bandwidth ÷ weight bytes
gpus = { # datasheet bandwidth, bytes/s
"L40S (GDDR6)": 864e9,
"A100 80GB SXM": 2039e9,
"H100 SXM": 3350e9,
}
for name, bw in gpus.items():
print(f"{name:16s} ~{bw / 15.2e9:5.0f} tok/s ceiling, batch 1")
# L40S (GDDR6) ~ 57 tok/s
# A100 80GB SXM ~ 134 tok/s
# H100 SXM ~ 220 tok/s
Your measured number will come in below this. Real kernels don't reach peak bandwidth, there are small extra reads beyond the weights, and plain Python/PyTorch loops add per-step launch overhead. Check the exact SKU, too: an H100 PCIe (2 TB/s) or A100 PCIe (1,935 GB/s) has a lower ceiling than the SXM part. The formula also tells you something you'll use later: fewer bytes per weight means a higher ceiling.
Hands-on: time prefill and decode separately
Rent one 24-80 GB GPU. Then run pip install torch transformers accelerate matplotlib.
import time, torch, matplotlib.pyplot as plt
from transformers import AutoModelForCausalLM
MODEL = "Qwen/Qwen2.5-7B-Instruct"
model = AutoModelForCausalLM.from_pretrained(
MODEL, torch_dtype=torch.bfloat16, device_map="cuda").eval()
def timed(fn):
torch.cuda.synchronize() # GPU work is async: wait before starting the clock
t = time.perf_counter(); out = fn()
torch.cuda.synchronize() # ...and wait again before stopping it
return out, time.perf_counter() - t
@torch.no_grad()
def run(prompt_len, new_tokens=64):
ids = torch.randint(0, 20000, (1, prompt_len), device="cuda") # content doesn't matter for timing
# PREFILL: the whole prompt in one forward pass
out, t_prefill = timed(lambda: model(input_ids=ids, use_cache=True))
past, nxt = out.past_key_values, out.logits[:, -1:].argmax(-1)
# DECODE: one token per forward pass (the cache of earlier work is Level 3's topic)
def decode():
nonlocal past, nxt
for _ in range(new_tokens):
o = model(input_ids=nxt, past_key_values=past, use_cache=True)
past, nxt = o.past_key_values, o.logits[:, -1:].argmax(-1)
_, t_decode = timed(decode)
return t_prefill, t_decode / new_tokens
run(256) # warm-up: first call pays CUDA/kernel setup costs
lens = [128, 512, 1024, 2048, 4096, 8192]
rows = [run(L) for L in lens]
for L, (p, d) in zip(lens, rows):
print(f"{L:5d} prompt tok | prefill {p*1000:7.1f} ms ({L/p:8.0f} tok/s) "
f"| decode {d*1000:5.1f} ms/tok ({1/d:5.1f} tok/s)")
plt.plot(lens, [p*1000 for p, _ in rows], "o-", label="prefill total (ms)")
plt.plot(lens, [d*1000 for _, d in rows], "s-", label="decode per token (ms)")
plt.xlabel("prompt tokens"); plt.legend(); plt.savefig("prefill_vs_decode.png")
What you should see, in shape if not in exact numbers:
- Prefill time grows with prompt length, roughly linearly at first and faster at long lengths as attention costs add up. Prefill throughput is huge: thousands of tokens per second.
- Decode time per token is nearly flat. It's set by the weight reads, not the prompt. It creeps up slightly at long contexts, and Level 3 explains why.
- Decode is tens to hundreds of times slower per token than prefill. Compare your decode tok/s with the ceiling you calculated. With this plain PyTorch loop, expect a sizeable gap. Dedicated engines, covered later, close much of it.
Gotcha: if you leave out
torch.cuda.synchronize(), you time how fast Python queued the work, and you get beautiful, meaningless numbers.
Which phase dominates your workload?
Estimate each phase as tokens divided by your measured rate. Suppose you measured prefill at 8,000 tok/s and decode at 35 tok/s:
def split(prompt_tok, reply_tok, prefill_rate=8000, decode_rate=35):
return prompt_tok / prefill_rate, reply_tok / decode_rate
print(split(6000, 150)) # RAG answer: (0.75 s prefill, 4.3 s decode)
print(split(300, 900)) # long chat: (0.04 s prefill, 25.7 s decode)
Even the RAG case spends most of its wall-clock time decoding at batch 1. But its prefill is large, and it sits right in front of the first token, so the user waits through it before seeing anything. The long-chat case is decode-dominated in every sense. Under load the balance shifts. Many users can share one decode pass, which spreads the cost of each weight read across them, but each prompt's prefill maths can't be shared that way. So long-prompt workloads end up spending most of their GPU compute on prefill. Later levels on batching, caching and disaggregation all come back to this split.
Key takeaways
- Prefill processes the whole prompt in one parallel pass and is compute-bound. Its time grows with prompt length.
- Decode emits one token per pass, re-reading all weights each time, so it's memory-bandwidth-bound. Its per-token time is nearly flat with prompt length.
- Decode ceiling ≈ bandwidth ÷ weight bytes: about 220 tok/s for a 7.6B BF16 model on an H100 SXM, and about 57 on an L40S. Measured speed comes in lower.
- At batch 1, decode does about 1 FLOP per byte read, while an H100 can do about 295, so most of its maths capacity goes unused.
- To classify a workload, split its time into prompt tokens ÷ prefill rate and reply tokens ÷ decode rate. Long RAG prompts make prefill heavy. Long replies make decode dominate.
- Always call
torch.cuda.synchronize()around GPU timings and do a warm-up run first.