Phase 01/How generation actually runs/Prefill versus decode
PHASE 01 · How generation actually runs

Prefill versus decode

0%
6 h5 subtopics2 lessons · 1 required
In plain English

Answering a prompt happens in two very different stages. First the model reads your whole prompt in one go, processing every token at once; this is prefill and it is like a chef chopping all the vegetables for a dish in a single burst of work. Then it produces the reply one token at a time, each new token requiring a full trip through the model; this is decode and it is like plating the dish one grain of rice at a time, where each grain costs the same fixed overhead. Prefill keeps the hardware busy doing arithmetic, while decode spends most of its time just moving the model's weights from memory for each single token. That is why the first word of a reply arrives after a pause and the rest stream out at a steady pace.

Why it matters

Time to first token is set by prefill and inter-token latency by decode, and the two stages have opposite bottlenecks (compute vs memory bandwidth). Batching, scheduling and even disaggregating the two stages onto different GPUs all follow from understanding this split.

Hiring signal

Skills this topic builds, with the number of the 46 analysed job postings that ask for each. Companies asking: Anthropic, Anyscale, Baseten, Cerebras, CoreWeave, Crusoe, Databricks, ElevenLabs, Fireworks, Hugging Face, Liquid AI, Modal, nvidia, OpenAI, Perplexity, Thinking Machines, Together AI, xAI.See all skills →

Learning objectives

  • Define prefill and decode in terms of the tensors each one processes.
  • Measure time to first token and per-token decode latency for GPT-2 on a CPU.
  • Compute achieved FLOP/s for each stage and explain the gap.
  • Explain why decode is memory-bandwidth bound using arithmetic intensity.
  • Predict how TTFT and ITL change with prompt length and batch size.

Key concepts

Prefill
The first forward pass over all prompt tokens at once; produces the first output token and fills the KV cache.
Decode
Each later step that feeds one new token (per sequence) through the model to produce the next.
Time to first token (TTFT)
Latency from request arrival to the first generated token; dominated by prefill.
Inter-token latency (ITL)
Time between consecutive generated tokens; dominated by one decode step.
Arithmetic intensity
FLOPs performed per byte moved from memory; low intensity means the memory system, not the compute units, is the limit.
Memory-bound vs compute-bound
Decode reads all weights to do little work per byte (memory-bound); prefill reuses each weight across many tokens (compute-bound).
Batching decode
Running several sequences' decode steps together so one weight read serves many tokens, raising intensity.

Subtopics

  1. 1. Two stages, one model

    Prefill processes a (B, T_prompt) input; decode processes (B, 1) with cached context; same weights, very different shapes.

  2. 2. Measuring TTFT and ITL

    Where to put timers around a generation loop and how to separate tokenizer, prefill and per-step decode costs.

  3. 3. Arithmetic intensity of each stage

    Prefill does about 2*N*T FLOPs per weight read; decode does about 2*N FLOPs per weight read, so its intensity is roughly 1 FLOP per byte.

  4. 4. The roofline view

    Plot FLOP/s against intensity for your hardware; locate prefill and decode and read off the bound for each.

  5. 5. Consequences for serving

    Why engines batch decode steps across requests, chunk long prefills and sometimes run prefill and decode on separate GPUs.

Resources

paper

Hands-on lessons

L1

Measure TTFT and ITL for GPT-2 small on your CPU

CPU · your Macexperiment90 minrequired

Goal · Produce a table of prefill time, per-token decode time and achieved GFLOP/s for prompt lengths from 16 to 1024 tokens.

  1. 1Load gpt2 in fp32, model.eval(), torch.set_num_threads to your physical core count, and fix torch.manual_seed.
  2. 2For T_prompt in [16, 64, 256, 1024] build a random token tensor of that length and warm up once.
  3. 3Time a single forward with use_cache=True on the full prompt (prefill) with time.perf_counter; repeat 5 times and take the median.
  4. 4Using the returned past_key_values, time 32 single-token forward steps (decode) and record the median per-step time.
  5. 5Compute prefill GFLOP/s as 2 * 124e6 * T_prompt / prefill_seconds and decode GFLOP/s as 2 * 124e6 / step_seconds.
  6. 6Compute the bytes of weights read per decode step (124e6 * 4) and the implied GB/s; compare with your laptop's memory bandwidth spec.
  7. 7Tabulate T_prompt, prefill_ms, decode_ms_per_token, prefill_GFLOPs, decode_GFLOPs and write three sentences on the pattern.
Deliverable
A CSV and a markdown table with the measured numbers plus a short interpretation.
Check
Prefill GFLOP/s at T=1024 is at least 5x higher than decode GFLOP/s, and decode ms per token is roughly flat across prompt lengths (within 2x).
L2

Roofline for Llama-2-7B on an A100 (pen and paper)

