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
How it works
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Same conversation for everyone: 131,072 tokens, batch one, BF16. Only the architecture term changes. Bars are to scale against the heaviest row.
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.
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.
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.
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.
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.
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 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:
For each token, at each of the 61 layers, the model's hidden state $h_t \in \mathbb{R}^{7168}$ is compressed twice:
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:
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.
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.
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.
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
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.
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.
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.
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.
Timeline
The cache went from an implementation detail to the central constraint of LLM serving. Step through the landmarks.
Key voices
Four camps argue about where the fix belongs: in the architecture, in the allocator, in reuse across calls, or nowhere lossy at all.
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.
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.
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.
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.
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 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
Researched October 2026. The field agrees the cache is the constraint. It splits, with named camps, on how aggressively to shrink it.
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.
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.
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.
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.
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
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.
Keep exploring
The full path from prompt to token, where the KV cache is one stop.
Context, retrieval, and real long-term memory, and why the cache is none of them.
The other great memory-versus-compute trade: sparse weights, dense cache.
Compute versus bandwidth, and why accelerators are rated on the wrong one for decode.
Sources