Search

Search papers and lessons

KV Cache

Level 3 · 10 min read

A KV cache stores the keys and values of past tokens so each new token needs only one fresh projection, at the cost of memory that grows with sequence length.

On this page

  • Colour = topic mix
  • Calculus
  • Probability
  • Neural network basics
  • Linear algebra
  • Architectures
  • Discrete math
  • Sign in to see your progress

TL;DR

A KV cache keeps the keys and values that a transformer has already computed for earlier tokens. When the model generates the next token, it only computes a query, key and value for that one new token, then attends over the stored keys and values. Without the cache, every generated token would redo the work for the whole prefix. The price is memory: the cache grows with every token, in every layer.

Where you'll see it: inside every LLM serving stack (vLLM, TensorRT-LLM, llama.cpp and similar), where it decides how many requests fit on a GPU and how long a context can be.

Intuition

Notes instead of re-reading

Imagine a student writing an essay from a long textbook, one sentence at a time. A careless student re-reads the whole book before every sentence. A sensible one takes notes the first time through and, for each new sentence, only reads the new source material and checks the notes. The notes are the cache. They hold work that was already done and that will not change.

An Autoregressive Model generates one token at a time, and each token depends on all earlier tokens. Those earlier tokens never change once written, so the attention inputs derived from them never change either. Recomputing them at every step is pure waste. The KV cache is the notebook for a transformer.

Why keys and values, and not queries? A new token needs its own query, because the query asks what this token is looking for. But every past token's key and value are fixed numbers that other tokens will read. The query of a past token is only needed when that token was itself the newest one, so it can be thrown away. Only the keys and values are worth keeping.

050001000015000200002500030000051015tokens in the sequencecache size (GiB per sequence)
  • multi-head, 32 KV heads
  • grouped, 8 KV heads
The cache grows in a straight line with length. Sharing key and value heads (the dashed line) cuts the slope by a factor of four for this example.

The math

Attention at one step

Recall attention for a sequence. Each token tt has an input vector xt\mathbf{x}_t, and the layer computes

qt=WQxt,kt=WKxt,vt=WVxt,\mathbf{q}_t = W_Q \mathbf{x}_t, \qquad \mathbf{k}_t = W_K \mathbf{x}_t, \qquad \mathbf{v}_t = W_V \mathbf{x}_t,

where WQW_Q, WKW_K and WVW_V are learned matrices. The symbol dd is the width of a key, and the output for token tt is

ot=softmax ⁣(qtKt⊤d)Vt.\mathbf{o}_t = \mathrm{softmax}\!\left(\frac{\mathbf{q}_t K_t^\top}{\sqrt{d}}\right) V_t.

Here KtK_t is the matrix whose rows are k1,…,kt\mathbf{k}_1, \dots, \mathbf{k}_t, and VtV_t has rows v1,…,vt\mathbf{v}_1, \dots, \mathbf{v}_t. The softmax gives one weight per past position, and the output is the weighted average of the values.

The cached update

Notice that KtK_t and VtV_t are just Kt−1K_{t-1} and Vt−1V_{t-1} with one extra row. So the cache update is

Kt=[Kt−1kt⊤],Vt=[Vt−1vt⊤].K_t = \begin{bmatrix} K_{t-1} \\ \mathbf{k}_t^\top \end{bmatrix}, \qquad V_t = \begin{bmatrix} V_{t-1} \\ \mathbf{v}_t^\top \end{bmatrix}.

At each step the model computes one qt\mathbf{q}_t, one kt\mathbf{k}_t and one vt\mathbf{v}_t, appends the last two to the cache, and attends. Nothing already in the cache is recomputed.

The cost, with and without the cache

Let the sequence grow to nn tokens. Count how many key-and-value projections (the products WKxW_K \mathbf{x} and WVxW_V \mathbf{x}) are computed.

  • Without a cache, step tt projects all tt past tokens again. The total is 1+2+⋯+n=n(n+1)21 + 2 + \dots + n = \frac{n(n+1)}{2}, which grows as n2n^2.
  • With a cache, step tt projects only token tt. The total is nn.

