Skip to content

Inference math: prefill, decode, KV cache

35 min read

Prerequisites: Rooflines and arithmetic intensity, Dynamic shapes and recompilation, Sharding, meshes and collectives

Serving a language model looks like running its forward pass many times, and the first estimate most engineers make treats it that way: count the FLOPs, divide by the chip's peak, done. That estimate is wrong by two orders of magnitude for the part of serving that users wait on. A request is processed in two phases. Prefill runs the whole prompt through the model in one step and is limited by the MXU, like training. Decode produces one token per sequence per step, re-reads every weight to do it, and is limited by HBM bandwidth. Between them sits the KV cache, the keys and values of every token seen so far, which grows with every request and context length until it, not the weights, decides how many users a chip can serve. This chapter builds the arithmetic for all three on TPU, with the roofline numbers of chapter 2: parameter and FLOP counts, the KV cache formula, floors for time to first token and time per output token, and the batch size trade-off between them. It then explains continuous batching, paged KV caches, speculative decoding, quantization and tensor parallelism as answers to that arithmetic, and ends by checking a decode floor against a measured Muse Glimmer 30B run on a v7x chip. The ideas come from Parts 4 and 7 of the scaling book, All the Transformer Math You Need to Know and All About Transformer Inference, restated for PyTorch serving on TPU.

What this chapter covers

  • Why prefill is compute-bound and decode is memory-bound, from the arithmetic intensity of a step and the ridge point of the device.
  • Parameter counts, the weight bytes a forward step reads, and KV cache size per token and per sequence, for multi-head, grouped-query and multi-query attention and for sliding-window layers.
  • Floors for time to first token (TTFT) and time per output token (TPOT), and how batch size trades one against throughput until HBM capacity stops it.
  • Continuous batching, paged KV caches, speculative decoding, quantization and tensor parallelism, each in terms of the bytes or FLOPs it changes.
  • A measured decode latency read as a fraction of the bandwidth floor, and the failure modes (KV cache exhaustion, decode stalled behind prefill, recompilation) that push a server away from it.

Counting parameters and FLOPs

Inference needs two numbers from a model's configuration: how many parameters a forward step multiplies by, and how many bytes those parameters occupy. Both come from the shapes. The scaling book's notation, adapted to PyTorch's nn.Linear layers:

Symbol Meaning Muse Glimmer 30B
\(L\) decoder layers 52
\(D\) model width, d_model 6,656
\(F\) FFN width, d_ff 19,968
\(N\) query heads 32
\(K\) KV heads 2
\(H\) head dimension 128
\(V\) vocabulary 202,048

Per layer, the attention projections hold \(2DNH + 2DKH\) parameters: \(W_Q\) and \(W_O\) scale with the query heads, \(W_K\) and \(W_V\) with the KV heads. A SwiGLU FFN holds \(3DF\) (up, gate and down). The embedding table and an untied LM head add \(DV\) each. Muse Glimmer adds a sigmoid output gate on attention, one more \(D \times NH\) projection per layer, and four RMSNorm weight vectors. Chapter 16 counts it all: 27,854,780,928 parameters, 55.71 GB in bf16, which matches the case study's "~55.7 GB of weights in TPU HBM".

A forward step costs 2 FLOPs per parameter per token in its matmuls: one multiply and one add. Training costs 6, because backward does two more matmuls of the same size; inference has no backward. One parameter group does no matmul at all: the embedding table is a lookup, so a step reads \(B\) of its rows, not the whole table. The count that sets both FLOPs and bytes per step is therefore every parameter except the embedding table:

\[ P_\text{active} = 27{,}854{,}780{,}928 - 202{,}048 \times 6{,}656 = 26{,}509{,}949{,}440 \]

A step over \(T\) tokens does \(2 P_\text{active} T\) matmul FLOPs and reads \(2 P_\text{active} = 53.02\) GB of bf16 weights. The LM head is a full matmul and is read every step: \(V \times D\) is 5% of those bytes. The Muse Glimmer case study computes logits for the last position only (self.lm_head(h[:, -1:, :])), so prefill does not pay the head for every prompt token.

Attention adds FLOPs that no parameter count captures. The two attention matmuls, \(QK^\top\) and the product with \(V\), cost about \(4 \cdot N H\) FLOPs per (query, key) pair per layer. With a causal mask, a prompt of \(T\) tokens has about \(T^2/2\) pairs in a full-attention layer and about \(T w\) in a sliding-window layer of width \(w\). For a 4,096-token Muse Glimmer prompt that is 2.7% of the matmul FLOPs: the scaling book shows attention FLOPs only dominate at sequence lengths of several times \(D\), and Muse Glimmer's 39 windowed layers push that point further out.

Prefill and decode on the roofline

Chapter 2 gave the test: an operation is compute-bound when its arithmetic intensity, FLOPs per byte moved, exceeds the device's ridge point. Apply it to a whole forward step of \(T\) tokens through the weight matmuls:

\[ \text{intensity} \approx \frac{2 P_\text{active} T}{2 P_\text{active}} = T \quad \text{(bf16 weights)} \]

Each weight byte loaded from HBM is used once per token in the step. On a v7x device the ridge is 313 FLOPs per byte, on v6e about 560. The two phases of serving land on opposite sides of it.

