Before you start: words you need#
| Word | Plain meaning |
|---|---|
| KV cache | The keys and values of every earlier token, kept in GPU memory so each new token does not recompute them (12.e). |
| Concurrency | How many sequences the server generates for at the same moment. Usually limited by how much KV cache fits. |
| KV pressure | How close the KV pool is to full, and how much of each decode step is spent reading KV rather than weights. |
| GQA / MQA / MLA | Attention designs that store fewer or smaller keys and values per token (12.g). |
| Sliding window | A layer that only looks at the last W tokens, so its cache never grows past W. |
| Eviction | Throwing away the cached keys and values of tokens judged unimportant. The only technique here that loses information. |
| Offloading | Moving cold KV blocks from GPU memory to CPU memory or disk, and fetching them back when needed (14.k). |
| Prefix caching | Storing one copy of a shared prompt start (a system prompt, a document) and reusing it across requests (12.m). |
This lesson is a catalogue and a decision guide. It names every way to shrink the KV cache, says which term of the size formula each one attacks, and tells you which to reach for first. Most techniques have their own home; this lesson gives the gist and the label.
1. Problem → Why → Optimization#
PROBLEM The KV cache limits concurrency, and at long context or high batch it
dominates decode bandwidth — more than the model weights do.
WHY KV grows as batch × context × layers × kv_heads × head_dim × bytes,
with no ceiling except your context limit.
OPTIMIZE A family of techniques, each attacking a different term of that product.
Some are chosen by the model's designers; others are yours to switch on.The split that matters in practice: architecture choices (GQA, MLA, sliding windows, sparse and hybrid attention, KV sharing) come with the model you pick; serving choices (paging, prefix caching, KV quantization, offloading, eviction) are flags on your engine.
Facts checked on 12 November 2026 (vLLM v0.32.0).
2. Why does it exist? The catalogue, term by term#
KV_bytes = 2 × L × n_kv_heads × head_dim × bytes × context × batch
↑ ↑ ↑ ↑ ↑ ↑ ↑
A B C D E F G| Term | Lever | Techniques | Status | Home |
|---|---|---|---|---|
| A — the “2” (K and V) | store less than both | not possible for standard attention; MLA stores one latent instead | — | 12.g |
| B — layers with a cache | fewer layers keep their own KV | cross-layer KV sharing (CLA, YOCO, Gemma 3n); hybrid linear attention keeps a fixed state in most layers | KV sharing [EMERGING]; hybrids [ESTABLISHED in 2026 models] | 12.g |
| C — KV heads | fewer heads | GQA (4–8× smaller), MQA (one head) | [ESTABLISHED] | 12.g |
| D — head_dim | smaller per-head vector | MLA compresses K and V into a small latent | [ESTABLISHED] | 12.g |
| E — bytes per value | lower precision | FP8 KV (2×), INT4/NVFP4 KV (≈4×) | FP8 [ESTABLISHED]; 4-bit [EMERGING] | 13.h |
| F — context kept | keep or read fewer tokens | sliding window; sparse attention (DeepSeek V3.2 DSA); eviction (H2O, SnapKV); attention sinks (StreamingLLM) | windows, sparse [ESTABLISHED]; eviction [EMERGING] | 12.g, 12.h |
| G — sequences in GPU memory | move them out | CPU/SSD offload; disaggregated prefill and decode | [ESTABLISHED in engines, hardware-dependent] | 14.k, 14.j |
Two more sit outside the formula:
- PagedAttention (12.l) removes fragmentation, so the KV you have is actually usable (typically 2.5–4× more effective capacity than contiguous allocation).
- Prefix caching (12.m) removes duplicates, so shared prompt starts are stored once.
The 2026 architecture rows, briefly#
12.g teaches these; here is only what they mean for KV planning:
- Sparse attention (DeepSeek-V3.2’s DSA, GLM-5.x): every token is still stored, but each step reads only the top 2,048. Saves bandwidth per step, not memory.
- Hybrid linear attention (Qwen3-Next, Kimi Linear, Nemotron-H): most layers keep a fixed-size state instead of a growing cache; only the few full-attention layers grow with context. Saves a lot at long context, nothing at short context, and makes prefix caching harder (17.i).
- KV sharing (YOCO, cross-layer attention, Gemma 3n’s top layers reusing a middle layer’s KV): fewer layers own a cache. Engines model it as one layer pointing at another layer’s cache.
3. Simple analogy#
Managing a hotel’s guest records.
- GQA / MQA: fewer fields per record. Decided when the system was designed.
- MLA: each record is written in shorthand that can be expanded when read.
- Quantization: shorter fields — abbreviate rather than write in full.
- Sliding window: keep only the last 30 days of records.
- Sparse attention: keep everything, but each lookup only opens the 20 most relevant folders.
- Eviction: keep only the records someone thinks are important; shred the rest.
- Paging: standard-size folders, so no shelf space is wasted.
- Prefix sharing: one copy of the shared welcome pack, referenced by many guests.
- Offloading: move older records to the basement — slower to fetch, but they still exist.
Each trades space, access speed and information loss differently. Only eviction (and, by design, sliding windows) loses information.
4. Tiny example: stacking the techniques#
Llama-3-70B (80 layers, 8 KV heads, head_dim 128) on 8 × 80 GB GPUs, 8k-token contexts. The program assumes BF16 weights (141 GB) and 40 GB set aside for activations, CUDA graphs and workspace:
// Concurrency for Llama-3-70B on 8 x 80 GB GPUs as KV techniques are stacked.
package main
import "fmt"
func main() {
const (
layers, kvHeads, headDim = 80, 8, 128
ctx = 8192
hbm = 8 * 80e9 // bytes across 8 GPUs
weights = 141e9 // BF16 weights
reserve = 40e9 // activations, CUDA graphs, workspace
)
free := hbm - weights - reserve
perTok := func(heads, bytes float64) float64 { return 2 * layers * heads * headDim * bytes }
steps := []struct {
name string
tok float64 // KV bytes per token
boost float64 // extra effective concurrency from sharing
}{
{"MHA-equivalent, BF16 (64 KV heads)", perTok(64, 2), 1},
{"+ GQA-8 (the real model)", perTok(kvHeads, 2), 1},
{"+ FP8 KV cache", perTok(kvHeads, 1), 1},
{"+ prefix caching, 1/3 of tokens shared", perTok(kvHeads, 1), 1.5},
}
fmt.Printf("free for KV: %.0f GB\n", free/1e9)
for _, s := range steps {
seq := s.tok * ctx
fmt.Printf("%-40s %5.0f KiB/token %6.2f GiB/seq %4.0f sequences\n",
s.name, s.tok/1024, seq/(1<<30), free/seq*s.boost)
}
}Output:
free for KV: 459 GB
MHA-equivalent, BF16 (64 KV heads) 2560 KiB/token 20.00 GiB/seq 21 sequences
+ GQA-8 (the real model) 320 KiB/token 2.50 GiB/seq 171 sequences
+ FP8 KV cache 160 KiB/token 1.25 GiB/seq 342 sequences
+ prefix caching, 1/3 of tokens shared 160 KiB/token 1.25 GiB/seq 513 sequencesFrom 21 to about 513 concurrent sequences — roughly 24×. The program assumes paged allocation throughout; a contiguous allocator would waste a large share of every row.
Not all of this is yours to choose. GQA came with the model. But paging, FP8 KV and prefix caching are engine settings, and together they typically give 4–8× over a naive setup.
5. Technical explanation of the main techniques#
Fewer or smaller heads: GQA, MQA, MLA ([ESTABLISHED])#
Taught in 12.g. The serving point: GQA-8 makes the cache 8× smaller and raises the arithmetic intensity of decode attention 8×, because each loaded K/V head serves 8 query heads. MLA goes further: DeepSeek-V3 caches 512 + 64 values per layer, about 69 KiB per token in BF16 across its 61 layers (12.g). These are selection criteria when you choose a model, not switches.
Sliding window ([ESTABLISHED])#
Cap a layer's KV at W tokens instead of S.
Mistral-7B (32 layers, 8 KV heads, head_dim 128, FP16), W = 4,096:
128k context, full attention: 16 GiB per sequence
128k context, sliding window: 0.5 GiB per sequence 32× smaller
Cost: information beyond W reaches the token only indirectly, through the layer stack.Modern models interleave: Gemma 3 uses 5 local layers per global layer, gpt-oss alternates full and 128-token-window layers. With 5:1, about 83% of layers have a capped cache, while the global layers keep real long-range access. Engines manage the two kinds of cache separately (17.i).
Cross-layer KV sharing ([EMERGING])#
Standard: every layer has its own K, V
CLA (pairs): layers 2i and 2i+1 share one K, V → 2× smaller
YOCO: the top half of the model reads one shared cache
Gemma 3n: the top layers reuse a middle layer's K, V (mainly to speed prefill)Published results show a modest quality cost. It is shipping in some small and on-device models, not yet in most large open models.
Sparse and hybrid attention ([ESTABLISHED in 2026 models])#
See section 2 and 12.g. For capacity planning, remember the asymmetry: sparse attention cuts bytes read per step, hybrids cut bytes stored. Size memory for a DSA model as if it were plain MLA plus a small index cache.
KV eviction and compression ([EMERGING] — be careful)#
H2O (Heavy-Hitter Oracle)
Keep tokens with high cumulative attention scores; evict the rest.
SnapKV
At the end of prefill, use the last few queries' attention to choose
which prompt tokens to keep.
StreamingLLM
Keep the first few "attention sink" tokens plus a recent window.
Bounded memory for endless streams. The model gains no long-range
ability — it just doesn't break.
PyramidKV and other adaptive budgets
Give lower layers more KV budget than upper ones.Honest assessment: these work well on benchmarks designed to show them working, and can fail badly on tasks that need an evicted token. The failure is silent — the model confabulates instead of erroring. Deploy only with task-specific validation. The attention-sink insight itself is well established and now built into several models’ training. Research status is tracked in 24.c.
Prefix caching ([ESTABLISHED])#
Taught in 12.m (and vLLM’s version in 17.f). Not compression — deduplication. Often the largest practical win for chat and agent workloads, where every request repeats a long system prompt and tool list.
Offloading ([ESTABLISHED in engines], hardware-dependent)#
Move cold KV blocks to CPU memory (or SSD), fetch them back on a cache hit.
Viability = link bandwidth vs the KV you need back per step.
PCIe Gen5 x16: ~50 GB/s in practice
Re-reading 30 GB of active KV every step over PCIe: 600 ms. Not viable.
Restoring a 2 GB cached prefix once, ahead of time: ~40 ms. Viable.
NVLink-C2C (Grace Hopper / Grace Blackwell): 900 GB/s total → far more viable.In vLLM, the native path is --kv-offloading-backend native --kv-offloading-size <GiB> (evicted
blocks go to CPU memory instead of being dropped); lmcache is the other backend. Offload extends
the prefix cache, not the working set: it works for cold, reusable blocks, not for the KV of
sequences being decoded right now. 14.k covers the design; 14.j covers moving KV between prefill and
decode machines.
6. Under the hood: the decision procedure#
START: measure your KV pressure.
kv_bytes_per_step / weight_bytes_per_step (12.f)
KV pool utilization and preemption count (engine metrics)
If the pool is rarely above ~60% and nothing is preempted:
→ KV is not your problem. Optimize elsewhere (13.a).
If KV bytes per step < weight bytes per step:
→ weight quantization (13.b) is the bigger lever. Do that first.
If KV bytes > weight bytes (long context and/or high batch):
1. Paged KV on? → on by default in vLLM, SGLang, TensorRT-LLM.
2. Requests share prefixes? → prefix caching. Often huge.
3. KV still in BF16? → FP8 KV cache: 2×, near-free (13.h).
4. Prefixes reused but evicted? → CPU offload to extend the prefix cache (14.k).
5. Can you change the model? → prefer GQA/MLA/sparse/hybrid designs (12.g).
6. Still constrained?
├─ very long context, low batch → context parallelism or disaggregation (14.f, 14.j)
├─ quality-tolerant task → 4-bit KV or eviction, with task validation
└─ otherwise → more GPUsThe order matters: steps 1–3 are lossless or near-lossless and cost a flag; steps 5–6 cost money or quality.
7. Performance implications#
| Technique | KV reduction | Quality cost | Who decides |
|---|---|---|---|
| GQA-8 | 8× | ~0 | model architecture |
| MQA | h× | small | model architecture |
| MLA | ~7× vs GQA, ~60× vs MHA (12.g’s DeepSeek-V2-scale example) | ~0 (reported) | model architecture |
| Sliding window 4k | up to 32× at 128k on windowed layers | task-dependent | model architecture |
| Sparse attention (DSA) | 0× memory, ~60× less read per step at 128k | near-equal (reported) | model architecture |
| Hybrid linear | large at long context, none at short | slightly lower on recall | model architecture |
| Cross-layer sharing | ~2× | small | model architecture |
| PagedAttention | 2.5–4× effective | 0 | you (default on) |
| FP8 KV | 2× | ~0 | you |
| INT4 / NVFP4 KV | ~4× | small–moderate | you |
| Prefix caching | workload-dependent | 0 | you |
| Eviction (H2O etc.) | 3–5× | task-dependent, risky | you, carefully |
| CPU offload | capacity for cold blocks, not bandwidth | 0 | you, if the link is fast |
8. Production implications#
- Measure KV pressure first. If you are not KV-bound, none of this matters.
- Do the free ones: paging (already on), prefix caching, FP8 KV.
- Treat architecture as a selection criterion. Between two models of similar quality, KV bytes per token is a direct cost multiplier — record it in your model registry (21.b) next to the parameter count.
- Size sparse-attention models for memory like MLA, and hybrids by the full-attention layers plus a fixed per-sequence state.
- Be conservative with eviction. Silent quality failures.
- Do the bandwidth arithmetic before relying on offload.
9. Common mistakes#
- Optimizing KV when weights dominate. Check the ratio first.
- Deploying eviction without task-specific validation.
- Designing around CPU offload without checking the link bandwidth.
- Setting
max_model_lento the model’s maximum “just in case.” It raises the per-sequence worst case the scheduler must plan for, and lowers how many sequences it admits. - Forgetting that cached prefixes use KV blocks too. They compete with active sequences and are evicted first under pressure.
- Expecting sparse attention to save memory. It saves bandwidth; the cache is still stored.
- Assuming a hybrid model is cheaper for short chats. Its fixed state can cost more than a short GQA cache.
10. Hands-on exercise#
A. Measure your pressure. For your workload, compute KV bytes vs weight bytes per decode step at your p50 and p95 (batch, context). Which dominates? Plot the crossover and mark your operating point.
B. Stack the techniques. Change the program in section 4 to your model and GPUs. Add a row for 4-bit KV. How many sequences do you gain at each step?
C. Sliding window. Compare a full-attention and a sliding-window model of similar size at 32k context. Measure maximum concurrency for each.
D. Evaluate eviction honestly. Use a simple scheme (keep the first 4 + last N tokens). Evaluate on a task where the answer is at the end (easy) and one where it is in the middle of a long document (hard). Quantify the failure.
E. Offload arithmetic. Compute the maximum KV fetch rate over your host link. Compare it with the KV your batch reads per step. Is offload viable for the working set, or only for cached prefixes?
11. Interview questions#
- Write the KV size formula and name a technique that attacks each term.
- Why does GQA give two benefits, not one?
- When does KV cache optimization matter more than weight quantization?
- What is sliding-window attention and what does it cost?
- DeepSeek-style sparse attention reduces bandwidth per step but not memory. Why?
- Why are KV eviction methods risky in production?
- How would you decide whether CPU KV offload is viable on your hardware?
- Rank the KV optimizations you can apply without changing the model.
12. Further reading#
Checked on 12 November 2026.
- [ESTABLISHED] Ainslie et al., “GQA” (2023); Shazeer, “Fast Transformer Decoding: One Write-Head is All You Need” (MQA) (2019)
- [ESTABLISHED] Jiang et al., “Mistral 7B” (2023) — sliding window
- [ESTABLISHED] DeepSeek-AI, “DeepSeek-V2” — MLA; DeepSeek-V3.2-Exp and DeepSeek Sparse Attention
- [ESTABLISHED] Kwon et al., “PagedAttention” (2023)
- [EMERGING] Brandon et al., “Cross-Layer Attention” (2024); Sun et al., “YOCO” (2024); Gemma 3n developer guide — KV cache sharing
- [EMERGING] Zhang et al., “H2O” (2023); Li et al., “SnapKV” (2024); Xiao et al., “StreamingLLM” (2023)
- [REFERENCE] vLLM hybrid KV cache manager design — sliding window, hybrid state and KV sharing in one pool