Primer llms ai

The KV cache: the memory that makes LLMs fast

Every word a language model generates, it has to look back at every word that came before. Doing that from scratch each time would be ruinously slow, so inference keeps a running notebook: the KV cache, a stored copy of the key and value vectors for every token, at every layer. The notebook is why chat feels instant. It is also why long context eats GPU memory alive, why a 128K conversation can need as much memory as the model itself, and why a whole subfield of systems research, from PagedAttention to DeepSeek's MLA, exists just to keep the notebook small. This primer works the numbers, names the tradeoffs, and flags where the experts still disagree.

"KV cache is one of the most important ideas in LLM inference, but it is usually explained too casually."

@techNmak, X, September 6, 2026; the post that commissioned this primer, linking a technical handbook on the topic

The one sentence to keep The KV cache trades memory for recomputation: it stores the past so the model never has to rebuild it, and almost every trick in modern LLM serving is a way to pay less for that storage.

Researched October 2026, from the primary sources in Sources. Paper and vendor numbers are flagged where they appear; the memory figures in Fig 1 are arithmetic from published model configs, worked live on the page.

Flat editorial illustration: a small robot stores glowing key and value cards into one drawer of an enormous wall of drawers stretching to the horizon, one drawer per token, while red sight lines scan the whole wall at a glance.
One drawer per token, per layer. The wall is the cache, and it grows with every word.

How it works

Six mechanisms, one growing notebook

Attention lets each new token consult all previous tokens through two vectors per token, a key that says what the token offers and a value that says what it contributes. The cache is simply those vectors, kept. Everything else in this primer is a fight over how much that keeping costs.

Fig 1. The memory calculator: what a conversation actually weighs Worked example
$$\text{KV bytes} = 2 \times L \times H_{kv} \times d_{\mathrm{head}} \times b \times S \times B$$

What the letters mean: $L$ is the number of layers, $H_{kv}$ the key-value heads in each layer, $d_{\mathrm{head}}$ the numbers in each head, $b$ the bytes per stored number (2 for BF16), $S$ the tokens, and $B$ the batch size. The 2 out front is keys plus values.

The formula has six parts: 2 (keys and values) times layers times KV heads times head dimension times bytes per element times tokens, times batch. Pick a model shape, drag the context length, and watch the cache grow. These are derived figures, computed on the page from the published configs in the research: a 7B-class model with full multi-head attention, the same shape with one shared KV head, Llama 3 at 8B and 70B with grouped-query attention, and DeepSeek-V3 with MLA, which caches one compressed latent instead of per-head keys and values.

131,072 tokens of context
128 KiBcache per token, all layers
16.0 GiBone request's cache at this length
128 GiBeight requests at once (batch 8)
Share of one 80 GiB H100, cache alone20%

Cross-checks: the KVQuant paper's own table puts a 7B full-attention model at 64 GB of KV for 128K context, matching the first row here. DeepSeek's V3 report contrasts its roughly 70 KB per token against 516 KB for Llama 3.1 405B. The uncomfortable headline: one 128K Llama 3 8B request carries about 16 GiB of cache, roughly the size of its own weights in BF16, and eight of them need 128 GiB of cache alone, before weights, on hardware that ships with 80.

Worked example: the 16 GiB, one multiplication at a time Checkable

No calculator needed beyond patience. Here is the Fig 1 default, Llama 3 8B at 128K context, built up in three steps. Every number is small enough to verify on paper.

Step 1: one token, one layer4,096 bytes

2 (keys and values) times 8 KV heads times 128 head dimension times 2 bytes per BF16 number: 2 times 8 is 16, times 128 is 2,048, times 2 is 4,096 bytes, exactly 4 KiB.

Step 2: one token, all 32 layers131,072 bytes = 128 KiB

Every layer keeps its own notebook, so multiply by 32: 4,096 times 32 is 131,072 bytes. That is the per-token price Fig 1 charges.

Step 3: the whole 128K conversation16 GiB

131,072 bytes times 131,072 tokens is 17,179,869,184 bytes. Divide by 1,073,741,824 bytes per GiB and you get exactly 16. The same shape with 32 KV heads instead of 8 quadruples step 1, which is how the full-attention 7B reaches 64 GiB.

$$2 \times 8 \times 128 \times 2\ \frac{\text{bytes}}{\text{number}} \times 32 \times 131{,}072 = 17{,}179{,}869{,}184\ \text{bytes} = 16\ \text{GiB}$$

The factors, in order: 2 for keys and values, 8 key-value heads, 128 numbers per head, 2 bytes per number, 32 layers, 131,072 tokens.