Prefill is compute-bound. A prompt is known in advance, so the engine runs all of its tokens through the model in one step, writing each token's key and value projections into the KV cache as it goes, and keeps the logits of the last position. A 4,096-token prompt has an intensity of about 4,096: every weight byte is reused 4,096 times and the MXU is the limit. Prefill behaves like a training forward pass, and everything that makes training fast (large matmuls, fusion, high MFU) makes prefill fast.

Decode is memory-bound. Each new token depends on the one before it, so a decode step processes one token per sequence. With \(B\) sequences decoding together, the step's intensity is about \(B\). At \(B = 1\) it is 1 FLOP per byte, more than 300 times below the ridge: the device streams 53 GB of weights from HBM to produce one token, and the MXU spends most of the step waiting.

Attention in decode is worse still. Each sequence reads its own KV cache, and nothing in the cache is shared between sequences, so batching does not raise its intensity. The scaling book works out that decode attention has an intensity of about 1 for multi-head attention and about \(G = N/K\), the number of query heads per KV head, for grouped-query attention: 16 for Muse Glimmer, still far below 313. Attention in decode is memory-bound at every batch size.

An animation in nine frames of one v7x device serving Muse Glimmer 30B in bf16. Each frame shows the tokens entering the step as squares on the left, a device box with an MXU block above an HBM bar filled with weights and KV cache, gauges for MXU busy and HBM busy on the right with the binding one outlined, and a line of FLOPs, bytes read and intensity against the ridge of 313. Frame 1, Setup: 53.02 GB of weights read in every step and an empty KV cache. Frame 2, Prefill of 4,096 prompt tokens: MXU busy 100%, HBM busy 7%, compute-bound, step 193.31 ms, intensity 4,206. Frames 3 and 4, Decode at batch 1: MXU busy 0.3%, HBM busy 100%, memory-bound, step 14.41 ms, intensity 1.0, and the note that the case study measured 23.58 ms per token. Frames 5 to 8, decode at batch 8, 64, 256 and 283: the KV segment of HBM grows, the step stays memory-bound and rises to 24.82 ms, and the last frame says the KV cache has filled HBM. Frame 9 summarizes: prefill 193 ms compute-bound, decode batch 1 14.4 ms memory-bound, decode batch 283 24.8 ms memory-bound.

Watch which gauge is outlined. Prefill fills the MXU with 4,096 tokens per weight read; every decode frame fills HBM instead, and growing the batch only moves the MXU gauge toward the middle before the KV cache runs out of room.

The same model gives two very different floors. Prefill of 4,096 tokens on one v7x device needs \(2 \times 26.51 \times 10^9 \times 4{,}096 / 1{,}153.5 \times 10^{12} = 188\) ms of matmuls, 193 ms with attention, against 14.4 ms to read the weights: compute-bound by a factor of 13. A batch-1 decode step needs 0.046 ms of matmuls against 14.4 ms of reads: memory-bound by a factor of 313, which is the ridge point, since bf16 weights cost 2 bytes and 2 FLOPs per parameter per token.

The KV cache

During decode, the new token's query must attend to the keys and values of every earlier token. Recomputing them would redo the whole prefix every step. The KV cache stores them instead: for every layer, the key and value projections of every token so far. Its size follows directly from what it stores:

\[ \text{KV bytes} = 2 \times L \times K \times H \times S \times B \times \text{bytes per element} \]

The leading 2 counts K and V; \(K\) is the number of KV heads, not query heads; \(S\) is the tokens held per sequence and \(B\) the sequences. kv_bytes(layers, kv_heads, head_dim, seq, batch, bytes_per_el=2) in the companion code computes exactly this, and the KV cache dtype sets the last factor: 2 for bf16, 1 for fp8.

Three attention variants change only \(K\):

  • Multi-head attention (MHA) has a KV head per query head, \(K = N\). LLaMA 2-13B (\(L = 40\), \(K = 40\), \(H = 128\)) stores \(2 \times 40 \times 40 \times 128 \times 2 = 819{,}200\) bytes per token, so one 8,192-token sequence holds 6.7 GB of KV cache. The scaling book's point is that four such sequences outweigh the model's 26 GB of bf16 weights.
  • Grouped-query attention (GQA) shares each KV head among \(N/K\) query heads. The scaling book's 1:5 variant of the same model, 8 KV heads, has a cache five times smaller. Muse Glimmer has 2 KV heads for 32 query heads: 1,024 bytes per token per layer, 53,248 bytes per token across 52 layers.
  • Multi-query attention (MQA) has a single KV head, \(K = 1\): LLaMA 2-13B's shape would drop to 20,480 bytes per token, 40 times smaller.

A fourth change caps \(S\) instead. Muse Glimmer's attention uses a sliding window of 2,048 tokens in three of every four layers and full attention in the fourth. A windowed layer never needs keys more than 2,048 positions back, so once a sequence passes the window only the 13 global layers keep growing: 13,312 bytes per token instead of 53,248. Whether a cache exploits this is up to its implementation: the case study's StaticCache deliberately does not cap its windowed layers, because its runs are far shorter than the window, and the attention mask alone keeps the result correct.

