TExcelTAD
Home › Math for Deep Learning & LLMs › The KV Cache and Inference Memory

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 tt recomputes the keys and values of all tt 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 jj in every layer depend only on tokens 1,…,j1, \ldots, j (Causal Masking). Appending token t+1t + 1 cannot change them. So at each step:

  1. compute q,k,v\mathbf{q}, \mathbf{k}, \mathbf{v} for the new token only;
  2. append k,v\mathbf{k}, \mathbf{v} to the cache of each layer;
  3. attend with the single new query over all cached keys and values.
python · try it yourself
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:

KV bytes=2⋅L⋅nkv⋅dh⋅nctx⋅B⋅bytes per value\text{KV bytes} = 2 \cdot L \cdot n_{\text{kv}} \cdot d_h \cdot n_{\text{ctx}} \cdot B \cdot \text{bytes per value}

for LL layers, nkvn_{\text{kv}} key/value heads of size dhd_h, context nctxn_{\text{ctx}} and batch BB. Grouped-query attention reduces nkvn_{\text{kv}} (Multi-Head Attention).

python · try it yourself
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 generate uses past_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

2⋅40⋅8⋅128⋅2=163,8402 \cdot 40 \cdot 8 \cdot 128 \cdot 2 = 163{,}840.

Exercise 2: Work saved

Without a cache, generating TT tokens recomputes keys and values for 1+2+⋯+T1 + 2 + \cdots + T positions. How many for T=1000T = 1000, compared with 1000 using a cache?

Answer

500,500 versus 1000.

Solution

T(T+1)/2=500,500T(T + 1)/2 = 500{,}500. The attention itself still costs O(t)O(t) at step tt, 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 8192⋅1288192 \cdot 128 KiB =1= 1 GiB.

python · try it yourself
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?

  1. They are random
  2. In a causal model they depend only on earlier tokens, so new tokens do not change them
  3. Attention is linear
  4. The model is frozen

The KV cache grows linearly with…

  1. the vocabulary size
  2. context length and batch size
  3. the number of MLP parameters
  4. the learning rate

The decode phase of LLM inference is usually limited by…

  1. arithmetic throughput
  2. memory bandwidth
  3. disk speed
  4. the tokenizer