Run the same three steps for DeepSeek-V3 and step 2 lands near 70 KB instead of 128 KiB, because MLA stores one compressed latent per layer rather than 8 heads of keys and values. Same formula family, one term changed, half the bill at a far larger model size.

At each layer, a token's hidden state is projected into three vectors per head: a query, a key, and a value. The new token's query is compared against the keys of everything before it, and the matching values are blended into its output. Queries are only ever needed for the token being generated right now, so nothing stores them. Keys and values are needed by every future token, so they are appended to the cache, one slice per step, shaped as batch by KV heads by sequence length by head dimension, per layer.

$$\mathrm{Attention}(Q, K, V) = \mathrm{softmax}\!\left(\frac{QK^{\top}}{\sqrt{d_{\mathrm{head}}}}\right) V, \qquad K, V \in \mathbb{R}^{B \times H_{kv} \times S \times d_{\mathrm{head}}}$$

What the letters mean: $Q$ is the query matrix, what each token is looking for. $K$ is the key matrix, what each token advertises. $V$ is the value matrix, what each token hands over when picked. $B$ is the batch size, requests served at once. $H_{kv}$ is the number of key-value heads. $S$ is the sequence length, tokens so far. $d_{\mathrm{head}}$ is the numbers in each head. The small $\top$ means transpose: $K$ flipped so its rows can be scored against the query. $\mathbb{R}$ just means real numbers.

The formula is the whole story: the new token's query row $Q$ is scored against every cached key in $K$, and the output is a blend of the cached values in $V$. Both cached tensors grow by one slice along $S$ at every step, at every layer.

Without the cache, step one thousand would recompute the keys and values of the previous 999 tokens, and total work grows with the square of the length: early tokens get rebuilt hundreds of times. With the cache, each key and value is computed exactly once. Attention compute per step grows linearly with length, but so does the memory traffic, because every step reads the whole notebook back.

Prefill processes the whole prompt in parallel, matrix against matrix, reusing the weights across every position. It is compute-bound, it fills the cache, and its cost is what you feel as time to first token. Decode then generates one token at a time: matrix against vector, roughly one to two floating point operations per byte of weights at batch one, far below what the accelerator can compute. Decode is memory-bandwidth-bound: every step streams all the weights plus the full KV cache through the chip. This framing is Noam Shazeer's, from 2019.

$$\text{bytes read per decode step} = \text{weights} + B \times S \times \text{bytes per token}$$

What the letters mean: $B$ is the batch size, $S$ is the tokens so far, and bytes per token is the per-token cache cost from Fig 1. There is no $L$ here because bytes per token already includes all layers.

Why batching helps only halfway: a batch shares the weight reads across sequences, but each sequence's cache reads are its own. Double the batch and the context, and the cache traffic quadruples. That is why decode-heavy serving buys memory bandwidth, not raw compute, and why every byte per token saved converts almost directly into concurrent capacity.

Multi-head attention gives every query head its own key and value head, which is what makes Fig 1's first row so heavy. Multi-query attention (Shazeer, 2019) shares one KV head across all query heads. Grouped-query attention (Ainslie and colleagues, 2023) splits the difference: groups of query heads share one KV head. In the GQA paper's T5-XXL runs, MQA decoded at 0.24 seconds per sample scoring 46.6 on average, GQA-8 took 0.28 seconds scoring 47.1, and full MHA took 1.51 seconds scoring 47.2: near-MQA speed at near-MHA quality. Llama 3 standardized on GQA with 8 KV heads at every size.

MLA goes further, and differently. DeepSeek-V2 (2024) compresses keys and values jointly, by a learned down-projection, into one low-rank latent vector plus a small decoupled rotary key, and caches only that. At decode time the up-projections are absorbed into the query and output projections, so full keys and values never need to be rebuilt. Against DeepSeek's own 67B dense model, the paper reports the KV cache down 93.3 percent and maximum generation throughput up 5.76 times, with stronger quality: learned compression, not sharing, trained into the model. Moonshot's Kimi K2 adopted MLA in 2025, and a 2025 retrofit paper, MHA2MLA, reports shrinking a trained Llama-2-7B's cache by 92 percent at a cost of half a point on LongBench.

The PagedAttention paper (Kwon and colleagues, SOSP 2023) measured the serving systems of the day and found only 20.4 to 38.2 percent of reserved KV memory held real token states. The rest was fragmentation and over-reservation: each request got a contiguous buffer sized for its maximum possible length, most of it never used, and the gaps between buffers unusable. Their fix stores the cache in fixed-size blocks, allocated on demand, with a logical-to-physical block table translating between them, exactly the way an operating system pages memory. Requests and beam candidates can even share blocks, copy-on-write.

