The KV Cache in Practice
Cached history removes repeated prefix work. Wrong history changes the model’s answer. Follow storage, append boundaries, positional alignment, and the comparison with a full uncached pass.
#Section 5KV Cache
Chapter 1 built the cache from scratch: Section 59 shows that a new token only needs its own query, key and value, plus the keys and values of everything before it, and Section 60 explains why the keys and values can be stored and the queries cannot. Here is the short version, then the parts Chapter 1 did not cover: the exact layout of a real cache.
What gets cached, and why
Cache each layer’s rotated keys and unrotated values. Their causal dependencies stay unchanged when later tokens arrive. Old queries have no future use; only the new position needs a query.
Cache tensor shapes
For a model with layers and key/value heads of size , each layer keeps two tensors:
Each sequence has its own history, and each layer has its own cache because it produces different features. Store the smaller KV-head representation; query-head sharing happens during attention.
Cache growth with sequence length
The cache grows by exactly one position per token. In bf16, one key/value head stores bytes per token per layer (key plus value, 128 numbers each, 2 bytes per number). Eight heads make 4,096 bytes per layer, and 28 layers make 114,688 bytes per token. After the 26-token prompt of Part X, the cache holds bytes, under 3 MB. After 32,768 tokens it holds 3.5 GiB, about three times the model's own 1.19 GB of weights.
cache_k = torch.empty(B, 8, S_max, 128, dtype=torch.bfloat16) # one per layer
cache_v = torch.empty_like(cache_k)
cache_k[:, :, pos:pos + n] = k_new # k_new: (B, 8, n, 128), already rotated
k_all = cache_k[:, :, :pos + n] # (B, 8, S, 128) view, no copyReal implementations either grow a list with torch.cat, which is simple and reallocates every step, or preallocate the full length once and write into it, as above. Serving engines go further and store the cache in fixed-size pages, the idea behind vLLM's PagedAttention (Kwon and colleagues, 2023), so that memory is allocated as sequences grow and nothing is wasted on reserved space a short reply never uses.
#Section 6KV Cache Memory
The size formula was derived in Chapter 1, Section 61 and pushed to Llama 3 8B in Chapter 2, Section 20. Here it is with every factor named, because each one is a lever someone has pulled:
Cache memory grows with the number of layers, number of KV heads, head dimension, retained sequence length, batch size, and bytes per element set by the data type.
For the three models in this book, per token per sequence:
Notice that Qwen3-0.6B, a model thirteen times smaller than Llama 3 8B, has almost the same cache per token. Its weights are small but it has 28 layers of eight 128-wide key/value heads, so its per-token memory is nearly a big model's.
Why long context becomes expensive
Weights are stored once, but each conversation retains its own history. At long contexts, caches can determine serving capacity more strongly than weight size.
GQA and KV-cache savings
Grouped-query attention reduces retained KV heads while preserving separate queries. See the sharing spectrum.
MHA, GQA, and MQA differ in how much KV memory queries share. Sharing reduces cache storage and reads, but does not imply an equal end-to-end latency gain.
Shrinking the cache further
Lower-precision caches reduce payload but need compatible kernels and quality checks. Latent representations and local windows change the architecture or retention policy instead.
#Section 7Cached Attention Step by Step
Here is one decode step inside one attention layer of Qwen3-0.6B, at the moment it generates token 27 of the Part X conversation. The prompt was 26 tokens, so the cache holds positions 0 to 25 and the new token sits at position 26. Batch size is 1. Follow the shapes.
- New token embedding. The new token ID is looked up in the embedding table and has gone through the earlier layers; this layer receives its hidden state , shape , and normalizes it with RMSNorm.
- New Q. gives , reshaped to : one 128-wide query per head. Qwen3 normalizes each head's query with its own small RMSNorm (Section 28), then RoPE rotates it by position 26.
- New K/V. and each give , reshaped to . The key is normalized and rotated by position 26; the value is not.
- Append K/V to cache. The cache tensors go from to . The new row is written before attention, so the token can attend to itself.
- Query against all cached keys. Each query head is matched with its key/value head (heads 0 and 1 with head 0, and so on) and scores are : shape , one row of 27 scores per head.
- Weighted sum over cached values. Softmax turns each row into 27 weights that sum to 1, and the weighted sum of the 27 value rows gives .
- Produce next hidden state. The heads are concatenated back to , projects to , and the result is added to the residual stream. The MLP half of the block follows, then the next layer.
- Repeat. After the last layer, the final norm and LM head produce one row of 151,936 logits; sampling picks token 28, and the step runs again at position 27 with a cache of 27 rows.
With real numbers
Shrink it to one head of size 2 so it fits on a page. The cache holds three keys , , and three values , , . The new token arrives with , and . Appending gives four keys and four values. The raw scores of against the four keys are ; divided by they are . Softmax gives weights , so the output is .
Two things are worth seeing in that arithmetic. The new token's own key and value took part (the fourth weight), which is why the append comes before attention. And nothing about the first three positions was recomputed: their keys and values were read, and that is all.
#Section 8Cache Correctness
A cached implementation produces the same text as a naive one most of the time even when it is wrong, because a wrong cache often degrades the model rather than breaking it. So correctness is not "the output looks fine". It is a pair of tests against the naive loop from Section 4.
Cached vs uncached generation
Run the same prompt through two loops: the naive loop, which reprocesses the full sequence each step, and the cached loop. Use greedy decoding (always pick the highest logit) so there is no randomness. Token parity means the two loops produce the identical sequence of token IDs for, say, 50 or 100 steps. Logit parity is stricter: at every step, compare the two rows of logits and require the largest absolute difference to be below a tolerance.
Cached and full passes can use different kernel shapes and summation orders. Floating-point rounding can therefore differ. Use a measured tolerance and inspect where disagreement begins; no universal logit threshold diagnoses every model.
ids_a, ids_b = prompt.clone(), prompt.clone()
cache = model.new_cache()
logits_b = model(ids_b, cache=cache, pos=0)[:, -1] # prefill
for step in range(50):
logits_a = model(ids_a, cache=None, pos=0)[:, -1] # naive, full sequence
assert (logits_a - logits_b).abs().max() < tol, step
nxt = logits_a.argmax(-1, keepdim=True)
ids_a = torch.cat([ids_a, nxt], 1)
logits_b = model(nxt, cache=cache, pos=ids_a.shape[1] - 1)[:, -1]Position handling with cache
With a cache, the model no longer sees where the new token sits; you have to tell it. The new token's position is the number of tokens already cached, here 26, and that position drives RoPE. Chapter 2 drew the classic bug, every new token rotated as if it were at position 0, in Section 5. The cached keys were rotated by their own positions when they were written, so they must never be rotated again.
Common cache bugs
Most cache bugs fall into a short list, and the parity test catches all of them.
| Bug | Symptom | Fix |
|---|---|---|
| New tokens get position 0 | fine for a few tokens, then drifts and repeats | position = cache length before the append |
| Keys cached before RoPE, rotated again on read | parity fails from the first decode step | cache keys after rotation, never rotate cached keys |
| Cache not reset between requests | the second request "remembers" the first | new cache per sequence, or reset its length |
| Expanded GQA heads stored in the cache | correct output, memory doubles or worse | store heads, expand at attention |
| Causal mask applied in decode with the wrong alignment | new token cannot see the prompt | no mask for one query row, or bottom-right alignment |
| Cache kept in fp32 while the model runs bf16, or the reverse | small parity gaps, dtype errors in fused kernels | cache in the model's compute dtype |
Off-by-one errors
Compute the new position before appending, append before attention, and include the new row in the read slice. These boundaries can be wrong even when shapes and generated text look plausible.
#Section 9Attention During Inference
The attention formula is the same in both phases, softmax of times (Chapter 1, Part VII). What differs is the shape of against the shape of , and that difference decides which mask is needed and which kernel is fast.
Prefill attention shape. All prompt positions are queries and all are keys: scores are . For a 26-token prompt that is a 26 by 26 grid per head.
Causal masking during prefill. The grid's upper triangle must be blocked, so position 5 cannot read position 9, exactly as in training (Chapter 1, Section 45). With SDPA this is is_causal=True.
Decode attention shape. One query against keys: scores are , a single row per head. At position 26 that row has 27 entries.
Why decode only has one new query row. Only the new token needs a new output; every earlier position's output was produced on an earlier step and is never revisited. And that one row needs no mask at all, because every key in the cache belongs to a position at or before the query. Passing is_causal=True here is a real bug in PyTorch: its causal mask is aligned to the top-left corner, so a “causal” mask lets the query see only the first key (Chapter 2, Section 25). Use is_causal=False for single-token decode, or a bottom-right-aligned mask when several new tokens arrive at once (chunked prefill, speculative decoding).
History grows at each step, so the new query reads more keys and values. Weight reads dominate some workloads; cache reads dominate others.