AI State of the Art
SOTA/Advanced Attention Mechanisms/25 min
Section 81

KV Cache: Operation, Compression, Quantization

Listen as a podcast →

Why the KV Cache exists

When a Transformer generates text token by token (autoregressive mode), each new token must "look at" all previous tokens via the attention mechanism. Without a cache, that means recomputing the keys (K) and values (V) for all previous tokens at each step. For the 1000th token, you'd have to recompute K/V for the 999 tokens before it. That's absurd waste.

The solution: the KV Cache. You store each token's K and V at the moment it's processed, and reuse them for all subsequent tokens. Each new token only costs the computation of its own K/V, plus the attention operation with the existing cache.

And why isn't the query stored? Because attention is causal: the current token's query is used once, at the moment the token is processed, and never again; the keys and values of the whole past, on the other hand, are re-read at every new step. You cache what gets re-read, not what is written once, the detailed explanation is here.

In terms of complexity, you go from O(L×d2)O(L \times d^2) per token to O(d2)O(d^2) for the K/V computation (the attention itself remains O(L×d)O(L \times d)), LL being the number of tokens in the context and dd the vector dimension: the cost of computing K/V no longer depends on the length of the text.

Two-stage diagram. Prefill phase: five prompt tokens are processed at once and produce the initial cache, K equals k1 through k5 and V equals v1 through v5. Generation phase: a new token arrives, only k6 and v6 are computed, and the cache grows to k1 through k6 and v1 through v6, with the first five entries reused as-is.
The mechanism in one image. The prompt is processed in a single pass (prefill) and fills the cache. Then, for each new token, a single key-value pair is computed and appended at the end: the whole past is read back from the cache instead of being recomputed. That is exactly the saving described above, and also why the cache only ever grows.Source : Marcel Brenndoerfer, Autoregressive Generation
The library analogy

Imagine you're looking for a book in a library of 10,000 volumes. Without a cache, for each question you go back to the shelves to find all the relevant books. With a cache, you keep the useful books stacked on your table. Next question? You look at your stack directly. Enormously faster.

Real KV Cache size: it blows up fast

Let's do the math for LLaMA 2 7B with an 8K token context in FP16 (2 bytes per value):

KV cache=2×32 layers×32 heads×8000 tokens×128 dim×2 bytes≈4 GB\text{KV cache} = 2 \times 32 \text{ layers} \times 32 \text{ heads} \times 8000 \text{ tokens} \times 128 \text{ dim} \times 2 \text{ bytes} \approx 4 \text{ GB}

The factor of 2 at the beginning counts both keys AND values (never the queries, which are used only once). 4 GB just for the cache of a single request.

For a model at the scale of GPT-3 175B (96 layers, 96 heads of dimension 128) with 8K tokens, the same arithmetic gives about 38 GB. On an A100 GPU with 80 GB, once the model is loaded and the cache allocated, there's almost nothing left to process other requests in parallel.

Chart of KV cache memory for a LLaMA 7B model in FP16 with batch size 1, as a function of context length. The curve starts below 1 GB at 512 tokens, reaches 4 GB at 8K tokens, 16 GB at 32K and 64 GB at 128K. A red dashed horizontal line marks the 13 GB of model weights, crossed by the curve between 16K and 32K tokens.
The same calculation as above, plotted across the whole range of context lengths. The point at 8K tokens is indeed 4 GB. The horizontal axis doubles at every tick, so the curve is really a straight line: the cache grows in proportion to the number of tokens. The red line is the size of the model weights, beyond roughly 24K tokens of context, the cache of a single request outweighs the model itself.Source : Marcel Brenndoerfer, KV Cache Memory
The real bottleneck: memory bandwidth