The receipts: waste falls to under 4 percent, only the last partial block, and the paper reports 2 to 4 times the throughput of FasterTransformer and Orca at matched latency. A separate vLLM launch blog claimed up to 24 times against Hugging Face Transformers; the two comparisons use different baselines and this primer keeps them separate, because conflating them is how numbers inflate.

SGLang's RadixAttention (Zheng and colleagues, 2023) keeps finished requests' KV in a radix tree keyed by token sequence, evicting least-recently-used branches, and schedules cache-aware so a new request lands where its prefix already lives. The paper reports up to 6.4 times throughput and 3.7 times lower latency across agent, RAG, and multi-turn workloads, with the honest flag that those gains include the structured-generation runtime, not prefix caching alone. vLLM's automatic prefix caching is hash-based instead: each full block is hashed from its parent hash plus its tokens, only full blocks are cached, eviction is LRU, and the match must be an exact token prefix.

API prompt caching is the retail version of this. Anthropic (beta August 2024, GA December 2024) claims up to 90 percent lower cost and 85 percent lower latency on long prompts, charging 25 percent extra to write the cache and 10 percent of base price to read it, with a roughly five-minute lifetime. OpenAI (October 2024) caches automatically above 1,024 tokens at a 50 percent discount on cached input at launch, cleared after five to ten idle minutes and always within an hour. You never see tensors; the provider keeps the prefix state server-side and bills hits cheaply.

Quantization stores each cached number in fewer bits. KIVI (2024) goes to 2 bits, keys per-channel and values per-token, and reports 2.6 times less peak memory with 2.35 to 3.47 times throughput. KVQuant reports under 0.1 perplexity degradation at 3 bits and fits a 7B model at one million tokens of context on a single 80GB card at 2 bits. Production reality is more conservative: mainline servers default to FP8 KV, a safe two-times saving, and the named 2-bit schemes remain research code rather than vLLM or SGLang defaults.

Eviction is the lossy frontier. H2O keeps heavy-hitter tokens, the few that attract most attention, plus recent ones. StreamingLLM found that the first few tokens act as attention sinks whose removal collapses quality, so it keeps about four of them plus a sliding recent window, and gives up the middle of the context permanently. SnapKV lets the end of the prompt vote on which earlier tokens matter, compressing roughly 13K-token prompts to 1,024 tokens with a reported negligible average drop. The structural catch is the same for all three: an evicted token is gone, and a token that looked unimportant to the queries seen so far may be the answer to the next one. The disagreements section below is mostly about whether that catch is priced in.

Fig 4. The shrink ray: one conversation, six architectures Derived

Same conversation for everyone: 131,072 tokens, batch one, BF16. Only the architecture term changes. Bars are to scale against the heaviest row.

7B, full MHA (32 KV heads)64 GiB
Llama 3.1 405B, GQA (8 KV heads, 126 layers)about 63 GiB
Llama 3 70B, GQA (8 KV heads, 80 layers)40 GiB
Llama 3 8B, GQA (8 KV heads, 32 layers)16 GiB
DeepSeek-V3, MLA (compressed latent)about 8.6 GiB
7B shape, MQA (1 shared KV head)2 GiB

Read the 405B row twice: a model with fifty times the parameters of the 8B carries only four times the cache, and the MLA row undercuts the 8B with a model eighty times its size. Architecture, not model size, sets the memory bill.

Flat editorial illustration: robot forklifts move equal glowing blocks between warehouse shelves while two houses share the same glowing blocks through dotted lines, showing paged allocation and block sharing.
PagedAttention, as a warehouse: small equal blocks, allocated on demand, shared between requests, almost nothing wasted.
Worked example: one system prompt, a thousand requests Say a support bot opens every conversation with the same 8,000-token system prompt, policy, product docs, and tone rules, and serves 1,000 conversations a day. On Llama 3 8B that prefix is 8,000 tokens at 128 KiB, about 1 GiB of cache, and 8,000 tokens of prefill compute per conversation. With prefix caching, the prefill happens once: 1,000 requests times 8,000 tokens is 8,000,000, minus the one 8,000 actually computed, so 7,992,000 prefill tokens a day are simply never computed. Edit one word near the top of that prompt and the saving evaporates from that token onward, which is why production prompts are append-only at the front.
$$\text{prefill tokens saved} = (N - 1) \times P = (1000 - 1) \times 8000 = 7{,}992{,}000$$

