Skip to content

Chapter 1 · KV Cache and Memory Management

1.1 What is the KV cache, and why do we cache only K and V but not Q? ★★★

One-sentence answer

The KV cache stores, during autoregressive generation, the key and value of every existing token at every layer in GPU memory, so that each step only computes Q, K and V for the new token and attends over the cached history, avoiding repeated computation over the whole prefix. It works because the causal mask guarantees that the K and V of past tokens never change as later tokens are added; Q is not cached because each token's query is used only once, when computing that token's own output, and later tokens need only the past K and V.

I will address three aspects: what the KV cache does, why it is exact, and why Q does not need to be cached.

(1) The KV cache stores the keys and values of past tokens, trading memory for compute.

In attention, each token is first projected into three vectors, a query, a key and a value: the query expresses "what am I looking for", the key expresses "how can I be matched", and the value expresses "what content do I provide once selected". When generating token \(t\), the new token's query computes similarities with the keys of all previous tokens and then takes a weighted sum of their values accordingly. Without a cache, every step would have to feed the entire prefix back into the model and recompute the K and V of all tokens at every layer, even though these results are identical to those of the previous step, which is a large amount of repeated computation. The KV cache instead stores the K and V of every token at every layer in GPU memory; each step computes Q, K and V only for the newest token, appends the new K and V to the cache, and attends with the new Q over all the cached K and V. This way, the compute of the linear layers and the FFN per step drops from proportional to the prefix length to a constant, at the cost of the cache occupying a large amount of memory (see 1.2).

(2) The KV cache is exact, because the causal mask guarantees that the K and V of past tokens never change.

In a decoder-only model, the causal mask lets each position see only itself and earlier tokens. Hence the output of token \(i\) at layer 1 depends only on the first \(i\) tokens, so its input to layer 2 also depends only on the first \(i\) tokens; continuing layer by layer, its K and V at every layer depend only on the first \(i\) tokens, and no later token, whatever it is, can affect them. Since these values never change during generation, the cached results are identical to recomputed ones, so the KV cache is not an approximation but an exact speedup. Conversely, in a bidirectional encoder such as BERT, every token can see the tokens after it, so adding a new token changes the representations of all past tokens, and the KV cache no longer works.

(3) Q is not cached because the queries of past tokens will never be used again.

Step \(t\) only needs to compute the new token's output, which is determined by the new token's own query together with the keys and values of all tokens. The query of a past token was used only once, when its own output was computed; that output has already been computed and is already reflected in the cache through the K and V of the next layer, and it will never be recomputed. Hence every future step needs only the past K and V, never the past Q, and caching Q would only waste memory. By the same reasoning, the attention outputs and FFN outputs of past tokens do not need to be cached either.

In summary: the essence of the KV cache is exploiting the "unchanging history" guaranteed by the causal mask to trade memory for compute; the only things worth caching are those that future tokens will use again, namely the K and V at every layer.

Going deeper: the attention formula and the compute with and without the cache

(1) Attention at step \(t\) uses only the new token's query.

\[ o_t = \sum_{i=1}^{t} \frac{\exp\!\big(q_t^\top k_i / \sqrt{d_h}\big)}{\sum_{j=1}^{t} \exp\!\big(q_t^\top k_j / \sqrt{d_h}\big)}\, v_i \]

Here \(o_t\) is the attention output of token \(t\), \(q_t\) is its query, \(k_i, v_i\) are the key and value of token \(i\), and \(d_h\) is the head dimension. Only \(q_t\) appears in the formula, while all of \(k_1,\dots,k_t\) and \(v_1,\dots,v_t\) are needed: the first \(t-1\) come from the cache, and \(k_t, v_t\) are newly computed at this step and appended to the cache.

(2) Compute with and without the KV cache.

Let the model have \(N\) parameters and the total generated length be \(n\):

Without the KV cache With the KV cache
Linear-layer and FFN compute at step \(t\) About \(2Nt\) (the whole prefix is recomputed) About \(2N\) (only the new token)
Attention at step \(t\) All pairs among \(t\) tokens, \(O(t^2)\) The new token against \(t\) past tokens, \(O(t)\)
Total linear-layer compute for \(n\) tokens About \(Nn^2\) About \(2Nn\)
Extra memory None Proportional to sequence length (see 1.2)

The KV cache thus removes the repeated linear-layer computation that grows quadratically with length; but each step still reads and scans the K and V of the whole history, so the time of each decode step still grows linearly with context length.

(3) With RoPE, the cache stores keys after rotation.

