Attention & the KV Cache
The cache that turns quadratic generation into linear, the memory it consumes, and why concurrency on a GPU is set by megabytes rather than by FLOPs.
#The problem the cache solves
Generation is autoregressive — each new token is produced by feeding everything written so far back in, so the model is always predicting the next word given all the previous ones. Done naively, that means reprocessing every earlier token at every single step.
The fix follows from a property of causal attention noted on the previous page: **position i's key and value vectors depend only on position i and the layers below it.** They are identical whether the sequence is 6 tokens long or 6,000. So compute them once, keep them, and each new token computes only its own K and V and attends over the stored set.
WITHOUT CACHE WITH CACHE
step 3: recompute K,V for step 3: K,V for positions 1-2
positions 1,2,3 already in cache
compute K,V for position 3 only
cost per token: O(N) cost per token: O(1) compute,
total: O(N²) O(N) memory read
total: O(N)Cost per token becomes constant. Total generation becomes linear. This is the single optimisation that makes LLM serving possible at all — and the price is paid in memory, because every stored K and V vector has to sit in GPU memory for as long as the request is alive.
#What it costs
Every token of every live request holds a K and a V vector, in every layer.
#Making it smaller: attention variants
Attention runs as several parallel copies called heads, each learning to look for something different — one might track grammatical subjects, another nearby repetition. Each head normally keeps its own keys and values, so the cache scales with the number of heads. The highest-leverage change is therefore to let several heads share one set.
MULTI-HEAD (MHA) GROUPED-QUERY (GQA) MULTI-QUERY (MQA)
Q1 Q2 Q3 Q4 ... Q64 Q1 Q2 Q3 Q4 ... Q64 Q1 Q2 ... Q64
K1 K2 K3 K4 ... K64 K1─────┘ K2─────┘ K1 ──────────┘
V1 V2 V3 V4 ... V64 V1─────┘ V2─────┘ V1 ──────────┘
64 KV heads 8 KV heads 1 KV head
baseline 8× smaller cache 64× smaller cache
best quality ~no measurable loss small quality loss| Variant | KV heads | Cache per token (same model) | Quality |
|---|---|---|---|
| MHA | 64 | 2.5 MB | Baseline |
| GQA (8 groups) | 8 | 0.31 MB | Essentially unchanged |
| MQA | 1 | 0.04 MB | Slight degradation |
GQA is close to free, which is why nearly every model released since 2023 uses it. Dropping the cache 8× multiplies concurrency roughly 8× — a bigger throughput win than most hardware upgrades, obtained by changing a hyperparameter (a setting fixed before training — here, the number of K/V heads).
Two further reductions:
- Quantized KV cache — store K and V at FP8 or INT8, i.e. fewer bytes per number. Halves or quarters the cache with modest quality impact. It's independent of GQA — GQA stores fewer heads, quantization stores each value in fewer bytes — so the savings multiply: 8× from GQA and 2× from FP8 gives 16×.
- MLA (multi-head latent attention) — instead of storing full K and V for each token, store one small compressed vector (a "latent") and expand it back into K and V when attention needs them. Trades a little compute for a large memory reduction; used by DeepSeek's models.
#Prefix sharing: the property that changes chat economics
Two requests beginning with identical tokens produce identical K and V for that prefix. There is no approximation involved — the values are bit-identical, because causal attention means a position's K and V don't depend on anything after it.
So the cache blocks for a shared prefix can be shared, not merely recomputed similarly.
1,000 concurrent requests, all with the same 2,000-token
system prompt:
Without sharing: 1,000 × 2,000 × 2.5 MB = 5,000 GB
With sharing: 1 × 2,000 × 2.5 MB = 5 GB
→ 1,000× reduction on the shared portionAnd within a conversation:
Multi-turn chat is append-only:
turn 1: [system][user₁] → prefill all
turn 2: [system][user₁][asst₁][user₂] → first 3 CACHED,
prefill only user₂
turn 3: [system][user₁][asst₁][user₂][asst₂][user₃]
→ prefill only user₃
Every turn after the first is mostly a cache hit.This is the mechanism behind "cached input" pricing tiers, and it is why time-to-first-token in a long conversation is often lower than in a short fresh one. It also creates a routing requirement. The cache lives in one server's GPU memory, so the conversation's next turn must go to the replica (copy of the model server) that already holds its prefix — otherwise that replica has to prefill from scratch and the hit is lost. That's consistent hashing on conversation ID, with a load-based escape hatch: if that replica is overloaded, send the turn elsewhere and accept the miss. This is developed further in KV cache management.
#Paged allocation
The naive allocator reserves max_context_length per request up front, because you don't know how long the generation will be.
NAIVE (contiguous, reserve max)
request may generate 50 tokens or 4,000 — unknown at admission
→ reserve for 4,000, typically use 50
→ most reserved memory is wasted
→ freed blocks of varying sizes fragment the pool:
free space ends up in gaps too small to reuse
PAGED (fixed-size blocks, like OS virtual memory)
allocate in blocks of e.g. 16 tokens
each request holds a block table pointing at scattered blocks
grow by one block as generation proceeds
→ near-zero waste, no external fragmentation
→ identical prefixes SHARE physical blocks, copy-on-writeThis is the operating system's virtual memory, applied to attention state, and the analogy is exact:
- The block table is a page table — a map from "my tokens 0–15, 16–31, …" to wherever those blocks physically sit.
- Prefix sharing is shared read-only pages — many requests point at the same physical block.
- When two sequences sharing a block start to differ, the one that changes gets its own copy of that block first. That is copy-on-write.
Reported utilisation improvements from PagedAttention were in the range of 2–4× more concurrent requests on the same hardware.
#Exercise
#Check yourself
What does the KV cache turn quadratic into?Show answer
What is the KV cache size formula?Show answer
What sets how many requests a GPU can serve concurrently?Show answer
What do GQA, MQA, quantized cache and MLA do?Show answer
Why can identical prefixes share cache blocks exactly?Show answer
Why does prompt order decide the cache hit rate?Show answer
How does paged KV allocation work?Show answer
Under memory pressure, why not just evict?Show answer
#What to carry forward
- The KV cache turns O(N²) generation into O(N) — non-optional, and paid for in memory.
- Cache size = 2 × layers × kv_heads × head_dim × bytes, per token, per request.
- Concurrency is set by how much cache fits alongside the weights. You schedule memory.
- GQA is a near-free 8× reduction; quantized cache and MLA stack on top of it.
- Identical prefixes share blocks exactly — so put stable content first and route by cache affinity.
- Paged allocation removes reservation waste and fragmentation, and is literally OS virtual memory.
- Under pressure the choice is preempt, swap, or reject — not evict.