Two log-scale charts. Left, KV bytes equals 2 times layers times KV heads times head dim times tokens times 2 bytes: KV cache per sequence in GiB against context length from 512 to 128K tokens for four configurations, with a dotted line at 96 GiB, all of one v7x device's HBM. LLaMA 2-13B with MHA and 40 KV heads rises from 0.39 to 100 GiB and is annotated 6.7 GB at 8K, the scaling book's figure. LLaMA 2-13B with 1:5 GQA and 8 KV heads sits five times lower. Muse Glimmer 30B with 2 KV heads, if every layer were global, dashed, sits lower again. Muse Glimmer 30B as built, with 39 of 52 layers windowed at 2,048, follows the dashed line to 2K and then rises more slowly, reaching 1.7 GiB at 128K. Right, Muse Glimmer 30B on one v7x device, 92% of 96 GiB minus 51.9 GiB of weights: sequences that fit against context length, for bf16 KV with windowed layers, ending at 21 at 128K; fp8 KV with windowed layers, ending at 42; and bf16 KV if every layer were global, ending at 5.

On the left, every line is straight on log axes because KV grows linearly with context; the vertical gaps are the factors \(K\) and the window remove. On the right, those gaps become the number of users a device can serve at once.

Two conclusions follow. First, KV cache memory scales with users times context, while weight memory is fixed, so a serving chip's capacity is mostly a statement about KV. Second, architecture decides most of it: the 1:5 GQA variant and the sliding window each matter more than any runtime trick. The scaling book's tables for LLaMA 2-13B on eight v5e chips show the consequence: with 40 KV heads the model runs out of memory beyond a batch of 16 at 8,192 tokens, and with 8 KV heads it fits a batch of 64, at about 4.8 times the best throughput the MHA model could fit.

A memory budget for one device

