By Sagi Shaier · 12 November 2026 · 6 min read
KV cache and grouped-query attention explained
What a transformer stores at each generation step, how big that store gets for a real model size, and how sharing key and value heads cuts it by four, with PyTorch code that checks each step.
A KV cache stores the keys and values that a transformer has already computed for earlier tokens, so that each new step of text generation computes them only for the newest token. Grouped-query attention (GQA) is a change to the attention layer that makes this cache smaller by letting several query heads share one set of keys and values. Both are about the cost of generating text one token at a time.
Why generation repeats work
A GPT-style model writes text one token at a time. At each step it runs the decoder on everything written so far, called the prefix, picks the next token and appends it. Inside every attention layer, each token gets three vectors: a query, a key and a value. The new token's query is compared with the keys of all tokens to get attention weights, and those weights mix the values into the token's output.
Without any shortcut, the step that writes token 6 recomputes keys and values for tokens 1 to 5, even though the step that wrote token 5 already computed them. The earlier tokens do not change, and with the causal mask they never attend to later tokens, so their keys and values come out the same every time. Storing them once and reusing them at every later step is called a KV cache.
The cache in one layer
At each generation step, one layer does four things:
- Compute the query, key and value for the new token only.
- Append the new key to the cached keys and the new value to the cached values.
- Let the new query attend over all cached keys and values, including the new ones.
- Produce one output vector for the new token.

The cache does not make generation parallel. The model still writes one token per step, and the cache removes the repeated work inside each step.
The code below checks that the cache changes the cost and not the result. It runs one attention head on 6 token vectors and computes the output for token 6 twice, once by recomputing every key and value and once from a cache that holds tokens 1 to 5:
1import torch
2
3torch.manual_seed(0)
4d = 4
5W_q, W_k, W_v = (torch.randn(d, d) for _ in range(3))
6x = torch.randn(6, d) # embeddings of 6 tokens, one row each
7
8def attend(q, K, V):
9 weights = torch.softmax(q @ K.T / d ** 0.5, dim=-1)
10 return weights @ V
11
12# Without a cache: recompute K and V for the whole prefix at step 6.
13full = attend(x[5] @ W_q, x @ W_k, x @ W_v)
14
15# With a cache: K and V for tokens 1 to 5 were stored at earlier steps.
16K_cache, V_cache = x[:5] @ W_k, x[:5] @ W_v
17k_new, v_new = x[5] @ W_k, x[5] @ W_v
18K = torch.cat([K_cache, k_new[None]]) # append on the position axis
19V = torch.cat([V_cache, v_new[None]])
20cached = attend(x[5] @ W_q, K, V)
21
22print(K.shape, torch.allclose(full, cached)) # torch.Size([6, 4]) TrueBoth outputs match. The cached version computed one key and one value instead of six. If the two disagree in your own code, check that the new key was appended on the position axis and not the feature axis.
How big the cache gets
In a real model each layer keeps its own cache, and attention has several heads, each with its own keys and values. A common per-layer shape is:
$$\text{keys: (batch, kv\_heads, past\_len, head\_dim)}$$
$$\text{values: (batch, kv\_heads, past\_len, head\_dim)}$$
Here batch is the number of sequences generated together, kv_heads is the number of key/value heads, past_len is the number of tokens so far and head_dim is the length of each head's vectors. Every new token adds one slice along the past_len axis.