With RoPE, each key has already been rotated according to its absolute position before it is written to the cache. Since each token's position does not change during generation, the cached keys remain valid. This also means that the same text at a different position has different K, so it cannot be reused directly (see 1.4).

Follow-up questions

Follow-up 1: Does using the KV cache change the model's output?

Not mathematically, but numerically there can be tiny differences. With and without the cache, the same function is computed, but the two use different kernels and different orders of floating-point operations, so the results differ slightly; the same happens when the composition of the batch changes. Such differences occasionally change the highest-probability token under greedy decoding, sending the rest of the generation down a different path. In RL training, this is part of why the probabilities computed by the inference engine and the training engine do not match exactly (see Chapter 8 of the "LLM Training Pipeline" direction).

Follow-up 2: Is the KV cache needed during training?

Not for ordinary training. During training the full sequence is known, and thanks to the causal mask a single forward pass computes the outputs of all positions in parallel; there is no step-by-step generation, so there is no history to reuse. Rollouts in RL training, however, are essentially generation, so they are usually handed to an inference engine with KV cache management such as vLLM.

Follow-up 3: Can the KV cache be shared across requests?

Not by default: each sequence has its own KV cache; only parts with identical prefixes can be shared. Different requests have different content, so their K and V naturally differ. But if several requests begin with exactly the same token sequence, for example a shared system prompt, that part of the KV cache is identical and can be stored only once; this is block sharing in PagedAttention and prefix caching (see 1.3 and 1.4).

Common mistakes

  • Do not say that the KV cache is an approximation: The causal mask guarantees that past K and V never change, so cached results are identical to recomputed ones.
  • Do not say that the KV cache makes attention \(O(1)\) per step: It removes the repeated computation of past K and V, but the new token still attends over the whole history, and the bytes read per step grow linearly with context length.
  • Do not say that the KV cache saves memory: It trades memory for compute, and it is in fact one of the largest memory costs in inference.
  • Do not say that caching Q would speed things up further: The queries of past tokens are never used again in any later step.

1.2 How much memory does the KV cache take, and how do you calculate it? ★★

One-sentence answer

The size of the KV cache is 2 × number of layers × number of KV heads × head dimension × sequence length × batch size × bytes per element, where the 2 stands for one copy each of K and V. For example, Llama 3 8B (32 layers, 8 KV heads, head dimension 128, bf16) needs about 128 KB per token, so one 8K-token sequence takes about 1 GB. It grows linearly with sequence length and batch size, while the size of the weights is fixed, so with long contexts or large batches the KV cache exceeds the weights and becomes the main factor determining concurrency and context length.

I will address three aspects: where the formula comes from, a concrete example, and why it becomes the memory bottleneck.

(1) The formula comes from "each token, at each layer, stores one key vector and one value vector for each KV head".

\[ M_{\text{KV}} = 2 \times L \times n_{kv} \times d_h \times s \times b \times \text{bytes} \]

Here \(L\) is the number of layers, \(n_{kv}\) the number of KV heads, \(d_h\) the dimension of each head, \(s\) the sequence length (the prompt plus the tokens generated so far), \(b\) the batch size, and bytes the number of bytes per element (2 for bf16, 1 for FP8); the factor 2 stands for one copy each of K and V. Note that the formula uses the number of KV heads, not the number of query heads: in standard multi-head attention (MHA) the two are equal, whereas GQA lets several query heads share one set of K and V, so \(n_{kv}\) is much smaller. The formula can be understood in two parts: \(2 L n_{kv} d_h \times \text{bytes}\) is the KV cache per token, determined by the model architecture; \(s \times b\) is the total number of tokens cached in the system, determined by the load.

(2) For Llama 3 8B, the KV cache is about 128 KB per token, so one 8K sequence takes about 1 GB.

Llama 3 8B has 32 layers, 8 KV heads (paired with 32 query heads) and a head dimension of 128, stored in bf16. Plugging into the formula, the KV cache per token is \(2\times32\times8\times128\times2\) bytes, i.e. 128 KB; one 8K-token sequence needs about 1 GB, and one 128K-token sequence needs about 16 GB, already comparable to the model's roughly 16 GB of bf16 weights. If it used MHA (32 KV heads), all of these numbers would be multiplied by 4.

(3) The weights are fixed in size, but the KV cache grows linearly with sequence length and concurrency, so it becomes the main bottleneck at long contexts.