What the letters mean: $N$ is the number of requests sharing the prompt (1,000 here) and $P$ is the shared prompt's length in tokens (8,000 here). Everyone after the first request skips the whole prompt.

Fig 2. One token at a time: generation with and without the cache Click per step

A tiny worked example, illustrative rather than measured: the prompt is four tokens long and the model generates three more. The red cells are cached keys and values, one per token so far. Step through it and watch what each new token has to read, and what it would have to rebuild if the notebook were thrown away after every step.

3 buildsfresh key/value computations to decode 3 tokens, with a cache: one per new token
15 buildswithout a cache: rebuild 4, then 5, then 6 (4 + 5 + 6), and the gap widens quadratically from here
15 readscached slices read back across those 3 steps (4 + 5 + 6): the bandwidth bill the cache trades for

Scale the toy up and the shape holds: at 100,000 tokens, one more token costs 1 build with a cache and about 100,000 builds without one, while reading about 100,000 cached slices either way. That trade, compute for bandwidth, is the entire primer in miniature.

$$\text{rebuilds without a cache} = \sum_{t=1}^{S} t = \frac{S(S+1)}{2} = O(S^2), \qquad \text{with a cache} = S = O(S)$$

What the letters mean: $S$ is the total number of tokens, $t$ counts the generation steps one by one, the big symbol adds up every step's rebuild count, and $O(\cdot)$ means "grows like": the total grows like $S$ squared without a cache and like $S$ itself with one.

At $S = 100{,}000$ tokens the sum is about five billion rebuilds against one hundred thousand. Nobody pays the left side; that is the point of the cache.

Fig 3. Inside the notebook: the actual numbers stored Toy model, checkable

Everything so far has been counts and sizes. Here is the thing itself, at toy scale: one layer, one head, head dimension 4, the prompt "The cat sat on". The numbers are invented for clean arithmetic and labeled as such, but every operation below is the real operation, and you can verify each line with the attention formula from card 1.

Scale check: this toy stores 4 tokens times 8 numbers, 32 numbers for one head of one layer. Llama 3 8B stores 65,536 numbers per token: 2 for keys and values, times 8 heads, times 128 per head, times 32 layers. Multiply by every token and the toy becomes Fig 1's 16 GiB.

The real thing: one token inside Kimi K2, unsimplified Real config

The toy above has a key and a value. Kimi K2, Moonshot's open frontier model, stores neither. It uses MLA, the DeepSeek design from card 3, so the honest answer to "what does a real K and V look like in Kimi" is: they do not exist as stored objects. What exists is one compressed latent per layer, from which every head's key and value are reconstructed on the fly. Here is that object at full depth. The simple analogy: it is a zip file of all 64 heads' keys and values, unzipped per head at read time. Now the real machinery.

From Kimi K2's published config, fetched for this primer:

"hidden_size": 7168, "num_hidden_layers": 61, "num_attention_heads": 64, "kv_lora_rank": 512, "q_lora_rank": 1536, "qk_nope_head_dim": 128, "qk_rope_head_dim": 64, "v_head_dim": 128, "rope_theta": 50000, "rope_scaling": {"type": "yarn", "factor": 32}

For each token, at each of the 61 layers, the model's hidden state $h_t \in \mathbb{R}^{7168}$ is compressed twice:

$$c_t^{KV} = W^{DKV} h_t \in \mathbb{R}^{512}, \qquad k_t^{R} = \mathrm{RoPE}\!\left(W^{KR} h_t\right) \in \mathbb{R}^{64}$$

What the letters mean: $t$ is the token's position, $h_t$ is that token's hidden state (7,168 numbers), $W^{DKV}$ is the learned compression matrix (512 rows by 7,168), $c_t^{KV}$ is the stored latent for that token (512 numbers), $W^{KR}$ is the position projection, and $k_t^{R}$ is the shared 64-number key that carries position.

That pair, 512 plus 64 numbers, is the entire cache entry for the layer. The rope key is shared across all 64 heads. When a later token attends, each head $i$ rebuilds its own key and value from the latent, up-projecting with matrices that during decode are absorbed into the query and output projections, so the full keys never need to be materialized:

$$k_{t,i} = \left[\, W^{UK}_i \, c_t^{KV} \;;\; k_t^{R} \,\right] \in \mathbb{R}^{192}, \qquad v_{t,i} = W^{UV}_i \, c_t^{KV} \in \mathbb{R}^{128}$$

What the letters mean: $i$ is the head number, 1 to 64. $W^{UK}_i$ and $W^{UV}_i$ are head $i$'s up-projection matrices, the unzippers that rebuild its key and value from the shared latent. The semicolon stacks two pieces into one key: 128 reconstructed numbers plus the 64 rope numbers makes 192.

