The KV Cache Explained: Why LLM Inference Runs Out of Memory Before It Runs Out of Compute
What the key-value cache stores during text generation, how to calculate its size from a model config, and how grouped-query attention, paging, prefix caching, and quantization keep it under control.
When a large language model generates text, the obvious cost is the model weights: an 8-billion-parameter model in 16-bit precision needs about 16 GB just to load. The less obvious cost shows up once real traffic arrives. Long prompts, long conversations, and many concurrent users all consume a second pool of GPU memory that grows with every token: the key-value cache, usually called the KV cache. On a busy inference server it is often the KV cache, not the weights or the arithmetic, that decides how many requests fit on a GPU at once.
This explainer covers what the KV cache actually stores, why it exists, how to compute its size from a model's configuration file, and the main techniques modern serving stacks use to shrink it or use it more efficiently.
Why generation needs a cache at all
Decoder-only transformers generate one token at a time. To produce token number 501, every attention layer compares a query vector for the newest position against a key vector for each of the 500 earlier positions, then takes a weighted sum of their value vectors. Without a cache, the model would recompute the keys and values for all 500 earlier tokens at every step, even though those vectors never change once computed. Generating a long reply would repeat almost identical work hundreds of times.
The KV cache removes that repetition. After a token's keys and values are computed in each layer, they are stored. On the next step, the model computes keys and values only for the single new token, appends them to the cache, and reads everything else back from memory. The Hugging Face Transformers documentation describes exactly this trade: store the calculations so they can be reused instead of recomputed. Compute per step drops sharply, and in exchange memory use climbs with every token in the context.
Prefill and decode
This splits inference into two phases. In prefill, the whole prompt is processed in one parallel pass, which fills the cache with keys and values for every prompt token; this phase is limited mostly by compute. In decode, the model emits one token per step, and each step must read the entire cache from GPU memory to attend over it. Decode does little arithmetic per byte it reads, so it tends to be limited by memory bandwidth. A bigger cache means more bytes to move on every single generated token.
How big is the KV cache?
The size follows directly from the model architecture. For every token, every layer stores one key vector and one value vector for each key-value head. Multiplying it out gives a formula that works for most standard decoder models:
KV cache bytes = 2 (key and value) × layers × KV heads × head dimension × tokens × batch size × bytes per element
Everything except the token count and batch size comes from the model's config. json. The relevant fields are num_hidden_layers, num_key_value_heads, and head_dim (or hidden_size divided by num_attention_heads when head_dim is absent). Bytes per element is 2 for float16 or bfloat16 caches.
A worked example with two real configs
Llama 2 7B uses classic multi-head attention: 32 layers, 32 attention heads, and 32 key-value heads, with a hidden size of 4096, so each head has 128 dimensions. Llama 3.1 8B also has 32 layers, 32 query heads, and a head dimension of 128, but its config lists only 8 key-value heads. The short script below computes the cache size for both. It uses only the Python standard library.
def kv_cache_bytes(layers, kv_heads, head_dim, tokens, batch=1, bytes_per_elem=2):
# 2 = one key vector and one value vector per head, per layer, per token
return 2 * layers * kv_heads * head_dim * tokens * batch * bytes_per_elem
GiB = 1024 ** 3
models = {
"Llama-2-7B (MHA, 32 KV heads)": dict(layers=32, kv_heads=32, head_dim=128),
"Llama-3.1-8B (GQA, 8 KV heads)": dict(layers=32, kv_heads=8, head_dim=128),
}
for name, cfg in models.items():
per_token = kv_cache_bytes(**cfg, tokens=1)
print(f"{name}: {per_token // 1024} KiB per token")
for tokens, batch in [(4096, 1), (32768, 1), (4096, 16)]:
size = kv_cache_bytes(**cfg, tokens=tokens, batch=batch)
print(f" {tokens:>6} tokens x batch {batch:>2}: {size / GiB:6.2f} GiB")Running it prints 512 KiB per token for Llama 2 7B and 128 KiB per token for Llama 3.1 8B. For a single 4,096-token sequence that is 2 GiB versus 0.5 GiB. At 32,768 tokens it is 16 GiB versus 4 GiB. Serving 16 users with 4,096-token contexts needs 32 GiB versus 8 GiB. The older model's cache for that batch is larger than its own weights, which is why long-context serving becomes a memory-planning problem so quickly. These figures line up with the Hugging Face Llama 3.1 launch post, which lists about 0.125 GB of FP16 cache per thousand tokens for the 8B model and notes that at the full 128k context the cache can rival the size of the weights.
Shrinking the cache: fewer key-value heads
The four-fold difference in the example comes entirely from the KV heads term. Multi-query attention (MQA) takes this to the extreme by sharing a single key-value head across all query heads, which makes decoding faster but can cost quality. Grouped-query attention (GQA), introduced by Ainslie and colleagues in 2023, sits in between: query heads are split into groups, and each group shares one key-value head. Their paper reports that GQA reaches quality close to full multi-head attention while running at speeds comparable to MQA, and that existing multi-head checkpoints can be converted using about 5 percent of the original pre-training compute.
Because the cache scales linearly with the number of KV heads, GQA is one of the most effective architectural levers for long-context inference, and it is a design decision made at training time. When comparing models for a serving workload, num_key_value_heads in the config is worth checking alongside parameter count.
Using the memory better: paging and prefix caching
Even a correctly sized cache can be wasted. Early serving systems reserved one contiguous memory region per request, sized for the maximum possible output length. Most requests finish early, so much of that reservation sat unused, and the gaps between regions caused fragmentation. The vLLM paper (Kwon et al. , 2023) identified this waste as a key limit on batch size and proposed PagedAttention, which borrows the idea of virtual-memory paging from operating systems. The cache is divided into fixed-size blocks of tokens, and each request keeps a table mapping its logical positions to physical blocks that can live anywhere in GPU memory. The paper reports near-zero KV cache waste and a 2 to 4 times throughput improvement at the same latency compared with FasterTransformer and Orca.
Blocks also make sharing possible. If many requests start with the same system prompt or the same long document, their opening blocks hold identical keys and values. vLLM's automatic prefix caching hashes each full block together with the hash of the block before it, so a block's identity covers the entire prefix that led up to it. A new request whose leading blocks match existing ones reuses them instead of recomputing them, and unused blocks are evicted least-recently-used first. For applications built around a long shared preamble, such as a retrieval system with fixed instructions or a chatbot with a large system prompt, this can skip a large part of prefill entirely.
Trading precision or speed for capacity
When the architecture is fixed and paging is already in place, the remaining options trade something else for memory:
- Quantized cache: storing keys and values in 8-bit or 4-bit formats halves or quarters the per-token cost. vLLM exposes this through the --kv-cache-dtype engine argument, with options such as fp8, and Transformers offers a QuantizedCache selected with cache_implementation="quantized". The Transformers docs warn that quantizing can hurt latency when the context is short and memory is plentiful.
- Offloading: Transformers can keep only the current layer's cache on the GPU and move the rest to CPU memory, prefetching layer by layer (cache_implementation="offloaded"). This avoids out-of-memory errors on small GPUs at the cost of some throughput.
- Sliding-window attention: some models attend only to a recent window of tokens in certain layers, so the cache for those layers stops growing once the window is full.
- Static allocation: a fixed-size cache (cache_implementation="static" in Transformers) pre-allocates the maximum length, which enables compilation for lower latency but wastes space when sequence lengths vary widely.
Sizing a server in practice
A serving engine like vLLM loads the weights, reserves a fraction of the remaining GPU memory for the KV cache, and then admits requests only while free blocks remain. A launch command that caps context length and uses an 8-bit cache looks like this:
vllm serve meta-llama/Llama-3.1-8B-Instruct \
--max-model-len 16384 \
--gpu-memory-utilization 0.90 \
--kv-cache-dtype fp8Here --gpu-memory-utilization sets the fraction of GPU memory the engine may use, --max-model-len bounds prompt plus output length, and --kv-cache-dtype chooses the cache precision. Whether an fp8 cache is supported and how much accuracy it costs depend on the GPU and the model, so it is worth testing on a representative evaluation set before rolling it out.
A quick capacity estimate follows the same arithmetic as the script above:
- Read num_hidden_layers, num_key_value_heads, and head_dim from the model's config. json and compute bytes per token.
- Subtract the weights and a safety margin for activations from the GPU memory budget to get the space left for the cache.
- Divide that space by bytes per token to get the total number of tokens the server can hold at once.
- Divide by your typical prompt-plus-output length to estimate how many requests can run concurrently, then confirm with a load test, because real traffic varies in length.
Key takeaways
- The KV cache trades memory for compute: it stores each token's keys and values so they are computed once rather than on every generation step.
- Its size is 2 × layers × KV heads × head dimension × tokens × batch × bytes per element, and every term except tokens and batch is in config. json.
- Grouped-query attention reduces the cache in proportion to the number of shared key-value heads, which is why Llama 3.1 8B holds four times as many tokens per gigabyte of cache as Llama 2 7B.
- Paging removes fragmentation, and prefix caching lets requests with shared openings reuse the same blocks.
- Quantization, offloading, and sliding windows buy additional capacity at a cost in accuracy, speed, or flexibility, so measure before adopting them.
Once the KV cache is understood, many inference behaviors make sense: why long contexts cost more than their token count suggests, why throughput drops as conversations grow, and why the same GPU can serve dramatically different numbers of users depending on the model's attention design.
Enjoyed this?
Get the next deep dive in your inbox. No spam — just the stories worth reading.
Subscribe to the newsletter