CPU · your Macdesign60 minoptional

Goal · Predict TTFT and ITL for Llama-2-7B in fp16 on one A100-80GB from first principles, before ever touching the GPU.

  1. 1Write down A100 peak fp16 tensor-core FLOP/s (312 TFLOP/s) and HBM bandwidth (about 2 TB/s); compute the ridge point in FLOPs per byte.
  2. 2Compute weight bytes for 6.7B parameters in fp16 and the minimum time to read them once.
  3. 3For batch 1 decode, compute FLOPs per step and intensity; state the bound and the predicted ITL.
  4. 4For a 1024-token prefill, compute FLOPs and the predicted TTFT if compute-bound.
  5. 5Find the batch size at which decode crosses the ridge point and becomes compute-bound.
  6. 6Compare your predictions with a published vLLM or TensorRT-LLM benchmark and explain the gap in one paragraph.
Deliverable
A one-page markdown document with the numbers and the roofline sketch.
Check
Your weight-read time is about 6.7 ms, your decode intensity is about 1 FLOP per byte, and the crossover batch size is in the low hundreds.

Build your own

Build your own token generator

PythonCPU · your Mac~6 h

A streaming generation loop on GPT-2-small with a separate prefill and decode path, sampling controls, stop sequences and per-phase timing, so you can see the two regimes in your own numbers.

The real thing: github.com/vllm-project/vllm/blob/main/vllm/v1/sample/sampler.py ↗

How you know a stage passes

Write tests/test_generate.py first. Correctness stages compare your tokens with Hugging Face generate() under the same settings and seed; timing stages run `python generate.py --bench` and parse the JSON it writes, asserting on ratios rather than absolute milliseconds so the tests pass on any machine. Run `pytest -q`; a stage is done when its test passes and all earlier tests still pass.

Stages, in order. Each one leaves you with something that runs.0/6
  1. 01prefill then decode
    `generate(prompt_ids, n)` runs one forward over the prompt, then a loop of single-token forwards using past_key_values, yielding each token as it is produced.
    test · 64 greedy tokens equal Hugging Face generate() with do_sample=False; the number of forward calls is exactly 1 + 63.
  2. 02time the two phases
    The generator records wall time for prefill and for each decode step and reports TTFT, mean ITL and tokens per second in a JSON file.
    test · For a 256-token prompt, TTFT is at least 5x the mean ITL; for a 1-token prompt, TTFT is within 2x of the mean ITL.
  3. 03sampling
    Temperature, top-k and top-p sampling applied to the last-position logits, with a seeded torch.Generator.
    test · With temperature 0 the output equals greedy; with top_k=1 it equals greedy; with seed 0, temperature 0.8 and top_p 0.95 the first 32 tokens equal Hugging Face generate() with the same seed and settings.
  4. 04stop sequences and max length
    Generation halts on EOS, on any of a list of stop strings (checked on decoded text, including strings that span token boundaries) or at max_new_tokens.
    test · With stop=["\n\n"] the returned text never contains a double newline and the trailing partial match is trimmed; with max_new_tokens=10 exactly 10 tokens are produced when no stop fires.
  5. 05stream it
    `python generate.py --prompt ... --stream` prints tokens as they arrive, handling multi-byte characters by buffering until the decoded text is valid UTF-8.
    test · Piping the output through `wc -c` matches the length of the non-streamed text; an emoji-heavy prompt produces no replacement characters.
  6. 06batched decode and the intensity curve
    The decode loop accepts a batch of sequences and the benchmark reports per-step time at batch sizes 1, 2, 4, 8, 16.
    test · Per-step time at batch 8 is less than 4x the time at batch 1 (decode is memory-bound, so batching is nearly free); the README plots tokens per second against batch size and marks where it stops growing.

Knowledge check

QWhy does decode run at a tiny fraction of peak FLOP/s at batch size 1?

Each step reads every weight from memory but performs only about 2 FLOPs per weight, so the step time is set by memory bandwidth, not compute.

QDoubling the prompt length roughly doubles which metric, TTFT or ITL?

TTFT. Prefill work scales with prompt tokens; a decode step still processes one token (plus a slightly longer attention over the cache).

QHow does batching 16 requests change decode?

One weight read now serves 16 tokens, so arithmetic intensity rises 16x and the step takes only slightly longer than for one request, multiplying throughput.

QWhat does prefill leave behind for decode to use?

The KV cache, the keys and values of every prompt token at every layer, so decode never recomputes the prompt.

Completion

  • All 5 subtopics marked done
  • All 1 required lessons done
  • All subtopics marked completed.
  • Lesson l1 CSV saved and its check passes.
  • Can explain TTFT vs ITL to a product manager in two sentences and to an engineer with a roofline.
Topic progress is derived; it reaches 100% when both checks above pass.Next recommended topic →