What do the 512 latent numbers themselves look like? Small decimals, positive and negative, mostly between about minus 3 and 3. Actual activations exist only inside a running model, so these eight are representative values at real magnitudes, shown exactly as the hardware stores them: BF16, 16 bits each. Tap to flip between the decimal and its raw BF16 hex.

Plus 504 more entries like those, per layer, per token. Now the byte arithmetic, all from the config above: stored, 576 numbers times 61 layers times 2 bytes is 70,272 bytes per token, 68.6 KiB, and 8.58 GiB at 128K context, the same MLA figure as DeepSeek-V3 in Fig 4 because K2 kept V3's latent dimensions. Had Kimi stored per-head keys and values at these dimensions, it would be 320 numbers per head times 64 heads times 61 layers times 2 bytes: 2,498,560 bytes per token, 305 GiB at 128K. The latent is a 35.6 times smaller cache entry, bought with two matrix multiplications per head at read time. One honest footnote: the config still declares "num_key_value_heads": 64, which reads like GQA bookkeeping. Under MLA that field describes the reconstructed heads, not anything stored. Kimi gets a full primer of its own: How Kimi Is Built.

Fig 5. The eviction lab: pick a policy, watch tokens disappear Illustrative

Twenty-four tokens of context, drawn to the policies' own descriptions. Red cells survive; outlined cells are the attention sinks; faded cells are evicted and can never come back. The middle tokens are where instructions hide.

Fig 6. The bits dial: quantization, priced in GiB Derived

Llama 3 8B at 128K context again. The cache scales linearly with bits per element, $\text{GiB} = 16 \times \text{bits} / 16$, so on this model the GiB number literally equals the bits. Pick a precision and see what production actually ships.

16 GiBcache at this precision
3 usersconcurrent 128K users on one H100 with 60 GiB left for cache
The baselinefull precision, what the papers compare against
Cache size against BF16100%

The dial is the disagreement from the camps section, made tangible: the left end is what the validation study crowned (FP8, the production default), the right end is what the research papers advertise. The gap between them is a quality argument, not an arithmetic one.

The serving stack

Long context is a memory bill, and everyone is negotiating it

Batch size in production is set by KV memory: concurrent sequences is roughly GPU memory minus weights minus activations, divided by bytes per token times average length. When the cache fills, vLLM preempts and recomputes sequences rather than evicting tokens. That one equation explains most of the engineering below.

$$N_{\max} \approx \frac{M_{\mathrm{GPU}} - M_{\mathrm{weights}} - M_{\mathrm{overhead}}}{\text{bytes per token} \times \bar{S}}$$

What the letters mean: the three $M$ terms are memory in bytes: the whole GPU, the model weights, and runtime overhead. Bytes per token is Fig 1's cost, and $\bar{S}$ (S with a bar) is the average context length per user.

16 GiBCache for one Llama 3 8B request at 128K tokens, about the size of its own BF16 weights. Derived from the published config.
Under 4%KV memory wasted under PagedAttention, down from systems where only 20.4 to 38.2 percent of reserved memory held real token states.
128 to 492 GiBExtrapolated cache at one million tokens for GQA models, against about 67 GiB for DeepSeek-V3 with MLA. Marketing context length is not affordable concurrent context length.
Worked example: how many users fit on one H100? Illustrative arithmetic

Stated assumptions, all checkable: one 80 GiB H100, Llama 3 8B weights take 16 GiB, call it 4 GiB of overhead, leaving 60 GiB for KV cache at 128 KiB per token. The only variable is how long each user's context runs.

2,000-token contexts: 0.25 GiB each240 users
8,000-token contexts: 1 GiB each60 users
32,000-token contexts: 4 GiB each15 users
128,000-token contexts: 16 GiB each3 users

Nothing about the model changed between rows. Context length alone divided the serving capacity by 80, which is why providers price long context the way they do, and why every shrink in this primer converts almost directly into concurrent users.

Tier it and move it

FlexGen (2023) spread a 175B model across GPU, CPU RAM, and SSD and ran it on one 16GB card at one token per second: fine for offline batch, not for chat. Mooncake, Moonshot's serving platform for Kimi, disaggregates prefill and decode clusters and pools idle CPU, DRAM, and SSD across the cluster as one shared KV store, with vendor-reported gains up to 525 percent in some simulated long-context scenarios and 75 percent more requests on real workloads. LMCache (2025) turns tiering into an engine-agnostic layer across vLLM and SGLang.

Split the phases

