The KV Cache Evolution

How long-context LLMs keep memory from taking over inference.

By thepradip

Table of Contents

  1. The Transformer Moment: Where This Starts
  2. Understanding Keys, Values, and Queries
  3. What Is KV Cache and Why Does It Exist?
  4. The Problem: When Memory Becomes the Bottleneck
  5. Multi-Head Attention (MHA): The Baseline
  6. Multi-Query Attention (MQA): Sharing One Memory Shelf
  7. Grouped-Query Attention (GQA): The Middle Path
  8. Multi-Head Latent Attention (MLA): DeepSeek's Different Approach
  9. Cross-Layer Attention (CLA): Sharing Across Layers
  10. Sliding Window & Local-Global Attention
  11. PagedAttention: Virtual Memory for KV Blocks
  12. KV Cache Eviction: Keeping Only What Matters
  13. KV Cache Quantization: Shrinking Each Number
  14. FlashAttention: Using Hardware Better
  15. Model-by-Model Comparison: How the Pieces Fit
  16. DFlash: Block Diffusion for Flash Speculative Decoding
  17. DeepSeek V4: Making Million-Token KV Practical
  18. Kimi K2.5: How Agent Workloads Change Memory
  19. Linear Attention & SSMs: The O(1) KV Cache Alternative
  20. Prefix Caching & RadixAttention: Reuse Across Requests
  21. Mixture of Experts & KV Cache: Sparse Activation
  22. KV Cache Offloading: CPU & NVMe as Overflow
  23. Disaggregated Prefill & Decode: Splitting the Serving Job
  24. Where Things Stand in 2026
  25. References

Source Verification Note

For the newer 2025–2026 claims, I used primary sources where I could: official Hugging Face configs and model cards for Qwen3.5, Gemma 4, Kimi K2, Llama 4, and DeepSeek V4; arXiv papers for DFlash, Kimi K2, Qwen3, TurboQuant, KIVI, KVQuant, PagedAttention, and related systems work; plus PrismML's Bonsai announcement and whitepaper for Bonsai-specific hardware and model-size claims. Local benchmark numbers are labeled as local measurements, not vendor guarantees.

Chapter 01

The Transformer Moment: Where This Starts

June 2017. Eight researchers at Google published a paper with a bold title: "Attention Is All You Need." Inside was the Transformer. At the time, it was a sequence-modeling architecture. Looking back, it also started the memory problem this article is about.

To see why it mattered, remember what came before. The dominant approach was the Recurrent Neural Network (RNN). Imagine passing a sticky note down a line of 500 people. Each person reads the previous note, compresses the whole story into their own short message, adds something new, and passes it along. By person 300, the first message is blurry. Worse, person 10 cannot even start until person 9 is finished. That was the shape of recurrence: useful, but painfully sequential.

The Transformer changed the setup. Instead of passing one note forward, it let every token look at every other token directly and decide what mattered. That is attention. There is no need to wait for the previous step to finish, and no single compressed hidden state has to carry the whole past. The cost is a large matrix operation, but that operation maps well to GPUs.

Vaswani, A., Shazeer, N., Parmar, N., et al. "Attention Is All You Need." NeurIPS 2017. arXiv: 1706.03762

The benchmark numbers made the case. On WMT 2014 English-to-German, the Transformer reached 28.4 BLEU, more than 2 points above the previous best. That may sound small from the outside, but in machine translation those points were hard to win. Training also became much faster. The architecture improved accuracy and fit the hardware better.

The next decade built on that foundation: BERT, GPT-2, GPT-3, GPT-4, LLaMA, Gemma, Qwen, DeepSeek, and Mistral. More layers, more parameters, more data. For a while, the recipe kept working. Then users started asking models to read long codebases, research archives, legal documents, and multi-hour conversations. A quieter cost began to dominate. It was not the cost of the weights. It was the cost of remembering the context. That cost is the KV cache.

2017
Transformer Architecture Published
Vaswani et al. introduce self-attention, replacing RNNs and CNNs for sequence modeling.
2018–2019
BERT and GPT-2 Emerge
Transformers dominate NLP. Models grow from millions to billions of parameters.
2020–2022
The Scaling Era
GPT-3 (175B parameters), PaLM (540B). KV cache memory becomes a serious concern.
2023–2024
The Optimization Era
GQA, MLA, PagedAttention, KIVI: the industry fights the memory wall.
2025–2026
The Efficiency Era
TurboQuant, Gemma 4, DeepSeek-V4, Bonsai: long-context and edge-friendly inference move closer to daily use.
Chapter 02

Queries, Keys, and Values: The Small Mechanism Behind the Big Cost

Before the cache makes sense, the objects inside it have to make sense. The Transformer's central operation, scaled dot-product attention, turns each token into three vectors: Query (Q), Key (K), and Value (V). The names come from database language, but a food court is an easier way to picture it.

Picture a food court with 200 stalls.

Query (Q)
Your Craving
"I want something spicy with noodles." This is what the current word is looking for in context.
Key (K)
Menu Board Descriptions
"Sichuan stir-fried noodles" or "vanilla milkshake." Each stall advertises what it offers so you can judge relevance.
Value (V)
The Actual Dish Served
The actual food you get, the content that gets "consumed" by the model's computation.

Inside the model, every token makes the same move. It sends out a Query, compares that Query against other tokens' Keys, and then blends the Values according to those scores. A token that looks relevant contributes more. A token that looks irrelevant fades into the background. The final representation is not copied from one place. It is mixed, weighted, and rebuilt from the full context. The operation is compact on paper. At scale, across every token and every layer, it becomes expensive.

The Attention Formula Attention(Q, K, V) = softmax(Q × KT / √dk) × V

The softmax turns raw scores into weights that sum to 100%. The √dk term, the square root of the key dimension, keeps the scores from becoming too large. Under the notation, the mechanism is plain: ask what matters, then blend the content that receives weight. It is simple, but it becomes memory-heavy once the context grows.

How Big Are These Vectors?

Each Q, K, and V vector has a specific size called the head dimension (dh), typically 128 numbers. In a model like LLaMA-2 7B, there are 32 attention heads, each with dimension 128, giving a total hidden size of 4,096.

Why This Matters for Memory

During training, the model can process the whole sequence together. During inference, it writes one token at a time. Each new token still needs to look back at the tokens already written, which means it needs their Keys and Values. That stored history is the KV cache.

Chapter 03

What Is KV Cache and Why Does It Exist?

The first time I looked closely at LLM inference, the slow part was more ordinary than I expected. The model does not write a paragraph in one breath. It writes one token, looks back, writes the next token, and looks back again. Every step repeats part of the same work.

Say it has written "The cat sat on the" and now needs token 6. It attends over tokens 1–5. Then token 7 attends over 1–6. Token 8 over 1–7. Without caching, the model keeps rebuilding Key and Value vectors for old tokens it has already processed. Nothing is mathematically broken. It is simply repetitive, and the repetition compounds.

The KV cache is the notebook the model keeps open beside it. Compute each token's Key and Value once. Store them. When the next token arrives, read the old entries instead of rebuilding them. It is a plain idea, which is why the memory cost is easy to underestimate.

Animation: Q × KT → Attention Scores → Weighted V → Output

Toy scaled-dot-product example: one 1×4 Query is compared against five cached Keys, scaled by √dk, then turned into attention weights and a weighted V output.

The Speed Benefit

Without the cache, the model keeps paying for old work. With the cache, each step computes K and V only for the new token, then attends over the stored history. This does not make attention constant-time. Each new token still scans a growing context, so decoding still gets more expensive as the sequence length grows. The gain is concrete: fewer repeated projections and fewer wasted bytes moving around.

The Memory Cost

Then the tradeoff arrives. The cached K and V vectors live in GPU memory, and they grow linearly with sequence length. In FP16, the memory formula is:

KV Cache Memory Formula (FP16) Memory = 2 × nlayers × nkv_heads × dhead × seq_len × batch_size × 2 bytes

The first "2" is for Keys and Values. The final "2 bytes" is FP16 precision. Put real model configs into that formula and the numbers get large quickly:

Model Layers KV Heads Head Dim KV Cache / Token (FP16) KV Cache @ 4K Tokens KV Cache @ 128K Tokens
LLaMA-1 65B MHA 80 64 128 2,560 KB 10 GB 320 GB
Falcon-7B MQA 32 1 64 8 KB 0.03 GB 1.0 GB
Mistral 7B GQA+SWA 32 8 128 128 KB 0.5 GB 0.5 GB*
Qwen3 235B GQA-4 94 4 128 189 KB 0.76 GB 24 GB
DeepSeek-V3 MLA 61 Latent (dc=512) 576* 69 KB 0.27 GB 8.6 GB
Gemma 4 31B GQA+LG 60 16 local / 4 global 256 local / 512 global Mixed; capped local ~0.43 GB† ~5.4 GB†
*Mistral 7B uses a 4,096-token sliding window, so the KV cache is capped at about 0.5 GB per sequence in this FP16-style calculation, even when nominal context is longer.
†Gemma 4 31B: 60 layers (50 sliding, 10 global), with 16 local KV heads, 4 global KV heads, attention_k_eq_v=true, 1,024-token sliding layers, and full-context global layers. The rough figures assume K=V is stored once: ~0.43 GB at 1K and ~5.4 GB at 128K. Source: official config.json.
*MLA stores a compressed latent of 576 dims (dc=512 + dR=64) instead of separate K and V vectors. Formula: layers × 576 × 2 bytes.
KV cache per token calculations based on architectural parameters from respective model papers. DeepSeek-V3 KV cache figure (70 KB/token) from "DeepSeek-V3 Technical Report," arXiv: 2412.19437

The Memory Wall

For LLaMA-1 65B with pure MHA at 128K context, the KV cache needs 320 GB. The FP16 model weights are about 130 GB. The memory used to remember the prompt is larger than the model itself. Even a 7B MHA model reaches 64 GB of KV cache at 128K context while the weights are roughly 14 GB. That imbalance is the memory wall.

Animation: KV Cache Growing Token by Token

Illustrative LLaMA-2 7B FP16-style baseline: each new token adds one more cached K/V state for every layer. Watch GPU memory fill up over time.

Chapter 04

The Problem: When Memory Becomes the Bottleneck

The cache saves time, then slowly becomes the thing that controls the system. At 2K tokens, it is easy to ignore. At 32K, 128K, or a million tokens, it decides which model fits, how many users can be batched, and whether the request can finish. Three pressure points show up again and again:

Memory Wall
GPU memory fills up before the model can process long documents
A 7B model at 128K context needs 64 GB just for the cache
Batch Size Limit
Fewer requests can be served simultaneously
Each user's request needs its own KV cache, multiplying memory usage
Bandwidth Bottleneck
Reading large caches from GPU memory slows down generation
Memory bandwidth, not compute, becomes the limiting factor

Why Memory Bandwidth Matters

An A100 can perform about 312 trillion floating-point operations per second, but it moves data at roughly 2 TB/s. During decode, the arithmetic is not the hard part: one query vector is compared against a long row of cached keys. The expensive part is hauling those cached vectors out of memory every step. Engineers call this memory-bandwidth bound. The GPU is not short on math. It is waiting for bytes.

It is like a very fast cook working from a pantry down the hallway. The cooking takes seconds. The walking takes most of the shift. A faster stove will not fix that; you need fewer trips, a closer pantry, or lighter ingredients.

The Memory Fragmentation Problem

There is also waste that comes from bookkeeping. In serving, requests have different lengths, but older systems often reserved fixed-size memory blocks anyway. A short prompt could occupy space reserved for a much longer one. The PagedAttention paper measured this kind of fragmentation at 60–80% of KV cache memory in existing systems.

Kwon, W., Li, Z., Zhuang, S., et al. "Efficient Memory Management for Large Language Model Serving with PagedAttention." SOSP 2023. arXiv: 2309.06180

Most KV cache work answers one of those pressures. The techniques fall into five groups:

The Five Strategies for Taming KV Cache

1. Fewer KV heads: MQA, GQA, MLA: reduce how many separate Key-Value pairs you store
2. Smarter memory management: PagedAttention: eliminate waste in how memory is allocated
3. Smaller numbers: KIVI, KVQuant, TurboQuant: use fewer bits per number
4. Fewer tokens cached: H2O, SnapKV, StreamingLLM: don't cache everything
5. Shorter attention span: Sliding window, local-global: limit how far back the model looks

Chapter 05

Multi-Head Attention (MHA): The Expensive Baseline