On a TPU device the HBM holds three things while serving: the weights, the working memory of the step being run, and the KV cache. A serving engine reserves a fraction of HBM, loads the weights, sets aside what a step needs, and gives the rest to the KV cache. The vLLM-TorchTPU guides express the fraction as --gpu-memory-utilization (from 0.82 to 0.95 across their recipes, with 0.92 in the parallelism guide's example), and the parallelism guide notes that buffers an engine needs are "reserved before the KV cache is sized". Activations are the small item: the scaling book estimates a single 8,192-token activation of LLaMA 2-13B at about 80 MB. For Muse Glimmer with a 4,096-token step budget, the residual stream and the two FFN intermediates come to 0.41 GiB.

Horizontal stacked bars of GiB on one v7x device with 96 GiB of HBM, titled Muse Glimmer 30B: where one device's HBM goes when 92% is reserved for serving. Each bar is split into weights, step activations, KV cache, unused space for a partial sequence, and the 8% not reserved. Row 1, bf16 weights and bf16 KV with 4,096-token sequences: weights 51.9 GiB and KV 35.9 GiB, 283 sequences of 136 MB. Row 2, the same with 32,768-token sequences: weights 51.9 GiB and KV 35.7 GiB, 74 sequences of 518 MB. Row 3, fp8 weights and fp8 KV with 32,768-token sequences: weights 25.9 GiB and KV 61.8 GiB, 256 sequences of 259 MB. Row 4, bf16 with TP=2 over one chip's two devices and 32,768 tokens: weights 25.9 GiB and KV 61.8 GiB per device, 256 sequences of 259 MB.

The blue segment is fixed by the model and the teal one is whatever is left. Rows 3 and 4 hold the same number of sequences per device, but row 4 spends two devices on one replica, while row 3 leaves the chip's second device free to serve another 256.

Read the rows as levers. Going from 4,096 to 32,768 tokens of context cuts the batch from 283 to 74, because each sequence's cache grows 3.8 times (not 8, thanks to the window). Storing weights and KV in fp8 halves both, so the weights shrink by 26 GiB and the freed space plus the halved cache take 74 sequences to 256. Tensor parallelism over two devices halves the weights per device and, because Muse Glimmer's 2 KV heads split one per device, halves the KV per sequence too. These are arithmetic, not measurements: an engine adds page rounding, compiled programs resident in HBM (each compiled token bucket keeps its program there) and its own buffers. Muse Glimmer serves here as a worked example; the fp8 rows assume a load-time quantization such as vLLM-TorchTPU's online_fp8, which quantizes a bf16 checkpoint to fp8 as it loads.

TTFT, TPOT and the batch trade-off

Serving adds latency to the metrics training cares about. Two numbers describe what a user sees:

  • Time to first token (TTFT): from sending the request to receiving the first generated token. It includes queueing and the prefill of the prompt.
  • Time per output token (TPOT): the average gap between later tokens. A streaming client measures it as the time between the first and last token divided by the number of tokens minus one, which is the decode step time as one sequence experiences it.

Throughput, tokens per second per chip, is the third: it sets the cost. The scaling book gives the model that ties them together. For a decode step over \(B\) sequences:

\[ t_\text{step} = \underbrace{\frac{B \times \text{KV per sequence}}{\text{HBM bandwidth}}}_\text{attention: always bandwidth-bound} + \max\left(\frac{2 B P_\text{active}}{\text{peak FLOP/s}},\ \frac{\text{weight bytes}}{\text{HBM bandwidth}}\right) \]

For small batches the max is the weight term and the step is \((\text{weights} + B \times \text{KV}) / \text{bandwidth}\), the TPOT floor that decode_step_time(params_bytes, kv_bytes, hbm_bw) returns. Throughput is \(B / t_\text{step}\). The scaling book builds its inference estimates from this model, and it reproduces the book's LLaMA 2-13B table exactly: 26 GB of weights plus \(B \times 6.7\) GB of KV over \(8 \times 0.82\) TB/s gives 4.98 ms at batch 1 and 12.13 ms at batch 8 (the companion tests check all six rows).

Two charts of Muse Glimmer 30B on one v7x device from the roofline model, KV over bandwidth plus the max of FLOPs over peak and weights over bandwidth, against sequences decoding together from 1 to 256 on a log2 axis, with a dashed vertical line at the ridge of 313 tokens. Left, decode step time, the TPOT floor in ms on a log scale: bf16 with 4,096-token context starts at 14.4 ms and reaches 24.8 ms at 283 sequences, marked HBM full at 283; bf16 with 32,768-token context rises faster and ends at HBM full at 74; fp8 weights and KV with 32,768 tokens, dashed, starts at 7.2 ms and ends near 30 ms at HBM full at 256. A dotted line marks bf16 weights alone at 14.4 ms, and a black diamond marks the case study's measured 23.58 ms at batch 1. Right, tokens per second from one device on a log scale: all three lines rise almost linearly, the bf16 4,096-token line to about 11,400 at 283, the 32,768-token line to about 3,000 at 74, and the fp8 line to about 8,600 at 256.

Moving right along either chart costs little latency and buys a lot of throughput, until an orange cross: there the KV cache has filled HBM and the batch cannot grow, long before the ridge where the MXU would become the limit.

Three regimes show in the chart:

  1. Small batch: latency is free to trade. From 1 to 64 sequences at 4,096 tokens, the step grows from 14.4 to 16.7 ms while throughput grows from 69 to 3,825 tokens per second. Every sequence added shares one read of the weights.
  2. Large batch: the KV term takes over. Each sequence brings its own cache to read. At 256 sequences the KV reads (9.4 ms) are two thirds of the weight reads, and at 32,768 tokens of context they dominate much earlier.
  3. The limit is memory capacity, not the MXU. The weight term would give way to the FLOPs term at 313 sequences, the ridge, but at 4,096 tokens HBM is full at 283 and at 32,768 tokens at 74. The scaling book reaches the same conclusion for v5e: the batch that would saturate the MXU often does not fit, and the fixes are to shrink the KV cache or to spread the model over more chips.

Quantization moves both ends. With fp8 weights the floor halves to 7.2 ms. With bf16 arithmetic, as in vLLM-TorchTPU's W8A16 path for small decode steps (TPU_FP8_LINEAR_W8A16_MAX_ROWS), each weight byte now feeds 2 FLOPs per token, so the weight matmuls become compute-bound at about 156 sequences instead of 313; that is the bend in the fp8 line. The scaling book generalizes it: the critical batch is the ridge times the ratio of bits per parameter to bits per activation.

Prefill has a floor of its own, and it is the TTFT of a request that waits for nothing:

\[ t_\text{prefill} = \max\left(\frac{2 P_\text{active} T + \text{attention FLOPs}}{\text{peak FLOP/s}},\ \frac{\text{weight bytes}}{\text{HBM bandwidth}}\right) \]

prefill_time(...) returns it: 193 ms for 4,096 tokens on one v7x device, about 94 ms of matmuls on a whole chip's two devices. Google's announcement of TorchTPU reports Muse Glimmer 30B prefill on one v7x chip at about 25.7k tokens per second, 59% MFU, at a sequence length of 5,120; at that rate a 4,096-token prompt takes about 159 ms. Since prefill is compute-bound, batching prompts together barely helps it; the scaling book's advice is to maximize MFU and keep prefill batches small, because a request's first token waits for its whole prefill batch.

How engines manage the two phases

The arithmetic explains the designs of the serving engines in the rest of this Part. Each idea below is a concept here; chapter 18 and chapter 19 show the flags.

Continuous batching. The simplest server prefills a batch of requests and decodes them all to completion. Sequences finish at different times, their slots sit empty, and a new request waits for the whole batch. Continuous batching keeps a decode batch of fixed maximum size and refills a slot as soon as its sequence finishes: the scheduler runs prefills into free slots and decode steps for every active sequence. vLLM-TorchTPU and SGLang-TorchTPU keep the upstream engines' schedulers unmodified, so this works on TPU as it does on GPUs. What TPU adds is the fixed-shape discipline of chapter 7: each step is padded to a precompiled token bucket. In vLLM-TorchTPU the buckets double from 16 up to --max-num-batched-tokens, so a 300-token step runs the 512-token program, and padding is wasted MXU work just past each boundary.

Chunked prefill. A 100k-token prompt would occupy the device for one enormous step while every decoding sequence waits. Capping the tokens per step (--max-num-batched-tokens in vLLM) splits a long prefill into chunks that share steps with decode, so decode keeps moving at the cost of a slower TTFT for the long prompt.

Paged KV cache. Preallocating max_len positions for every sequence, as a static cache does, wastes the memory of every position a request never reaches, and its attention reads the padding too: the case study's StaticCache masks unwritten positions but still reads them. A paged cache stores KV in fixed-size blocks (pages) taken from one pool, with a table per sequence that lists its pages, the way an operating system pages memory. A sequence holds only the pages it has filled, and a ragged attention kernel reads only those. vLLM-TorchTPU's default attention for MHA and GQA models is a Pallas kernel, Ragged Paged Attention v3, and the two v7x recipes that set a block size, like the parallelism and disaggregated-serving guides' examples, pass --block-size 256 (the v6e recipes leave it at the default). The shapes stay static, as XLA needs: the pool and the page tables have fixed sizes, and only their contents change.

Prefix caching. Requests that share a prefix, such as a system prompt or the earlier turns of a chat, share the KV of that prefix. Keeping finished caches and reusing them skips the prefill of the shared part. The scaling book notes that this is limited by memory and that it needs requests routed to the replica holding their prefix; chapter 20 shows how llm-d routes for it.

Speculative decoding. Decode is memory-bound, so a step that scores several tokens per sequence costs almost the same as one that scores one. Speculative decoding exploits that: a cheap drafter (a small model, extra heads trained with the model, or n-gram matching) proposes \(k\) tokens, and the target model scores all \(k+1\) positions in one forward pass. It keeps the longest prefix of drafted tokens that it agrees with, plus one token of its own. If on average \(a\) drafts are accepted, each target step yields \(a + 1\) tokens. The output distribution does not change, because every kept token is checked by the target model. The win shrinks as the batch grows: \(B(k+1)\) tokens per step eventually cross the ridge, and then verifying costs real FLOPs. vLLM-TorchTPU supports six methods through --speculative-config, among them EAGLE-3, MTP heads built into a checkpoint, and n-gram matching.

Disaggregation. Prefill and decode want different things: prefill wants FLOPs and tolerates any sharding that suits training; decode wants HBM bandwidth and room for KV. When both share a device, every prefill step pauses every decode. Disaggregated serving runs them on separate pools and sends the KV cache from the prefill pool to the decode pool. vLLM-TorchTPU's guide describes it as separating compute-bound prefill from memory-bandwidth-bound decode, which "prevents long-prompt prefills from stalling ongoing decode steps". The cost is moving the cache, one more reason to keep it small. Chapter 20 covers the mechanics.

Sharding a model for serving

A model whose weights do not fit one device, or whose TPOT is too slow on one, is split with tensor parallelism (TP): each of \(n\) devices holds \(1/n\) of every weight matrix, sharded over heads in attention and over \(F\) in the FFN, as in chapter 13. The scaling book explains why TP, and not the FSDP of chapter 14, is the layout for decode. FSDP moves weights over ICI to the devices that use them, and decode is already starved for bytes; moving weights over a link slower than HBM makes it worse. TP moves activations instead, which in decode are tiny.

What TP buys is bandwidth. Each device reads only its share of the weights, so the weight term of the decode step falls by \(n\). What it costs is two all-reduces per layer, one after attention and one after the FFN, of the \(B \times D\) activations. For Muse Glimmer at a batch of 64, an all-reduce moves 852 KB; on a ring of 4 devices with wraparound at 90 GB/s per link, chapter 13's model gives 7.1 µs, and 104 of them per step cost 0.74 ms.

TP degree Weights read per device KV per device HBM time All-reduces Decode step
1 53.02 GB 8.72 GB 16.73 ms 0 16.73 ms
2 26.51 GB 4.36 GB 8.37 ms 0.49 ms 8.86 ms
4 13.25 GB 4.36 GB 4.77 ms 0.74 ms 5.51 ms
8 6.63 GB 4.36 GB 2.98 ms 0.86 ms 3.84 ms

Muse Glimmer 30B, batch 64, 4,096-token context, v7x devices, ICI ring model of chapter 13; from kv_cache.py.

Two details in the table matter. The KV per device stops shrinking at TP=2, because Muse Glimmer has only 2 KV heads: beyond \(K\)-way sharding, each device still needs a whole head, so heads are replicated. A practical rule of thumb is to cap TP at the KV head count; the scaling book's alternative is to shard the KV cache over the batch as well, which costs two all-to-alls per layer. And the all-reduces grow relative to the step: at TP=8 they are 22% of it. On v7x, TP=2 across the two devices of one chip uses the die-to-die link, which llm-d's Google Cloud TPU page puts at about 6 times the ICI between chips, so the table's ICI figure is pessimistic for that row. The scaling book's point holds throughout: because decode is memory-bound, you can shard further than the compute roofline would allow in training and still win latency, until the collectives' fixed latency takes over.

Failure modes

Symptom Mechanism What to check or change
Requests preempted or aborted under load; throughput collapses at high concurrency KV cache exhausted. The batch times context outgrew the pool; the engine evicts running sequences and recomputes them, or aborts them. vLLM-TorchTPU's decode pools in disaggregated mode abort with stop_reason "kv_cache_preempted" and count vllm:num_preemptions Compute the KV budget as in this chapter; cap --max-model-len or concurrency; use an fp8 KV cache; shard over more devices
TPOT spikes whenever a long prompt arrives Decode stalled behind prefill. A prefill step on the same device takes hundreds of milliseconds while decoding sequences wait Chunked prefill with a smaller per-step token budget; disaggregate prefill and decode
One step after warm-up takes seconds Recompilation. A shape no warm-up compiled reached the serving path (chapter 7) VLLM_XLA_CHECK_RECOMPILATION=1 in CI logs any graph compiled while serving; warm up every bucket
TPOT well above the bandwidth floor at small batch Fixed per-step costs: host dispatch, non-matmul work, kernels below peak bandwidth, padding to buckets, a static cache reading unused positions Profile one decode step (chapter 10); compare HBM bytes per step with the estimate
Throughput stops growing with concurrency well before HBM is full The weight matmuls have crossed the ridge (compute-bound), or the batch is padded to a larger bucket Compare batch with the ridge (313 on v7x in bf16, half with fp8 weights)
Estimate and measurement disagree by exactly 2 Per chip mixed with per device on v7x (chapter 2), or bf16 assumed where the weights or KV are fp8 Recompute with numbers that describe the same thing

The same arithmetic as a diagnosis, one metric at a time: TTFT and throughput first, then TPOT.

Two short decision trees on one grid, one above the other, each starting from a dark pill on the left. Top tree: the pill TTFT above target leads right to the question Is TTFT near the prefill floor? Yes leads right to an orange card, Compute-bound: more chips, prefix caching, shorter prompts; under it a note reads Prefill floor: 2 × active params × tokens / peak. No leads down to an orange card, Queued or recompiling: prefill capacity, disaggregation, warm up every bucket. Bottom tree: the pill Throughput below target leads right to the question Is the batch limited by KV memory? Yes leads right to an orange card, Shrink the KV cache: fp8 KV, paging, shorter max length, more devices; under it a note reads Ridge: 313 sequences on v7x in bf16. No leads down to an orange card, Raise concurrency: until the batch nears the ridge.

Compare each metric with its floor before changing anything. Even an unqueued prefill runs above this floor (at the published 59% MFU a prefill takes 1.7× it), and throughput usually stops at HBM long before the ridge.

A decision tree read from the left. A dark pill, TPOT above target, leads right to the question Is the step near the TPOT floor? Yes leads right to an orange card, Memory-bound: as expected; fp8 weights or KV, TP, speculative decoding. No leads down to the question Spikes rather than a steady gap? Yes leads right to an orange card, Prefill or recompiles: chunked prefill, disaggregation, warm up every bucket. No leads down to a grey card, Fixed per-step costs: profile one decode step, chapter 10. Beside it a note reads: TPOT floor: (weights + batch × KV) / bandwidth.

A TPOT at its floor is the bandwidth bill: only fewer bytes per token, more devices, or more tokens per weight read (speculative decoding) lower it. Spikes point at prefill or a recompile in the decode path; a steady gap above the floor is per-step overhead that only a profile can name.

Verifying the result

A serving estimate holds up when it predicts the decode step from bytes and bandwidth before the measurement, and the measurement lands above the floor by a margin you can explain.

  1. Reproduce the arithmetic. python code/ch17_inference_math/kv_cache.py --cpu-smoke (source) prints every number in this chapter and checks them: Muse Glimmer's parameter count against chapter 16, LLaMA 2-13B's 6.7 GB per 8,192-token sequence, all six rows of the scaling book's step-time table, the decode floor and the published prefill MFU. It ends with cpu-smoke: OK.
  2. Compare a floor with a measured decode step. The Muse Glimmer 30B case study decodes greedily at batch 1 on what it calls a single TPU v7x chip, with a StaticCache of 27 positions (its 7-token prompt plus 20 decoded tokens), and measures 23.58 ms per token in steady state (steps 2 to 20). Predict it before reading that number: the step reads 53.02 GB of weights and about 1.4 MB of KV (27 positions at 53,248 bytes per token), so

    \[ \text{TPOT floor} = \frac{53.02 \times 10^9 + 1.4 \times 10^6}{3{,}690 \times 10^9} = 14.37 \text{ ms} \]
    python code/ch17_inference_math/kv_cache.py --model muse-glimmer-30b --batch 1 --context 27 \
        --measured-tpot-ms 23.58
    # Muse Glimmer 30B on one v7x device: weights 53.02 GB, KV 0.001 GB, predicted step 14.37 ms, 70 tokens/s
    #   measured 23.58 ms: the floor is 61% of it
    

    The measurement is 1.64 times the floor. That ratio rests on an assumption the case study does not state: whether its run used one device's bandwidth or both devices of the chip (chapter 1: a v7x chip is two devices). The case study's code allocates everything on a single torch.device("tpu"), which is one device, so the per-device reading is the likely one, but the text only says "chip". Per device, the floor is \(53.02 \times 10^9 / 3{,}690 \times 10^9 = 14.37\) ms and the loop runs at \(14.37 / 23.58 = 61\%\) of peak HBM bandwidth, or 70% of the practical 3,207 GB/s that chapter 1 recommends for judging measurements. Had the run used both devices (7,380 GB/s per chip), the floor would be 7.18 ms and the ratio \(7.18 / 23.58 = 30\%\), a gap too large to blame on small per-step costs alone.

    On the per-device reading, a gap of this size above the floor is plausible for per-step costs the floor leaves out. The candidates, to confirm with a profile rather than assume, are the case study's plain F.scaled_dot_product_attention reading the padded static cache, the norms and soft-capped logits on the VPU, and one host dispatch per token. A measurement below the floor means an input is wrong. The same comparison works for prefill: the published 25.7k tokens per second per chip is 59% of the \(2 P_\text{active}\) ceiling of 43.5k. 3. Do the same for an engine benchmark. Run the serving benchmark of chapter 18 (vllm bench serve is what vLLM-TorchTPU's disaggregation quickstart runs) at a fixed concurrency and fixed input and output lengths, and read the median TPOT. Predict it with --batch set to the concurrency, --context to input plus half the output, and --bytes-per-param and --kv-bytes set to the model's dtypes. Expect the measurement above the floor and the gap to shrink as concurrency grows, until the KV term or a bucket boundary shows. If the measured TPOT rises with concurrency faster than the KV term predicts, look for prefill steps interleaved with decode. 4. Measure your own chip's bandwidth. On a TPU VM, python code/ch17_inference_math/kv_cache.py --tpu streams 16 bf16 matrices of \(8192 \times 8192\) (2.1 GB) through a small token batch, the shape of a decode step, and reports the fraction of peak HBM bandwidth reached. Use that fraction, not the spec sheet, as the expected ratio between floor and measurement for your setup.