Splitwise and DistServe put prefill and decode on separate hardware pools, because prefill wants compute and decode wants bandwidth. DistServe's paper reports up to 7.4 times the goodput under latency targets. The crux is transfer: one 128K Llama 3 8B request's 16 GiB of cache has to reach the decode machines fast enough, which is why RDMA transfer engines and layer-by-layer streaming of KV as prefill produces it exist.

Chunked prefill, the quiet default A long prompt used to stall everyone. A monolithic prefill blocks all in-flight decodes, so one user pasting a book made every other user's next token late. Sarathi-Serve (2024) splits prefill into chunks and piggybacks one chunk onto each decode iteration, bounding the interference; the paper reports 2.6 to 5.6 times the serving capacity of vLLM under tail-latency targets, depending on the model. Chunked prefill is now a default in both vLLM and SGLang, which is what a mature idea looks like: invisible.
Three misconceptions to retire It is not memory in the human sense. The cache holds transient activations computed from frozen weights for one sequence. Delete it and the model knows exactly as much as before; it has only lost this conversation's precomputed state. It is not training. No gradients, no parameter updates, nothing persists across model loads. Fine-tuning changes weights and retrieval changes inputs; the cache is downstream of both, rebuilt from scratch per sequence. Its lifetime is one request by default. Prefix caches extend selected blocks across requests under LRU or a few minutes of TTL, and invalidation is positional: change any token and every block from that point on is invalid, while appending preserves the prefix untouched.

Timeline

Seven years of shrinking the notebook

The cache went from an implementation detail to the central constraint of LLM serving. Step through the landmarks.

Key voices

Who says what

Four camps argue about where the fix belongs: in the architecture, in the allocator, in reuse across calls, or nowhere lossy at all.

The founding position

Noam Shazeer

Google; Fast Transformer Decoding, November 2019

Decode is a memory-bandwidth problem, and multi-head attention spends that bandwidth re-reading a separate key and value set per head. Shazeer's answer, multi-query attention, shares one KV head across every query head: much faster decoding for a minor quality cost. Every architecture argument since is a refinement of the tradeoff he named.

Fix the allocator

Woosuk Kwon, Ion Stoica, and the vLLM team

UC Berkeley; PagedAttention, SOSP 2023

The model was never the bottleneck; the memory manager was. When only a fifth to a third of reserved KV memory holds real tokens, paging the cache like operating-system memory recovers the waste without touching the architecture, and throughput multiplies. Leave the model alone, fix the bookkeeping.

Fix reuse

Lianmin Zheng and the SGLang team

RadixAttention, SGLang paper, December 2023

The bigger win is across calls, not inside one: real workloads repeat prefixes constantly, in system prompts, few-shot blocks, chat history, and retrieved documents. Keep finished requests' KV in a radix tree, schedule new work toward the GPU already holding its prefix, and recomputation mostly disappears.

Fix the architecture

The DeepSeek authors

DeepSeek-V2, May 2024; DeepSeek-V3, December 2024

Sharing heads is a compromise; compression is the answer. MLA learns to squeeze keys and values into one small latent, cutting the cache by a reported 93.3 percent against their dense baseline while improving quality. The cost is real implementation complexity, absorbed projections and a decoupled rotary key, which is exactly what GQA's defenders say a serving team should not have to carry.

The hybrid pragmatists

Meta and Google, by revealed preference

Llama 4, April 2025; Gemma 3 technical report, March 2025

Neither lab followed DeepSeek to MLA. Llama 4 kept GQA with 8 KV heads and mixed chunked-attention and full-context layers; Gemma 3 runs five local sliding-window layers per global layer, which its report says cuts KV overhead from about 60 percent to under 15 percent of memory at 32K context. Their bet: mostly-local attention plus GQA is small enough, and simpler. Moonshot took the other side of that bet, adopting MLA in Kimi K2.

The skeptics

Chen and colleagues; the reasoning-cache assessors

The Pitfalls of KV Cache Compression, 2025; Hold Onto That Thought, December 2025

Eviction papers report negligible loss on average benchmarks, and the skeptics show what averages hide: compressed caches can silently drop whole instructions from multi-instruction prompts, a failure they call selective amnesia, and on reasoning models, where the generation itself fills the cache, no single strategy wins and tight budgets can lengthen reasoning traces until the saving evaporates. Production stacks have quietly sided with the skeptics: neither vLLM nor SGLang ships an eviction policy as a serving default.

Predictions

Where leaders think this goes

Researched October 2026. The field agrees the cache is the constraint. It splits, with named camps, on how aggressively to shrink it.

Where they agree

