Highlights

Contents

Part II
02

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.

YOU ARE HEREmessageschat templatetokenizertoken IDsconfig.jsonmodel.safetensorsint8 / int4 weightsOUR DECODER, REBUILT FROM THE CONFIGprefilldecodeattention kernelKV cacheparity checkvs referenceLM head → logitssamplingdetokenizereply textnext token

#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 LL layers and HkvH_{kv} key/value heads of size dhd_h, each layer keeps two tensors:

K(ℓ), V(ℓ)∈RB×Hkv×S×dhK^{(\ell)},\ V^{(\ell)} \in \mathbb{R}^{B \times H_{kv} \times S \times d_h}

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.

QWEN3-0.6B KV CACHE: PER LAYER, ONE K AND ONE V TENSOR OF SHAPE (B, 8, S, 128)new row, step tK (rotated by RoPE)d_h = 128H_kv = 8 heads deepnew row, step tV (not rotated)d_h = 128H_kv = 8 heads deepSlayer 1:K and V× 28 layers = 56 tensorsper token: 2 × 28 layers × 8 heads × 128 × 2 bytes = 114,688 bytes
Figure 4.9The cache of Qwen3-0.6B. Each of 28 layers stores a key tensor and a value tensor of shape (B, 8, S, 128); every decode step adds one row of 128 numbers to each of the 8 heads in all 56 tensors.

Cache growth with sequence length

The cache grows by exactly one position per token. In bf16, one key/value head stores 2×128×2=5122 \times 128 \times 2 = 512 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 26×114,688=2,981,88826 \times 114{,}688 = 2{,}981{,}888 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.

python
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 copy

Real 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 bytes=2×L×Hkv×dh×S×b×B\text{cache bytes} = 2 \times L \times H_{kv} \times d_h \times S \times b \times B

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.

QWEN3-0.6B, ONE SEQUENCE, BF16: KV CACHE vs WEIGHTStokens in contextbytesweights1.19 GB10,394 tokens: cache = weights3.5 GiB4.375 GiB010,24020,48032,76840,9601 GB2 GB3 GB4 GB5 GBlong context costsmore than the model
Figure 4.10Qwen3-0.6B's KV cache for one sequence as the context grows, against its 1.19 GB of weights. The lines cross near 10,400 tokens; at the config's 40,960 positions the cache is almost four times the model.

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.

EVERY FACTOR IN THE CACHE FORMULA IS A LEVER SOMEONE HAS PULLED2×K and VfixedL×layerssliding windows in some layersHkv×KV headsGQA, MQAdh×head sizelatent compression (MLA)S×tokenswindows, eviction, pagingb×bytesfp8 cache: × 0.5Bsequencesbatch sizeQwen3-0.6B: 2 × 28 × 8 × 128 × S × 2 × 1 = 114,688 × S byteswith an fp8 cache: 57,344 × S as MQA: 14,336 × S as MHA: 229,376 × S
Figure 4.11The cache formula as a row of levers. Orange factors are the ones real systems shrink; the bottom line prices each choice for Qwen3-0.6B.

#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.

  1. 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 xx, shape (1,1,1,024)(1, 1, 1{,}024), and normalizes it with RMSNorm.
  2. New Q. q=xWQq = x W_Q gives (1,1,2,048)(1, 1, 2{,}048), reshaped to (1,16,1,128)(1, 16, 1, 128): 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.
  3. New K/V. k=xWKk = x W_K and v=xWVv = x W_V each give (1,1,1,024)(1, 1, 1{,}024), reshaped to (1,8,1,128)(1, 8, 1, 128). The key is normalized and rotated by position 26; the value is not.
  4. Append K/V to cache. The cache tensors go from (1,8,26,128)(1, 8, 26, 128) to (1,8,27,128)(1, 8, 27, 128). The new row is written before attention, so the token can attend to itself.
  5. 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 qK⊤/128q K^\top / \sqrt{128}: shape (1,16,1,27)(1, 16, 1, 27), one row of 27 scores per head.
  6. 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 (1,16,1,128)(1, 16, 1, 128).
  7. Produce next hidden state. The heads are concatenated back to (1,1,2,048)(1, 1, 2{,}048), WOW_O projects to (1,1,1,024)(1, 1, 1{,}024), and the result is added to the residual stream. The MLP half of the block follows, then the next layer.
  8. 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.
