Separate prefill time from decode time
Time the first pass over a prompt and the per-token passes that follow, then compute TTFT without hiding either phase.
A request’s latency is not one number. Prefill processes the prompt in one pass and produces the first logits. Decode produces each later token, one step at a time. Time to first token (TTFT) includes prefill and the first decode step; inter-token latency describes the steps after that. Reporting a single average hides which phase dominates and which one a change affected.
This example times the two phases separately on the toy transformer. It uses no
KV cache, so every decode step re-runs the whole sequence. That makes the decode
times a record of naive recomputation, not a production decode benchmark. The
value of the example is the accounting: ttft = prefill + first_decode, and the
mean inter-token time is the mean of the later decode steps.
Run it
From the canonical repository at commit
f958967d70992d7b09d9c75000bd8c543f1644d4:
python examples/ch09/prefill_decode.py --prompt-len 16 --output-len 8 --jsonPython 3.11 or later with PyTorch. CPU-only, seeded, no model download, network,
GPU or credentials. It finishes in about a second. The optional --real path
loads GPT-2 and is not required here.
Implementation
The prefill is one forward pass over the prompt ids. The decode loop appends one
argmax token per iteration and times each full forward pass. ttft is computed
from the measured prefill and the first decode step, not from a separate clock.
def toy_prefill_decode(prompt_len: int, output_len: int, seed: int = 0) -> PhaseResult:
torch.manual_seed(seed)
model = TinyTransformer(vocab_size=32, d_model=16, n_heads=2, n_layers=1, d_ff=32)
model.eval()
prompt_ids = list(range(1, prompt_len + 1))
# Prefill: one forward pass over the prompt.
prefill_start = time.perf_counter()
with torch.no_grad():
logits = model(torch.tensor([prompt_ids]))[0]
prefill_seconds = time.perf_counter() - prefill_start
generated = list(prompt_ids)
decode_seconds: List[float] = []
with torch.no_grad():
for _ in range(output_len):
step_start = time.perf_counter()
out = model(torch.tensor([generated]))[0]
next_id = int(torch.argmax(out[0, -1]).item())
generated.append(next_id)
decode_seconds.append(time.perf_counter() - step_start)
ttft = prefill_seconds + (decode_seconds[0] if decode_seconds else 0.0)
mean_inter = sum(decode_seconds) / len(decode_seconds) if decode_seconds else 0.0
return PhaseResult(
prompt_len=prompt_len,
output_len=output_len,
prefill_seconds=prefill_seconds,
decode_seconds=decode_seconds,
ttft_seconds=ttft,
mean_inter_token_seconds=mean_inter,
metadata={"backend": "toy", "seed": seed},
)Expected outcome
Observed with the command above (exit 0). Selected stable fields:
"prompt_len": 16,
"output_len": 8,
"metadata": {
"backend": "toy",
"seed": 0
}In this run prefill took about 0.00177 s, the eight decode steps ranged from
about 0.00024 s to 0.00035 s, TTFT was about 0.00212 s, and mean
inter-token time was about 0.000269 s. TTFT is prefill plus the first decode
step, as the code defines it. The decode times fell slightly over the run; that
is warm-up and allocator behaviour, not evidence that decode gets cheaper with
longer context.
Mechanism and limitations
Documented: the toy path builds a one-layer transformer with vocabulary 32
and processes the prompt once. Each decode step calls the model on the full
generated sequence, takes the last logit vector’s argmax, and appends it. The
tests check the number of decode entries, the TTFT identity, the empty-decode
case at output_len=0, and JSON serialisation.
Observed: the command exited 0 with the phase structure above. The targeted
tests.test_ch09_prefill is part of the canonical suite; no independent test
count is claimed here. The times are from one process on this machine.
Not shown: a real model’s prefill/decode ratio; KV-cached decode; batched prefill; chunked prefill; queueing delay; or GPU behaviour. Because the toy loop recomputes the whole sequence, its decode cost includes work a cached engine would not repeat. The absolute timings are not portable, and the falling decode times are not a scaling law.
Challenge this result
Run with --output-len 0. The decode list should be empty and TTFT should equal
prefill exactly. Then run with --output-len 32 and compare the mean inter-token
time with the 8-token run. If the decode path recomputes the full sequence, the
later steps should tend to be slower; if warm-up dominates, they may not. Explain
why this toy cannot decide whether a production engine is prefill-bound or
decode-bound.
Source and verification
Canonical source:
examples/ch09/prefill_decode.py
at commit f958967d70992d7b09d9c75000bd8c543f1644d4. Tests:
tests/test_ch09_prefill.py
.
Chapter: Prefill and Decode
.
The run above is a fresh local execution on Windows 11 with Python 3.13.15 and
PyTorch 2.6.0+cu124; it uses the toy model, not GPT-2.
Understand this example
Copy this prompt into your AI tool. No code runs here.
Apply this example
Copy this prompt into your AI tool. No code runs here.