Worked problems

Problem 1. Doubling the prompt from 4,096 to 8,192 tokens roughly doubles prefill time on a v7x device, but doubling the decode batch from 1 to 2 sequences leaves the decode step almost unchanged. Explain both with one formula.

Answer

A step's weight matmuls take \(\max(2 P_\text{active} T / \text{peak},\ \text{weight bytes} / \text{bandwidth})\), where \(T\) is the tokens in the step. Prefill has \(T\) in the thousands, far past the ridge of 313, so the first term wins and time grows linearly with \(T\) (attention grows a little faster, since its pairs grow as \(T^2\) in the global layers). Decode at batch 1 or 2 has \(T\) = 1 or 2, far below the ridge, so the second term wins and does not depend on \(T\): both steps read the same 53 GB of weights. The only extra cost of the second sequence is reading its own KV cache, 136 MB at 4,096 tokens, about 0.04 ms.

Problem 2. The scaling book's worked example invents a model with \(L = 64\), \(K = 8\) KV heads and \(H = 256\). How many bytes of bf16 KV cache does it need per token, and per 131,072-token sequence? Could one v7x device hold that sequence next to the model's 18.4 billion bf16 parameters?

Answer

Per token: \(2 \times 64 \times 8 \times 256 \times 2 = 524{,}288\) bytes, 512 KiB. Per sequence: \(524{,}288 \times 131{,}072 = 2^{36}\) bytes, exactly 64 GiB. The weights are \(18.4 \times 10^9 \times 2 = 36.8\) GB, about 34.2 GiB. Together they need about 98 GiB, more than a v7x device's 96 GiB before any reservation or activations. One long sequence does not fit on one device; it needs the KV cache in fp8 (32 GiB), the weights sharded over two devices, or both.