The attention scores themselves still cost O(t⋅d)O(t \cdot d) at step tt, so the total attention work is quadratic either way. What the cache removes is the repeated projection of past tokens, which would otherwise multiply the per-token work by the length of the prefix.

The memory cost

For each token, each layer stores one key and one value vector. If the model has LL layers, a model width of dmodeld_{\text{model}}, and each stored number takes bb bytes (2 for 16-bit floats), then one token costs

bytes per token=2⋅L⋅dmodel⋅b.\text{bytes per token} = 2 \cdot L \cdot d_{\text{model}} \cdot b.

The factor 2 is for keys and values. For a sequence of nn tokens, the cache is nn times this. The size is linear in nn and independent of how many tokens you generate later, so it is set by how long the context gets.

Worked examples

Example
A three-token cache with scalar keys and values

Use a single attention head with width d=1d = 1, so the scale d\sqrt{d} is 1. Keys and values are plain numbers. Token 1 has key 00 and value 22, token 2 has key 11 and value 44, token 3 has key 22 and value 66.

  1. Step 1. The cache holds only token 1: keys [0][0], values [2][2]. The query is 00, so the single weight is 11 and the output is 22.
  2. Step 2. Append token 2. The cache is keys [0,1][0, 1], values [2,4][2, 4]. Token 2 has query 11. Scores are [0⋅1,1⋅1]=[0,1][0 \cdot 1, 1 \cdot 1] = [0, 1].
  3. The softmax weights are e0/(e0+e1)≈0.2689e^0 / (e^0 + e^1) \approx 0.2689 and e1/(e0+e1)≈0.7311e^1 / (e^0 + e^1) \approx 0.7311.
  4. Output =0.2689⋅2+0.7311⋅4≈3.4621= 0.2689 \cdot 2 + 0.7311 \cdot 4 \approx 3.4621.
  5. Step 3. Append token 3. The cache is keys [0,1,2][0, 1, 2], values [2,4,6][2, 4, 6]. The query is 22, so the scores are [0,2,4][0, 2, 4].
  6. Weights are about 0.01590.0159, 0.11730.1173 and 0.86680.8668. Output =0.0159⋅2+0.1173⋅4+0.8668⋅6≈5.7019= 0.0159 \cdot 2 + 0.1173 \cdot 4 + 0.8668 \cdot 6 \approx 5.7019.

Interpretation: at step 3 the model computed one new key and one new value, 22 and 66. The entries 0,10, 1 and 2,42, 4 were read from the cache. The output is pulled most strongly towards the value 66 because the query 22 matches the newest key best.

Example
Cache size for a 7B-class model

Take a model with L=32L = 32 layers and width dmodel=4096d_{\text{model}} = 4096, stored in 16-bit floats (b=2b = 2), with one key and one value per model dimension. This is a typical configuration for a model of about seven billion parameters, and the numbers are illustrative rather than measured from a specific checkpoint.

  1. Bytes per token =2⋅32⋅4096⋅2=524,288= 2 \cdot 32 \cdot 4096 \cdot 2 = 524{,}288 bytes, which is 512 KiB.
  2. For a 4,096-token sequence: 4096⋅512 KiB=2 GiB4096 \cdot 512 \text{ KiB} = 2 \text{ GiB}.
  3. For a batch of 16 such sequences served together: 16⋅2 GiB=32 GiB16 \cdot 2 \text{ GiB} = 32 \text{ GiB}.
  4. The weights of the model itself are roughly 14 GB in 16-bit precision, which is smaller than this cache at batch 16.

Interpretation: at modest batch sizes and context lengths the cache can outgrow the model weights. That is why serving systems spend most of their effort on managing it. If the model shares key and value heads so that only 8 heads of width 128 are stored (grouped-query attention, see Grouped-Query Attention), the same 4,096-token sequence needs 512 MiB instead of 2 GiB.

Example
How many projections the cache saves

Generate n=1000n = 1000 tokens.

  1. Without a cache: 1000⋅10012=500,500\frac{1000 \cdot 1001}{2} = 500{,}500 key-and-value projections.
  2. With a cache: 10001000 projections.
  3. The cache does about 500 times less projection work here.

