Highlights

Contents

Part XI
11

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.

YOU ARE HERE"raw text"tokenizerembeddings+ positionslearnedwavesRoPEDECODER BLOCK× NnormattentionQKVsoftmaxmaskheadsn × n+normMLP+residual streamKV cachefinal normLM headsoftmaxP(next)training: the loss sends a correction back to every weight

#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.

WITHOUT A CACHE: EVERY STEP RECOMPUTES K AND V FOR THE WHOLE PREFIXstep 1k, v1 computedstep 2k, vk, v2 computedstep 3k, vk, vk, v3 computedstep 4k, vk, vk, vk, v4 computedstep 5k, vk, vk, vk, vk, v5 computedstep 6k, vk, vk, vk, vk, vk, v6 computedThecatsatbec.itwasorange = workalready donelast steptotal: 1 + 2 + … + 6 = 21
Figure 1.79Generation without a cache. Each row is one step. Orange cells recompute keys and values that were already computed in the previous step; the waste forms a growing triangle.

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.

WITH A CACHE: COMPUTE THE NEW TOKEN’S q, k, v, APPEND k, v, LOOK UP THE RESTKV CACHE (ONE LAYER)k0 v0Thek1 v1catk2 v2satk3 v3bec.k4 v4itk5 v5was (new)"was"compute q5, k5, v5appendq5 scores against all six keysnothing old is recomputed;the shelf grows by one box per step
Figure 1.80Generation with a cache. The new token computes its own q, k and v, appends k and v to the shelf, and scores its query against every key on the shelf. Nothing old is recomputed.
Figure 1.81Hover a tab or use arrow keys. Cached prefix pages stay fixed while the continuation opens; the notebook is an analogy, not the cache layout. Open illustration
python
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.

K/V COMPUTATIONS TO GENERATE T TOKENS, PER LAYERtokens generatedk/v computationsno cache: 500,500cache: 1,00002505007501000T(T + 1)/2 versus T
Figure 1.82Total key/value computations to generate T tokens. Without a cache the count grows as T(T + 1)/2; with a cache it is a straight line.

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.

DURING GENERATION, ONLY THE NEWEST ROW OF THE WEIGHT GRID IS COMPUTEDTheThecatcatsatsatbec.bec.ititwaswasold queries: used once,never needed againnew query: needs every keyand value, old and newso we cache K and V, not Q
Figure 1.83The weight grid during generation. Only the newest row is computed. Old queries (grey rows) were used once and are never needed again; every key and value column is needed by the newest query.

#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:

cache bytes=2×L×Hkv×dhead×T×B×bytes per number\text{cache bytes} = 2 \times L \times H_{kv} \times d_{\text{head}} \times T \times B \times \text{bytes per number}

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.

KV CACHE SIZE = 2 × LAYERS × KV HEADS × HEAD SIZE × TOKENS × BATCH × BYTESFinch-19, 1,024 tokens16.0 MiBLlama 3 8B, 8,192 tokens1.0 GiBLlama 3 8B, 128k tokens16.0 GiBsame, batch of 8128.0 GiBsame, 32 KV heads (no GQA)512.0 GiB80 GB GPUlog scale
Figure 1.84KV cache sizes on a log scale. A small model's cache is tiny; a Llama 3 8B-sized model at 128k tokens needs 16 GiB per sequence, and a batch of eight overflows one 80 GB GPU. Without grouped-query attention it would be four times larger again.

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.

TWO PHASES OF GENERATIONPREFILLwhole prompt at oncefills the cache+1+1+1+1+1+1+1+1DECODE: one token per steplimited by arithmeticeach weight used for many tokenslimited by memory readsevery step re-reads all weights and the whole cachesmaller cache = faster decoding, not just cheaper
Figure 1.85Prefill processes the prompt in one wide, compute-bound pass. Decode adds one token per step and is limited by reading the weights and the cache from memory.

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.

EDIT THE PAST, REBUILD THE SUFFIXcached sequenceThepos 0catpos 1satpos 2becausepos 3itpos 4waspos 5tiredpos 6after the editThepos 0reusedogpos 1recomputesatpos 2recomputebecausepos 3recomputeitpos 4recomputewaspos 5recomputetiredpos 6recomputethe changed token and everything after iteven unchanged words now have different context
Figure 1.86Editing position 1 preserves the cache at position 0 and invalidates positions 1 through 6 in every layer. Later words may be unchanged, but their context has changed. Token labels and positions are illustrative.

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.