Problem 3. LLaMA 2-13B uses multi-head attention with 40 KV heads. What would its KV bytes per token be with grouped-query attention of 8 KV heads, and with multi-query attention? Which other quantity in the decode step does this change, besides memory?

Answer

MHA: 819,200 bytes per token. GQA with 8 heads: \(2 \times 40 \times 8 \times 128 \times 2 = 163{,}840\), five times smaller. MQA: 20,480, 40 times smaller. The KV cache is read in full by every decode step, so the attention term of the step, \(B \times \text{KV per sequence} / \text{bandwidth}\), shrinks by the same factor. That is why the scaling book's 1:5 GQA table shows lower latency at every batch size, not only a larger maximum batch. Fewer KV heads per query head also raise decode attention's intensity (to about \(G = N/K\)), though not near the ridge.

Problem 4. A colleague estimates the time per output token for Muse Glimmer 30B at batch 1 on one v7x device as \(2 \times 26.51 \times 10^9 / 1{,}153.5 \times 10^{12} = 0.046\) ms and concludes the model could stream 21,700 tokens per second to one user. What did they assume, and what is the right floor?

Answer

They assumed the step is compute-bound, that is, that the MXU is the limit. At batch 1 the intensity is about 1 FLOP per byte against a ridge of 313, so the step is limited by reading the weights: \(53.02 \times 10^9 / 3{,}690 \times 10^9 = 14.37\) ms, a floor of about 70 tokens per second for one user, 313 times slower than their estimate. The case study measures 23.58 ms. Their number is the right floor only for a batch at or above the ridge, which is a throughput figure shared among hundreds of users, not one user's TPOT.