ONE DECODE STEP IN ONE QWEN3-0.6B LAYER, NEW TOKEN AT POSITION 26, BATCH 1RMSNorm(x)(1, 1, 1024)q_proj(1, 1, 2048)k_proj(1, 1, 1024)v_proj(1, 1, 1024)q_norm, RoPE @ 26(1, 16, 1, 128)k_norm, RoPE @ 26(1, 8, 1, 128)reshape only(1, 8, 1, 128)append to cache: (1, 8, 26, 128) → (1, 8, 27, 128)scores q Kᵀ / √128 → (1, 16, 1, 27) → softmax → × V → (1, 16, 1, 128)concat (1, 1, 2048) → o_proj (1, 1, 1024) → + residual → MLPheads 2j, 2j+1read KV head jold rows are read, never recomputed
Figure 4.12One cached decode step inside one Qwen3-0.6B layer at position 26, with every shape. Only the new token's row is computed; the 26 earlier rows of K and V are read from the cache.

With real numbers

Shrink it to one head of size 2 so it fits on a page. The cache holds three keys [1,0][1, 0], [0,1][0, 1], [1,1][1, 1] and three values [1,2][1, 2], [3,0][3, 0], [0,4][0, 4]. The new token arrives with q=[2,1]q = [2, 1], k=[1,−1]k = [1, -1] and v=[2,2]v = [2, 2]. Appending gives four keys and four values. The raw scores of qq against the four keys are 2,1,3,12, 1, 3, 1; divided by 2\sqrt{2} they are 1.4142,0.7071,2.1213,0.70711.4142, 0.7071, 2.1213, 0.7071. Softmax gives weights 0.2491,0.1228,0.5052,0.12280.2491, 0.1228, 0.5052, 0.1228, so the output is 0.2491⋅[1,2]+0.1228⋅[3,0]+0.5052⋅[0,4]+0.1228⋅[2,2]=[0.8633,2.7648]0.2491 \cdot [1, 2] + 0.1228 \cdot [3, 0] + 0.5052 \cdot [0, 4] + 0.1228 \cdot [2, 2] = [0.8633, 2.7648].

THE SECTION 7 TOY: ONE HEAD, d_h = 2, THREE CACHED ROWS + ONE NEWq = [2, 1]Kscaled scoreweightV[1, 0]1.41420.2491[1, 2][0, 1]0.70710.1228[3, 0][1, 1]2.12130.5052[0, 4][1, -1]0.70710.1228[2, 2]appendedthis stepoutput = Σ weight × V = [0.8633, 2.7648]rows 0 to 2 read from the cache
Figure 4.13The worked example of this section. Three keys and values come from the cache, the fourth was appended this step; the weights come from the scaled scores, and the output is their weighted sum of values.

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.

Figure 4.14The notebook represents retained history. Selecting a tab opens its continuation while earlier pages stay unchanged. Hover a tab or use arrow keys. Open illustration
PICTURE THIS: THE SHARED MEETING NOTESmeeting notesAna: budget is fixedBen: launch in MayCy: needs two hiresDee: ship docs firstDee arrivesreads alladds one lineearlier linesnever rewrittenher question isasked once, not filednotes = KV cache, reading = attention, one new line = append
Figure 4.15The shared notes of the analogy. A newcomer reads every line, adds exactly one, and never rewrites what is there.

#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.

CACHE CORRECTNESS: RUN BOTH LOOPS, COMPARE EVERY STEPprompt IDsnaive: whole sequenceevery stepcached: one tokenper step + cachemax |Δ logits|< tol ?argmaxappendedsame token fed to both loops, 50 to 100 steps
Figure 4.16The cache parity test. The naive and cached loops consume the same prompt, their logits are compared at every step, and the same argmax token is fed back into both.
python
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 HkvH_{kv} 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 QK⊤/dhQK^\top / \sqrt{d_h} times VV (Chapter 1, Part VII). What differs is the shape of QQ against the shape of KK, and that difference decides which mask is needed and which kernel is fast.

Prefill attention shape. All TT prompt positions are queries and all TT are keys: scores are (B,H,T,T)(B, H, T, T). 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 SS keys: scores are (B,H,1,S)(B, H, 1, S), 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 1×271 \times 27 “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).

SCORE SHAPES PER HEAD: PREFILL (T × T, MASKED) vs DECODE (1 × S, NO MASK)prefill, T = 8querieskeysfutureblockedis_causal=Truedecode at position 8, S = 9the only new rowearlier rows: done onearlier steps, not redoneis_causal=False
Figure 4.17Attention scores in the two phases. Prefill is a square with its future masked; decode is a single row over the whole cache, and needs no mask.

History grows at each step, so the new query reads more keys and values. Weight reads dominate some workloads; cache reads dominate others.