Memory at inference time consists mainly of the weights and the KV cache; activations take only a small share, because they need not be kept for backpropagation. The size of the weights does not depend on the load, whereas the KV cache is proportional to "sequence length × batch size", so with long contexts or high concurrency the KV cache exceeds the weights. For example, Llama 3 70B has about 140 GB of bf16 weights and about 320 KB of KV cache per token, so serving four 128K-token sequences at once needs about 160 GB of KV cache. This has two direct consequences:

  • It determines concurrency, and hence throughput: The system can serve at most as many concurrent requests as the KV cache that fits in the memory left after the weights; if the batch cannot be large, the weight reads in decode cannot be amortized well (see Chapter 0).
  • It determines the supported context length and the decode speed: The KV cache of a single sequence must fit; moreover, every decode step reads the entire KV cache, so the longer the context, the slower each token is generated.

In summary: to estimate the KV cache, first compute the per-token size \(2Ln_{kv}d_h\times\text{bytes}\), then multiply by the total number of cached tokens; the weights are fixed in size while the KV cache grows with the load, which is exactly why inference systems invest so much effort in managing and compressing the KV cache (see 1.3 and 1.5).

Going deeper: the KV cache of common models, and how much concurrency one GPU can hold

(1) The KV cache per token of a few common models (16-bit precision; KB and GB use powers of 1024).

Model Attention type Layers Elements cached per token per layer KV cache per token
Llama 2 7B MHA, 32 KV heads 32 \(2\times32\times128 = 8192\) 512 KB
Llama 3 8B GQA, 8 KV heads 32 \(2\times8\times128 = 2048\) 128 KB
Llama 3 70B GQA, 8 KV heads 80 \(2\times8\times128 = 2048\) 320 KB
DeepSeek-V3 MLA, caches a compressed vector 61 \(512 + 64 = 576\) About 69 KB

DeepSeek-V3 caches only a 512-dimensional compressed vector and a 64-dimensional position-dependent key per layer (see Chapter 2 of the "Model Architecture" direction for how MLA works), so despite its 671B total parameters, its KV cache per token is only about one fifth of Llama 3 70B's.

(2) How much concurrency an 80 GB GPU can hold.

Take Llama 3 8B: subtract about 16 GB for the weights, reserve some for activations and other overhead, and suppose about 60 GB remain for the KV cache. At 128 KB per token, this caches about 490,000 tokens, i.e. about 120 sequences of 4K tokens, or fewer than four sequences of 128K tokens. With the same memory, a 32× longer context cuts concurrency to about 1/32.

(3) How the KV cache is split under tensor parallelism.

Tensor parallelism usually splits by attention head, and each GPU stores only the KV heads it is responsible for, so the KV cache is also divided evenly across the GPUs. But if the parallel degree exceeds the number of KV heads (for example, 8 KV heads with 16-way tensor parallelism), the KV heads must be replicated across GPUs, and this part of memory no longer shrinks as the parallel degree grows.

Follow-up questions

Follow-up 1: Where does the memory go at inference time, compared with training?

At inference time it goes mainly to the weights and the KV cache; during training it goes mainly to model states and activations. During training, each parameter needs its weight, gradient, fp32 master weight and Adam states, about 16 bytes, and the forward activations must be kept for backpropagation (see Chapter 3 of the "LLM Training Pipeline" direction); at inference time, bf16 weights need only 2 bytes per parameter, there are no gradients or optimizer states, and activations are discarded after use, but there is the KV cache, which grows with the load.

Follow-up 2: Why does the formula use the number of KV heads rather than query heads? How much does GQA save?

Because only K and V are cached, and GQA reduces exactly the number of K and V heads. Queries are used only at the current step and are not cached (see 1.1), so the number of query heads does not affect the size of the KV cache. GQA lets each group of query heads share one set of K and V; for example, with 32 query heads and 8 KV heads the KV cache is 1/4 of MHA's, while the computation on the query side stays essentially the same.

Follow-up 3: As the context gets longer, what gets worse besides memory?

The bytes read per decode step and the compute of prefill both increase. Every decode step reads the entire KV cache, so the bytes read are proportional to the context length; for example, at a 128K context, the KV cache Llama 3 8B reads per step (about 16 GB) is already comparable to the weights, so the time per generated token roughly doubles. The attention compute in prefill grows quadratically with length, so TTFT rises rapidly.

Common mistakes

  • Do not forget the factor of 2: One copy each of K and V is stored.
  • Do not use the number of query heads instead of KV heads: For a model with GQA, this overestimates the size several times over.
  • Do not say that the KV cache depends only on model size: It is proportional to sequence length and batch size, which are set by the load.
  • Do not assume that quantizing the weights also shrinks the KV cache: The KV cache is computed at runtime and must be quantized separately (see 1.5).

