Skip to content
LearnAI

4.1The KV cache

Why generating text token by token would be painfully redundant, the cache that fixes it, and the memory bill that cache runs up.

⏱ 14 minIntermediate

Generation repeats itself

A language model is autoregressiveAutoregressive generationGenerating one token at a time, appending each output to the input before predicting the next.: to write a reply, it predicts one token, appends it to the input, and runs again to predict the next (see next-token prediction). A 500-token answer therefore takes 500 forward passes.

The naive way to do that is wasteful in a very specific way. On pass 200, the input is the prompt plus 199 generated tokens, and the model pushes all of them through every layer again, even though 199 of them were already processed on pass 199, and on pass 198, and so on. If the only thing that changed is one new token at the end, most of that work produces numbers we have already seen.

The question this lesson answers is: which of those numbers can we safely keep? The answer is the keys and values from self-attention, and keeping them is called the KV cacheKV cacheStored keys and values from earlier tokens, reused during generation so they aren't recomputed at every step.. It is the single most important optimization in LLM inferenceInferenceRunning a trained model to produce outputs, as opposed to training it.. Almost everything else in this part of the course (grouped-query attention, PagedAttention, KV quantization) exists because this cache gets big.

ANALOGY· Index cards for a long meeting

Imagine you are taking minutes at a long meeting, and before writing each new sentence you must check what everyone said earlier. The slow way: replay the entire recording from the start before every sentence. The smart way: after each speaker finishes, write one index card with a short label on top (what it is about) and the content underneath, and drop it in a box. To write your next sentence you form a question, scan the labels, and read the content of the cards that match.

The question is the new token’s query. The labels are keys, the content is values, and the box is the KV cache. Earlier cards never need rewriting, because what someone said at minute 5 doesn’t change when someone speaks at minute 50. The catch: the box keeps growing, and a long meeting fills a lot of boxes.

Why past keys and values never change

Recall the mechanics of attention. Each token’s hidden vector xix_i is projected into a query qi=xiWQq_i = x_i W_Q, a key ki=xiWKk_i = x_i W_K and a value vi=xiWVv_i = x_i W_V (the Q/K/VQuery, key, value (Q/K/V)Three learned projections of each token. A query is compared with keys to get attention weights, which then mix the values. projections). Token tt‘s output is a weighted average of values, with weights from how well its query matches each key:

outt=∑i≤tsoftmaxi ⁣(qt⋅kid)vi.\text{out}_t = \sum_{i \le t} \text{softmax}_i\!\left(\frac{q_t \cdot k_i}{\sqrt{d}}\right) v_i .

The sum runs only over i≤ti \le t because of the causal maskCausal maskA mask that stops each token from attending to later tokens, so the model can't peek at the future during training.: a token may look at the past, never the future. That single fact is what makes caching legal. Token 5’s hidden state in layer 1 depends only on tokens 1 to 5, so appending token 6 cannot change it. Inductively, the same is true in every layer. So k5k_5 and v5v_5, in every layer and every head, are final the moment they are computed.

Notice what is not cached: the queries. Old queries are only needed to compute old tokens’ outputs, which we already have. At each step, only the newest token needs a query; it is compared against all the cached keys.

INTERACTIVEAn animated KV cache
Mode
Thecatsatonprompt (black) · press Next to run prefill
K cacheV cacheattention of qThecatsatonthematbecauseitwastired.cache empty
Ready
K/V rows computed (this step)
0
q·k dot products (this step)
0
Total K/V rows: cache vs none
0 vs 0
Total dot products: cache vs none
0 vs 0

Counts are per attention head per layer. Without a cache, every step reprocesses the whole prefix, so total work grows like n²/2 instead of n. For a 1,000-token reply on an 8B model that is roughly 16.0T FLOP vs 8.0P FLOP of matrix work.

KV-cache memory calculator2 × layers × KV heads × head dim × bytes, per token
Cache dtype
per token
128 KiB
131,072 bytes
per sequence
1.00 GiB
whole batch (8 seq)
8.00 GiB
share of one 80 GB GPU used by the KV cache alone11%

For comparison, Llama-3-8B's weights take about 16 GB in BF16.

Step through generation. Prefill writes the whole prompt into the cache in one pass; each decode step appends one row to K and V, and the new token's query attends over every cached row. Switch to 'Without cache' to see every row recomputed on every step, and watch the totals diverge. Below, size the cache for real models.