Autoregressive inference is limited by memory bandwidth, not by compute power. For each generated token, the GPU must read the entire KV cache from HBM (High Bandwidth Memory, the card's main memory). For 4 GB of cache on an A100 at 2 TB/s bandwidth, that takes about 2 ms per token (4 ÷ 2000). The GPU may be incredibly powerful in compute, but it spends its time waiting for data to arrive from memory.

KV Cache compression techniques

Cache quantization

The most direct approach: reduce the precision of stored K/V.

INT8: instead of FP16 (2 bytes), you store in INT8 (1 byte). The cache is cut in half. Degradation is minimal for most tasks.

INT4: 4x reduction, but trickier. You need to quantize by groups to preserve precision.

FP8: a good compromise that preserves FP16's dynamic range while halving the size.

Key/value asymmetry

Keys and values have different statistical distributions. Keys tend to be uniformly distributed, while values exhibit outliers (extreme values). Asymmetric quantization (with a zero-point) works better than symmetric for values. A detail that matters in practice.

Smart eviction: dropping what's no longer useful

Instead of keeping everything, you can intelligently remove cache entries that contribute little to attention.

Heavy Hitter Oracle (H2O): identifies tokens that receive the most attention (the "heavy hitters") and only keeps those, plus a local window of recent tokens. Keeping roughly 20% of the tokens divides the cache by 5.

Sink Tokens: systematically keeps the very first tokens (typically the system prompt) in addition to the local window. Essential for tasks that depend on an initial instruction.

Sliding Window: a radical approach used by Mistral. You only keep the last WW tokens in the cache. Ultra memory-efficient, but only works if the recent context is sufficient for the task.

Structural compression: rethinking the architecture

Multi-Head Latent Attention (MLA), introduced by DeepSeek, is the most aggressive compression. Instead of computing and then storing each head's K and V, you cache a small latent vector from which they can be reconstructed:

ct=Wcompress htc_t = W_{\text{compress}} \, h_t K=Wdecompress_K⋅ct,V=Wdecompress_V⋅ctK = W_{\text{decompress\_K}} \cdot c_t, \quad V = W_{\text{decompress\_V}} \cdot c_t

In plain terms: hth_t is the representation of token tt at the entrance of the attention layer. A learned matrix WcompressW_{\text{compress}} squeezes it into a small latent vector ctc_t, and the cache stores only that. When you need K and V to compute attention, you reconstruct them on the fly with two decompression matrices, also learned. The full mechanism (and its delicate coexistence with positional encoding) is detailed in the MLA lesson.

MLA in DeepSeek-V2: 93% compression

DeepSeek-V2 reports a 93.3% KV cache reduction with MLA. This is far more aggressive than GQA (Grouped Query Attention) while being more expressive: K and V share a rich representation in latent space, rather than simply sharing heads.

Comparison of four attention variants, with hatching indicating what is cached during inference. Multi-Head Attention: one key and one value cached per head. Grouped-Query Attention: one key and one value shared per group of queries. Multi-Query Attention: a single key and value for all heads. Multi-Head Latent Attention: the per-head keys and values are not cached, only a compressed latent KV vector is, and keys and values are projected back out of it.
What actually sits in the cache, per attention variant. Only the hatched blocks take up memory. MHA keeps two per head, GQA shares them across groups, MQA drops to a single pair. MLA (right) does something different: none of the tensors used by attention are cached at all, only the small compressed latent vector is, and keys and values are reconstructed by projection at compute time.Source : DeepSeek-V2 paper (figure 3), via Lior Sinai

CSA + HCA: the logical sequel to MLA (DeepSeek V4, April 2026)

DeepSeek V4 goes further with a hybrid compressed attention. Instead of compressing uniformly (MLA) or evicting (H2O), V4 alternates two kinds of compression layer by layer:

  • Compressed Sparse Attention (CSA): a learned compressor merges the K/V of every group of mm consecutive tokens into a single cache entry, and each query then consults only the most relevant compressed entries.
  • Heavily Compressed Attention (HCA): much more aggressive compression (far larger groups), in the alternating layers.
DeepSeek-V4: Towards Highly Efficient Million-Token Context Intelligence

The effect at 1M tokens, per the technical report: V4-Pro (a 1.6T-parameter mixture of experts, with 49 billion active per token) runs with only 10% of the KV cache of V3.2 and 27% of the inference FLOPs per token (FLOPs, floating-point operations, count the compute work). Concretely: a whole novel in context, served at a fraction of the previous generation's cost.

The key idea: KV cache compression is no longer uniform, it is learned and hierarchical, like a multi-level memory. V4 confirms that the future of long context runs through layer-specific compression, not a single trick applied everywhere.

Implementation optimizations

PagedAttention (vLLM)

vLLM's brilliant idea: manage the KV cache like an OS's virtual memory.

  • The cache is divided into pages (fixed-size blocks, typically 16 tokens)
  • Pages are dynamically allocated as needed, not pre-allocated
  • Multiple requests with the same prefix (system prompt) share the same pages

The result: near-zero memory fragmentation. Where naive allocation wasted 60-80% of GPU memory, PagedAttention achieves near-optimal utilization.

Prefix Caching

If 100 requests share the same 2000-token system prompt, you compute the KV cache for that prompt once and share it across all requests. The savings are massive in production deployments where the system prompt is fixed.

Speculative Decoding

Instead of generating one token at a time (very bandwidth-inefficient), a small fast model generates several candidate tokens, then the large model verifies them in a single batch. The cache is updated in batch rather than token by token, which makes much better use of GPU bandwidth.

The direct economic impact

Reducing KV cache per request means being able to process more requests in parallel on the same GPU:

batch_max=GPU_memory−model_weightsKV_cache_per_request\text{batch\_max} = \frac{\text{GPU\_memory} - \text{model\_weights}}{\text{KV\_cache\_per\_request}}

Halving the cache = doubling the batch size = doubling the throughput = cutting the cost per token in half. For a production LLM service, KV cache size is directly linked to profitability.

This is not an optional optimization

Cache quantization, GQA, MLA, eviction, PagedAttention: these are not marginal optimizations to squeeze out a few percentage points of performance. They are fundamental elements of economic viability. Without them, serving LLMs at scale would be financially impossible.

TurboQuant: quantizing the KV cache to around 3 bits (Google Research / DeepMind and NYU)

TurboQuant is a training-free compression algorithm (from researchers at Google Research, Google DeepMind and New York University) that quantizes the KV cache to about 3 bits per coordinate: per the paper, 3.5 bits are enough for intact quality, and 2.5 bits for marginal degradation. The process relies on two complementary steps:

  1. A random rotation, then a precomputed quantizer: each K/V vector receives a random rotation that makes the distribution of every coordinate known in advance (a so-called Beta distribution, the same for all vectors). You can therefore precompute the optimal level assignment once (the Lloyd-Max algorithm) and reuse it everywhere, which eliminates the costly per-block normalization of classical quantizers.

  2. QJL (Quantized Johnson-Lindenstrauss): uses 1 additional bit per dimension to correct the first stage's residual error, only the sign of the residual (+1 or −1) is stored. This single bit is enough to make the dot product estimate mathematically unbiased: no more systematic error, only noise that averages out.

In total, the first stage uses all bits but one, and QJL the last. At 3.5 bits per coordinate instead of FP16's 16 bits, cache memory is divided by roughly 4.5 (16 ÷ 3.5).

Results are validated on Llama-3.1-8B with the LongBench and Needle in a Haystack benchmarks (finding a piece of information hidden inside a very long text). The compressed cache maintains near-perfect fidelity, including on those long-context retrieval tasks.

No training or fine-tuning is needed: TurboQuant applies directly to any existing model in a single pass.

TurboQuant: Online Vector Quantization with Near-optimal Distortion Rate
Implications for long-context serving

With context windows now exceeding a million tokens (Gemini, Claude), the KV cache becomes the primary limiting factor. A cache 4 to 6 times smaller means serving correspondingly longer contexts on the same hardware, or correspondingly more requests in parallel. TurboQuant makes serving very long contexts economically viable without quality compromise.

In summary

The KV Cache is what makes autoregressive inference practical, but it quickly becomes a bottleneck in memory and bandwidth. Compression techniques (quantization, eviction, MLA) and optimization techniques (PagedAttention, prefix caching) are pillars of modern LLM infrastructure. This is a very active area of research, directly tied to the profits and viability of LLM services.

Check your understanding0 / 5

1. In the KV cache size formula, the factor 2 counts the keys and the values. Why is there no factor 3 including the queries?

2. During token-by-token generation, what actually limits the GPU?

3. With DeepSeek's Multi-Head Latent Attention, what actually sits in the cache?

4. What is the idea behind PagedAttention, vLLM's flagship optimization?

5. Why does halving the KV cache size per request roughly halve the cost per token?