Lesson 4: The KV cache · Workbook
The KV cache: the workbook
The full working behind lesson 4. What attention keeps from the past, how much arithmetic the cache saves, the size formula, how many conversations fit on a GPU, and seven exercises to check yourself.
Lesson 1 showed that one decode step for one user is bound by memory: the GPU spends its time reading weights. That lesson quietly assumed something else as well. Each new token only went through the model once, as a single row of activations. That is only possible because the model keeps a record of every earlier token’s attention state. This record is the KV cache.
This lesson explains what goes in it, why keeping it saves almost all of the arithmetic of generation, and how much memory it costs. The short version: the cache trades FLOPs for bytes, and at long contexts or large batches the bytes become the main constraint on a serving system.
What attention needs from the past
Inside every transformer layer, attention turns each token’s hidden state into three vectors: a query (Q), a key (K) and a value (V). To produce the output for a token, the layer compares that token’s query against the keys of every token up to and including it, turns the scores into weights, and takes a weighted sum of those tokens’ values. (Lesson 2 counts the FLOPs of each piece.)
Two facts make caching possible. First, a language model’s attention is causal: a token can look at earlier tokens but never at later ones. So the key and value of token 5 in layer 12 depend only on tokens 1 to 5. Generating token 6, 7 or 600 never changes them. Second, a new token needs the keys and values of all earlier tokens in every layer, but it does not need their queries, or anything else about them.
So after computing a token’s K and V in each layer, store them. When the next token arrives, compute only its own Q, K and V, append its K and V to the store, and attend over the store. That store is the KV cache. “Prefill” (lesson 3) fills it with the whole prompt in one pass; each “decode” step adds one token.
Without a cache, every step redoes the whole sequence
Suppose you threw the keys and values away after each step. To generate the next token you would need them again, and recomputing them is not cheap. Layer 12’s key for an old token depends on that token’s hidden state coming out of layer 11, which depends on layer 10, and so on down. Recomputing the old keys and values means running every old token through the full model again. Each step becomes a prefill of the whole sequence so far.
Take Llama 3.1 8B with 4,096 tokens already in the sequence. The numbers below use the same FLOP counts as lessons 1 and 2 (2 FLOPs per weight per token for the matrix multiplies, plus the attention FLOPs from lesson 2).
- Without a cache, producing the next token runs all 4,096 tokens through the model: 61.6 TFLOP.
- With a cache, it runs only the newest token through the matrix multiplies and lets it attend over 4,096 stored keys and values: 17.2 GFLOP.
That is 3,589 times less arithmetic for this one step. On an H100, the floor for the uncached step is 62.2 ms, a compute-bound prefill, against 4.64 ms for the cached, memory-bound decode step. The time ratio (13×) is smaller than the FLOP ratio because the cached step is limited by reading weights, not by arithmetic. For one user at this length, 62.2 ms per token (about 16 tokens per second) is tolerable. The real cost is throughput: the uncached step keeps the GPU’s compute fully busy for that one user, while the cached step leaves almost all of it free to batch other users, so the tokens a GPU can serve fall by up to the FLOP ratio. And the uncached step keeps getting longer with every token.
The gap widens as the sequence grows. Let be the matmul parameters outside the vocabulary projection, about 6.98 billion for Llama 3.1 8B (as in lesson 1, the projection runs only for the token being predicted, so it adds the same small amount per generated token either way). If the prompt has tokens and you generate more, the matrix-multiply FLOPs are roughly
Without a cache the work is quadratic in the number of generated tokens. With one, the matrix multiplies are linear: each token passes through the weights once. Attention still grows with length, because every new token reads all stored keys and values, but in FLOPs it is a small part of a model this size.
For a 1,024-token prompt and 1,024 generated tokens, the totals for Llama 3.1 8B, which also count attention and the vocabulary projection and so come in a little above the formula (and their ratio a little below it), are 22.6 PFLOP without a cache and 30.7 TFLOP with one, about 735 times less. Generate 2,048 tokens instead and the ratio grows to about 1,284.
Every serving system keeps the cache. The rest of this lesson is about what it costs.
How big the cache is
For each token, the cache holds one key vector and one value vector per KV head per layer. Each vector has head_dim numbers. So the bytes per token are
where the leading 2 counts K and V, is the number of layers, the number of KV heads and the size of each head. For Llama 3.1 8B in BF16:
This course quotes every size in decimal units, as spec sheets do: 1 KB is 1,000 bytes and 1 GB is 109 bytes. (An H100 sold as “80 GB” physically has 80 GiB, binary gigabytes of 1,024³ bytes, or 85.9 GB; the course uses the rated 80 GB, so its capacity figures err slightly low.)
Llama 3.1 70B has 80 layers with the same 8 KV heads of 128, so it stores bytes, 328 KB, per token.
Notice = 8, while both models have more query heads (32 and 64). They use grouped-query attention, in which several query heads share one K and V head. If Llama 3.1 8B gave each of its 32 query heads its own K and V, the cache would be 524 KB per token, 4 times larger. Lesson 5 covers this and other ways of shrinking the cache. For comparison, the vLLM paper computes 800 KB per token for OPT-13B, an older model without shared KV heads.
The per-token size multiplies by the sequence length. One conversation in BF16 needs:
| Context (tokens) | Llama 3.1 8B | Llama 3.1 70B |
|---|---|---|
| 1,024 | 134 MB | 336 MB |
| 8,192 | 1.07 GB | 2.68 GB |
| 32,768 | 4.29 GB | 10.7 GB |
| 131,072 | 17.2 GB | 42.9 GB |
The last row is the models’ full context length of 131,072 tokens. A single 8B conversation at full length needs 17.2 GB of cache, more than the 16.1 GB of weights.
The 3D figure in the lesson draws the cache of one Llama 3.1 8B sequence as two blocks, one for keys and one for values. The height is the 32 layers, the depth is the 8 KV heads, and the length is tokens. Each small cell is one vector of 128 numbers (256 bytes in BF16). The prompt fills the first slices in one pass; after that, each generated token adds exactly one slice to each block. Nothing already in the cache is ever rewritten.
From one sequence to a whole GPU
A server keeps many conversations in flight at once, because batching is how decode stops being wasteful (lesson 1). Each sequence has its own cache. So the memory a GPU must hold is
Serving engines leave headroom: vLLM uses at most 90% of GPU memory by default (gpu_memory_utilization = 0.9), and activations and CUDA graphs come out of that 90% too, so the real cache is a little smaller than the estimates below. This lesson holds back 10% the same way.
For Llama 3.1 8B in BF16 on one H100: 80.0 GB of memory, minus 8.00 GB held back, minus 16.1 GB of weights, leaves 55.9 GB for the cache. At 131 KB per token that is 426,784 tokens in total, shared among all sequences. Divide by the context length and round down to get how many sequences fit at once:
| Context (tokens) | 8B, 1× H100 | 70B, 2× H100 | 70B, 4× H100 |
|---|---|---|---|
| 1,024 | 416 | 8 | 437 |
| 8,192 | 52 | 1 | 54 |
| 32,768 | 13 | 0 | 13 |
| 131,072 | 3 | 0 | 3 |
The 70B model’s weights are 141 GB in BF16, which does not fit on one 80.0 GB GPU at all. The columns on the right assume the model is split across GPUs, with its weights and its cache divided evenly between them, so the memory acts as one pool. (Lesson 13 covers how that split works.) On two H100s the weights fit with only 2.89 GB to spare, enough for 1 sequence of 8,192 tokens. Doubling to four GPUs doubles the memory but not the weights, so the room for cache grows from 2.89 GB to 147 GB.
Try it below. The bar is the GPU memory: grey for weights, teal for the KV cache, hatched for the reserve. Push the batch or the context up until the cache turns red.
GPU memory budget
16-bit weights on NVIDIA H100s (80 GB each)
- Weights
- KV cache
- Held back (10%)
- Free
Why the cache dominates at long context
The weights are a fixed cost. The cache is paid per token per sequence, with no upper bound except the context limit. So there is always a point past which the cache is the bigger of the two.
For Llama 3.1 8B in BF16, that point is 122,532 cached tokens in total: 16.1 GB of weights divided by 131 KB per token. That could be one sequence near its 131,072-token limit, or about 30 sequences of 4,096 tokens. A server that hits its memory limit at long context or high batch has, by then, more cache than model in memory.
Published systems show the same pattern. The vLLM paper’s Figure 1 shows a 13B model on an A100 40GB with about 65% of memory used by weights and about 30% by the KV cache. Pope et al. give a larger example: a 500B+ model with multi-head attention, at batch 512 and context 2,048, needs a 3 TB KV cache, three times the size of its parameters.
The cache costs time as well as space. Every decode step reads each sequence’s whole cache, because the new token’s query is compared against every stored key. Fill the H100 with 52 sequences of 8,192 tokens and one decode step reads 55.8 GB of cache against 15.0 GB of weights (the input embedding table is a lookup, so only one row of it is read). Attention takes 16.7 ms of the 21.2 ms step. Pope et al. report the same effect on TPUs: at batch 512 and contexts of 2,048 tokens or more, the time to load the KV cache dominates the memory time. Batching shares the weight reads across users; it does not share the cache reads, because each user’s cache is different.
What follows from this
Once the cache is the largest thing in memory, the number of conversations a GPU can serve at once is set by how well the cache is stored. Much of the rest of this course works on that, from different directions:
- Make each token smaller. Share K and V heads across query heads, or compress them (lesson 5), or store them in fewer bits (lesson 10).
- Waste less of the memory. Early serving systems reserved a contiguous block per request for its maximum possible length. The vLLM paper measured that only 20.4% to 38.2% of their KV cache memory held actual token states; the rest was reserved or lost to fragmentation. Allocating the cache in small pages fixes that (lesson 7).
- Share what is identical. Requests that start with the same system prompt have the same keys and values for those tokens, so they can share one copy (lesson 8).
- Keep the batch full. Sequences finish at different times and free their cache. Scheduling new ones into that space as soon as it frees up is continuous batching.
Check yourself
Work each one out on paper before opening the answer. The answers come from the same tested functions as the figures in the lesson; the last two recall lessons 1 and 3.
Exercise 1. Qwen2.5 7B has 28 layers, 4 KV heads and a head dimension of 128. How many bytes of KV cache does it store per token in BF16, and how much for a 32,768-token conversation? Enter the bytes per token.
Show the worked answer
57,344 bytes (57.3 KB) per token: 2 × 28 × 4 × 128 × 2. A 32,768-token conversation needs 1.88 GB. That is less than half of Llama 3.1 8B’s 131 KB, because Qwen2.5 7B has 4 KV heads to Llama’s 8 and 28 layers to its 32.
Exercise 2. On one H100 with 10% held back, Llama 3.1 8B with BF16 weights fits 52 sequences of 8,192 tokens. How many fit if the KV cache is stored in FP8 (1 byte per number) while the weights stay in BF16?
Show the worked answer
104. Each sequence’s cache halves, to 537 MB, and the space left after the weights is unchanged at 55.9 GB. Whether FP8 keys and values keep output quality is a separate question, taken up in lesson 10.
Exercise 3. At 4,096 tokens, the uncached Llama 3.1 8B step has a floor of 62.2 ms on an H100 and the cached step 4.64 ms. Estimate both floors at 32,768 tokens. How many tokens per second does each allow for one user?
Show the answer
About 747 ms without a cache and 5.76 ms with one, so about 1 against 174 tokens per second. The uncached step is a 32,768-token prefill: compute-bound, with matmul FLOPs that grow 8× with the length and attention FLOPs that grow 64×. The cached step is still memory-bound: it reads the same 15.0 GB of weights plus a cache that is now 4.29 GB, so it grows only a little. The time gap is now about 130×, and at this length dropping the cache is no longer tolerable even for one user.
Exercise 4. Llama 3.1 70B in BF16 fits 1 sequence of 8,192 tokens on 2 H100s and 54 on 4 H100s. Why does doubling the GPUs give far more than twice the capacity?
Show the answer
The weights, 141 GB, are a fixed cost. On two GPUs (144 GB usable) they leave only 2.89 GB for the cache. On four GPUs (288 GB usable) the weights take the same space and the cache gets 147 GB. Capacity depends on what is left after the weights, not on total memory.
Exercise 5. Mistral 7B v0.1 uses a sliding window: each token attends only to the most recent 4,096 tokens, so older keys and values can be dropped. Its per-token KV size equals Llama 3.1 8B’s, and its BF16 weights are 14.5 GB. How much KV cache does one 32,768-token conversation need, and how many such conversations fit on an H100 with 10% held back? Enter the number of conversations.
Show the worked answer
The cache never holds more than 4,096 tokens, so one conversation needs 537 MB however long it gets. 107 such conversations fit, against 13 for Llama 3.1 8B at the same length. The window caps memory, at the cost of the model no longer seeing tokens outside it directly.
Exercise 6. From lesson 1: Llama 3.1 8B in BF16 on one H100 SXM (3.35 TB/s), one user, short context. What is the ceiling on tokens per second while it writes a reply?
Show the worked answer
About 223 tokens per second. Each decode step reads 15.0 GB from memory, almost all of it the weights, and at 3.35 TB/s that takes 4.48 ms. The arithmetic is tiny by comparison, so the step is bound by memory. That ceiling assumes the KV cache: only the newest token goes through the weights each step. Without the cache, each step would redo the whole conversation and the ceiling would fall as the reply grows.
Exercise 7. From lesson 3: a request to Llama 3.1 8B in BF16 on one H100 SXM has a 2,048-token prompt and a 256-token answer. What is the floor on its time to first token (TTFT)? Enter it in milliseconds.
Show the worked answer
30.0 ms, and the 256-token answer length does not change it: TTFT is the prefill alone. The time per output token is 4.57 ms. Prefill runs all 2,048 prompt tokens through the model in one compute-bound pass, and that pass is what writes the prompt’s keys and values into the cache. Every decode step after it reads that cache instead of recomputing it, which is why a later token costs about 4.57 ms on average, not another prefill.
Sources
- Pope, Douglas, Chowdhery, Devlin, Bradbury, Heek, Xiao, Agrawal, Dean (2023). Efficiently Scaling Transformer Inference. Proceedings of Machine Learning and Systems 5 (MLSys 2023). arXiv:2211.05102. Section 2.1: for a 500B+ multi-head model at batch 512 and context 2048, the KV cache totals 3 TB, three times the parameters; section 2 (Memory costs): at larger batch sizes and sequence lengths (e.g. 2048+ tokens with batch 512+), the time to load the KV cache dominates the memory time
- Kwon, Li, Zhuang, Sheng, Zheng, Yu, Gonzalez, Zhang, Stoica (2023). Efficient Memory Management for Large Language Model Serving with PagedAttention. SOSP 2023. arXiv:2309.06180. Figure 1: a 13B model on an A100 40GB uses about 65% of memory for weights and about 30% for the KV cache. Section 3: OPT-13B needs 800 KB of KV cache per token. Figure 2: earlier systems used only 20.4% to 38.2% of KV cache memory for actual token states
- kipply (2022). Transformer inference arithmetic. The same per-token formula, written for multi-head attention, and the observation that without a cache sampling time grows quadratically
- vLLM engine arguments: --gpu-memory-utilization. Defaults to 0.9: the fraction of GPU memory the engine may use for weights, activations and KV cache together; this lesson leaves the other 10% unused the same way
- Llama 3.1 8B config.json (ungated copy). 32 layers, 8 key-value heads, head dimension 128, max_position_embeddings 131072
- Llama 3.1 70B config.json (ungated copy). 80 layers, 64 query heads, 8 key-value heads, head dimension 128, max_position_embeddings 131072
- NVIDIA H100 product page, specifications table. H100 SXM: 80 GB HBM3 (80 GiB: five 16 GiB stacks)