Log inStart free
LESSON 29.01 · 5 STAGES · 2 CONTROLS · 2 CHECKS

Prefill vs decode

See why a GPU reads a whole prompt fast but writes each new token slowly.


EXPLAINER · 29.01 · INFERENCE BAY
01
Stage 1 of 5 · Prefill
Prefill sends all 512 tokens of the prompt through the model in one pass. Its last row gives the first output token.
Explain it simply

The model reads the whole prompt at once. All 512 tokens form one tall matrix, and one big multiply with the weights handles every row in parallel. The last row's result is the word The. The keys and values of the prompt go into the KV cache for later.

The chat request's prefill is one block on the timeline, 7.30 ms long. 512 token rows times the weights give the first output token.

prompt tokens, prefill, KV cacheweights, GPU limitsoutput tokens, decodewaiting time
Toy: 4 requests, an 8B model (Llama 3 8B shape, BF16), one H100, ideal roofline
HOVER OR TAP A SHAPE TO SEE ITS NUMBERS
Chat (512)
Pick the request, and with it the prompt length.
1 request
Decode one request alone, or all 4 together.
STAGE 1 / 5
MATH · STAGE 1HOVER A SYMBOL OR A SHAPE
F=2 P n+Frest\sy{f}{ink}{F} = 2\,\sy{p}{param}{P}\,\sy{n}{data}{n} + F_{\text{rest}}
F=2⋅6.98 G⋅512+69.9 G≈7.22 TFLOPF = 2 \cdot 6.98\,\text{G} \cdot 512 + 69.9\,\text{G} \approx 7.22\,\text{T}\text{FLOP}

Each prompt token does 2 FLOPs per layer weight, plus attention and the head.

Show the code ▾Hide the code ▴ · Try it yourself · Python 3
# Prefill vs decode on an ideal roofline: an 8B model (Llama 3 8B shape), BF16, on one H100.
LAYERS, D, HEADS, KV_HEADS, HEAD_DIM, FFN, VOCAB = 32, 4096, 32, 8, 128, 14336, 128256
BYTES = 2                    # BF16
PEAK, BW = 989e12, 3.35e12   # FLOP/s and HBM bytes/s

layer_w = LAYERS * (2 * D * HEADS * HEAD_DIM + 2 * D * KV_HEADS * HEAD_DIM + 3 * D * FFN)
head_w = VOCAB * D
weight_bytes = (layer_w + head_w) * BYTES          # every pass reads all of them
kv_per_token = LAYERS * 2 * KV_HEADS * HEAD_DIM * BYTES
attn_per_pos = 4 * HEADS * HEAD_DIM * LAYERS

def forward_pass(parts):
    """parts: one (new_tokens, cached_tokens) pair per request in the pass."""
    tokens = sum(new for new, _ in parts)
    flops = 2 * layer_w * tokens + 2 * head_w * len(parts)
    flops += sum(attn_per_pos * (new * old + new * (new + 1) // 2) for new, old in parts)
    nbytes = weight_bytes + tokens * D * BYTES
    nbytes += sum(old for _, old in parts) * kv_per_token + tokens * kv_per_token
    t_math, t_mem = flops / PEAK, nbytes / BW
    return flops, nbytes, max(t_math, t_mem), "compute" if t_math >= t_mem else "memory"

def ms(t):
    v = t * 1e3
    return f"{v:.1f}" if v >= 10 else f"{v:.2f}" if v >= 1 else f"{v:.4f}"

prompts = {"chat": 512, "summary": 3072, "short question": 96, "code": 1024}
request = "chat"
batch = [request]            # or list(prompts): all 4 decode together

f, b, t, bound = forward_pass([(prompts[request], 0)])
print(f"prefill: {f / 1e12:.2f} TFLOP, {b / 1e9:.2f} GB, {ms(t)} ms, {bound}-bound")
# prefill: 7.22 TFLOP, 15.08 GB, 7.30 ms, compute-bound
pre = (f / b, prompts[request] / t)

f, b, t, bound = forward_pass([(1, prompts[r]) for r in batch])   # the first decode step
print(f"decode step: {f / 1e9:.1f} GFLOP, {b / 1e9:.2f} GB, {ms(t)} ms, {bound}-bound")
# decode step: 15.3 GFLOP, 15.08 GB, 4.50 ms, memory-bound
print(f"intensity: prefill {pre[0]:.1f}, decode {f / b:.1f}, ridge {PEAK / BW:.1f}")
# intensity: prefill 478.5, decode 1.0, ridge 295.2
print(f"tokens per second: prefill {round(pre[1])}, decode {round(len(batch) / t)}")
# tokens per second: prefill 70166, decode 222

Copy it into a file and run it. Change request or batch to match the controls.

Common mix-ups

MYTHPrefill is always compute-bound.

FIXA 96-token prompt does 89 FLOP per byte, under the ridge of 295. Its prefill waits for memory too.

MYTHDecode is slow because each token needs heavy math.

FIXA decode step does 15.3 GFLOP in 0.0154 ms of math. Reading 15.08 GB takes the whole 4.50 ms, and the math waits for it.

Predict, then reveal
0 / 2 REVEALED
Q01If 4 requests decode together, does one step take about 4 times as long?
1 · GUESS2 · TRY IT IN THE DIAGRAM
Q02How does the prefill of the 3,072-token summary compare with the 512-token chat?
1 · GUESS2 · TRY IT IN THE DIAGRAM

Takeaways

  1. Prefill runs the whole prompt in one pass; a long prompt makes it compute-bound.
  2. Decode writes one token per pass and reads every weight again, so it is memory-bound.
  3. Intensity follows the tokens per pass, so a decode batch shares one weight read.