1.3 What problem does PagedAttention solve? ★★

One-sentence answer

PagedAttention (Kwon et al. 2023, vLLM) solves the problem of wasted KV cache memory: earlier systems reserved one contiguous chunk of memory per request sized for the maximum length, causing reservation waste, internal fragmentation and external fragmentation, so that only 20%–38% of KV cache memory actually stored token states. Borrowing virtual-memory paging from operating systems, it splits the KV cache into fixed-size blocks that are allocated on demand and need not be contiguous, with a block table recording the mapping, which brings the waste down to a very low level, lets the same memory hold a larger batch, and allows multiple sequences to share blocks.

Figure
The PagedAttention block table: logically contiguous KV blocks are mapped to non-contiguous physical blocks in GPU memory (Kwon et al. 2023, Figure 6)

I will address three aspects: the problem with the traditional approach, how PagedAttention works, and the benefits and costs it brings.

(1) The problem: each request's output length is unknown in advance, so reserving contiguous memory for the maximum length wastes a great deal.

In a serving system, most of the memory left after the weights holds the KV cache, and the number of requests whose KV cache fits determines how large the batch can be (see 1.2). The difficulty is that how many tokens a request will eventually generate is not known in advance. Earlier systems pre-allocated one contiguous chunk of memory per request, sized for the maximum possible length, which wastes memory in three ways:

  • Reservation waste: A request that will eventually generate 500 tokens holds all 500 slots from the start; until generation gets there, those slots sit empty, and no other request can use them.
  • Internal fragmentation: Space is reserved for the maximum length (say 2,048), but only 100 tokens are actually generated, and the rest of the space is wasted.
  • External fragmentation: After contiguous chunks of different sizes are repeatedly allocated and freed, memory is left with many small holes that add up to a lot but cannot be combined into one whole chunk.

Kwon et al. (2023) measured that in the systems of the time, only 20.4%–38.2% of KV cache memory was actually used to store token states.

(2) How it works: like OS paging, it splits the KV cache into fixed-size blocks, allocates them on demand, and addresses them through a block table.

PagedAttention splits each sequence's KV cache into fixed-size blocks (by default, each vLLM block holds 16 tokens) that can live anywhere in GPU memory, with no need to be contiguous. Each sequence keeps a block table recording which physical block holds each logical block, just like a page table in an operating system. During generation, a new physical block is allocated only when the current last block is full, so memory usage grows with the sequence's actual length instead of being fully reserved for the maximum length from the start. Correspondingly, the attention kernel is rewritten to read K and V from non-contiguous locations by following the block table.

(3) The benefits are that waste nearly disappears, the batch grows, and sharing and preemption become possible; the cost is a small overhead from indirect addressing.

Because blocks are allocated on demand and need not be contiguous, reservation waste and external fragmentation disappear, and internal fragmentation is limited to each sequence's last, partly filled block; the vLLM team reports waste below 4%. The saved memory holds more requests, so the batch grows; the paper reports 2–4× higher throughput than systems such as FasterTransformer and Orca at the same latency. In addition, paging brings two new capabilities:

  • Sharing: Several sequences can point to the same physical block, managed by reference counts. For example, when sampling several answers to the same prompt, the prompt's KV cache is stored only once; different beams in beam search can also share their prefix (see Chapter 2). When a sequence needs to modify a shared block, it first makes its own copy and then writes to it (copy-on-write). This is also the foundation of prefix caching (see 1.4).
  • Preemption: When memory runs short, some requests' blocks can be swapped out to CPU memory, or simply dropped and recomputed later (preemption), freeing space for other requests.

The cost is that the kernel must address memory indirectly through the block table, which is slightly more complex than reading contiguous memory, but the overhead is small compared with the memory saved. PagedAttention works hand in hand with continuous batching (which lets requests join and leave the batch at every step; see Chapter 3), and together they form the foundation of modern inference engines.

In summary: the essence of PagedAttention is applying the operating system's virtual-memory paging to the KV cache, using small blocks allocated on demand to eliminate fragmentation and reservation waste, so that the same memory holds a larger batch.

Going deeper: a diagram, the choice of block size, and the gains from sharing

(1) An illustration of the block table.

Request A, block size = 4 tokens
Logical blocks:   [The cat sat on] [the mat and ...]
Block table:      logical 0 → physical 7,   logical 1 → physical 2
Physical memory:  [ 0 ][ 1 ][A:1][ 3 ][B:0][ 5 ][ 6 ][A:0] ...

