Chapter 19
Prefill, Decode, and Performance Modeling
On this page
- Phase anatomy
- Transformer work per phase
- Arithmetic intensity and roofline reasoning
- A lower-bound model for decode
- KV-cache accounting
- Batch as a reuse and latency control
- Long prompts and chunked prefill
- Prefix reuse changes prefill accounting
- Phase-specific optimization
- Design Exercises
- Worked Solutions
A request moves through phases with different shapes and bottlenecks. Prefill exposes token parallelism and often high arithmetic intensity; decode is sequential across time and repeatedly reads weights and growing KV state.
The lifecycle defined where time can go; this section models how much the model itself must cost. The tool is the same resource ledger used throughout the book: count the bytes each phase must move and the FLOPs it must execute, and let the running service make the quantities concrete.
Phase anatomy¶
Text-only autoregressive serving has two primary model phases:
- Prefill processes all uncached prompt tokens, produces the first-token state, and materializes their KV cache.
- Decode adds one token per active sequence per iteration, reads prior KV state, samples a token, and appends new KV.
Multimodal models may add an encoder phase before prefill. Image, audio, or video preprocessing and encoding can dominate first-token latency, expand into many model tokens, and require a different accelerator profile. Treat encode, prefill, and decode as distinct stages even when one engine executes all three.
| Property | Prefill | Decode |
|---|---|---|
| Token parallelism | Many prompt positions | One new position per sequence |
| Typical linear shape | Large token dimension | Small token dimension, often batch-sized |
| Common limit | Compute or attention IO | Weight/KV bandwidth, collectives, launch overhead |
| KV behavior | Creates prompt state | Reads history and appends one position |
| Primary user metric | Time to first token | Token cadence and output rate |
A numerical teaching roofline with 1 TB/s memory bandwidth and a 100 TFLOP/s arithmetic ceiling. The knee is at 100 FLOP/byte. The highlighted point lies on a theoretical ceiling, not a measured kernel result; actual throughput can be lower.
Transformer work per phase¶
Each layer performs normalization, projections for attention, attention itself, an output projection, another normalization, and an MLP, with residual paths and optional routing for mixture-of-experts models.
For a dense model, most parameter FLOPs occur in linear layers. Prefill applies them to many prompt positions at once, creating GEMM shapes with substantial reuse. Decode applies them to one new position per sequence, so the effective token dimension is approximately active batch size.
Attention has a different scaling. For sequence length S and head dimension d, full causal prefill performs work proportional to S squared d but IO-aware kernels avoid materializing the full score matrix. One decode query attends to S cached keys and values, so per-step attention work and KV traffic grow approximately linearly with context length. At very long context, attention can dominate a decode step even when weight reads dominate at shorter context.
Arithmetic intensity and roofline reasoning¶
Arithmetic intensity is useful FLOPs divided by bytes moved from the limiting memory level. A first-order roofline is:
attainable compute rate <= min(peak compute, bandwidth times arithmetic intensity)
For an unbatched decode linear layer, a weight may be fetched for only one multiply-accumulate before the next layer. Batching sequences reuses each weight across rows, raising intensity. Weight quantization reduces bytes but adds scale reads and dequantization. A fused epilogue removes intermediate reads and writes. The correct denominator is bytes actually transferred, not tensor size on paper.
Prefill matrix multiplications can become compute-bound because tiled kernels reuse weights and activations. Attention can remain IO-bound if an implementation materializes scores or makes extra HBM passes. The roofline identifies a bound, not a schedule: low achieved performance may still come from poor tiling, serialization, launch gaps, or an imbalanced distributed peer.
A lower-bound model for decode¶
Let W be active model weight bytes per replica or model-parallel group and BW_w sustainable bandwidth for those reads. For small-batch decode:
t_weights >= W / BW_w
Let K(S, B) be KV bytes read at current context and batch. When weights and KV share one HBM interface with bandwidth ceiling BW, their traffic consumes the same resource. Ignoring other traffic gives:
t_step >= max((W + K(S, B)) / BW, t_compute)
Compute may overlap memory traffic, but weight and KV bytes still count against the shared bandwidth budget. With distinct memory paths, use a separate traffic bound for each. Add collective and host overhead only to the extent that it is exposed on the critical path; summing all measured communication with the roofline term can double-count overlap. Use consistent per-device or group-wide byte and bandwidth units, and measure access-pattern efficiency rather than treating an unrelated throughput measurement as a ceiling.
If latency is near the weight-read bound, optimizing scalar arithmetic cannot produce a large gain. Reduce bytes, increase batch reuse, improve placement, or change the model. If latency is far above every bound, examine kernel efficiency, launch gaps, collectives, and scheduling.
The running service's step floor¶
Plug in the numbers. Weights are approximately 14 GB in FP16 and the replica sustains roughly 3 TB/s from HBM, so a small-batch decode step cannot beat:
t_weights >= 14e9 / 3e12 = 4.7 ms
That is a weight-only ceiling near 210 steps per second, shared by every sequence in the batch. At batch 8 with 4,096-token contexts, a step additionally reads about 8 * 4096 * 131 kB = 4.3 GB of KV, raising the shared-HBM floor to about 6.1 ms before other costs. Weight and KV byte counts are equal when the batch holds about 107,000 cached tokens (14 GB / 131 kB) - for example, eight sequences of about 13,000 tokens each. This is a traffic crossover, not a guarantee about which kernel controls latency. It reappears in the KV, quantization, and disaggregation sections.
KV-cache accounting¶
For layers L, batch B, cached sequence length S, KV heads H_kv, head dimension d, and element bytes b:
KV_bytes = 2 L B S H_kv d b
The factor two represents keys and values. For heterogeneous sequence lengths, replace B S with the sum of cached tokens across sequences. Add page-table metadata, partial blocks, allocator reserve, prefix-cache entries, speculative branches, and temporary workspaces.
This equation makes architectural effects explicit. Grouped-query or multi-query attention reduces H_kv. Lower KV precision reduces b. Sliding-window attention caps effective S for selected layers. None of these is free: each changes model quality, kernels, or both.
For the running service the equation gives 2 * 32 * 8 * 128 * 2 = 131072 bytes per cached token. A median request holding 2,300 tokens occupies 301,465,600 bytes. Subtracting 14,000,000,000 weight bytes and the explicit 8 GiB reserve from 80,000,000,000 device bytes leaves 57,410,065,408 bytes: 438,004 cached tokens, or 106 complete 4,096-token reservations before page rounding. This is the ledger computed by examples/reference_config.py and used in Part I. Treating the device as 80 GiB would incorrectly add almost eleven such reservations. Every architectural lever above moves one factor of the product.
Batch as a reuse and latency control¶
Increasing active decode batch can reuse weights and amortize launches, but it also:
- increases per-iteration duration;
- consumes more KV capacity;
- may raise collective message size;
- delays newly arrived work until a scheduling boundary;
- makes one iteration include more heterogeneous states.
Therefore the useful batch is SLO-dependent. Throughput-oriented jobs may use a large batch near saturation. Interactive traffic often needs a smaller iteration budget or a deadline-aware scheduler. Report the full throughput-latency curve rather than one maximum-throughput point.
Long prompts and chunked prefill¶
A long prefill is efficient in isolation but can monopolize an accelerator long enough to stall active decodes. Chunked prefill divides uncached prompt tokens into bounded pieces and interleaves them with decode iterations. The chunk size trades:
- smaller generation gaps versus better prefill kernel efficiency;
- earlier service for other requests versus later first token for the long request;
- stable iteration shapes versus more scheduling and state transitions.
Chunk by a measured compute or time budget rather than assuming equal token chunks cost the same. Attention work changes with prefix length, and multimodal tokens or architecture-specific layers may have different cost.
Prefix reuse changes prefill accounting¶
When a request reuses cached state for S_hit prefix tokens and has S_new uncached tokens, its prefill work is determined primarily by S_new plus attention against the reused history. A high token hit rate can reduce compute while consuming substantial cache memory. Distinguish:
- request hit rate;
- reused-token fraction;
- prefill FLOPs avoided;
- first-token time saved;
- bytes occupied and eviction cost.
Routing a request away from a useful prefix may cost more than waiting briefly for the node that holds it. Cache locality becomes a scheduling input rather than a storage statistic.
Phase-specific optimization¶
Prefill commonly benefits from efficient attention, large matrix shapes, fused projections and epilogues, balanced long-prompt partitioning, prefix reuse, and topology that supports compute-heavy parallelism.
Decode commonly benefits from continuous batching, lower weight and KV bytes, efficient small-row matrix operations, paged attention, launch amortization, graph capture, and carefully chosen model parallelism. At long context, decode attention and KV placement deserve separate analysis from weight-dominated layers.
Design Exercises¶
- Why can the same model be compute-bound in prefill and bandwidth-bound in decode?
- Derive the KV-cache memory equation and explain every omitted overhead.
- How does decode batch size change arithmetic intensity and user latency?
- When does long-context decode stop being mainly a weight-streaming problem?
- Design a chunked-prefill policy for interactive and batch traffic.
- How should a multimodal request change phase accounting and capacity planning?
Worked Solutions¶
1. Different phase bounds¶
Prefill applies weight matrices to many token rows, so tiled GEMMs reuse weights and can reach high arithmetic intensity. Decode adds one row per sequence; at small batch, weights and KV state are moved for relatively little new computation, so bandwidth and launch overhead dominate. Long prompts can make prefill attention IO-limited, and a large decode batch can move linear layers toward compute-bound. The answer must be shape-specific rather than an absolute label for the model.
2. KV memory¶
For L layers, B equal-length sequences of S cached tokens, H_kv KV heads, dimension d, and b bytes per element, keys plus values require 2 L B S H_kv d b bytes. With variable lengths, sum cached tokens instead of multiplying by B S. Add partially filled pages, allocator reserve, block tables, shared-prefix reference metadata, speculative branches, quantization scales, temporary attention workspace, and replication or sharding effects.
3. Decode batch¶
More active sequences reuse each fetched weight across more rows and amortize launch and collective overhead, which raises arithmetic intensity and throughput. The iteration also becomes longer, consumes more KV memory, and may delay admission or token emission. Sweep batch under the actual latency SLO and context distribution; choose the largest budget that improves goodput rather than the batch with the highest unconstrained tokens per second.
4. Long-context decode¶
Weight traffic is roughly stable per step, while each query reads a KV history that grows with context. When measured KV read time or attention compute approaches and then exceeds the weight-streaming term, attention controls the step. GQA, KV precision, sliding windows, cache layout, page locality, and attention parallelism then matter more. Use per-layer profiling and a bytes model; total model bandwidth alone cannot identify the crossover.
5. Chunked prefill¶
Reserve a decode budget against the declared token-gap SLO, then spend remaining per-iteration compute or token budget on one or more prefill chunks. Adapt chunk size to decode pressure, estimated chunk time, prompt progress, priority, and pipeline shape. Age long prompts so they cannot starve, reserve KV before executing a chunk, and measure both cadence improvement for active decodes and added first-token latency for chunked requests. Validate the p99 gap over request traces; a per-iteration budget does not guarantee a hard maximum at the client.
6. Multimodal accounting¶
Add preprocessing and encoder time, memory, and queueing as a separate phase. Account for media-size distributions and the number of model tokens produced by the encoder, which affect later prefill and KV. The encoder may need different hardware or batching, and large media payloads affect network and host memory. Capacity tests must preserve correlations between media size, text length, output length, and model variant; text token counts alone understate cost.