Problem 5. Serving Muse Glimmer 30B at a batch of 64 with 4,096-token contexts, TP=2 halves both the weights and the KV cache per device, but TP=4 halves only the weights again. Explain, and say what the scaling book suggests instead.

Answer

The KV cache is sharded over KV heads, and Muse Glimmer has only 2. At TP=2 each device holds one head, so the per-device cache halves (8.72 to 4.36 GB). At TP=4 there are still only 2 heads to split: each device needs one whole head, so each head is replicated on two devices and the per-device cache stays 4.36 GB. Weight reads keep falling (26.51 to 13.25 GB), so the step still gets faster (8.86 to 5.51 ms), but the KV term no longer shrinks and the all-reduces grow. The scaling book's alternative is to shard the KV cache along the batch once the heads run out, at the cost of two all-to-alls per attention layer to move the queries to the batch shards and the outputs back.

Problem 6. With speculative decoding, the target model verifies 3 drafted tokens plus one of its own per step, and on average 2 drafts are accepted. Ignoring the drafter's cost, estimate the TPOT floor for Muse Glimmer 30B on one v7x device at batch 1 and at batch 256 (4,096-token contexts), and compare with plain decoding.

Answer

Each step scores 4 positions per sequence and yields \(2 + 1 = 3\) tokens. Batch 1: 4 tokens per step is still far below the ridge, so the step costs what a plain step costs, 14.4 ms, for 3 tokens: about 4.8 ms per token against 14.4 ms. Batch 256: the step scores 1,024 tokens, past the ridge, so the weight matmuls become compute-bound: \(2 \times 26.51 \times 10^9 \times 1{,}024 / 1{,}153.5 \times 10^{12} = 47.1\) ms plus 9.4 ms of KV reads, 56.5 ms per step, or 18.8 ms per token against 23.8 ms plain. Speculation helps most when decode is far below the ridge; at large batches the verification FLOPs stop being free.