Request A's two logical blocks live in physical blocks 7 and 2, with blocks of other requests (such as B) in between.

(2) The choice of block size.

The smaller the block, the less space is wasted in the last block and the finer the granularity of sharing; but the block table gets longer, and the kernel's memory accesses become more scattered and less efficient. Larger blocks have the opposite properties. vLLM uses 16 tokens by default as a compromise between the two.

(3) The gains from sharing.

The paper reports, across different datasets, that parallel sampling saves about 6%–30% of KV cache memory by sharing the prompt, and beam search saves about 38%–66% by sharing prefixes. Beam search gains more because, beyond the prompt, different beams also share long stretches of already generated prefixes.

(4) An alternative that does not rewrite the kernel.

vAttention (Prabhu et al. 2024) uses the GPU's virtual-memory mechanism to keep the KV cache contiguous in virtual address space while mapping physical memory on demand, so unmodified attention kernels can be used directly. This shows that the core value of PagedAttention lies in on-demand allocation, and "paging inside the kernel" is just one way to implement it.

Follow-up questions

Follow-up 1: How do PagedAttention and FlashAttention differ?

They solve problems at different levels and can be used together. FlashAttention optimizes how attention is computed: it splits the computation into tiles processed in on-chip SRAM, avoiding writing the \(s\times s\) attention matrix back to GPU memory and thereby reducing memory traffic (see Chapter 2 of the "Model Architecture" direction). PagedAttention optimizes how the KV cache is stored, i.e. how memory is allocated and managed. Mainstream attention kernels now support reading a paged KV cache directly, and inference engines use both at the same time.

Follow-up 2: What does PagedAttention do when memory runs out?

It temporarily frees some requests' memory through preemption. vLLM selects some requests (following first-come-first-served, it preempts the most recently arrived requests first) and swaps all of their blocks out to CPU memory or simply drops them, then swaps them back or recomputes them once memory frees up. A sequence's blocks are either all kept or all evicted, because every decode step of that sequence needs its complete history.

Follow-up 3: Does PagedAttention make a single request faster?

Generally not; what it improves is throughput. Its benefit comes from reducing wasted memory, so that the same memory holds more concurrent requests and system throughput rises; for a single request with ample memory, indirect addressing actually adds a small overhead.

Common mistakes

  • Do not confuse PagedAttention with FlashAttention: The former manages the memory allocation of the KV cache, while the latter optimizes the computation and memory traffic of attention.
  • Do not say that PagedAttention shrinks the KV cache itself: The amount of data cached per token is unchanged; what shrinks is the allocation waste.
  • Do not say that PagedAttention eliminates fragmentation completely: Each sequence's last, partly filled block still has internal fragmentation.

1.4 What is prefix caching? ★

One-sentence answer

Prefix caching keeps the KV cache of prompt prefixes that have already been computed, and when a new request begins with exactly the same token sequence, it reuses that cache directly and prefills only the part that differs. It works because the causal mask makes each token's K and V depend only on itself and the tokens before it, so an identical prefix always yields an identical KV cache. It greatly reduces TTFT and compute in scenarios with long shared prefixes (system prompts, multi-turn chat, agents, few-shot examples), but it requires an exact token-by-token match starting from the very first token.

I will address three aspects: why it works, how it is implemented, and its benefits and limitations.

(1) The principle: an identical prefix always produces an identical KV cache, so there is no need to recompute it.

Many requests share the same beginning: an application's system prompt, few-shot examples, the history of a multi-turn chat, an agent's tool descriptions, or several questions about the same long document. Because of the causal mask, a token's K and V at every layer depend only on itself and the tokens before it (see 1.1), so prefixes that are identical from the very first token produce identical KV caches. Prefix caching keeps these computed KV caches: when a new request arrives, it first finds the longest common prefix between the request and the cached content, reuses the KV cache for that part directly, and prefills only the remaining tokens.

(2) Implementation: at the block level, reusable prefixes are found with hashes or a radix tree.

  • Hash-based block lookup: vLLM's automatic prefix caching builds on PagedAttention's blocks, computing a hash for each full block that is determined by the tokens of the block together with all the tokens before it; new requests look up reusable physical blocks by hash.
  • Radix-tree-based prefix matching: SGLang's RadixAttention (Zheng et al. 2023) organizes all cached token sequences in a radix tree, which quickly finds the longest common prefix.

When memory is tight, both evict caches that are no longer referenced using an LRU (least recently used) policy. In multi-replica deployments, requests must also be routed to the instance that already caches their prefix (cache-aware routing); otherwise, the more replicas there are, the lower the hit rate.

