The KV Cache and Inference Memory
Generating text is a loop: run the model on the sequence so far, sample one token, append it, repeat. Done naively, step recomputes the keys and values of all previous tokens, although they have not changed. The KV cache stores them, so each step computes attention only for the newest token. It turns generation from quadratic to linear work per token, at the price of memory that grows with context length and batch size, often more than the weights themselves.
Why caching is exact
In a causal transformer, the key and value vectors of token in every layer depend only on tokens (Causal Masking). Appending token cannot change them. So at each step:
- compute for the new token only;
- append to the cache of each layer;
- attend with the single new query over all cached keys and values.
import numpy as np
rng = np.random.default_rng(0)
d, T = 8, 6
Wq, Wk, Wv = (rng.normal(size=(d, d)) / np.sqrt(d) for _ in range(3))
X = rng.normal(size=(T, d))
def softmax(s): e = np.exp(s - s.max(-1, keepdims=True)); return e / e.sum(-1, keepdims=True)
# full recomputation with a causal mask
S = (X @ Wq) @ (X @ Wk).T / np.sqrt(d) + np.triu(np.full((T, T), -1e9), 1)
full = softmax(S) @ (X @ Wv)
# incremental with a KV cache
K_cache, V_cache, outs = [], [], []
for t in range(T):
x = X[t]
K_cache.append(x @ Wk); V_cache.append(x @ Wv)
q = x @ Wq
a = softmax(np.array(K_cache) @ q / np.sqrt(d))
outs.append(a @ np.array(V_cache))
print("cached generation equals full recomputation:", np.allclose(np.array(outs), full))
print("projections computed: cached", T, "tokens vs naive", T * (T + 1) // 2)cached generation equals full recomputation: True
projections computed: cached 6 tokens vs naive 21
Cache size
Each layer stores a key and a value vector per token for each KV head:
for layers, key/value heads of size , context and batch . Grouped-query attention reduces (Multi-Head Attention).
def kv_bytes(L, n_kv, d_h, n_ctx, B, bytes_per=2):
return 2 * L * n_kv * d_h * n_ctx * B * bytes_per
configs = [("7B, MHA (32 KV heads)", 32, 32, 128), ("7B-class, GQA (8 KV heads)", 32, 8, 128),
("70B-class, GQA (8 KV heads)", 80, 8, 128)]
for name, L, n_kv, d_h in configs:
per_token = kv_bytes(L, n_kv, d_h, 1, 1)
big = kv_bytes(L, n_kv, d_h, 32768, 8)
print(f"{name:28s}: {per_token / 1024:6.0f} KiB per token, {big / 1e9:6.1f} GB for 8 x 32k tokens")7B, MHA (32 KV heads) : 512 KiB per token, 137.4 GB for 8 x 32k tokens
7B-class, GQA (8 KV heads) : 128 KiB per token, 34.4 GB for 8 x 32k tokens
70B-class, GQA (8 KV heads) : 320 KiB per token, 85.9 GB for 8 x 32k tokens
A 7B model's weights take about 14 GB in bf16; with full multi-head attention, eight 32k-token conversations need about 137 GB of cache, ten times the weights. This is why GQA, cache quantization (8-bit or 4-bit), and paged memory management are standard in serving systems.
Prefill and decode
Inference has two phases. Prefill processes the whole prompt in parallel (compute-bound, like training). Decode generates one token at a time; each step reads all weights and the whole cache to do little arithmetic, so it is memory-bandwidth bound (Counting Parameters and FLOPs). Batching many requests shares the weight reads, but each request brings its own cache, so cache memory limits the batch size.
In software
- Hugging Face
generateusespast_key_values; serving engines such as vLLM manage the cache in fixed-size pages (PagedAttention) to avoid fragmentation and share prompt prefixes. - Prefix caching reuses the KV cache of a shared system prompt across requests.
- Sliding-window attention caps the cache at the window size; multi-head latent attention compresses keys and values into a low-rank latent (LoRA and Low-Rank Adaptation uses the same low-rank idea for weights).
Go further: Fast Inference: KV Cache, Batching and Speculative Decoding shows how serving systems use this memory budget.
Exercises
Exercise 1: Per-token cache
A model has 40 layers, 8 KV heads of size 128, and stores the cache in bf16. How many bytes per token?
Answer
163,840 bytes (160 KiB).
Solution
.
Exercise 2: Work saved
Without a cache, generating tokens recomputes keys and values for positions. How many for , compared with 1000 using a cache?
Answer
500,500 versus 1000.
Solution
. The attention itself still costs at step , but the projections and MLPs run once per token.
Exercise 3: Maximum batch (code)
A GPU has 80 GB. The weights take 14 GB and each token of cache 128 KiB. How many concurrent 8k-token requests fit?
Answer
Solution
Each request needs KiB GiB.
free = 80e9 - 14e9
per_request = 8192 * 128 * 1024
print(int(free // per_request))61
Test yourself
Why can past keys and values be cached during generation?
- They are random
- In a causal model they depend only on earlier tokens, so new tokens do not change them
- Attention is linear
- The model is frozen
The KV cache grows linearly with…
- the vocabulary size
- context length and batch size
- the number of MLP parameters
- the learning rate
The decode phase of LLM inference is usually limited by…
- arithmetic throughput
- memory bandwidth
- disk speed
- the tokenizer