Shazeer, the vLLM team, the SGLang team, and the DeepSeek authors all start from the same diagnosis, reached from four directions: decode is bounded by memory traffic, and the KV cache is the traffic that grows. Long context, large batches, and long reasoning traces all spend the same currency. Nobody serious argues the cache gets cheaper on its own; the argument is only about which layer pays.

Split 1: evict tokens, or never lose one?

Side A: the eviction papers

H2O (2023), StreamingLLM (2023), and SnapKV (2024) report near-baseline quality at a fraction of the cache: heavy hitters plus recent tokens, attention sinks plus a window, or prefill-time voting. On their benchmarks, most tokens are provably dead weight.

Side B: the exactness critics

The Pitfalls study (2025) found whole instructions silently dropped, and the December 2025 reasoning assessment found no universal winner and budgets backfiring through longer traces. The production tiebreaker so far: vLLM and SGLang ship no eviction default.

Split 2: how low can quantization go?

Side A: TurboQuant's authors, Google

TurboQuant (2025) reports quality-neutral caching at about 3.5 bits per element, at least six times smaller, using random rotation plus a one-bit error correction. KIVI and KVQuant's 2 to 3 bit results point the same direction.

Side B: the vLLM and Red Hat validation

Their May 2026 study found FP8 KV the best default, two times capacity at negligible loss, with aggressive 3-bit modes dropping accuracy meaningfully on reasoning, coding, and long-context retrieval. Lossless six-times remains contested, not settled.

Split 3: is exact-prefix reuse enough?

Side A: SGLang and vLLM

RadixAttention and automatic prefix caching reuse KV only for exact token prefixes: system prompts, shared documents, earlier turns. Simple, provably correct, and most of the real-world win.

Side B: CacheBlend and LMCache

Retrieval workloads reuse the same chunks in different orders and contexts, which is not a prefix. CacheBlend (EuroSys 2025) argues for selective recomputation of reused chunks in place, and LMCache builds the cross-engine tiering layer to make non-prefix reuse practical.

The state of play, October 2026

Hybrid attention is the mainstream answer: sliding-window layers cap most of the cache while a few global layers keep full reach, in Gemma 3, Llama 4, and GPT-oss alike. DeepSeek layered sparse attention on top of MLA in V3.2-Exp (September 2025) with a vendor-reported API price cut above 50 percent. And reasoning models have moved the frontier: when a short prompt generates ten thousand tokens of thought, the decode side fills the cache, and that problem has no consensus winner yet.

Takeaways

The cache is the bill

Strip the papers away and one picture remains: generation speed is bought with stored context, the storage grows linearly with everything users want more of, and the last seven years of inference research is the industry negotiating that bill down at every layer at once.

  • Memory for speed. The KV cache stores keys and values, never queries, so each token is computed once. Without it, generation cost grows with the square of length.
  • Do the Fig 1 arithmetic before believing a context window. One 128K Llama 3 8B request needs about 16 GiB of cache. A million-token window is a memory claim, not just a model claim.
  • Architecture is the deepest cut. GQA shares heads and is the safe default; MLA compresses to a latent and goes seven times smaller still, at real complexity. Watch which labs adopt which.
  • Systems wins are free quality-wise. PagedAttention recovered most of a wasted GPU with better bookkeeping, and prefix caching deletes repeated beginnings. Neither changes a single output token.
  • Lossy tricks carry a burden of proof. Eviction and 2-bit quantization post beautiful averages and documented silent failures. Production defaults, FP8 and no eviction, tell you how the field actually prices the risk.
  • Prompt caching is this, productized. The discount on your API bill for a repeated prefix is the KV cache showing up in pricing. Keep prompts prefix-stable: append, never edit early.

Keep exploring

Related primers

Sources

Primary sources