(3) Benefits and limitations: the longer the shared prefix, the larger the benefit, but the prefix must match exactly, token by token.

On the benefit side, when the shared prefix is long, both TTFT and prefill compute drop sharply. This is especially pronounced in agents and multi-turn chat: every turn carries an ever-longer history, and if each turn were prefilled from scratch, the cumulative compute would grow quadratically with the number of turns. This is also why API providers charge less for input tokens that hit the cache (prompt caching). However, a hit requires an exact token-by-token match starting from the very first token: any change in the prefix, such as putting the current time at the start of the system prompt, forces every KV after it to be recomputed; moreover, positional encodings such as RoPE make keys depend on position, so the same text at a different position has different KV and cannot be reused directly. In addition, prefix caching saves only prefill and does not speed up decode, and the cache itself occupies memory, competing for space with running requests. When designing prompts, therefore, put the fixed content first and the changing content last.

In summary: prefix caching extends the property "identical prefixes have identical KV caches" from within a single request to across different requests, trading a little memory for a large reduction in TTFT, on the condition that the prefix matches exactly, token by token.

Going deeper: high-benefit scenarios, how to organize prompts, and non-prefix reuse

(1) Common scenarios and where the benefit comes from.

Scenario Reused prefix Benefit
Many requests to the same application System prompt, few-shot examples Every request skips this part of prefill
Multi-turn chat The full history of previous turns Each turn prefills only the new content
Agents Tool descriptions and the trajectory of all previous steps With long trajectories, most of the prefill is skipped; the biggest impact on TTFT
Several questions about one document The long document itself The document is prefilled only once
Parallel sampling, RL rollouts The same prompt The prompt is computed only once when sampling several answers

(2) Organizing prompts so the cache hits more easily.