Things to try:

  1. Press Next once. That’s prefillPrefillThe first phase of generation: the whole prompt is processed in one parallel forward pass, filling the KV cache and producing the first output token. It is usually compute-bound.: four prompt tokens enter the cache together, in one parallel pass.
  2. Keep stepping. Each decode step adds exactly one row to K and one to V. The attention bars show where the new query looks; the percentages always sum to 100%.
  3. Switch to “Without cache” and replay. Now every row gets a gold outline on every step, because it is recomputed. Compare the totals at the end: 10 K/V rows with the cache versus 49 without, and the gap widens quadratically with length.
  4. In the calculator, pick Llama-2-7B, then Llama-3-8B. Same layer count and head size, but 4× less cache, because Llama 3 uses grouped-query attention with only 8 KV heads.

Prefill and decode: two very different jobs

Serving a request has two phases, and they stress the hardware in opposite ways.

Prefill processes the whole prompt at once. All prompt tokens are known up front, so their Q, K and V can be computed in parallel as big matrix–matrix multiplications, the kind of work GPUs are built for. Prefill fills the cache and produces the first output token. Its duration largely determines the time until the user sees anything.

The decode phaseDecode phaseThe token-by-token phase of generation after prefill. Each step processes one new token per sequence and reads the whole KV cache and all weights, so it is usually memory-bandwidth-bound. generates the rest, one token per step. Each step processes a single new token per sequence: compute its q, k and v, append k and v to the cache, attend over the cache, run the MLP, sample. The arithmetic per step is small, but to do it the GPU must read every weight of the model and the sequence’s entire KV cache from memory.

That difference has a name. A workload is memory-boundMemory-bound (vs compute-bound)A workload is memory-bound when its speed is limited by how fast data can be moved from memory, not by arithmetic. The deciding ratio is arithmetic intensity: FLOPs performed per byte moved. when the GPU spends its time waiting for data rather than computing. The yardstick is arithmetic intensity: FLOPsFLOPsFloating-point operations, the standard measure of compute. Training a dense Transformer costs about 6 × parameters × tokens FLOPs. performed per byte moved. In a matrix–vector product with 16-bit weights, each 2-byte weight is used in one multiply and one add, so the intensity is about 1 FLOP per byte. An H100 can do roughly 300 times more FLOPs per second than bytes it can stream from memory, so a single decoding sequence leaves most of the chip idle.

Here is the consequence in numbers. Llama-3-8B has about 16 GB of weights in BF16BF16 (bfloat16)A 16-bit floating-point format with the same exponent range as FP32 but less precision, widely used for training.. An H100 SXM reads memory at about 3.35 TB/s, so just streaming the weights once takes about 4.8 ms. That puts a ceiling of roughly 200 tokens per second on a single sequence, no matter how fast the arithmetic units are.

How big is the cache?

For every token, every layer stores one key vector and one value vector per KV head. So the cache per token is

bytes per token=2×layers×KV heads×head dim×bytes per number.\text{bytes per token} = 2 \times \text{layers} \times \text{KV heads} \times \text{head dim} \times \text{bytes per number}.

The 2 is for K and V. Plug in Llama-3-8B, whose published config has 32 layers, 8 KV heads and head dimension 128 (4096 hidden size divided by 32 query heads), stored in 16-bit precision:

2×32×8×128×2=131,072 bytes=128 KiB per token.2 \times 32 \times 8 \times 128 \times 2 = 131{,}072 \text{ bytes} = 128 \text{ KiB per token}.

That sounds small until you multiply. An 8,192-token conversation needs exactly 1 GiB of cache. Thirty-two such conversations served at once need 32 GiB, twice the size of the model’s own weights.

Model (from its config)layersKV headshead dimKV per token (16-bit)one 8K-token sequence
Llama-2-7B (full multi-head)3232128512 KiB4 GiB
Llama-3-8B (GQA)328128128 KiB1 GiB
Llama-3-70B (GQA)808128320 KiB2.5 GiB
Qwen3-235B-A22B (GQA)944128188 KiB1.5 GiB

Two things jump out. First, the cache grows linearly with context length and batch size, without limit. Llama 3.1 70B uses the same layout as Llama-3-70B and supports 128K tokens, so a single maximum-length conversation needs 40 GiB of cache. Second, the number of KV heads is a design choice. Llama-2-7B keeps one KV head per query head; Llama 3 shares each KV head among four query heads (grouped-query attentionGrouped-query attention (GQA)Attention in which groups of query heads share one key/value head, shrinking the KV cache. MQA is the extreme case of one shared KV head.), cutting the cache by 4×. The attention variants lesson takes that idea all the way to DeepSeek’s latent compression.

The other levers are the bytes per number (an 8-bit or 4-bit cache halves or quarters the bill, see quantization) and how efficiently the memory is managed. Early serving systems reserved a contiguous chunk for each request’s maximum length and wasted much of it, a problem PagedAttention solves by allocating the cache in small blocks.

MATH CORNER · optionalWork with and without the cache, and decode's arithmetic intensity