Multiply the shape out, double it for keys and values, and multiply by the number of layers and the bytes per number to get the cache size. Take a model with 32 layers, 32 key/value heads and a head_dim of 128 that stores 16-bit numbers (2 bytes each). It generates one sequence of 4096 tokens:
1def kv_cache_bytes(layers, kv_heads, head_dim, seq_len, batch=1, bytes_per_value=2):
2 # 2 tensors (keys and values) per layer, each (batch, kv_heads, seq_len, head_dim)
3 return 2 * layers * batch * kv_heads * seq_len * head_dim * bytes_per_value
4
5mha = kv_cache_bytes(layers=32, kv_heads=32, head_dim=128, seq_len=4096)
6print(mha / 2**30, "GiB with 32 K/V heads") # 2.0 GiB with 32 K/V headsThat is 2 GiB for a single sequence, and it doubles with every doubling of the length or the batch. The memory goes up with generated length, number of layers, number of key/value heads and head_dim. Grouped-query attention reduces the number of key/value heads.
Grouped-query attention
In standard multi-head attention every head has its own queries, keys and values, so a model with 32 query heads also caches 32 key/value heads. Grouped-query attention keeps many query heads but uses fewer key/value heads. Several query heads form a group and share one key/value head.
Write $H_q$ for the number of query heads, $H_k$ for the number of key/value heads, $T$ for the number of tokens and $d_k$ for the head size. The query tensor $Q$ has shape $(B, H_q, T, d_k)$, while $K$ and $V$ have shape $(B, H_k, T, d_k)$ with $H_k$ smaller than $H_q$. Only $K$ and $V$ go into the cache, so the cache shrinks by the factor $H_q / H_k$.

Take a model with 16 query heads and 4 key/value heads. Each key/value head is shared by
$$16 \text{ query heads} / 4 \text{ kv heads}$$
$$= 4 \text{ query heads per kv head}$$

In code, the 4 key/value heads are repeated so that each of the 16 query heads has a key and value tensor to attend over. The cache stores the small tensors and the repeat happens at attention time:
1import torch
2
3B, T, head_dim = 1, 10, 64
4n_q_heads, n_kv_heads = 16, 4
5group = n_q_heads // n_kv_heads # 4 query heads per K/V head
6
7q = torch.randn(B, n_q_heads, T, head_dim)
8k = torch.randn(B, n_kv_heads, T, head_dim) # this is what the cache stores
9v = torch.randn(B, n_kv_heads, T, head_dim)
10
11k_expanded = k.repeat_interleave(group, dim=1) # (B, 16, T, head_dim)
12v_expanded = v.repeat_interleave(group, dim=1)
13scores = q @ k_expanded.transpose(-2, -1) / head_dim ** 0.5
14out = torch.softmax(scores, dim=-1) @ v_expanded
15
16print(k.shape, k_expanded.shape, out.shape)
17# torch.Size([1, 4, 10, 64]) torch.Size([1, 16, 10, 64]) torch.Size([1, 16, 10, 64])
18print(torch.equal(k_expanded[:, 0], k_expanded[:, 3]), torch.equal(k_expanded[:, 3], k_expanded[:, 4]))
19# True FalseQuery heads 0 to 3 read the same keys, and query head 4 starts the next group. The output still has 16 heads, one per query head.
Back to the 32-layer model from the memory example. With 8 key/value heads instead of 32, the same 4096-token sequence needs a quarter of the cache:
1gqa = kv_cache_bytes(layers=32, kv_heads=8, head_dim=128, seq_len=4096)
2print(gqa / 2**30, "GiB with 8 K/V heads") # 0.5 GiB with 8 K/V headsA smaller cache also means less data to read from memory at every step, which helps most with long prefixes.
Common mistakes
- Expecting the cache to make generation parallel. Each step still waits for the token before it. The cache only cuts the repeated key and value work inside a step.
- Caching the queries. Only keys and values are reused. Each step needs the query of the new token alone.
- Appending on the wrong axis. New keys and values go on the
past_lenaxis, the third axis in the shape(batch, kv_heads, past_len, head_dim). - Forgetting that the cache grows with the batch. Generating 8 sequences at once needs 8 times the cache of one.
- Reducing query heads instead of key/value heads. GQA keeps all the query heads. The number of query heads also has to be a multiple of the number of key/value heads, so the groups come out even.
Related concepts
Causal masking explained shows why earlier tokens never attend to later ones, which is what makes their keys and values safe to reuse. Multi-head attention explained covers how the heads split the model dimension, and build a small GPT from scratch has the generation loop the cache speeds up. Modern transformer variants covers the other common changes to the block, RoPE, RMSNorm and SwiGLU.
QuiddityML teaches the KV cache and grouped-query attention as one concept in the Intro to NLP track. The exercises include picking which cache axis grows with each token, putting the lines of one cached generation step in order and following the cache shape as a new token is appended.