Put unchanging content (system prompt, tool definitions, documents) first, and content that changes each time (the user's question, timestamps, retrieval results) later; in multi-turn chat, only append at the end and never modify the history; keep the order and serialization of tool definitions fixed. A common problem in agent frameworks is that adding or removing tools dynamically each turn, or rewriting earlier context, invalidates all of the cache after that point.

(3) Non-prefix reuse.

In RAG, retrieved document chunks appear in the middle of the prompt, and both their positions and the preceding text vary, so strict prefix caching cannot reuse them. Work such as CacheBlend (Yao et al. 2024) tries to reuse the KV cache of such non-prefix chunks, recomputing only a small number of tokens to correct the cross-chunk attention, but this is an approximate method, and the output may differ slightly from full computation.

Follow-up questions

Follow-up 1: Why does putting a timestamp at the start of the system prompt break prefix caching?

Because a hit requires an exact match from the very first token, so every token after the timestamp must be recomputed. The timestamp differs every time, so each request diverges from the cache within its first few tokens; even if the following thousands of system-prompt tokens are identical, their K and V differ because the preceding text differs, and they cannot be reused. The fix is to move dynamic information such as timestamps to the end of the prompt.

Follow-up 2: How does prefix caching differ from the KV cache?

They store the same kind of data; the difference lies in the scope and lifetime of reuse. The KV cache is reused within a single request across decode steps and is freed when the request ends; prefix caching keeps the KV cache after the request ends so that other requests arriving later can reuse it, which also requires management mechanisms such as lookup, reference counting and eviction.

Follow-up 3: How does prefix caching differ from semantic caching?

Prefix caching reuses intermediate computation, whereas semantic caching reuses the final answer. A semantic cache encodes the user's question as a vector, and if a new question is similar enough to a past one, it returns the answer given back then, skipping the model entirely; it saves the most, but it is approximate and may treat different questions as the same. Prefix caching is exact: the model's output is identical to that without the cache, and only the repeated prefill is skipped.

Common mistakes

  • Do not say that similar content is enough for a hit: The match must be exact, token by token, starting from the very first token.
  • Do not say that prefix caching speeds up decode: It skips only prefill, reducing TTFT and compute.
  • Do not say that the same text can be reused at any position: Positional encoding makes keys depend on position, and different preceding text gives different K and V.

1.5 What methods can reduce the KV cache? ★★

One-sentence answer

The KV cache can be compressed term by term following its formula: in the model architecture, GQA/MQA reduce the number of KV heads, MLA compresses K and V into a low-dimensional vector, and sliding window attention caps the number of tokens cached per layer; without changing the model, KV cache quantization reduces the bytes per element, eviction and compression methods (such as H2O, StreamingLLM and SnapKV) keep only important tokens, and offloading moves KV cache that is not currently needed to CPU memory or SSD. Architectural methods must be decided at training time, while inference-time methods can be applied directly, but eviction methods are lossy.

I will address four aspects: which terms of the formula can be compressed, architectural methods, methods usable directly at inference time, and the trade-offs among them.

(1) Starting from the formula, each term corresponds to a family of compression methods.

The size of the KV cache is \(2 \times L \times n_{kv} \times d_h \times s \times b \times \text{bytes}\) (see 1.2). Here \(n_{kv}\times d_h\) is the dimension cached per token per layer, which can be reduced by changing the attention architecture; \(s\) is the number of tokens cached per layer, which can be reduced by limiting the window or discarding unimportant tokens; bytes is the number of bytes per element, which can be reduced by quantization. Moreover, even without reducing the total, parts that are not currently needed can be moved out of GPU memory. The batch size \(b\) is set by the load and is usually not a target of compression.

(2) Architectural methods must be decided at training time, but they barely hurt quality and have become standard in mainstream models.

  • GQA and MQA: Several query heads share one set of K and V, directly reducing \(n_{kv}\); for example, with 32 query heads sharing 8 KV heads, the KV cache becomes 1/4 of MHA's (Ainslie et al. 2023; Shazeer 2019).
  • MLA: Each token's K and V are compressed into a low-dimensional latent vector, only this vector is cached, and it is expanded back when used; DeepSeek-V2 reports a 93.3% smaller KV cache than DeepSeek 67B (DeepSeek-AI 2024).
  • Sliding window attention: Each token attends only to the most recent \(W\) tokens, so these layers cache at most \(W\) tokens, no longer growing with the context; models such as Gemma 2/3 interleave sliding-window layers with global attention layers (for example, Gemma 3 pairs every 5 local layers with 1 global layer), and the global layers keep the ability to retrieve over long distances.

The principles and trade-offs of these methods are covered in Chapter 2 of the "Model Architecture" direction.

(3) Three families of methods can be applied directly at inference time, without retraining.

  • KV cache quantization: Storing the KV cache in FP8 or INT8 halves both its memory and the bytes read per step, with essentially no quality loss, and mainstream inference frameworks all support it. Going down to 4 or 2 bits requires handling K and V separately according to their different distributions; for example, KIVI (Liu et al. 2024) quantizes keys per channel and values per token. Note that quantizing only the weights does not shrink the KV cache (see Chapter 3 for weight quantization).
  • Eviction and compression: Only some important tokens are kept, and the K and V of the remaining tokens are discarded. H2O (Zhang et al. 2023) keeps the "heavy hitter" tokens with the highest cumulative attention scores plus the most recent tokens; StreamingLLM (Xiao et al. 2023) keeps only the first few tokens (which absorb a large share of the attention scores and are called attention sinks) plus a window of recent tokens, allowing the model to generate stably over an infinitely long input stream; SnapKV (Li et al. 2024) uses the attention pattern of a small window of tokens at the end of the prompt to select the important K and V in the prompt to keep.
  • Offloading: KV cache that is not currently needed is moved to CPU memory or even SSD and fetched back when needed, for example to keep a conversation's cache between turns of a multi-turn chat. It loses no information, but it is limited by the bandwidth and latency of PCIe or the network; Mooncake (Qin et al. 2024) organizes CPU memory and SSDs into a distributed KV cache pool.

(4) The trade-offs among these methods depend mainly on whether training is needed and whether they are lossy.

Architectural methods must be introduced at training time (or through continued training), but once adopted they deliver several-fold compression with almost no loss of quality, reducing both memory usage and the bytes read in decode. FP8 quantization is nearly lossless and simple to implement, making it the most common inference-time technique; lower-bit quantization requires more careful design. Eviction and compression can achieve large compression ratios, but they are lossy: discarded tokens can never be recovered, and whether a token is important is often known only later, so on tasks that require precisely retrieving a detail from a long context, quality can drop noticeably. Offloading loses no information, but the latency of fetching data back affects TTFT or TPOT, so it suits scenarios with gaps between interactions, such as multi-turn chat and agents.

In summary: to reduce the KV cache, work through the formula term by term: fewer heads and dimensions through architecture, fewer tokens through windows and eviction, fewer bytes through quantization, and a different storage location through offloading; in practice these are usually combined, for example GQA plus an FP8 KV cache, together with prefix caching and offloading.

Going deeper: a summary of methods, why K and V are quantized differently, compression for reasoning models, and hybrid architectures

(1) Summary of methods.

Method Which term of the formula it reduces Training needed? Lossy? Representative work
GQA / MQA \(n_{kv}\) Yes (an MHA model can be converted by continued training) GQA is close to MHA; MQA loses slightly more Llama 3, Mistral
MLA \(n_{kv}\times d_h\) Yes Reported to match MHA DeepSeek-V2/V3, Kimi K2
Sliding window \(s\) in local layers Yes Information outside the window passes only indirectly Mistral 7B, Gemma 2/3
KV quantization bytes No FP8 is essentially lossless; lower bits need careful design KIVI, KVQuant
Eviction and compression \(s\) No Lossy; discarded tokens cannot be recovered H2O, StreamingLLM, SnapKV
Offloading Does not reduce the total, only changes where it is stored No Lossless, but with transfer latency Mooncake, LMCache

(2) Why K and V are quantized differently.

KIVI (Liu et al. 2024) found that keys have channel-wise outliers, i.e. some dimensions are large for every token, so keys should be quantized per channel, giving each channel its own scale; values have no such pattern, and the attention output is a token-weighted sum of values, so it is better to keep errors isolated per token, and values are quantized per token. The most recent tokens are usually kept in full precision, since they matter most for the current generation. KVQuant (Hooper et al. 2024) further found that quantizing keys before the RoPE rotation works better, because the position-dependent rotation scrambles the otherwise fairly stable channel-wise outlier pattern.

(3) Compression for reasoning models.

Early eviction methods mainly targeted the "long prompt, short output" setting and compressed the KV cache of the prompt. Reasoning models are the opposite: their KV cache comes mostly from chains of thought of thousands or tens of thousands of tokens. Work such as R-KV (Cai et al. 2025) compresses the KV cache during decoding, considering both the importance and the redundancy of tokens, since long chains of thought contain much repeated content.

(4) Hybrid architectures make the cache of most layers fixed in size.

Linear attention and state-space models compress the history into a fixed-size state that does not grow with the context. Recent hybrid architectures keep only a few full-attention layers and use linear attention in the rest; for example, Qwen3-Next and Kimi Linear both interleave them at a 3:1 ratio, and Kimi Linear reports up to a 75% smaller KV cache at a 1M context (Kimi Team 2025). The cost is that a fixed-size state is a lossy compression of the history, so precise retrieval still relies on the remaining full-attention layers (see Chapter 2 of the "Model Architecture" direction).

Follow-up questions

Follow-up 1: How does sparse attention (such as DeepSeek's DSA) differ from KV eviction?

Eviction reduces storage, whereas sparse attention reduces the reads and compute of each step. Eviction methods permanently delete the K and V of some tokens: memory shrinks, but the information is lost for good. DeepSeek Sparse Attention in DeepSeek-V3.2 (DeepSeek-AI 2025) instead keeps the full KV cache; each query first uses a lightweight indexer to score all past tokens and then attends only to the top-scoring subset (for example, 2,048 tokens); Quest (Tang et al. 2024) follows a similar idea of query-dependent dynamic selection. Such methods lose no information permanently, but they do not reduce the storage of the KV cache, so they are often combined with offloading.

Follow-up 2: Can StreamingLLM let a model remember an infinitely long context?

No; it guarantees stable generation, not memory. StreamingLLM keeps only the first few tokens and a window of recent tokens; all tokens in between are discarded, and the model can no longer recall them. The problem it solves is that ordinary sliding windows collapse in quality once the first tokens are pushed out of the cache; keeping those few initial tokens lets the model generate stably over an infinitely long input stream, but its effective context is still just the window.

Follow-up 3: Can quantizing only the weights reduce the KV cache?

No. The KV cache is computed at runtime from activations and is unrelated to the storage precision of the weights, so it must be quantized separately. The two are complementary: weight quantization reduces the bytes of weights read per step, while KV cache quantization reduces the memory and reads of the KV; the longer the context and the larger the batch, the greater the gain from KV cache quantization.

Common mistakes

  • Do not say that StreamingLLM extends the model's context length or memory: It discards the tokens in between and only guarantees stable generation over long input streams.
  • Do not say that eviction methods are lossless: Discarded K and V cannot be recovered, and quality can drop noticeably on tasks that require precise retrieval over a long context.
  • Do not say that weight quantization also compresses the KV cache: The KV cache must be quantized separately.
  • Do not say that GQA mainly reduces compute: GQA mainly reduces the memory and reads of the KV cache; the parameter count and compute change very little.