Problem 7. You switch Muse Glimmer 30B's weights to fp8 while keeping bf16 arithmetic. Estimate the new batch-1 decode floor on a v7x device and the batch at which the weight matmuls become compute-bound. Why does that batch fall?

Answer

The weights read per step halve to 26.51 GB, so the floor is \(26.51 \times 10^9 / 3{,}690 \times 10^9 = 7.18\) ms. Each weight byte now feeds 2 FLOPs per token instead of 1, so the intensity of the weight matmuls is about \(2B\), and they become compute-bound at about \(313 / 2 \approx 156\) sequences. The scaling book's rule: the critical batch is the ridge times bits per parameter over bits per activation, here \(313 \times 8/16\). With fp8 arithmetic as well, the device's peak doubles and the critical batch returns to about 313.

Quick questions

  1. Why does a forward step cost 2 FLOPs per parameter per token in inference but 6 in training?
  2. Which parameters does a decode step multiply by, and why does the embedding table not count toward the bytes it reads?
  3. Write the KV cache formula and say what each factor is. Which factor does GQA change, and which does a sliding window cap?
  4. Why is decode attention memory-bound at every batch size, while the weight matmuls in decode stop being memory-bound at a large enough batch?
  5. Define TTFT and TPOT. Which phase of serving sets the floor of each?
  6. Why does throughput grow almost linearly with batch at small batches, and what usually stops it before the ridge on a TPU?
  7. What does a paged KV cache save compared with a static, preallocated cache, and what does it keep the same so that XLA still sees static shapes?
  8. Why is speculative decoding nearly free at batch 1 and not at batch 256?
  9. Why does decode use tensor parallelism rather than FSDP, and what does TP cost per layer?
  10. A measured decode step is below your floor. Name two input mistakes that would cause that.

Key takeaways

  • A forward step reads every weight except the embedding table and does 2 FLOPs per parameter per token; its intensity in bf16 is about the number of tokens in the step. Prefill (thousands of tokens) is compute-bound; decode (one token per sequence) is memory-bound below about 313 sequences on a v7x device.
  • KV cache bytes are \(2 \times L \times K \times H \times S \times B \times\) bytes per element, counting K and V. KV heads, sliding windows and an fp8 cache shrink it; for Muse Glimmer 30B it is 53,248 bytes per token in bf16 before the window caps 39 of its 52 layers.
  • The TPOT floor is (weights + batch × KV per sequence) / HBM bandwidth; the TTFT floor is the prefill's FLOPs over peak. For Muse Glimmer 30B on one v7x device these are 14.4 ms per token at batch 1 and 193 ms for a 4,096-token prompt.
  • Batch trades a little latency for a lot of throughput until the KV cache fills HBM, which on a single device usually happens before the MXU becomes the limit; shrinking KV or sharding over more devices raises the ceiling.
  • Continuous batching, chunked prefill, paged KV caches, prefix caching, speculative decoding, quantization and disaggregation each target one term of that arithmetic; tensor parallelism divides the weight reads and adds two activation all-reduces per layer.
  • A measured decode step belongs above its bandwidth floor: the Muse Glimmer case study's 23.58 ms is 61% of one device's peak bandwidth (30% if its run really spanned the chip's two devices; the source says only "chip"). A result below the floor means a wrong input, usually per chip against per device, or the wrong dtype.

References