Inference: KV Cache Basics
By Ludovico Bessi, Senior ML Engineer at Google ยท Updated
What the key-value cache is, how big it gets, and how PagedAttention manages it.
Why Cache Keys and Values
When a decoder-only model generates token t, its attention layers need the keys and values of tokens 1 to tโ1. Those keys and values depend only on the earlier tokens, so they never change once computed.
Without a cache, every decode step would recompute keys and values for the entire sequence so far โ quadratic total work for a linear-length output. With a KV cache, each step computes keys and values for just the one new token, appends them to the cache, and attends over the stored entries. Per-step compute becomes constant for the weights plus linear in context length for attention.
Prefill: K, V for all prompt tokens โ write to cache
Decode: q, k, v for the new token โ append k, v to cache
attention(q, cache.K, cache.V)
Every production serving engine uses a KV cache. The interesting questions are how big it is and how to manage it.
How Big Is It?
Per token, the cache stores one key and one value vector for every KV head in every layer:
bytes per token = 2 (K and V) ร n_layers ร n_kv_heads ร d_head ร bytes_per_value
| Model | Layers | KV heads | d_head | KV cache per token (FP16) |
|---|---|---|---|---|
| Llama 2 7B (MHA) | 32 | 32 | 128 | 512 KB |
| Llama 3 8B (GQA) | 32 | 8 | 128 | 128 KB |
| Llama 2 70B (GQA) | 80 | 8 | 128 | 320 KB |
Multiply by tokens and requests:
- One Llama 2 7B request with 4,096 tokens of context: 2 GB.
- 32 concurrent Llama 3 8B requests at 8,192 tokens each: 32 ร 8,192 ร 128 KB โ 32 GB โ twice the model's 16 GB of weights.
This is the central fact of LLM serving: the KV cache, not the weights, usually limits how many requests fit on a GPU, and the number of concurrent requests (the batch size) is what drives throughput.
The Cache Makes Decode Memory-Bound
Each decode step reads the full weights and every request's KV cache. As contexts grow, reading the cache becomes a large share of each step's memory traffic. Reducing the bytes per cached token โ through GQA, quantization or eviction โ speeds up decode, not just capacity. See Memory Optimizations.
The Fragmentation Problem
Early serving systems allocated each request's cache as one contiguous tensor sized for the maximum possible length (prompt plus maximum output tokens). Because output length is unknown in advance, this wastes memory three ways:
- Reservation waste: space reserved for tokens that are not generated yet.
- Internal fragmentation: space reserved for tokens that are never generated because the request stops early.
- External fragmentation: gaps between allocations that are too small to use.
The vLLM paper (Kwon et al., 2023) profiled existing systems and found that only 20.4โ38.2% of KV cache memory held actual token states. The rest was waste โ which meant much smaller batches and much lower throughput than the hardware allowed.
PagedAttention
PagedAttention applies the idea of virtual memory paging from operating systems to the KV cache.
Blocks
The cache is divided into fixed-size blocks, each holding the keys and values for a small number of tokens (for example 16). A request's cache is a list of blocks that need not be contiguous in GPU memory.
Block tables
Each request has a block table mapping its logical blocks (tokens 0โ15, 16โ31, โฆ) to physical blocks in GPU memory โ exactly like a page table. A new physical block is allocated only when the previous one fills up.
The attention kernel
Because a request's keys and values are scattered, the attention kernel looks up the block table and gathers keys and values block by block. The extra indirection costs a little kernel efficiency, which is far outweighed by the memory savings.
What it buys
- Near-zero waste: at most one partially filled block per request. vLLM reports under 4% waste.
- Larger batches: more requests fit, so throughput rises. The original paper reported 2โ4ร higher throughput than earlier systems such as FasterTransformer and Orca at the same latency.
- Sharing: multiple sequences can point to the same physical blocks. Parallel sampling (several outputs for one prompt) and beam search share the prompt's blocks; a block is copied only when one sequence modifies it (copy-on-write).
- Simple eviction: when memory runs out, whole blocks can be swapped to CPU memory or dropped and recomputed later.
Prefix Caching
Many requests share a prefix: the same system prompt, the same few-shot examples, the same long document. Their KV cache for that prefix is identical. Prefix caching keeps those blocks after a request finishes and reuses them when a new request starts with the same tokens, skipping that part of the prefill entirely.
With paged blocks this is natural: hash each full block by its token contents (and everything before it), and look up the hash before computing. vLLM's automatic prefix caching works this way; SGLang's RadixAttention organizes cached prefixes in a radix tree. Both are covered in Attention Optimizations.
Prefix caching can cut time to first token dramatically for chat applications with long system prompts and for multi-turn conversations, where each turn re-sends the whole history.
Managing a Full Cache
When KV memory runs out mid-generation, an engine must choose a victim request and either:
- Swap its blocks to CPU memory and bring them back later (cost: PCIe transfer), or
- Recompute: drop its blocks and redo its prefill when it resumes (cost: compute).
Recomputation is often cheaper for short contexts; swapping wins for long ones. Schedulers also limit how many new requests they admit based on the free blocks, to avoid thrashing.
Key Takeaways
- The KV cache stores past keys and values so each decode step does constant weight work instead of reprocessing the whole sequence.
- Its size is 2 ร layers ร KV heads ร head dimension ร bytes per value, per token โ often larger than the weights at high concurrency.
- KV cache capacity sets the batch size, and batch size sets throughput.
- Contiguous max-length allocation wastes 60โ80% of cache memory; PagedAttention's fixed-size blocks and block tables cut that to a few percent.
- Paged blocks enable sharing, copy-on-write and prefix caching. For production numbers, see KV Cache Optimization.