The KV Cache: Keep the Keys, Skip the Redo
Naive generation repeatedly processes an unchanged prefix. Causality makes its previous computations reusable. Cache keys and values, then distinguish prompt processing from incremental decoding.
#Section 58Generation Without a Cache
Naive generation reruns the entire prefix after each new token. That recomputes every old position even though the causal model cannot use the new suffix to change its past.
The causal mask makes each position depend only on its prefix. Appending a later token leaves that dependency unchanged, so earlier keys and values can be reused under the same computation settings.
#Section 59The Cache: Compute One Row, Append, Look Up the Rest
Save each token’s keys and values in every layer when first computed, then reuse them. This saved store is the KV cache. At each generation step, only the newest token goes through the model. In each layer, it computes its own query, key and value; appends its key and value to that layer’s cache; and then uses its query to score against all the cached keys, old and new, and to blend all the cached values.
k_cache = torch.cat([k_cache, k_new], dim=2) # (B, H, T_old + 1, d_head)
v_cache = torch.cat([v_cache, v_new], dim=2)
att = softmax(q_new @ k_cache.transpose(-2, -1) / 8.0, dim=-1) # (B, H, 1, T_old + 1)
out = att @ v_cache # (B, H, 1, d_head)Each step computes new keys and values only for the appended token. Its query still compares with the growing history, so caching removes recomputation rather than making attention free.
This is the single biggest reason chat models answer at a usable speed. Every production inference system uses it.
#Section 60Why K and V, but Not Q?
If caching keys and values helps, why not cache queries too? Because nobody ever needs an old query again.
Look at the attention weight grid during generation. The new token’s row is the only one we compute: its query against every key. The rows above it belong to old queries. Each old query was used exactly once, at the step when its token was new, to compute that token’s output. The causal mask guarantees no later step will ever need that row again, because outputs for old positions never change. Keys and values are different: every future query will be scored against every old key and will blend every old value. So keys and values are reused at every step from now on, and queries are not. That is why it is called a KV cache and not a QKV cache.
#Section 61The Cost: Memory
Speed is not free. The cache holds a key and a value for every token, in every layer, for every key/value head. Counting it is pure multiplication:
The cache holds keys and values for each layer, KV head, and retained position in each sequence. More history or a larger batch needs more storage.
Long contexts and concurrent conversations can make cache memory a major deployment constraint, even when the model weights fit.
That number, not the size of the weights, is often what limits how many users a server can handle at once and how long a context it can offer.
Sharing keys and values shrinks the cache
GQA shares keys and values across query heads. It reduces retained history and its memory traffic while preserving separate queries.
#Section 62Prefill, Then Decode
Generation has two phases.
First, prefill. The whole prompt is processed in one forward pass, all tokens in parallel, exactly like a training step without the backward pass. This fills the cache for every prompt token. A GPU loves prefill: each weight it loads from memory is used for every prompt token, so it does a lot of arithmetic per byte moved. Prefill is compute-bound: limited by how fast the GPU can multiply.
Decode processes the new position against cached history. At small batches, reading model weights and the cache can dominate arithmetic, making the workload memory-bound.
Batching can reuse a weight read across several conversations. A smaller cache helps most when history reads are a significant part of the bottleneck.
Sharp edges of the KV cache
Editing an earlier token invalidates everything after it. The cache assumes the past never changes. If a user edits a word in the middle of a conversation, every cached key and value after that point is wrong. Truncate the cache at the edit and recompute from there.
The position offset. A new token's position is the number of tokens already in the cache, not 0. Get this wrong with RoPE (Part V) and the new token is rotated as if it were at the start of the text. Pass the cache length as the position offset.
Ragged batches waste memory. Conversations in a batch have different lengths, and allocating every cache for the longest one wastes most of the memory. Paged attention, introduced with the vLLM system by Woosuk Kwon and colleagues in 2023, stores the cache in fixed-size blocks, like pages of memory in an operating system, and allocates them only as needed.
Evicting old entries breaks sinks. To cap memory on very long chats you can drop old cache entries. But dropping the first few tokens breaks the attention-sink heads of Section 50. Keep the first few tokens plus a recent window.
Quantized caches. Storing the cache in 8-bit or 4-bit numbers halves or quarters its memory. The quality loss is usually small but tends to appear first on long-context tasks, so measure there.
Shared prefixes can share a cache. Many requests start with the same long system prompt. Its cache can be computed once and reused for every request that starts the same way. This is what "prompt caching" in commercial APIs does.