The original Transformer used what we now call Multi-Head Attention (MHA). It is the reference point for almost every optimization that follows. The design is still elegant: instead of one large attention pass, the model runs many smaller heads in parallel. One head may become sensitive to grammar. Another may track coreference. Another may notice negation. Nobody writes those roles by hand; they emerge during training.

The price is memory. In MHA, every head keeps its own separate Key and Value matrices. For a 32-head, 32-layer model, the cache grows like this:

MHA KV Cache Size KV Cache per token = 2 × nlayers × nheads × dhead × 2 bytes

For LLaMA-2 7B: 2 × 32 layers × 32 heads × 128 dim × 2 bytes = 524,288 bytes = 512 KB per token.

This is why MHA remains a good baseline. It gives every head its own memory, so each head can specialize freely. But the cost is blunt: more heads mean more cached vectors. With 32 heads and 128-dimensional heads, the model stores 64 vectors per token per layer. That is a lot of memory just to remember what has already been read.

Multi-Head Attention (MHA): Each Head Has Its Own K and V (Two Separate Vectors)

32 Query Heads → 32 Key Heads + 32 Value Heads (1:1:1 mapping) QUERIES KEYS VALUES Q₁ Qβ‚‚ Q₃ ... Q₃₂ K₁ Kβ‚‚ K₃ ... K₃₂ V₁ Vβ‚‚ V₃ ... V₃₂ 32 K vectors each 128 dims × 2 bytes + 32 V vectors each 128 dims × 2 bytes = 512 KB/token total per layer × 32 layers (LLaMA-2 7B) ▲ These K and V rows are CACHED (the KV Cache)

A Clarification Worth Making Explicitly

The "KV" in "KV cache" does not mean one fused vector. K and V are separate objects. K is the lookup key, compared against queries to produce attention scores. V is the content that gets weighted and summed into the output. They are computed by different matrices and stored separately. That small detail matters; it is the first "2" in the memory formula.

Vaswani, A., et al. "Attention Is All You Need." NeurIPS 2017. arXiv: 1706.03762
Chapter 06

Multi-Query Attention (MQA): Sharing One Memory Shelf

November 2019. Noam Shazeer, one of the original Transformer authors, published a short paper with a very sharp idea: what if all attention heads shared one set of Keys and Values?

That is Multi-Query Attention (MQA). You keep many Query heads, so the model can still ask many different questions. But instead of giving each head its own Key-Value archive, every head reads from the same archive. Imagine 32 researchers working from one filing cabinet. They disagree, they ask different questions, they write different notes, but the cabinet itself is shared.

The idea is simple. Queries need variety because each head asks a different question. Keys and Values are the context being questioned. Maybe the model does not need 32 full copies of that context.

MQA KV Cache Size KV Cache per token = 2 × nlayers × 1 × dhead × 2 bytes

For a model with 32 query heads but only 1 KV head, the KV cache shrinks by 32× compared with MHA.

Shazeer, N. "Fast Transformer Decoding: One Write-Head is All You Need." arXiv: 1911.02150, November 2019.

The Results

The speed gain follows the memory story. Decode is usually bandwidth-bound, so a 32× smaller KV cache means far fewer bytes read every step. Tokens per second improves. The quality cost exists, but in 2019 it looked small enough to be worth the trade.

The Trade-off

Over time, that phrase "modest quality loss" became less comforting. MQA holds up well on short answers and many factual tasks. On long code, multi-step reasoning, and dense document analysis, the gap becomes easier to feel. By 2023, "slightly worse" was no longer good enough for many top models. That is where GQA enters.

Multi-Query Attention (MQA): All Heads Share One K and One V

32 Query Heads → 1 shared K + 1 shared V (32:1 mapping) Q₁ Qβ‚‚ Q₃ ... Q₃₂ K₁ V₁ ▲ Only these two vectors cached 1 K + 1 V = 0.5 KB/token/layer 32× reduction!

Models Using MQA

MQA did make it into real models, including PaLM, Falcon-7B, and StarCoder. One detail worth keeping straight: Falcon-40B and Falcon-180B use GQA with 8 KV heads, not single-head MQA. The distinction matters because the field eventually moved toward that middle ground.

Chapter 07

Grouped-Query Attention (GQA): The Middle Path

By mid-2023, MQA had a reputation problem. The memory savings were excellent. The quality tradeoff was harder to ignore. Forcing 32 query heads to share one KV head was efficient, but too severe for many larger models and harder tasks.

Joshua Ainslie and the Google team asked the practical question: if MHA is too expensive and MQA is too compressed, what sits between them? Their answer was Grouped-Query Attention (GQA). Divide the query heads into groups. Each group shares one KV head. With 32 query heads and 8 KV groups, the cache drops by 4×. Not as dramatic as MQA, but often much easier to live with.

The conversion recipe may be the most valuable part of the paper. A trained MHA model could be uptrained into GQA using about 5% of the original pretraining compute. No full restart. No huge retraining bill. GQA-8 stayed close enough to MHA on benchmarks that the quality gap became a deployment tradeoff rather than a blocker.

Ainslie, J., Lee-Thorp, J., de Jong, M., et al. "GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints." EMNLP 2023. arXiv: 2305.13245
GQA KV Cache Size (with G groups) KV Cache per token = 2 × nlayers × G × dhead × 2 bytes

where G = number of KV head groups (MHA: G = n_heads, MQA: G = 1)

What the Paper Actually Shows

GQA fit the way model teams actually work. It saved enough memory to matter, and it could be adopted without throwing away an already-trained model. That combination is why it spread so quickly through open model families.

Grouped-Query Attention (GQA): 4 Query Heads Share 1 K + 1 V Per Group