Paper
Shazeer: Fast Transformer Decoding, One Write-Head is All You Need
November 6, 2019. Multi-query attention and the memory-bandwidth framing of decode.
Paper
Ainslie and colleagues: GQA, Training Generalized Multi-Query Transformers
May 22, 2023. Grouped-query attention, mean-pooling conversion, uptraining on about 5 percent of original compute, T5-XXL speed and score table.
Paper
Meta: The Llama 3 Herd of Models
July 2024. GQA with 8 KV heads at all sizes, 128K context; the configs behind Fig 1.
Paper
DeepSeek: DeepSeek-V2 and Multi-head Latent Attention
May 7, 2024. MLA: KV cache down 93.3 percent, generation throughput up 5.76 times, against DeepSeek 67B, author-reported.
Paper
DeepSeek: DeepSeek-V3 Technical Report
December 2024. The roughly 70 KB per token MLA figure, contrasted in the report with 516 KB for Llama 3.1 405B.
Paper
Kwon and colleagues: PagedAttention (Efficient Memory Management for LLM Serving)
September 12, 2023, SOSP 2023. Reserved-memory utilization of 20.4 to 38.2 percent, waste under 4 percent paged, 2 to 4 times throughput.
Blog
The vLLM team: vLLM launch post
June 20, 2023. Vendor figures, up to 24 times Hugging Face Transformers; kept separate from the paper comparisons on this page.
Paper
Zheng and colleagues: SGLang and RadixAttention
December 2023. Radix-tree prefix reuse with LRU eviction and cache-aware scheduling; up to 6.4 times throughput, runtime included.
Docs
vLLM docs: Automatic Prefix Caching design
Hash-based full-block caching, parent-hash chaining, LRU eviction, sha256 default since v0.11. Exact token prefixes only.
Product
Anthropic: Prompt caching with Claude
Beta August 2024, GA note December 17, 2024. Up to 90 percent cost and 85 percent latency claims; write at plus 25 percent, read at 10 percent of base input price.
Product
OpenAI: Prompt Caching
October 1, 2024. Automatic above 1,024 tokens, 128-token increments, 50 percent cached-input discount at launch, caches cleared within an hour.
Paper
Liu and colleagues: KIVI, a Tuning-Free Asymmetric 2bit Quantization for KV Cache
February 2024. Keys per-channel, values per-token; 2.6 times less peak memory, 2.35 to 3.47 times throughput, author-reported.
Paper
Hooper and colleagues: KVQuant
January 31, 2024. Under 0.1 perplexity change at 3 bits; the 7B FP16 table, 64 GB at 128K and 512 GB at 1M, cross-checks Fig 1.
Paper
Zhang and colleagues: H2O, Heavy-Hitter Oracle
June 2023. Keep heavy hitters plus recent tokens; at a 20 percent budget, up to 29 times throughput against its baselines, author-reported.
Paper
Xiao and colleagues: StreamingLLM and attention sinks
September 2023. About four sink tokens plus a sliding window streams to 4M tokens; the middle is given up permanently.
Paper
Li and colleagues: SnapKV
April 2024. Prefill observation window votes per head; roughly 13K-token prompts compressed to 1,024 tokens, author-reported negligible average drop.
Paper
Sheng and colleagues: FlexGen
March 2023. GPU plus CPU plus SSD placement; a 175B model at one token per second on a single 16GB GPU, an offline batch tradeoff.
Paper
Qin and colleagues: Mooncake, a KVCache-centric disaggregated architecture
Moonshot AI and Tsinghua, July 2024. Disaggregated prefill and decode with a pooled KV store; vendor-reported gains flagged on the page.
Paper
Agrawal and colleagues: Sarathi-Serve and chunked prefill
March 2024. Stall-free hybrid batches; 2.6 to 5.6 times serving capacity under tail-latency targets, author-reported.
Paper
Zandieh and colleagues: TurboQuant
April 2025. Quality-neutral claims at about 3.5 bits per element and at least six times KV reduction, contested by the 2026 validation below.
Blog
vLLM and Red Hat AI: A First Comprehensive Study of TurboQuant
May 11, 2026. FP8 KV as the best default; meaningful accuracy drops from aggressive 3-bit modes on reasoning, coding, and retrieval.
Paper
Chen and colleagues: The Pitfalls of KV Cache Compression
2025. Compressed caches silently dropping whole instructions in multi-instruction prompts: selective amnesia.
Paper
Hold Onto That Thought: KV cache compression for reasoning models
December 12, 2025. No single winning strategy; tight budgets can lengthen reasoning traces and erase the nominal saving.
Paper
MHA2MLA: converting MHA models to MLA
February 20, 2025. Llama-2-7B cache down 92.19 percent at minus 0.5 percent LongBench, author-reported.
Paper
Moonshot AI: Kimi K2 technical report
July 2025. The clearest non-DeepSeek adoption of MLA in a frontier-scale open model.
Repo
LMCache: an engine-agnostic KV cache layer
Paper October 2025. Tiering and reuse across vLLM and SGLang deployments, building on CacheGen and CacheBlend.
Post
Google: Gemma 3 release post
March 2025. Hybrid local and global attention; the technical report puts KV overhead falling from about 60 percent to under 15 percent of memory at 32K context.
Post
@techNmak: the seed post and handbook link
September 6, 2026, 198.8K views when read. The handbook PDF linked there exposed only its cover to this research, so no finding on this page rests on it.