Interpretation: the saving grows with length, which is why the cache matters most for long generations. It does not change the output at all, only the cost.

Tradeoffs and failure modes

The cache is almost always worth it during generation. The practical question is how to keep its memory under control.

SituationProblemBetter choice
Long context (tens of thousands of tokens)The cache dominates GPU memoryShare key and value heads (Grouped-Query Attention), or cap the window (Sliding Window Attention)
Many concurrent requestsPreallocating the maximum length for each one wastes memoryAllocate the cache in small blocks on demand, as in PagedAttention
Many requests with the same system promptThe same prefix is cached again for each userReuse the cached prefix across requests
Training or scoring a fixed textNo generation step exists, and the whole sequence is processed in parallelDo not use a cache; use masked attention over the full sequence
Lower-quality output is acceptableCache entries use too much memoryQuantize the cache to 8-bit or lower, accepting a small error

Failure modes to watch for:

  • Out of memory. The cache is allocated per sequence and per layer. A request that asks for a longer output than planned can take a server down or force it to evict other requests.
  • Leaking between requests. If the cache is not cleared when a request ends, the next user's tokens can attend to the previous user's text. This is a real security bug, not just a wrong answer.
  • Position errors after truncation. If old entries are removed to make room, the remaining tokens must keep their original position information, or the model reads the wrong distances. Methods that drop entries therefore need care with Positional Encoding.
  • Stale results after editing. If the prompt in the middle changes, every cached entry after the change is invalid and must be recomputed.

History

The transformer paper of 2017 by Vaswani and colleagues described the decoder as attending over previously generated outputs. Because earlier tokens' keys and values do not change during generation, decoder implementations can store them rather than recompute them. The cache is an implementation technique rather than a result of one paper.

Noam Shazeer's 2019 note on multi-query attention showed that sharing one key and one value head across all query heads makes the cache much smaller, with a modest loss in quality. Ainslie and colleagues in 2023 proposed grouped-query attention as a middle path between one shared head and one head per query. Both target the same bottleneck: the memory the cache occupies during decoding.

In 2023 the vLLM project and its paper on PagedAttention (see Efficient Memory Management for LLM Serving with PagedAttention (vLLM)) applied operating-system ideas of paged memory to the cache. Storing the cache in fixed-size blocks avoids most of the waste from preallocating the maximum length for each request. Exact figures for memory waste and throughput gains depend on the workload, and are not repeated here.

Check yourself

QuestionWhy does the cache store keys and values but not queries?Show answer

A query is used once, by the token that produced it, to look up what that token needs at its own step. Keys and values of past tokens are read again by every later token, and they do not change once computed. Storing queries would save nothing, because no later step reads them.

QuestionA model has 24 layers and width 2048, stored in 16-bit floats. How many bytes does one token add to the cache?Show answer

Bytes per token =2⋅24⋅2048⋅2=196,608= 2 \cdot 24 \cdot 2048 \cdot 2 = 196{,}608 bytes. That is 192 KiB. The first factor 2 is for keys and values, and the last factor 2 is the number of bytes in a 16-bit float.

QuestionGenerating 500 tokens without a cache requires how many key-and-value projections, and with a cache how many?Show answer

Without a cache it is 500⋅5012=125,250\frac{500 \cdot 501}{2} = 125{,}250. With a cache it is 500, one per generated token.

QuestionWhy can a cache that is correct at the start of a conversation become wrong later?Show answer

If the text earlier in the context changes, for example when the prompt is edited or the middle of a conversation is removed, the keys and values computed from the old text no longer describe the new context. Every entry from the changed point onwards must be recomputed.

QuestionExplain why shrinking the cache can reduce the cost of serving a model even when the arithmetic stays the same.Show answer

Serving is often limited by memory rather than compute. The cache for each active sequence takes up GPU memory, and that memory limits how many sequences can run at once. A smaller cache lets more sequences share the same GPU, so the same hardware can serve more users, even though each attention step does the same arithmetic.

Sources