QuiddityML

By · 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:

  1. Compute the query, key and value for the new token only.
  2. Append the new key to the cached keys and the new value to the cached values.
  3. Let the new query attend over all cached keys and values, including the new ones.
  4. Produce one output vector for the new token.

The KV cache in one decoder layer at generation step t plus 1. Only the new token goes through the linear projections, giving k_new, v_new and q_new, each of shape (batch, kv_heads, 1, head_dim). k_new is appended after positions 0, 1 and 2 in the cached keys, and v_new after the cached values, on the past_len axis. q_new attends over the cached keys and values plus the new ones and gives one output vector for the new token. The cache removes repeated work inside each step and does not make the steps parallel.

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]) True

Both 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.

KV cache shapes: keys and values each have shape (batch, kv_heads, past_len, head_dim). Along the past_len axis sit pos 0, pos 1, pos 2 and the new token. At each generation step the model computes K and V for the new token and appends them on the past_len axis. The new query attends over all cached positions plus the current one. Cache memory grows with generated length, layer count, kv_heads and head_dim.

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 heads

That 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$.

Grouped-query attention. Tensor shapes: Q has shape (B, H_q, T, d_k), K and V have shape (B, H_k, T, d_k), and H_k is smaller than H_q. Query heads 1, 2 and 3 all point to one shared K and V group, and one group is shown. Fewer K and V streams means less cache memory and bandwidth during generation.

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}$$

GQA shape example: 16 query heads / 4 kv heads = 4 query heads per kv head. Query heads 1, 2, 3 and 4 each have one arrow into kv head 1, so four query heads read the same K and V. 1 of 4 kv head groups is shown. Fewer K and V streams means a smaller cache.

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 False

Query 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 heads

A smaller cache also means less data to read from memory at every step, which helps most with long prefixes.

Common mistakes

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.