Counting work. Let a model have PP parameters. A forward pass costs about 2P2P FLOPs per token processed (one multiply and one add per weight), ignoring the attention-score term. Generating NN tokens:

  • Without a cache, step tt reprocesses all tt tokens: total ∑t=1N2Pt=2P⋅N(N+1)2≈PN2\sum_{t=1}^{N} 2Pt = 2P \cdot \frac{N(N+1)}{2} \approx P N^2.
  • With a cache, step tt processes one token: total 2PN2PN.

The ratio is (N+1)/2(N+1)/2. For N=1000N = 1000, recomputation does about 500× more matrix work.

The attention scores themselves still grow: at step tt the new query takes tt dot products with the cached keys, so attention costs ∑tt≈N2/2\sum_t t \approx N^2/2 dot products per head with the cache, versus ∑tt(t+1)/2≈N3/6\sum_t t(t+1)/2 \approx N^3/6 without it.

Worked example (the demo’s toy). Prompt of 4 tokens, then 6 decode steps, counting K/V rows computed per head:

stepcached rows after steprows computed (cache)rows computed (no cache)
prefill444
decode 1515
decode 2616
decode 3717
decode 4818
decode 5919
decode 610110
total1049

Arithmetic intensity of decode. With batch size BB, a weight matrix W∈Rd×dW \in \mathbb{R}^{d \times d} in 16-bit precision is read once (2d22d^2 bytes) and used for 2Bd22Bd^2 FLOPs, so the intensity is about BB FLOPs per byte. An H100 offers on the order of 1,000 dense BF16 TFLOPS against 3.35 TB/s of bandwidth, a ratio near 300. Decode stays memory-bound until BB is in the hundreds. Attention over the cache is worse: each cached number is used by only one query per KV head (or by the gg query heads of its group under GQA), whatever the batch size.

In code

This is what the cache looks like inside a single attention layer during decoding. Real implementations (for example past_key_values in Hugging Face Transformers) store one such pair per layer:

import torch

class CachedAttention(torch.nn.Module):
    def __init__(self, d, n_heads):
        super().__init__()
        self.h, self.dh = n_heads, d // n_heads
        self.qkv = torch.nn.Linear(d, 3 * d, bias=False)
        self.out = torch.nn.Linear(d, d, bias=False)
        self.k_cache = self.v_cache = None          # (batch, heads, seq, dh)

    def forward(self, x):                           # x: (batch, new_tokens, d)
        B, T, _ = x.shape
        q, k, v = self.qkv(x).view(B, T, 3, self.h, self.dh).unbind(2)
        q, k, v = (t.transpose(1, 2) for t in (q, k, v))
        if self.k_cache is not None:                # decode: append, never recompute
            k = torch.cat([self.k_cache, k], dim=2)
            v = torch.cat([self.v_cache, v], dim=2)
        self.k_cache, self.v_cache = k, v
        # Prefill (T > 1) needs the causal mask; decode (T == 1) sees everything cached.
        y = torch.nn.functional.scaled_dot_product_attention(q, k, v, is_causal=(T > 1))
        return self.out(y.transpose(1, 2).reshape(B, T, -1))

Prefill calls forward once with the whole prompt; each decode step calls it with a single token. Production engines preallocate or page the cache instead of growing it with torch.cat, which copies memory on every step.

COMMON MISCONCEPTIONS
  • “The KV cache stores the model’s previous outputs.” It stores intermediate keys and values for every token (prompt and generated), in every layer and every KV head. The generated text itself is a few bytes; the cache for it is hundreds of kilobytes per token.
  • “With a cache, each new token costs the same no matter how long the context is.” The MLP and projection work is constant per token, but the new query still has to read and score every cached key, so per-token attention cost and memory traffic grow linearly with context.
  • “The cache is an approximation that slightly changes the output.” It is exact. Because of the causal mask, cached keys and values are identical to what recomputation would produce (up to floating-point ordering differences).
  • “Model weights are always the main memory cost of serving.” For long contexts and large batches the KV cache can exceed the weights. Thirty-two 8K-token conversations on Llama-3-8B need 32 GiB of cache against 16 GB of weights.
  • “Why not cache the queries too?” Old queries are never needed again: they were only used to compute old tokens’ outputs, which are already done.

Check your understanding

0/5 answered
  1. Q1.Why is it valid to reuse the keys and values of earlier tokens when generating a new token?

  2. Q2.A model has 40 layers, 8 KV heads, head dimension 128, and stores its cache in FP16. How much cache does one token need?

  3. Q3.Why is the decode phase usually memory-bandwidth-bound?

  4. Q4.You double the batch size during decoding. What happens to the memory traffic per step, roughly?

  5. Q5.Llama-2-7B and Llama-3-8B both have 32 layers and head dimension 128, yet Llama-3-8B's KV cache per token is 4× smaller. Why?

Further reading

Progress is saved in this browser only.
Type to search across all lessons and glossary terms.