32 Query Heads ÷ 8 groups = 4 queries per group, each sharing 1 K + 1 V Group 1 Q₁ Qβ‚‚ Q₃ Qβ‚„ K₁ V₁ Group 2 Qβ‚… Q₆ Q₇ Qβ‚ˆ Kβ‚‚ Vβ‚‚ . . . Group 8 Q₂₉ Q₃₀ Q₃₁ Q₃₂ Kβ‚ˆ Vβ‚ˆ 8 groups × (1 K + 1 V) = 16 vectors cached (4× less than MHA's 64) 32 Q heads ÷ 8 groups = 4 Q per group. Each group: 4 Q share 1 K + 1 V. Total cached: 8K + 8V = 16 vectors.

GQA's Impact on the Industry

After that, GQA became ordinary in the best possible way. LLaMA-3, Qwen2, Gemma 2, Phi-4, Mistral: the pattern shows up everywhere. Many 7–8B models settled around 8 KV heads. Larger models sometimes go lower. The exact number varies, but the direction is consistent.

Model Year Attention Type Query Heads KV Heads KV Reduction vs MHA
LLaMA-2 7B/13B 2023 MHA 32 / 40 32 / 40 1× (baseline)
LLaMA-2 70B 2023 GQA 64 8 8×
LLaMA-3/3.1 8B/70B/405B 2024 GQA 32/64/128 8 4× / 8× / 16×
Mistral 7B 2023 GQA 32 8 4×
Qwen-2 2024 GQA varies varies 4–8×
Gemma 2 2024 GQA varies varies 4–8×
Touvron, H., et al. "Llama 2: Open Foundation and Fine-Tuned Chat Models." arXiv: 2307.09288, 2023.
Llama Team, AI @ Meta. "The Llama 3 Herd of Models." arXiv: 2407.21783, 2024.
Chapter 08

Multi-Head Latent Attention (MLA): DeepSeek's Different Question

May 2024. GQA had become the sensible default, and it would have been easy for the field to keep refining that line of work. Then DeepSeek-V2 introduced MLA, and the question changed.

MHA, MQA, and GQA all ask some version of the same question: how many copies of Keys and Values should we store? DeepSeek asked a more unsettling one: do we need to store full Keys and Values at all? MLA stores a compact latent vector per token, then reconstructs the needed Key and Value information through learned projections during inference.

DeepSeek-AI. "DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Model." arXiv: 2405.04434, May 2024.

How MLA Works (The Intuition)

The music analogy helps. MHA stores full uncompressed recordings of every instrument. GQA stores one recording per section. MLA stores something closer to a compact score: enough structure to reconstruct what is needed later. The latent vector is the score; the model weights are the synthesizer. Reconstruction costs compute, but GPUs are good at matrix multiplication. The cache stays small.

The important trick is placement. Reconstruction matrices live in the model weights, not in the per-token cache. You pay for them once when the model is loaded, while the memory that grows with context remains compact.

In formula form, MLA stores a compressed vector ct rather than the full Key and Value matrices for each token. The dimension dc is much smaller than the full KV representation.

MLA: Low-Rank Joint KV Compression ct = WDKV × ht     (compress hidden state to latent)

Kt = WUK × ct     (reconstruct Keys from latent)
Vt = WUV × ct     (reconstruct Values from latent)

Only ct is stored in cache. WUK and WUV are fixed model weights, not cached.

The Numbers Make the Point

93.3%
KV Cache Reduction
vs. DeepSeek-67B (MHA)
5.76×
Maximum Generation
Throughput Improvement
70 KB
KV Cache Per Token
in DeepSeek-V3

DeepSeek-V2 MLA Configuration

In DeepSeek-V2, the specific parameters are:

The cache stores 512 + 64 = 576 elements per token per layer. Standard MHA with 128 heads would store 2 × 128 × 128 = 32,768 elements. That is about a 56× reduction in the V2 configuration. It is roughly like having 2.25 KV groups, a configuration GQA cannot naturally express.

DeepSeek-V3: Scaling MLA Further

V2 proved the idea. V3 showed it could scale. DeepSeek kept MLA while moving to a 671B-parameter MoE model with 61 transformer layers. The cache cost landed around 70 KB per token. That is not tiny in isolation, but it is low for a model of that scale.

DeepSeek-AI. "DeepSeek-V3 Technical Report." arXiv: 2412.19437, December 2024.
Model Attention Type Total Params KV Cache / Token vs. LLaMA-3.1 405B
LLaMA-3.1 405B GQA (8 heads) 405B 504 KB 1× (baseline)
Qwen-2.5 72B GQA 72B 320 KB 0.63×
DeepSeek-V3 MLA 671B (37B active) 69 KB 0.14× (7.3× smaller)

The Claim That Changed the Tone

The DeepSeek-V2 paper does more than claim MLA preserves quality. It reports better benchmark results than MHA in their setup, with the suggestion that compression may act like regularization. The exact cause still needs study, but the result weakened an old assumption: smaller KV cache does not automatically mean worse quality.

Interactive Comparison

Live: How KV Cache Works in MHA vs MQA vs GQA vs MLA

The animation below runs all four attention methods side by side. Watch tokens arrive one at a time and see how much cached attention state each method stores. This is a normalized 32-layer FP16 comparison so the methods are compared on the same footing.

Chapter 09

Cross-Layer Attention (CLA): Sharing Across Layers

Every approach so far has attacked the "head" axis of the KV cache, fewer heads, smaller heads, compressed heads. But a transformer has two axes that matter for cache size: heads and layers. If you have 32 layers, you're storing 32 separate sets of KV vectors per token. Nobody questioned this for years. Then a paper from Microsoft did.

The May 2024 CLA paper asks: do adjacent transformer layers really need their own independent KV cache? The observation is that nearby layers tend to attend to similar positions, they're looking at roughly the same context. So what if layers within a group just shared the KV cache from the first layer in that group?

Brandon, W., Mishra, M., Nrusimha, A., et al. "Reducing Transformer Key-Value Cache Size with Cross-Layer Attention." arXiv: 2405.12981, May 2024.

That's Cross-Layer Attention (CLA). Group your 32 layers into pairs. Each pair shares one KV cache instead of two. Immediately, your cache is half the size. The accuracy loss is small enough that on most benchmarks you can't confidently attribute degradation to CLA specifically. And because CLA acts on the layer axis and GQA/MQA act on the head axis, you can combine them, the reductions multiply.

Results

CLA alone gives roughly 2Γ— KV cache reduction. Stack it with GQA (8 groups) and you're looking at 8–16Γ— over vanilla MHA. It's not widely deployed yet as a primary technique, most labs are still on GQA, but CLA sits in the toolbox as a clean, low-risk complement to anything else you're doing.

Chapter 10

Sliding Window & Local-Global Attention

There's one more lever that hasn't come up yet: you can limit how far back the model looks at all. Every approach so far caches everything and then figures out how to compress it. This one asks: what if most of that history isn't needed in the first place?

Sliding Window Attention (Mistral 7B)

The Mistral 7B paper from October 2023 introduced Sliding Window Attention (SWA), each layer only attends to the 4,096 most recent tokens, and older tokens fall off the window. The KV cache per layer is capped at a fixed size no matter how long the conversation gets. That's a hard memory ceiling, which is very appealing from a serving perspective.

Jiang, A.Q., et al. "Mistral 7B." arXiv: 2310.06825, October 2023.

The natural worry is that important early context gets lost. The Mistral answer to this is stacking: with a window of 4,096 and 32 layers, information can propagate across a theoretical span of roughly 131,000 tokens as signals pass between layers. Whether that theoretical span translates to practical recall on hard tasks is a separate question, and I think it's fair to be somewhat skeptical about very long-range dependencies in SWA-only models. But for most real-world queries, where the relevant context is recent, it works well.

Interleaved Local-Global Attention (Gemma 2 and Gemma 3)

Google's Gemma team took a more careful approach. Rather than making every layer local, they interleaved two types:

Model Local Window Global Layers Local:Global Ratio KV Cache Benefit
Gemma 2 4,096 tokens Every other layer 1:1 ~50% of full attention cache
Gemma 3 1,024 tokens Every 6th layer 5:1 Major reduction for 128K context
Gemma 4 (31B / E4B / E2B) 1024 (31B) / 512 (E4B, E2B) Every 6th layer 5:1 128K/256K context by variant; E4B shares KV across 18 layers; 31B does not share (num_kv_shared_layers=0)
Gemma Team, Google. "Gemma 2: Improving Open Language Models at a Practical Size." arXiv: 2408.00118, 2024.
Gemma Team, Google. "Gemma 3 Technical Report." arXiv: 2503.19786, 2025.

Local layers use sliding window attention with a short, fixed window, tiny KV cache, fast, cheap. Global layers use full attention across all tokens, accurate, but expensive. The trick is the ratio. Gemma 3 runs 5 local layers for every 1 global. So only one out of every six layers actually needs to see the full context. The other five cap out at 1,024 tokens. At 128K context, that's the difference between paying for 128K-length KV cache at every layer versus paying for it at 1 in 6 layers. The memory curve flattens dramatically.

Gemma 3's Clever Design

Gemma 3 is unusually selective. Many KV cache tricks are blunt instruments: compress everything, quantize everything, or drop some tokens. Gemma 3's 5:1 local-global ratio gives distant context to specialized global layers and keeps most layers cheap. The architecture enforces that division of labor directly, without a runtime heuristic. The Gemma 4 E4B and E2B variants take this further for mobile and edge hardware, where even the global layers need to be lean.

Chapter 11

PagedAttention: Virtual Memory for KV Blocks

Everything up to this point has been about making the KV cache smaller in theory. MLA stores latents instead of full KV. GQA cuts the head count. Quantization shrinks each number. But there is a separate systems problem: the software managing GPU memory for KV cache can waste a lot of space.

Before vLLM, most serving systems pre-allocated a contiguous block of memory for each request, sized for the maximum possible sequence length. If you pre-allocate for 4,096 tokens and the user sends 200, you've wasted 3,896 tokens worth of memory. Multiply by thousands of concurrent users and you're throwing away 60–80% of your GPU memory before a single token is generated. The SOSP 2023 paper that measured this was not subtle about how bad the situation was.

Woosuk Kwon and the Berkeley team borrowed from a place software engineers already knew well: operating systems. Linux virtual memory does not require physically contiguous RAM. It breaks memory into pages, maps them through a page table, and lets the OS place pages wherever space exists. PagedAttention applies that pattern to GPU KV cache.

Kwon, W., Li, Z., Zhuang, S., et al. "Efficient Memory Management for Large Language Model Serving with PagedAttention." SOSP 2023. arXiv: 2309.06180

The Problem: Memory Fragmentation

The way pre-vLLM systems handled memory is almost comically wasteful once you see it. Each incoming request got a contiguous block of GPU memory sized for the maximum possible response. Ask for a 4,096-token limit, get 4,096 tokens of memory, whether you use 50 tokens or 4,000. Three kinds of waste compound on each other:

Internal Fragmentation
Pre-allocated blocks are larger than actually needed
External Fragmentation
Free memory exists but in scattered, unusable chunks
Reservation Waste
Memory reserved for future tokens that may never be generated

The paper found that existing systems waste 60–80% of KV cache memory!

The Solution: Paging

PagedAttention splits the KV cache into small fixed-size blocks, often 16 or 32 tokens per block. Blocks are allocated as needed, not upfront. They also do not need to be physically adjacent in memory. A page table maps logical sequence positions to wherever the physical blocks actually sit. Request A's block 3 can sit next to Request B's block 7 in physical memory. The attention kernel does not care; it uses the table.

Request arrives
→
Allocate KV blocks on demand
→
Blocks stored anywhere in GPU memory
→
Page table maps logical → physical

Results

The system built on this, vLLM, quickly became one of the most used LLM servers. The throughput numbers are strong, but the bigger change is KV cache sharing across requests. Multiple users hitting the same system prompt do not each need their own copy of its KV blocks. That sharing follows naturally from the paging design.

2–4×
Throughput Improvement
vs. FasterTransformer and Orca
~0%
Memory Waste
Down from 60-80% in traditional systems
Free
KV Cache Sharing
Multiple requests can share common prefixes

TensorRT-LLM and SGLang both adopted similar paging approaches. For production LLM serving, paged KV cache management is now one of the first memory tools to check.

Chapter 12

KV Cache Eviction: Keeping Only What Matters

One uncomfortable finding keeps showing up in KV eviction papers: much of the cache is barely used. Attention is highly skewed. A small set of tokens attracts most of the attention weight, while many others contribute almost nothing during generation. Once you see that pattern, the next question is natural: why keep every token at full cost?

H2O: Heavy-Hitter Oracle (NeurIPS 2023)

Zhang et al. studied how attention scores are distributed across tokens during generation and found that they are not spread evenly. A small number of tokens, the "heavy hitters", absorb most cumulative attention across heads and decode steps. Many other tokens receive almost none. H2O tracks which tokens collect the most attention weight and keeps those, plus a small window of recent tokens for continuity. Everything else gets evicted.

Zhang, Z., Sheng, Y., et al. "Hβ‚‚O: Heavy-Hitter Oracle for Efficient Generative Inference of Large Language Models." NeurIPS 2023. arXiv: 2306.14048

With only 20% heavy hitters retained, H2O improved throughput by up to 29× over DeepSpeed Zero-Inference and Hugging Face Accelerate on OPT-6.7B and OPT-30B models.

Scissorhands (NeurIPS 2023)

Scissorhands builds on an observation that complements H2O. Where H2O measures importance dynamically as generation proceeds, Scissorhands asks: is importance stable over time? Their answer, the "Persistence of Importance" hypothesis, is that once a token is heavily attended to, it tends to stay heavily attended to. You don't need to keep re-evaluating which tokens matter. Identify them early, keep them, discard the rest. It's a simpler runtime than H2O but relies on this stability assumption holding.

Liu, Z., Desai, A., et al. "Scissorhands: Exploiting the Persistence of Importance Hypothesis for LLM KV Cache Compression at Test Time." NeurIPS 2023. arXiv: 2305.17118

Scissorhands achieves up to 5× KV cache reduction without quality loss, and when combined with 4-bit quantization, reaches 20× compression.

StreamingLLM: Infinite Context with Fixed Cache (ICLR 2024)

Xiao et al. at MIT studied why removing the first few tokens from the KV cache causes such severe quality loss, more than their content alone would suggest. They found that those initial tokens work as "attention sinks." No matter what the tokens say, the model routes a large share of attention weight to them. The beginning of the sequence seems to act like a scratch pad for attention that does not belong anywhere else. Remove the sinks, and attention becomes unstable. Keep the sinks plus a sliding window of recent tokens, and the model can process very long sequences with a fixed cache budget.

Xiao, G., Tian, Y., Chen, B., et al. "Efficient Streaming Language Models with Attention Sinks." ICLR 2024. arXiv: 2309.17453

StreamingLLM enabled models like Llama-2, MPT, and Falcon to process up to 4 million tokens with stable performance, achieving 22.2× speedup over sliding window recomputation baselines.

SnapKV (NeurIPS 2024)

SnapKV shifts the problem earlier. Instead of deciding what to keep during generation, it decides during prefill, before a single output token is written. The observation is that attention patterns in the last few tokens of a prompt are already highly predictive of which earlier prompt tokens will matter during generation. So SnapKV reads those final prompt attention weights, pre-selects the high-importance prefix tokens, and throws away the rest before generation even begins. You're compressing the cache at the moment it's cheapest to do so.

Li, Y., et al. "SnapKV: LLM Knows What You are Looking for Before Generation." NeurIPS 2024. arXiv: 2404.14469
3.6×
Speed Increase
Generation speed at 16K tokens
8.2×
Memory Savings
Compared to full KV cache
380K
Max Tokens
On a single A100-80GB GPU

PyramidInfer and PyramidKV

Both PyramidInfer and PyramidKV reached the same insight from different angles: token importance is not uniform across layers. Lower layers, which build basic syntactic structure, need to attend to more tokens. Higher layers, which handle abstraction and semantics, can often get by with fewer. Instead of giving every layer the same cache budget, early layers get more and late layers get less. That gives the cache a pyramid shape. PyramidKV matched full-cache performance while keeping only 12% of the total cache in the reported benchmarks.

Yang, D., et al. "PyramidInfer: Pyramid KV Cache Compression for High-throughput LLM Inference." arXiv: 2405.12532, 2024.
Cai, Z., et al. "PyramidKV: Dynamic KV Cache Compression based on Pyramidal Information Funneling." arXiv: 2406.02069, 2024.

PyramidInfer achieved 2.2× throughput improvement with over 54% GPU memory reduction. PyramidKV matched full KV cache performance while retaining only 12% of the cache.

Chapter 13

KV Cache Quantization: Shrinking Each Number

All the approaches so far have tried to store fewer things in the KV cache. Quantization takes a different angle: store the same things, but use fewer bits per number. Think of it like image compression. You are not removing pixels; you are encoding each one more compactly. Standard KV cache uses 16-bit floats (FP16). That is two bytes per number. The quantization question is: how far can you push this before the model starts getting confused by its own rough memories? 8 bits? 4 bits? 2 bits?

This is harder than it sounds. Keys and Values are not arbitrary numbers. They carry structures that attention depends on. Distort the Key representations and the model starts attending to the wrong tokens. Distort the Values and the output gets garbled. KV quantization methods have to respect those structures instead of applying generic compression blindly.

What is Quantization?

Think about how you describe someone's height. With FP16 precision, you would say "175.38 cm," exact to a fraction of a millimeter. With INT8, you round to "175 cm." With INT4, maybe "tall" or "short" with a few buckets. With INT2, just four choices: "very short," "short," "tall," "very tall." Each step saves storage but loses detail. The question with KV cache quantization: can the model still reason accurately when its cached memories are stored as rough sketches instead of precise numbers?

Animation: KV Cache Quantization: FP16 → INT8 → INT4 → INT2

Illustrative scalar view of KV quantization: the values are rounded more aggressively as bit width drops. Real systems such as KIVI and TurboQuant use more sophisticated schemes than this simple bar demo.

KIVI: 2-Bit Quantization (ICML 2024)

KIVI is the paper I would point people to for why KV quantization is harder than it looks. Keys and Values have different outlier problems. Key matrices have specific channels (column indices) that produce very large values across all tokens. If you quantize naively, those channels dominate the scale and precision is lost everywhere else. Value matrices have the opposite issue: certain tokens produce spiking activations across all channels. KIVI handles this by using per-channel quantization for Keys and per-token quantization for Values, matching the compression axis to the actual outlier axis. The result is stable 2-bit quantization with near-lossless quality. Moving from 16 bits to 2 bits is an 8Γ— compression, and KIVI does it without fine-tuning.

Liu, Z., Yuan, J., Jin, H., et al. "KIVI: A Tuning-Free Asymmetric 2bit Quantization for KV Cache." ICML 2024. arXiv: 2402.02750
2.6×
Peak Memory Reduction
Including model weights
4×
Batch Size Increase
More users served simultaneously
2.35–3.47×
Throughput Improvement
On real LLM workloads

The results held across LLaMA, Falcon, and Mistral families with negligible quality degradation. No retraining, no fine-tuning. Just better quantization choices. The throughput improvements come largely from the reduced memory bandwidth, smaller cache means fewer bytes to move per decode step.

KVQuant: Toward 10 Million Context (NeurIPS 2024)

Hooper et al. pushed harder. Where KIVI focuses on the quantization axis and granularity, KVQuant layers in several additional tricks: applying quantization before RoPE (positional encoding) is added to keys, using non-uniform quantization bins, and handling outliers with a dense-and-sparse decomposition. Each addition is well-motivated in the paper, and the cumulative effect is significant.

Hooper, C., Kim, S., et al. "KVQuant: Towards 10 Million Context Length LLM Inference with KV Cache Quantization." NeurIPS 2024. arXiv: 2401.18079

The results enabled:

TurboQuant: Near-Optimal Compression (2025)

TurboQuant is the most theoretically grounded method in this space, and the data-oblivious claim is its most striking property. No calibration data, no model-specific tuning, no setup cost, apply it to any model at inference time. This works because TurboQuant doesn't try to learn from the model's activation statistics. Instead it applies a random rotation to spread information uniformly across vector coordinates, then runs near-optimal scalar quantizers on each coordinate independently. The theoretical backing for random rotation is solid (it's a randomized dimensionality technique with good guarantees), and the empirical results track the theory closely, which is rarer than you'd think in this area.

Google Research. "TurboQuant: Online Vector Quantization with Near-optimal Distortion Rate." arXiv: 2504.19874, 2025.

The method works in three steps:

  1. Randomly rotating input vectors to distribute information evenly across coordinates
  2. Applying optimal scalar quantizers to each coordinate independently
  3. Using a 1-bit Quantized JL transform on residuals for unbiased inner products
3.5 bits
Quality Neutral
Absolute zero quality loss
2.5 bits
Marginal Degradation
Nearly imperceptible quality loss
4–7×
Compression Ratio
vs FP16 baseline

Bonsai 8B + Turbo1Bit: 1-Bit Weights Meet KV Cache Compression

All the quantization methods above shrink the KV cache. But what happens when you also shrink the model weights to the extreme? On March 31, 2026, Caltech spinoff PrismML announced Bonsai 8B, a language model where every weight is represented as just one bit: either +1 or −1. An 8.2 billion parameter model that fits in 1.15 GB (compared to ~16 GB for a standard FP16 8B model), a 14× size reduction for the weights alone.

PrismML / Caltech. "Announcing 1-bit Bonsai: The First Commercially Viable 1-bit LLMs." prismml.com, March 31, 2026. Whitepaper: GitHub

There is a catch: 1-bit weights do NOT mean 1-bit KV cache. The weights (WK, WV, WQ, etc.) are 1-bit, but when they multiply against input activations, the resulting Key and Value vectors are still full-precision floating point numbers. Bonsai's weights are tiny, but the KV cache during inference remains FP16-sized and grows linearly with context length. The memory wall is still there.

This is where Turbo1Bit comes in: an open-source project that stacks TurboQuant-style KV cache quantization on top of Bonsai's 1-bit weights.

Turbo1Bit. "Combining 1-bit LLM weights (Bonsai) with TurboQuant KV cache compression." GitHub, 2026.
Config (Bonsai 8B @ 65K context) Model Weights KV Cache Total Memory Reduction
Standard FP16 8B model ~16 GB ~8 GB ~24 GB 1× baseline
Bonsai 1-bit (no KV compression) 1.15 GB ~8 GB (FP16) 10.6 GB 2.3×
Bonsai 1-bit + Turbo1Bit (Q4_0 KV) 1.15 GB ~2 GB 4.0 GB 6×

Turbo1Bit's KV cache compression findings for 1-bit models specifically:

KV Quantization Perplexity (WikiText-2) vs Baseline Memory Saving
FP16 (baseline)25.51N/A1×
Q8_0 (8-bit)25.49−0.1%1.75×
Q5_0 (5-bit)25.87+1.4%2.5×
Q4_0 (4-bit)26.82+5.1%2.91×

The 1-Bit Insight: KV Cache Becomes the Dominant Cost

Bonsai shows a clear reality about 1-bit models. When you compress model weights to 1-bit (1.15 GB for an 8B model), the KV cache becomes the largest part of memory usage. At 65K context with FP16 KV cache, the cache is 7× larger than the model itself. This flips the usual assumption that model weights dominate memory. For 1-bit models, KV cache optimization is required. This is why combining Bonsai with TurboQuant-style KV compression has such a large effect: total memory drops from 10.6 GB to 4 GB.

Expert Take: 1-Bit Only Matters If the KV Cache Falls Too

Bonsai 8B cleanly separates weight compression from runtime memory. The weights are tiny at about 1.1 GB, but the local benchmark logs in PrismML/Bonsai-demo still show 4,608 MiB of FP16 KV cache at 32K context. The bottleneck has not gone away; it has simply moved from the model file to the cache.

The more interesting deployment story is Bonsai 8B plus TurboQuant-style Q4_0 KV compression. In the same local logs, the KV cache falls from 4,608 MiB to 1,296 MiB at 32K, and total resident memory drops from 6,011 MiB to 2,699 MiB. At 60K context, the compressed run still lands at about 3,782 MiB total. That is the point where 1-bit weights stop being a neat packaging trick and start looking like a serious long-context systems design.

Proof points: the local benchmark artifacts in PrismML/Bonsai-demo/memory_benchmark_results.json and PrismML/Bonsai-demo/turboquant_kv_results.json record Bonsai-8B at 32K with 4,608 MiB FP16 KV vs 1,296 MiB Q4 KV, and total resident memory of 6,011 MiB vs 2,699 MiB. The companion Bonsai materials identify the 8B GGUF weights at roughly 1,099 MiB. Public references: Bonsai-demo, Turbo1Bit GitHub.
1.15 GB
Bonsai 8B Model Size
vs ~16 GB for FP16 8B model
70.5
Avg Benchmark Score
Beats LLaMA 3.1 8B (67.1)
44 tok/s
On iPhone 17 Pro Max
Full 8B model on a phone

Quantization Comparison Overview

Method Year Bits (K/V) Memory Reduction Needs Calibration? Quality Impact
FP16 (Baseline) N/A 16 / 16 1× N/A Baseline
INT8 Quantization Various 8 / 8 2× Minimal Negligible
KIVI 2024 2 / 2 ~8× No (tuning-free) Near-zero loss
KVQuant 2024 3 / 3 ~5× Minimal <0.1 perplexity
TurboQuant 2025 2.5–3.5 4–7× No (data-oblivious) Near-zero loss
Chapter 14

FlashAttention: Using Hardware Better

FlashAttention is a slightly different kind of topic for this survey. It does not shrink the KV cache. It does not change how many KV heads you have or what precision you use. I include it because it explains why memory movement matters so much in long-context inference.

The core observation from Tri Dao's 2022 paper is that standard attention implementations move data between GPU HBM (large, slower) and SRAM (small, fast) more often than needed. FlashAttention restructures the computation into SRAM-sized tiles, reducing that movement. The algorithm is mathematically identical. The output is the same. The implementation is 2–4× faster and uses memory proportional to sequence length rather than its square.

FlashAttention (NeurIPS 2022)

Standard attention computes the full n×n score matrix and holds it in HBM while doing later operations. For a 32K-token sequence with 128 heads, that matrix is enormous. Every operation has to load data from HBM into the GPU cores, do work, and write results back. FlashAttention breaks the attention matrix into chunks small enough to fit in on-chip SRAM, finishes the operations for each chunk while it is in fast memory, and never materializes the full matrix in HBM. The output is the same, but the memory access pattern is different.

Dao, T., Fu, D.Y., Ermon, S., et al. "FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness." NeurIPS 2022. arXiv: 2205.14135

Key result: 2–4× speedup over optimized baselines, with linear memory usage instead of quadratic. This means the n×n attention matrix is never fully materialized in GPU memory.

FlashAttention-2 (2023)

FlashAttention-2 is mostly an engineering improvement. Dao revisited work partitioning between GPU thread blocks, reduced non-matmul operations, and improved handling of varying sequence lengths. None of these changes affect the algorithm. They push GPU utilization from around 35% to 72%, which matters a lot in deployment.

Dao, T. "FlashAttention-2: Faster Attention with Better Parallelism and Work Partitioning." arXiv: 2307.08691, 2023.
1.7–3×
Faster than FlashAttention-1
3–10×
Faster than Standard Attention
72%
Model FLOP Utilization
225 TFLOPs/s on A100

FlashAttention is now common in vLLM, Hugging Face Transformers, PyTorch, and many other stacks. Its link to KV cache is indirect but real: when attention is computed more efficiently, the per-step cost of attending over a long KV cache is lower. That makes the other memory reductions pay off more.

Chapter 15

Model-by-Model Comparison: How the Pieces Fit

After the methods, the fastest way to build intuition is to look at real configs. The tables below use published configs and model cards where available. When a row needs an assumption because of mixed head dimensions, shared KV, or sliding-window layers, I flag it rather than hiding the uncertainty.

A pattern appears quickly. LLaMA-2 7B, with pure MHA, sits at 512 KB per token. Mistral 7B, with GQA plus a sliding window, drops to 128 KB before any KV quantization. MLA cuts far deeper. Qwen3.5-9B gets to 32 KB per token by mixing attention with DeltaNet-style recurrent layers. The table is dense, but the pattern is simple: modern models are not relying on one trick. They are stacking several.

Part A: Legacy & Foundational Models (2023–2024)

Model Year Params Attention Q Heads KV Heads Context KV/Token (FP16)
LLaMA-2 7B 2023 7B MHA 32 32 4K 512 KB
LLaMA-2 70B 2023 70B GQA 64 8 4K 320 KB
Mistral 7B 2023 7B GQA+SWA 32 8 32K (4K window) 128 KB
Gemma 1 7B 2024 7B MHA 16 16 8K 448 KB
LLaMA-3.1 8B 2024 8B GQA 32 8 128K 128 KB
LLaMA-3.1 405B 2024 405B GQA 128 8 128K 504 KB
Qwen-2 72B 2024 72B GQA 64 8 128K 320 KB
Gemma 2 27B 2024 27B GQA+LG 32 16 8K (4K local) Reduced (~50%)
Phi-4 14B 2024 14B GQA 24 8 16K 128 KB
DeepSeek-V2 2024 236B (21B active) MLA 128 Latent (dc=512) 128K ~Eq. 2.25 GQA groups
DeepSeek-V3 2024 671B (37B active) MLA+MoE 128 Latent (dc=512) 128K 70 KB

Part B: Frontier Models (2025–2026)

Model Year Params Attention Q Heads KV Heads Context Key Innovation
Gemma 3 27B 2025 27B GQA+LG 32 Varies 128K (1K local) 5:1 local-global ratio; only 1/6 layers full-attention
Qwen3 0.6B 2025 0.6B GQA 16 8 32K QK-Norm; no QKV-bias; tied embeddings
Qwen3 4B 2025 4B GQA 32 8 32K 36 layers; 4:1 Q-to-KV ratio
Qwen3 8B 2025 8.2B GQA 32 8 128K Thinking mode (hybrid reasoning)
Qwen3 32B 2025 32.8B GQA 64 8 128K 64 layers; 8:1 Q-to-KV ratio
Qwen3 235B-A22B 2025 235B (22B active) GQA+MoE 64 4 128K 128 experts × 8 active; 16:1 Q-to-KV
Qwen3.5 4B 2025 4B GQA N/A N/A 262K Latest Qwen iteration; context length should be checked against the specific model config.
LLaMA 4 Scout 2025 109B (17B active) LongCtx+MoE N/A N/A 10M (!) Official model card lists a 10M-token context window; detailed KV internals are not broken out in this survey.
LLaMA 4 Maverick 2025 400B (17B active) LongCtx+MoE N/A N/A 1M Long-context multimodal MoE model; detailed KV internals not broken out here.
Kimi K2 2025 ~1T (32B active) MLA+MoE 64 Latent (MLA) 128K 384 experts (8 active); MuonClip optimizer; 15.5T tokens
Gemma 4 E2B 2026 ~5.1B (2.3B eff.) GQA+LG 8 1 128K PLE; KV sharing across 20/35 layers (num_kv_shared_layers=20)
Gemma 4 E4B 2026 ~8B (4B eff.) GQA+LG 8 2 128K PLE; 42 layers; head_dim 256/512; sliding_window=512; num_kv_shared_layers=18
Gemma 4 26B-A4B 2026 26B (3.8B active) GQA+LG+MoE N/A 8 local / 2 global 256K 128 experts (8 active) + 3× shared expert
Bonsai 8B 2026 8.2B (1-bit weights!) GQA+1-bit N/A N/A 128K 1.15 GB model; KV cache is FP16 (weights 1-bit, cache is not). +Turbo1Bit for Q4 KV.
Gemma 4 31B 2026 31B (Dense) GQA+LG N/A 16 local / 4 global 256K 5:1 local-global; p-RoPE; attention_k_eq_v=true; 1,024-token local window
Qwen Team. "Qwen3 Technical Report." arXiv: 2505.09388, 2025. Qwen3.5 architecture details in this section are checked against the official Qwen3.5-9B config.json.
Kimi Team, Moonshot AI. "Kimi K2: Open Agentic Intelligence." arXiv: 2507.20534, 2025; architecture fields checked against Kimi-K2-Instruct config.json.
Gemma Team, Google. "Gemma: Open Models Based on Gemini Research and Technology." arXiv: 2403.08295, 2024.
Qwen Team. "Qwen2 Technical Report." arXiv: 2407.10671, 2024.
Microsoft. "Phi-4 Technical Report." arXiv: 2412.08905, 2024.

Exact KV Cache Memory Requirements, Calculated from config.json

Below are KV cache memory calculations derived from published config.json files where available. Rows marked with * are estimates due to hybrid architectures (mixed head dimensions, KV sharing, or sliding windows) where an exact single number is not straightforward.

Model Layers KV Heads Head Dim KV/Token @ 1K Tokens @ 128K Tokens Calculation Notes
LLaMA-1 65B
MHA
80 64 128 2,560 KB 2.5 GB 320 GB 2×80×64×128×2 = 2,621,440 B. Pure MHA: every head has its own K+V. Source: HF config.
Falcon-7B
MQA
32 1 64 8 KB 8 MB 1.0 GB 2×32×1×64×2 = 8,192 B. All 71 query heads share 1 K + 1 V (multi_query=true). Source: HF config.
Mistral 7B
GQA+SWA
32 8 128 128 KB 128 MB 512 MB* 2×32×8×128×2 = 131,072 B. *Sliding window caps cache at 4K tokens, so 128K nominal context still stores about 4K tokens of KV per sequence.
Qwen3 235B
GQA-4+MoE
94 4 128 189 KB 189 MB 24 GB 2×94×4×128×2 = 193,536 B. Only 4 KV heads for 64 query heads (16:1 ratio).
DeepSeek-V3
MLA+MoE
61 Latent (dc=512) 576* 69 KB 69 MB 8.6 GB 61×(512+64)×2 = 70,272 B. Stores compressed latent, not raw K+V. *576 = dc+dR.
Gemma 4 31B
GQA+LG
60 (50 local + 10 global) 16 local / 4 global 256 / 512 Mixed ~0.43 GB ~5.4 GB† †50 sliding layers (16 local KV, d=256, capped at 1,024 tok) + 10 global layers (4 global KV, d=512, full ctx), with attention_k_eq_v=true. Approximate figures assume K=V is stored once. Source: official config.json.
Qwen3.5 9B
GQA+DeltaNet
32 (8 attn) 4 256 32 KB 32 MB 4 GB 2×8×4×256×2 = 32,768 B. Only 8/32 layers use attention; 24 use DeltaNet (no KV cache).
Qwen3.5-9B, Gemma 4 E4B, Gemma 4 31B, and Kimi K2 parameters are sourced from official Hugging Face config/model pages (Qwen3.5-9B, Gemma 4 E4B, Gemma 4 31B, Kimi K2). LLaMA 4 Scout/Maverick context-window claims are sourced from Meta's official model card; detailed attention internals are not treated as independently verified here.

The Standout: Qwen3.5 9B Uses Only 32 KB Per Token

Qwen3.5-9B gets a low KV cache through a hybrid DeltaNet + Attention architecture. Out of 32 layers, only 8 use traditional attention, which requires KV cache. The remaining 24 use Gated DeltaNet, a form of linear attention that maintains a fixed-size recurrent state instead of a growing cache. This means 75% of the model's layers add zero KV cache overhead regardless of context length. Combined with just 4 KV heads and head_dim=256, the result is 32 KB per token, 16× less than the LLaMA-2 7B baseline of similar parameter count. At 128K context, that is 4 GB for the entire KV cache.

Gemma 4 E4B: Aggressive KV Sharing Across Layers

Gemma 4 E4B uses just 2 KV heads and shares KV cache across 18 of its 42 layers (num_kv_shared_layers=18). This means only 24 layers maintain unique KV caches. Sliding window layers are capped at 512 tokens regardless of context length. The result: a 4B-effective model that can handle 128K context with roughly 2 GB of KV cache, putting it in the mobile/edge-friendly range.

Expert Take: Gemma 4 E4B Is What Edge-Friendly Long Context Looks Like

Gemma 4 E4B is compelling because the base architecture already puts 128K context in roughly the 2 GB KV-cache range. That means the model is not relying on a heroic post-training trick to become usable on constrained hardware; it gets there by design through a very low KV-head count, cross-layer sharing, and local-global attention.

In our local turboquant-llamacpp measurements on Gemma 4 E4B running on an M2 Pro, TurboQuant-style 4-bit KV reduced cache memory from 104 MiB to 29 MiB at 4K, 296 MiB to 83 MiB at 16K, and 552 MiB to 155 MiB at 32K, staying near a 3.56× reduction throughout. If that ratio holds at 128K, a ~2.1 GB FP16 KV budget lands around 600 MiB, which is why Gemma-class models are appealing for on-device long-context inference.

Proof points: Google's official Gemma 4 E4B model card lists 42 layers, a 512-token sliding window, and 128K context. The local TurboQuant measurements cited here come from the public turboquant-llamacpp README: 104 MiB → 29 MiB (4K), 296 MiB → 83 MiB (16K), and 552 MiB → 155 MiB (32K) on an M2 Pro. Sources: Gemma 4 E4B model card, turboquant-llamacpp README.

Kimi K2: Trillion-Scale Parameters, DeepSeek-Style MLA Cache

Despite scaling from 671B (DeepSeek-V3) to roughly 1T parameters (Kimi K2), the KV cache remains in the same ~70 KB per token range. Both use MLA with kv_lora_rank=512 and qk_rope_head_dim=64 across 61 layers. Kimi K2's extra scale comes from more experts and expert capacity rather than larger cached attention state, showing how MLA helps decouple KV cost from total MoE parameter count.

Patterns in the Table

Three KV Cache Patterns Keep Reappearing

1. GQA-style sharing (LLaMA, Qwen, Gemma, Phi, Mistral): many model families use 4–8 KV heads instead of giving every query head its own cache. Qwen3 235B pushes this to 4 KV heads for 64 query heads.

2. Latent KV compression (DeepSeek, Kimi K2): MLA stores compact latent state instead of raw K and V. Kimi K2 shows this idea can scale to roughly 1T total parameters.

3. Hybrid attention layouts (LLaMA 4, Gemma 3/4): these models combine short-range local layers with global or sparse layers. The goal is not to remember every token with the same resolution everywhere.

KV Cache Memory Per Token Comparison (FP16)

Memory Reduction vs. FP16 MHA Baseline (Lower is Better)

Visual Summary: How Each Technique Reduces KV Cache

The Practical Pattern: Stack the Boring Wins

The largest gains usually come from combining techniques rather than waiting for one perfect method. A modern deployment might use:

GQA (4–8×) + Local-Global attention (3–5×) + TurboQuant (4–7×) + PagedAttention (eliminates waste) + SnapKV eviction (further reduction)

These reductions can compound. An 8 × 4 × 5 stack is a 160× theoretical reduction from a naive FP16 MHA baseline. Real deployments are messier than multiplication on a slide, but the direction is clear: newer systems use more than one lever.

Chapter 16

DFlash: Drafting More Than One Token at a Time

So far, most of the story has been about making the cache smaller. DFlash comes from a neighboring problem: even with a smaller cache, generation still happens one token at a time unless the serving system finds a way around it. Speculative decoding is one such workaround. In February 2026, Z Lab published DFlash, which changes the drafter itself: instead of drafting autoregressively, it drafts a block with diffusion.

Z Lab. "DFlash: Block Diffusion for Flash Speculative Decoding." arXiv preprint, February 2026. arXiv:2602.06036

The Speculative Decoding Bottleneck

Standard autoregressive decoding is narrow by design: one forward pass, one new token. Even after the KV cache is optimized, each decode step still has to read the relevant cache from HBM, compute attention, and produce a single output token. The GPU often has plenty of compute left unused; the step is waiting on memory.

Speculative decoding uses a smaller draft model to propose several candidate tokens, then asks the larger target model to verify them in one pass. If k candidates are accepted, one expensive target-model step yields k output tokens. The catch is that most draft models are also autoregressive. They still draft token by token. The bottleneck moves to a cheaper model, but it remains serial.

DFlash replaces that serial drafter with a block diffusion model. The draft block is generated together, not one token at a time. That single change makes the speculative path much wider.

How DFlash Works

Step 1: Context Feature Extraction

After prefill or verification, DFlash reads hidden-state features from the target model. It does not rely only on the final layer. It samples across depth, so early syntactic signals and later semantic signals both reach the draft model. A lightweight projection fuses those features.

Step 2: KV Cache Injection into the Draft Model

This is the heart of the method. The fused target-model features are injected into the Key/Value projections of every draft-model layer and stored in the draft model's own KV cache. The drafter is not handed a one-time summary and left to drift. It carries target-model context throughout the diffusion process.

Target Model Prefill
→
Extract Hidden States (all depths)
→
Fuse & Project Features
→
Inject into Draft KV Cache
→
Block Diffusion Draft (1 pass)
→
Target Model Verification (1 pass)

Step 3: Parallel Verification

The target model then verifies the proposed block in one pass. Matching tokens are accepted. At the first mismatch, the target model corrects the output and the remaining draft tokens are discarded. The output distribution stays the same as the target model alone; only the route to that output changes.

Why KV Cache Injection Matters for Acceptance Rate

Speculative decoding lives or dies by acceptance rate. If the target model rejects too many draft tokens, the speedup evaporates. DFlash improves that odds by keeping target-model context inside every draft layer's KV cache, so the draft block stays closer to what the target model would have written.

Performance Results

Method Drafting Strategy Speedup vs Autoregressive vs EAGLE-3
Autoregressive baseline 1 token per pass 1× (baseline) N/A
EAGLE-3 (SOTA prior) Autoregressive draft tree ~2.5× 1×
DFlash Block diffusion (1 pass) 6×+ 2.5×

Interactive: compare autoregressive, standard speculative decoding, and DFlash block diffusion side-by-side

The paper reports over 6× lossless acceleration across a range of models and benchmarks. "Lossless" has a precise meaning here: with correct rejection sampling, speculative decoding preserves the target model's output distribution. The model does not say something different; it reaches the same distribution with fewer expensive target-model passes.

Relationship to KV Cache Efficiency

DFlash sits beside KV-cache architecture work rather than replacing it:

Architectural (MLA, GQA, HCA)
Reduce KV cache size
Less memory per token → fit longer contexts, serve more users per GPU, reduce memory-bandwidth pressure during each decode step.
DFlash (Block Diffusion)
Reduce decode steps
More tokens per target-model pass → amortize the fixed cost of loading the KV cache across more output tokens, directly improving tokens-per-second.

When the two are combined, the gains can compound. A smaller KV cache makes target-model verification cheaper; DFlash reduces how often the target model has to run. One shrinks the memory bill per step. The other reduces the number of expensive steps.

Why DFlash Matters

The reported 6× speedup is only part of the point. The paper also suggests that speculative decoding was limited by the shape of the drafter as well as its size. If the drafter can generate a whole block at once, the limit changes.

Chapter 17

DeepSeek V4: Making Million-Token KV Practical

In April 2026, vLLM published implementation notes for DeepSeek-V4-Pro and DeepSeek-V4-Flash. The attention design is built for contexts up to one million tokens. The number that matters for this article is the cache: vLLM reports about 9.62 GiB of BF16 KV cache for one 1M-token V4-Pro sequence, compared with its 83.9 GiB estimate for a V3.2-style stack.

V4 is not simply "use GQA and quantize harder." It combines shared K=V cache, a short sliding window for local information, and two compressed long-range attention modes: c4a and c128a. In this article, CSA/HCA is shorthand for that split between moderately compressed sparse attention and heavily compressed long-range attention.

Source: vLLM. "DeepSeek V4 in vLLM: Efficient Long-context Attention," April 2026. The implementation write-up reports 1M-token support, c4a/c128a compression, a 128-token sliding window, and 9.62 GiB BF16 KV cache per 1M-token V4-Pro sequence. Model cards: DeepSeek-V4-Pro, DeepSeek-V4-Flash. vLLM blog: vllm.ai/blog/deepseek-v4.

Two Model Variants

V4-Pro
1.6T total / 49B active
vLLM reports 1M-token context support and about 9.62 GiB BF16 KV cache per 1M-token sequence.
V4-Flash
~285B total / 13B active
vLLM describes Flash as the smaller V4 variant with 1M-token context support.

The Hybrid Attention Architecture

Both V4 variants use a Hybrid Attention design. Instead of forcing every layer to remember context in the same way, V4 gives different layers different memory budgets:

1. Compressed Sparse Attention (CSA): Precision for Critical Layers

CSA is used where fine-grained token interactions matter most. It works in two moves:

Full KV Sequence
→
Dynamic Sequence Compression
→
Compressed KV Cache
→
DeepSeek Sparse Attention (DSA)
→
Sparse Attention Output

First, KV entries are compressed. Then DeepSeek Sparse Attention (DSA) computes attention mainly where the token relationships look important. Precision is kept where it matters; the rest of the matrix becomes cheaper.

2. Heavily Compressed Attention (HCA): Aggressive Compression for Supporting Layers

HCA is used for layers that need broad context more than exact token identity. Instead of keeping individual compressed entries, HCA consolidates multiple consecutive tokens into a shared KV entry. It is closer to summarizing a paragraph into one sentence: detail is lost, but the broad signal remains.

CSA vs HCA: When to Use Which

CSA layers keep more token identity, useful where precise relationships matter.

HCA layers collapse groups of tokens, useful where broad pattern signal is enough.

The CSA/HCA mix changes by model variant. V4-Flash leans harder on HCA to reach its smaller KV footprint.

Additional Architectural Innovation: Manifold-Constrained Hyper-Connections

DeepSeek V4 also replaces the standard residual path with Manifold-Constrained Hyper-Connections (mHC). A normal residual connection adds x + f(x). mHC constrains that path through a learned manifold, which helps stabilize signal flow when the network alternates between layers with very different attention behavior.

Inference Efficiency: By the Numbers

Metric at 1M-token context DeepSeek-V3.2 (baseline) V4-Pro V4-Flash
Single-token inference FLOPs 100% (baseline) 27% 10%
KV cache memory 100% (baseline) 10% 7%
KV memory reduction vs V3.2 N/A 9.5–10× 13.7–14×
Total parameters 671B 1.6T 284B
Active parameters per token 37B 49B 13B
Context window 128K 1M 1M

Interactive: watch CSA and HCA layers shape the KV cache footprint across a 12-layer model stack

Inference Implementation: vLLM Integration

The vLLM work is important because the architecture is only half the story. A heterogeneous cache layout has to be served efficiently. Their implementation reports about 9.62 GiB of BF16 KV cache per 1M-token V4-Pro sequence before additional FP8/FP4 cache optimizations.

Shared K=V Cache
One cached KV tensor
DeepSeek V4 uses a shared K=V multi-query-style cache, reducing stored attention state before compression is applied.
c4a + c128a Layers
Heterogeneous compression
Some layers compress KV by roughly 4×, while heavily compressed layers use roughly 128× compression.
PagedAttention Packing
One logical block size
vLLM maps different compression rates into a consistent block layout so prefix caching, disaggregation, and scheduling still work.
Kernel Fusion + Streams
Lower serving overhead
The implementation uses fused kernels and multi-stream execution to keep the GPU busy despite the more complex attention path.

What V4 Shows

Million-token context is not won by brute-force memory alone. V4 makes the cache practical by letting different layers remember at different resolutions: local windows for nearby detail, CSA for precise long-range interactions, and HCA for broad compressed context. The full V4-Pro weights still require multi-GPU serving; the single-card point applies to KV-cache capacity, not to hosting the whole model.

Chapter 18

Kimi K2.5: How Agent Workloads Change Memory

Everything up to this point assumes the model gets one prompt and writes one response. Agents work differently. An agent may get a task like "research competitors and write a market analysis" and then run for hours. It searches the web, reads documents, calls code tools, checks outputs, revises its plan, and searches again. Each tool call can return 5,000–20,000 tokens. After 100 tool calls, the context can contain millions of tokens, many of them stale. At that point, KV cache is no longer only an efficiency issue. It becomes a session-management issue.

Moonshot AI's Kimi K2.5 paper (February 2026) is worth reading because it describes both the system and the failures they hit while running long agent sessions. Those failure modes explain why the design looks the way it does.

Kimi Team, Moonshot AI. "Kimi K2.5: Visual Agentic Intelligence." arXiv: 2602.02276, February 2026.

The Problem: Why Agents Break Traditional KV Cache

In a standard chatbot conversation, the context grows slowly: one user message, one model response, and so on. The KV cache grows predictably and stays within the context window.

An agent is nothing like this. Consider an agent researching a topic:

User Task
→
Plan Steps
→
Call Tool #1
→
Read Result (10K tokens)
→
Call Tool #2
→
Read Result (8K tokens)
→
... ×200 more calls

After 200 tool calls, the context might contain millions of tokens, most of which are tool outputs the model only needed briefly. The KV cache grows out of control, latency spikes, and eventually the model hits its context limit.

Kimi K2.5's Three-Part Solution

1. Agent Swarm: Parallel Decomposition

Instead of one agent working through a problem step by step, which creates one large and growing KV cache, K2.5 introduces Agent Swarm. A central orchestrator breaks a complex task into independent sub-problems, then starts multiple sub-agents to work on them at the same time.

How Agent Swarm Manages KV Cache

Each sub-agent runs in its own isolated context window with its own KV cache. Instead of one 500K-token context, you get ten 50K-token contexts running in parallel. When a sub-agent finishes, only its final output (a few hundred tokens) gets sent back to the orchestrator, not its full reasoning chain or tool outputs. The sub-agent's KV cache is then freed entirely.

This applies a PagedAttention-like idea at the agent level: allocate memory where needed, free it when done, and avoid letting one context grow without a bound.

The result: 4.5× latency reduction over single-agent baselines on complex web search tasks, and a 17.8% accuracy improvement on BrowseComp (60.6% → 78.4%).

2. PARL: Teaching the Model When to Parallelize

The orchestrator doesn't use hand-coded rules to decide when to spawn sub-agents. Instead, Moonshot trained it with a custom reinforcement learning method called Parallel-Agent RL (PARL). The reward function has three components:

PARL Reward Function rPARL = λ1 · rparallel + λ2 · rfinish + rperf(x, y)
rparallel
Instantiation Reward
Encourages the model to actually spawn parallel agents instead of doing everything sequentially ("serial collapse")
rfinish
Completion Reward
Prevents spawning useless sub-agents that don't finish their tasks ("spurious parallelism")
rperf
Task Performance
The final answer quality: did the agent actually solve the user's problem?

A key design choice: sub-agents are frozen, so their weights do not update during PARL training. Only the orchestrator learns. This avoids a hard credit-assignment problem in multi-agent RL, where it is unclear which agent caused a good outcome.

3. Toggle: Budget-Aware Reasoning

Kimi K2.5 uses a training technique called Toggle that alternates between two modes:

Budget-Limited Phase
Forces the model to reason concisely
Reduces output tokens by 25–30%. The model learns to skip unnecessary reasoning steps.
Standard Scaling Phase
Allows extended reasoning chains
For hard problems, the model can use 7K–36K reasoning tokens before acting.

For KV cache, reasoning tokens are expensive. A thinking model like K2.5 might generate 36,000 internal reasoning tokens before producing a 200-token answer. Those 36K tokens all live in the KV cache. Toggle teaches the model to spend fewer tokens on easy sub-tasks and save the larger budget for harder ones. At ~70 KB per token with MLA, that is the difference between 490 MB and 2.5 GB of KV cache just for the thinking phase.

Discard-All Context Management

For very long agent sessions, K2.5 uses a strategy called "Discard-all". After each major reasoning phase, the model discards the full context, including tool outputs, and starts fresh with only the accumulated conclusions. This resets the KV cache periodically instead of letting it grow to the context limit.

On the BrowseComp benchmark, using Discard-all boosted accuracy from 60.6% to 74.9%, beating GPT-5.2's reported 65.8%, Claude Opus 4.5 (37.0%), and Gemini 3 Pro (37.8%). The useful lesson is that throwing away context can help when old tool outputs add more noise than value.

The KV Cache Implications

Aspect Standard Chat Mode Kimi K2.5 Agent Mode
Context growth Linear, predictable Bursty (tool outputs spike it), then reset
Max KV cache per session Context window × 70 KB Bounded by sub-agent window (~50K tokens)
Parallelism One cache per user Multiple caches (orchestrator + N sub-agents)
Cache lifetime Entire conversation Sub-agent caches freed after each sub-task
Reasoning overhead Minimal (short CoT) 7K–36K reasoning tokens per step (Toggle-managed)
Tool calls per session 0–5 typically Hundreds of tool calls across parallel sub-agents (paper reports up to 100 tool calls per sub-agent in BrowseComp)
Context resets None Periodic (Discard-all after each phase)

Why This Changes KV Cache

Kimi K2.5 shows that as AI moves from chatbots to agents, the KV cache problem shifts from memory scaling into dynamic memory management. Compression still matters, but the system also has to decide which contexts to keep alive, when to reset them, and how to distribute work across parallel cache instances. Agent Swarm is close to PagedAttention at the agent level: instead of paging KV blocks within one context, it spreads whole contexts across multiple agents.

Chapter 19

Linear Attention & SSMs: The O(1) KV Cache Alternative

Every chapter so far has assumed the cache exists and asked how to make it smaller. This chapter is different. What if you got rid of the cache altogether?

That's the premise behind State Space Models and linear attention. Instead of storing a growing list of Key and Value vectors for every previous token, these architectures compress the entire history into a single fixed-size state, and update it as each new token arrives. No cache that grows with context length. Constant memory at inference time, regardless of how long the sequence gets.

The Trade-off in Plain Terms

Standard attention keeps a full diary, every entry preserved, any page retrievable on demand. An SSM keeps a rolling summary that gets updated after each sentence. The summary can't grow larger than a fixed size, but it can lose fine details from early in the book by the time you reach the end. Whether that loss matters depends entirely on what you're trying to do.

How Standard Attention Scales

For context: standard self-attention is O(nΒ²) in compute and O(n) in memory per layer. At 1 million tokens, the KV cache is enormous, and every new decode step requires loading the entire thing from HBM. SSMs break that scaling entirely, but they break it by accepting lossy compression of the past, which Transformers never do.

State Space Models (Mamba, RWKV, RetNet)

Mamba (Selective State Spaces)

Mamba (Gu & Dao, 2023) is probably the most-discussed SSM in the LLM space. The key word in its full name, selective state space model, is "selective." Earlier SSMs like S4 had fixed transition matrices. Mamba learns to select which information to retain and which to discard based on the current input, which makes it much more expressive. The hidden state is fixed-size regardless of sequence length; what changes is how that state gets updated. Hardware-efficient scan operations make this fast on GPU without needing custom attention kernels.

Gu, A. & Dao, T. "Mamba: Linear-Time Sequence Modeling with Selective State Spaces." arXiv, 2023. arXiv:2312.00752

RWKV (Receptance Weighted Key Value)

RWKV is interesting for a different reason. It's been developed almost entirely as an open, community-driven effort, unlike most of the models in this survey. Technically it reformulates attention as a linear recurrence, the running "KV cache" collapses to a single exponentially-weighted state. O(1) memory at inference. The cost is that old information decays; you can't retrieve something from 10,000 steps ago with the same fidelity as something from 100 steps ago. For many practical tasks that's fine. For precise document lookup, it's not.

Peng, B. et al. "RWKV: Reinventing RNNs for the Transformer Era." arXiv, 2023. arXiv:2305.13048

RetNet (Retention Networks, Microsoft)

RetNet is clever in a specific way: it offers parallel training (O(nΒ²), like a Transformer) and recurrent inference (O(1) memory, O(1) per step) from the same underlying formulation. Training is efficient on GPU because you can parallelize. Inference is efficient because it's recurrent. Microsoft scaled this to 65B parameters with results they describe as competitive, though independent evaluation at that scale is limited enough that I'd hold that claim loosely.

Sun, Y. et al. "Retentive Network: A Successor to Transformer for Large Language Models." arXiv, 2023. arXiv:2307.08621

Liquid Foundation Models (LFM)

Liquid AI's LFMs are worth mentioning as a different flavor of the same idea. Where Mamba and RWKV use discrete recurrence, LFMs are built on Liquid Time-Constant networks, continuous-time dynamical systems where each neuron has a learnable time constant that controls how fast it forgets. The key difference from standard SSMs is that these time constants adapt per input, rather than being fixed structure. This makes LFMs more expressive for data with irregular timing, audio, sensor streams, time series, though less clearly better for straightforward text generation.

LFM Key Properties

  • O(1) inference memory: hidden state size is fixed regardless of context
  • Input-adaptive forgetting: LTC time constants change per token, unlike fixed SSM matrices
  • Strong on structured data: time-series, audio, code with regular patterns
  • Weaker on rare long-range dependencies: if the answer requires exact recall of token 1 at token 100,000, fixed state struggles

Head-to-Head: Transformer KV Cache vs SSM Hidden State

PropertyTransformer (MHA/GQA/MLA)SSM / LFM
Memory at n tokensO(n), grows foreverO(1), fixed state size
Exact recall of token kβœ… Perfect (it's in the cache)❌ Lossy (compressed into state)
Parallelism during trainingβœ… Full parallel⚠️ Parallel via scan (slower)
Inference memory costScales with context lengthConstant regardless of length
Hardware efficiencyFlashAttention helpsCustom CUDA kernels needed
Long-range reasoningβœ… Exact attention to any token❌ Degrades at very long ranges
Best use caseGeneral reasoning, chat, codeStreaming, audio, long structured docs

Hybrid Models: Getting Practical

The pure-SSM vs pure-Transformer debate has been largely settled by practitioners: you want both. Attention for precise recall. SSM layers for cheap context compression. Several architectures now alternate between them:

The Core Trade-off

SSMs give you constant memory in exchange for lossy recall. Whether that's acceptable depends entirely on the task. For general chat and code generation, losing some distant context rarely hurts. For tasks that require pulling a specific fact from 50,000 tokens ago, precise document retrieval, long-term codebase reasoning, you need the cache. Hybrid models are a practical acknowledgment that most workloads need both, in different proportions at different layers.

Chapter 20

Prefix Caching & RadixAttention: Reuse Across Requests

All the optimization techniques so far are about a single request, one user, one conversation, one growing KV cache. But production LLM services don't look like that. You're serving thousands of users at once, and many of them start with the exact same system prompt, the exact same few-shot examples, maybe even the same retrieved documents. Without prefix caching, you're recomputing those KV vectors from scratch for every request. You're literally doing the same work thousands of times over.

I find this one of the most under-discussed efficiency wins in the whole space, maybe because it doesn't require any model changes. It's purely a serving-layer optimization. But the math is stark. A 2,000-token system prompt served to 1,000 users per second means 2 billion redundant KV computations per second. Cache that prefix once and you've eliminated all of them.

Think of It This Way

Every waiter in a restaurant reads the full 10-page menu from scratch before each table, even though it hasn't changed since morning. Prefix caching is printing the menu once and handing each waiter a copy. First table pays the full read cost. Every table after that is free.

What Counts as a Prefix?

Any text that appears at the start of multiple requests. The obvious cases: system prompts, few-shot examples, long documents sent with every question, RAG chunks that keep appearing in similar queries. The less obvious case: multi-turn conversation history. Once a user has had 10 turns with your assistant, the first 9 turns are a shared prefix for every subsequent request. Cache those and you're not re-reading the whole conversation history on every new message.

Automatic Prefix Caching (APC)

APC in vLLM hashes incoming token sequences, checks for prefix matches in a stored KV block pool, and if a match exists, reattaches those cached blocks to the new request without recomputing them. The prefill phase for those matched tokens is skipped entirely. It's completely transparent to the model, the output is identical to a full recompute.

Request A: [SysPrompt + "What is 2+2?"]
→
Compute KV for SysPrompt β†’ store in cache
→
Generate answer
Request B: [SysPrompt + "What is 3+3?"]
→
Cache HIT: SysPrompt KV already computed
→
Generate answer (prefill cost: 0)

RadixAttention (SGLang)

APC handles exact prefix matches. RadixAttention, from the SGLang paper, goes further. It organizes the KV cache as a radix tree, basically a trie over token sequences. This lets you cache and reuse shared subtrees along with common leading prefixes. If Request A and Request B share the same first 500 tokens but diverge after that, they still share those 500 tokens of KV cache in the tree, even if neither request is an exact prefix of the other. Multi-turn conversations fit this structure well because they branch from shared history.

Zheng, L. et al. "SGLang: Efficient Execution of Structured Language Model Programs." arXiv, 2024. arXiv:2312.07104

LRU eviction happens at the leaves. The least recently used branches get dropped first when memory is needed, preserving the most commonly used paths. Multiple concurrent requests can read from the same node without lock contention. It is a simple data structure doing useful work.

Real-World Impact

Use CasePrefix Hit RateThroughput Gain
Fixed system prompt (1K tokens)~100%2–5Γ—
RAG with shared top-k docs60–80%1.5–3Γ—
Multi-turn chat50–90%1.3–2Γ—
Unique user prompts~0%1Γ— (no benefit)

Often the Highest-ROI Fix Available

KIVI's 2-bit quantization saves 75% of KV memory per token. Prefix caching saves 100% of KV compute for matched tokens because those tokens do not get processed again. It requires no model changes and carries no accuracy risk. If you have a fixed system prompt and are not running prefix caching, it is often the first thing to fix before quantization or eviction.

Chapter 21

Mixture of Experts & KV Cache: Sparse Activation

Some recent KV cache efficiency gains come from a different architectural choice: Mixture of Experts (MoE). DeepSeek V3, Qwen3-MoE, Mixtral, and DeepSeek V4 all use MoE. The KV cache benefits are indirect, but they matter.

MoE is often left out of KV cache surveys because it is not a KV cache technique by itself. But when choosing a model architecture, MoE versus dense affects how much memory headroom is left for the cache. That makes it relevant here.

The Core Idea

A dense model runs every parameter on every token. An MoE model has far more parameters total, but for any given token, only a small fraction (typically 2 out of 64 expert networks) activates. Total parameter count is huge. Active parameter count per token is small. Memory bandwidth cost follows the active count, not the total.

How MoE Works

Standard Transformer FFN layers run every token through the same network. MoE replaces each FFN with N parallel "expert" FFNs and a learned router that picks the top-k experts for each token. In DeepSeek V3, that's 256 experts with top-8 routing. For any given token, 248 of the experts do nothing. Their weights sit in memory but don't consume compute or bandwidth for that token.

Token embedding
→
Router: score all 64 experts
→
Select top-2 experts
→
Run only those 2 FFNs
→
Weighted sum β†’ output

MoE's Effect on KV Cache

1. Attention stays dense, MoE doesn't directly help the cache

The important nuance: MoE only applies to FFN sublayers. The attention layers are fully dense, every token attends to every other token, and full KV is kept for every layer. MoE does not reduce KV cache size on its own. DeepSeek V3 at 671B total parameters has the same KV cache structure as a dense model with 37B active parameters. The 93% KV reduction in V3 comes from MLA, not MoE. The two techniques are separate and can be stacked.

2. More parameters, same cache, the memory split matters

MoE does affect total GPU memory, but indirectly. Expert weights all need to live somewhere; you cannot load 64 expert FFNs from disk on every decode step. The GPU memory budget gets split between KV cache, which scales with context, and expert weights, which scale with model size. Serving a large MoE model can leave less memory headroom for KV cache, which may force more aggressive quantization or eviction even when the cache architecture is efficient.

ModelTotal ParamsActive Params/TokenAttentionKV Cache (128K)
LLaMA 3 70B (dense)70B70BGQA~18 GB
Mixtral 8Γ—7B46B13B activeGQA~5 GB
DeepSeek V3 (MoE+MLA)671B37B activeMLA~8.6 GB
DeepSeek V4-Pro (MoE+CSA/HCA)1.6T49B activeCSA/HCA~9.6 GiB at 1M
Qwen3-235B-A22B235B22B activeGQA~6 GB

DeepSeek's MoE + MLA Combination

DeepSeek combines MoE for compute efficiency with MLA for KV cache efficiency. Together, they make a 671B-parameter model practical to serve on a small GPU cluster. MoE reduces active compute; MLA reduces memory bandwidth. Neither solves the other's problem directly, but together they address two major bottlenecks in serving large models.

The MoE KV Cache Gotcha

When load balancing fails and most tokens route to the same few experts, those experts become a bottleneck. This also affects KV cache indirectly: if the model is stalled waiting for an expert, the decode step takes longer, and the KV cache must be held in memory for the duration. Expert load balancing (DeepSeek uses an auxiliary loss for this) is therefore a KV cache latency concern as well as a throughput concern.

Chapter 22

KV Cache Offloading: CPU & NVMe as Overflow

Sometimes GQA, quantization, and prefix caching are still not enough. The context is too long for GPU memory. You may be generating a 300,000-token legal analysis, and the cache simply does not fit. Now what?

You spill it. Move the blocks that are not needed right now to CPU RAM, or to NVMe if RAM is full. Load them back when the attention head reaches those positions. It is slow, but it can be the difference between a failed request and a completed one. For batch workloads where latency is flexible, the throughput can be acceptable.

Memory Hierarchy Reminder

  • 🟒 GPU HBM: ~80 GB (A100/H100), ~3.5 TB/s bandwidth, expensive
  • 🟑 CPU DRAM: ~512 GB–2 TB per node, ~100 GB/s PCIe bandwidth
  • πŸ”΄ NVMe SSD: ~10–50 TB, ~10 GB/s, very slow but vast

FlexGen

FlexGen (Sheng et al., 2023) treats offloading as a scheduling problem, rather than only an emergency fallback. GPU, CPU DRAM, and NVMe are resources with different bandwidth and capacity. A linear programming solver chooses where to place model weights, activations, and KV cache across all three, given the throughput target and memory constraints.

Sheng, Y. et al. "FlexGen: High-Throughput Generative Inference of Large Language Models with a Single GPU." ICML, 2023. arXiv:2303.06865

Running a 30B model on a single 16 GB GPU is normally unrealistic. FlexGen makes it possible by accepting high latency and optimizing throughput instead. For research workloads and offline batch jobs, this can be a valid tradeoff. For interactive use, it usually is not.

InfiniGen

InfiniGen is selective about what it offloads. Rather than moving everything to CPU and fetching it back blindly, it runs a lightweight predictor that scores which KV blocks the current decode step will likely need. It prefetches those blocks and leaves low-scoring blocks on disk. Attention bandwidth is spent only on blocks that are likely to matter.

Current token query Q
→
Attention predictor: score all offloaded KV blocks
→
Prefetch top-k blocks from CPU β†’ GPU
→
Compute attention on GPU (only fetched blocks)

When to Use Offloading

ScenarioBest StrategyLatency Impact
Short context (<32K tokens)Keep all KV in GPU HBMNone
Medium context (32K–256K)Quantization (KIVI/KVQuant)Minimal
Long context (256K–1M), batchCPU offload (FlexGen/vLLM)+20–50ms per step
Very long context, low-latencyArchitectural (MLA, CSA/HCA)No offload needed
Single GPU, giant modelFlexGen (weights + KV to disk)High but functional

The Bandwidth Wall

The fundamental limit of KV offloading is PCIe bandwidth. A 16-lane PCIe 5.0 link transfers ~64 GB/s, fast enough to fetch a 1 GB KV cache block in ~16ms. At 10 decode steps per second, that is 160ms per second spent on PCIe transfers alone. This is why offloading works best for batch workloads (high throughput, relaxed latency) rather than real-time chat (low latency required). Architectural solutions like MLA that reduce KV size by 93% are almost always preferable to offloading if the model supports it.

Chapter 23

Disaggregated Prefill & Decode: Splitting the Serving Job

In a standard LLM server, the same GPU handles prefill and decode. Prefill processes the prompt. Decode generates output one token at a time. They look similar from the outside, but they stress the hardware in very different ways.

Prefill Phase
Compute-bound
Processes all prompt tokens in parallel. High GPU utilisation (~90%). Short duration. KV cache is written here: one big write of nΓ—layers blocks.
Decode Phase
Memory-bandwidth-bound
Generates one token per step. Low GPU utilisation (~20–40%). Long duration. KV cache is read every step: thousands of small reads of the full cache.

The Problem: Prefill-Decode Interference

When a new request arrives during ongoing decode, the GPU has to make a bad choice. Handle the compute-heavy prefill and delay existing users, or keep decoding and make the new user wait for the first token. That collision is prefill-decode interference.

Disaggregated Serving (Splitwise, DistServe, Mooncake)

The fix is easy to describe and harder to operate: separate the two phases. A prefill cluster builds the prompt's KV cache. The KV blocks are transferred over NVLink or InfiniBand. A decode cluster handles generation. Two fleets with different resource profiles create much less interference.

User request
→
Prefill GPU cluster: compute KV cache for prompt
→
Transfer KV cache over NVLink / InfiniBand
→
Decode GPU cluster: generate tokens using transferred KV
Zhong, Y. et al. "DistServe: Disaggregating Prefill and Decoding for Goodput-Optimized Large Language Model Serving." OSDI, 2024. arXiv:2401.09670
Qin, P. et al. "Mooncake: A KVCache-centric Disaggregated Architecture for LLM Serving." arXiv, 2024. arXiv:2407.00079

Ring Attention: Sequence Parallelism for 1M+ Tokens

Even with disaggregated serving and aggressive quantization, there are contexts long enough that no single GPU can hold the full KV cache. A million-token context at even 70 KB/token is 70 GB, bigger than most GPU memory budgets. Ring Attention handles this by distributing the KV cache across a ring of GPUs. Each GPU holds a slice of the sequence. The attention computation rotates KV blocks around the ring in a round-robin while queries stay local. Every GPU participates; the total capacity scales with the ring size.

Liu, H. et al. "Ring Attention with Blockwise Transformers for Near-Infinite Context." arXiv, 2023. arXiv:2310.01889

Production long-context systems rarely disclose whether they use Ring Attention specifically. Most model cards say "supports 1M token context" without describing the serving stack. Ring Attention is the main published technique for this problem, but that does not mean it is used everywhere.

TechniqueProblem SolvedKV Transfer RequiredUsed By
Standard servingNothing (baseline)NoneAll early systems
Splitwise / DistServePrefill-decode interferenceGPU→GPU per requestProduction serving
MooncakeKV cache as a first-class resourcePooled KV transferMoonshot AI (Kimi)
Ring AttentionKV cache larger than 1 GPURing-wise per stepResearch / sequence-parallel long-context training and inference

The Serving Layer Now Carries Part of the Intelligence

By this point, KV cache optimization is no longer only a model architecture problem. It is also scheduling, placement, transfer, and memory ownership. Compression helps, but a bad serving layout can still waste the win by making prefill and decode fight each other.

Chapter 24

Where Things Stand in 2026

This field moves quickly, so any summary has a short shelf life. By early 2026, one pattern is clear: KV cache efficiency is a stack, not a single technique.

What's Working Today

GQA
Industry Standard
LLaMA-3/4, Qwen3, Gemma 4, Phi-4, Mistral
MLA
Best Compression Ratio
DeepSeek-V3, Kimi K2 (~1T params)
Hybrid Attention
Extreme Long Context
LLaMA 4 Scout (10M), Gemma 4 E2B/E4B (128K mobile/edge)

What Is Still Unsettled

1. Trillion-scale MLA: Kimi K2 from Moonshot AI is the main data point. It takes DeepSeek-style MLA to roughly 1 trillion parameters with 384 routed experts. The public config shows the latent cache approach survives at that scale. Quality tradeoffs still need broader evaluation.

2. Ten-million-token context: Meta's LLaMA 4 Scout model card reports a 10 million token context window, roughly thousands of pages in one prompt. The card does not expose enough attention internals to map every technique, but the target shows how far long-context systems are being pushed.

3. On-device long context: Gemma 4 E2B and E4B aim at mobile and edge hardware while keeping 128K context. Their KV budget comes from a blend of low KV-head counts, local-global attention, cross-layer sharing, and per-layer embeddings. Gemma 4 26B-A4B is the MoE member; E2B and E4B are not.

4. Aggressive KV-head reduction: Qwen3's MoE variant uses 4 KV heads with 64 query heads, a 16:1 ratio. The field keeps testing how few KV heads are enough.

5. Data-oblivious quantization: TurboQuant does not require calibration per model. That makes it attractive for teams serving many architectures. The exact compression factor still depends on model, workload, and context length.

The Journey in Numbers

Metric Naive FP16 MHA Baseline (e.g. LLaMA-2 7B, 2023) 2026 (State of the Art) Improvement
KV Cache per token (7B model) 512 KB (FP16 MHA) ~10–20 KB (MLA + quant) 25–50×
Long-context serving target ~2K tokens 1M-token KV-cache designs; full large-model serving still often needs multi-GPU Architecture-dependent
Serving throughput Baseline Multi-× gains with paging, batching, eviction, quantization, or speculative decoding Workload-dependent
Memory waste in serving 60–80% ~0% (PagedAttention) Eliminated
Smallest device for 8B+ models Data center GPUs Phone-class demos (Bonsai 8B: PrismML reports ~44 tok/s on iPhone 17 Pro Max) Moved closer to edge devices

My Takeaway

The KV cache problem was never one problem. It was memory size, memory bandwidth, fragmentation, precision, token importance, and serving layout tangled together. MQA, GQA, and MLA changed the architecture. PagedAttention changed allocation. KIVI and TurboQuant changed the number format. Sliding windows and eviction changed what gets kept. Disaggregated serving changed where the work runs. None of these made the others obsolete. Strong systems in 2026 combine them, then tune the mix to the workload.

Visual Recap

The Full Journey: MHA to MLA

Interactive Canvas

Scrub the visual recap from MHA to MLA

This article keeps the live canvas animation embedded. Social-ready MP4/WebM exports are generated locally in the videos/ folder for upload to LinkedIn.

Chapter 25

References

  1. Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A.N., Kaiser, L., and Polosukhin, I. "Attention Is All You Need." NeurIPS 2017. arXiv:1706.03762
  2. Shazeer, N. "Fast Transformer Decoding: One Write-Head is All You Need." arXiv preprint, 2019. arXiv:1911.02150
  3. Ainslie, J., Lee-Thorp, J., de Jong, M., Zemlyanskiy, Y., Lebron, F., and Sanghai, S. "GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints." EMNLP 2023. arXiv:2305.13245
  4. Touvron, H., et al. "Llama 2: Open Foundation and Fine-Tuned Chat Models." arXiv preprint, 2023. arXiv:2307.09288
  5. Llama Team, AI @ Meta. "The Llama 3 Herd of Models." arXiv preprint, 2024. arXiv:2407.21783
  6. DeepSeek-AI. "DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Model." arXiv preprint, 2024. arXiv:2405.04434
  7. DeepSeek-AI. "DeepSeek-V3 Technical Report." arXiv preprint, 2024. arXiv:2412.19437
  8. Jiang, A.Q., et al. "Mistral 7B." arXiv preprint, 2023. arXiv:2310.06825
  9. Gemma Team, Google. "Gemma: Open Models Based on Gemini Research and Technology." arXiv preprint, 2024. arXiv:2403.08295
  10. Gemma Team, Google. "Gemma 2: Improving Open Language Models at a Practical Size." arXiv preprint, 2024. arXiv:2408.00118
  11. Gemma Team, Google. "Gemma 3 Technical Report." arXiv preprint, 2025. arXiv:2503.19786
  12. Yang, A., et al. "Qwen2 Technical Report." arXiv preprint, 2024. arXiv:2407.10671
  13. Kwon, W., Li, Z., Zhuang, S., Sheng, Y., Zheng, L., Yu, C.H., Gonzalez, J.E., Zhang, H., and Stoica, I. "Efficient Memory Management for Large Language Model Serving with PagedAttention." SOSP 2023. arXiv:2309.06180
  14. Dao, T., Fu, D.Y., Ermon, S., Rudra, A., and RΓ©, C. "FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness." NeurIPS 2022. arXiv:2205.14135
  15. Dao, T. "FlashAttention-2: Faster Attention with Better Parallelism and Work Partitioning." arXiv preprint, 2023. arXiv:2307.08691
  16. Liu, Z., Yuan, J., Jin, H., Zhong, S., Xu, Z., Braverman, V., Chen, B., and Hu, X. "KIVI: A Tuning-Free Asymmetric 2bit Quantization for KV Cache." ICML 2024. arXiv:2402.02750
  17. Hooper, C., Kim, S., et al. "KVQuant: Towards 10 Million Context Length LLM Inference with KV Cache Quantization." NeurIPS 2024. arXiv:2401.18079
  18. Google Research. "TurboQuant: Online Vector Quantization with Near-optimal Distortion Rate." arXiv preprint, 2025. arXiv:2504.19874
  19. Zhang, Z., Sheng, Y., et al. "Hβ‚‚O: Heavy-Hitter Oracle for Efficient Generative Inference of Large Language Models." NeurIPS 2023. arXiv:2306.14048
  20. Liu, Z., Desai, A., Liao, F., Wang, W., Xie, V., Xu, Z., Kyrillidis, A., and Shrivastava, A. "Scissorhands: Exploiting the Persistence of Importance Hypothesis for LLM KV Cache Compression at Test Time." NeurIPS 2023. arXiv:2305.17118
  21. Xiao, G., Tian, Y., Chen, B., Han, S., and Lewis, M. "Efficient Streaming Language Models with Attention Sinks." ICLR 2024. arXiv:2309.17453
  22. Li, Y., et al. "SnapKV: LLM Knows What You are Looking for Before Generation." NeurIPS 2024. arXiv:2404.14469
  23. Yang, D., et al. "PyramidInfer: Pyramid KV Cache Compression for High-throughput LLM Inference." arXiv preprint, 2024. arXiv:2405.12532
  24. Cai, Z., et al. "PyramidKV: Dynamic KV Cache Compression based on Pyramidal Information Funneling." arXiv preprint, 2024. arXiv:2406.02069
  25. Brandon, W., Mishra, M., Nrusimha, A., Panda, R., and Ragan Kelly, J. "Reducing Transformer Key-Value Cache Size with Cross-Layer Attention." arXiv preprint, 2024. arXiv:2405.12981
  26. Qwen Team. "Qwen3 Technical Report." arXiv preprint, 2025. arXiv:2505.09388
  27. Kimi Team, Moonshot AI. "Kimi K2: Open Agentic Intelligence." arXiv preprint, 2025. arXiv:2507.20534
  28. Meta AI. "The Llama 4 Herd: The Beginning of a New Era of Natively Multimodal AI Innovation." Meta AI Blog, 2025. meta.ai
  29. Microsoft Research. "Phi-4 Technical Report." arXiv preprint, 2024. arXiv:2412.08905
  30. Microsoft Research. "Phi-4-Mini Technical Report: Compact yet Powerful Multimodal Language Models via Mixture-of-LoRAs." arXiv preprint, 2025. arXiv:2503.01743
  31. Kimi Team, Moonshot AI. "Kimi K2.5: Visual Agentic Intelligence." arXiv preprint, 2026. arXiv:2602.02276
  32. Touvron, H., Lavril, T., Izacard, G., et al. "LLaMA: Open and Efficient Foundation Language Models." arXiv preprint, 2023. arXiv:2302.13971
  33. Penedo, G., et al. "The RefinedWeb Dataset for Falcon LLM: Outperforming Curated Corpora with Web Data, and Web Data Only." arXiv preprint, 2023. arXiv:2306.01116
  34. Qwen Team. "Qwen3.5 Model Series." Model card, 2025. HuggingFace: Qwen3.5-9B
  35. PrismML / Caltech. "1-bit Bonsai: The First Commercially Viable 1-bit LLMs." Whitepaper, 2026. GitHub
  36. DeepSeek-AI. "DeepSeek-V4: Towards Highly Efficient Million-Token Context Intelligence." Model card / technical report, 2026. HuggingFace: DeepSeek-V4-Pro; vLLM. "DeepSeek V4 in vLLM: Efficient Long-context Attention." 2026. vLLM blog
  37. Z Lab. "DFlash: Block Diffusion for Flash Speculative Decoding." arXiv preprint, February 2026. arXiv:2602.06036