A language-model server handles short conversations comfortably, then begins running out of memory when users bring longer documents. Part of that growth comes from the KV cache, which keeps information about earlier tokens so the model can reuse it. Shrinking the cache means examining what each attention head needs to store. Our 7B-class sizing example needs 64 GB of cache for one 128K request with full multi-head attention.
Llama-3 uses grouped-query attention to share keys and values, while DeepSeek-V2 compresses them through multi-head latent attention. We fit both arrangements in the same small transformer, checking the storage arithmetic against measured prediction quality. Changing the attention block sets how many vectors each token needs to retain.
This post is the direct sequel to why LLM inference runs out of memory. The attention layouts below reduce storage per token. We build one tiny transformer with a switchable attention block, train all four variants on the same data, and measure two things side by side: how much the cache shrinks (deterministic arithmetic) and what that costs in quality (the part that can bite you). By the end you will know why an 8x smaller cache can cost roughly 1% in loss, and when that trade is worth taking.
Let's Build It
Click the badge to open the interactive notebook:
We train a 4-layer, 4-head character-level transformer on tiny-shakespeare, four times over, changing only the attention block. The query heads stay identical. What changes is how many key-value heads they share, and for MLA, whether we cache full K and V at all. All four converge to almost the same validation loss.

Here is what the cache costs at the end of training, and what it buys:
| Variant | KV cached / token / layer | Reduction | Val loss | Val accuracy |
|---|---|---|---|---|
| MHA (4 KV heads) | 256 | 1x | 1.546 | 53.8% |
| GQA (2 KV heads) | 128 | 2x | 1.557 | 54.1% |
| MQA (1 KV head) | 64 | 4x | 1.552 | 54.0% |
| MLA (latent dim 32) | 32 | 8x | 1.563 | 53.3% |
The cache drops by 8x from top to bottom. Validation loss moves by about 1%, and next-token accuracy barely moves at all. GQA and MQA actually edge out plain MHA on accuracy here, which is noise, but it makes the point: at this scale the compression is close to free.

What Just Happened?
The redundancy in multi-head attention
Multi-head attention gives every head its own query, key, and value projection. With heads, you compute separate sets of keys and values, and you cache all of them. For a token at position , every one of those vectors has to be stored so future tokens can attend back to it.
The observation behind every trick in this post: queries genuinely benefit from being different per head (each head asks a different question), but keys and values are far more shareable. You can hand several query heads the same key-value head and lose surprisingly little. The cache stores keys and values, not queries, so sharing K and V is exactly where the savings live.

The three sharing schemes
Multi-Query Attention (MQA) is the extreme: all query heads share one key-value head. With 4 heads, that cuts the cached K and V by 4x. Shazeer proposed it in 2019 precisely to make autoregressive decoding cheaper, since the KV cache is what you re-read at every step.
Grouped-Query Attention (GQA) is the compromise that won. Instead of one shared KV head (MQA) or one per query head (MHA), you pick a number in between. Group the 4 query heads into 2 groups, give each group its own KV head, and you cut the cache by 2x while keeping more of MHA's expressiveness. Llama-2 70B, Llama-3, Mistral, and Gemma all use GQA. It is the default modern choice.
Multi-Head Latent Attention (MLA) takes a different route. Rather than reducing the number of KV heads, it compresses the KV representation. The token is projected down to a small latent vector , and that latent is the only thing cached. Keys and values for all heads are reconstructed from on demand. Cache a 32-dim latent instead of 256 dims of K and V, and you get an 8x reduction while every head still gets its own full-width key and value.
Going Deeper
One attention block, four behaviours
The cleanest way to see the difference is to write a single attention module where the variant is a config flag. Queries are always projected per head. The MHA/GQA/MQA path projects and over n_kv heads and repeats them to line up with the query heads. The MLA path replaces that with a down-projection to a latent, then two up-projections.
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class CausalAttention(nn.Module):
def __init__(self, cfg):
super().__init__()
self.cfg, self.n_head, self.head_dim = cfg, cfg.n_head, cfg.head_dim
d = cfg.n_head * cfg.head_dim
# n_kv: how many key-value heads this variant keeps
self.n_kv = {"mha": cfg.n_head, "mqa": 1,
"gqa": cfg.n_kv_head, "mla": cfg.n_head}[cfg.attn]
if cfg.attn == "mla":
self.W_q = nn.Linear(d, cfg.n_head * cfg.head_dim, bias=False)
self.W_dkv = nn.Linear(d, cfg.d_latent, bias=False) # down-project
self.W_uk = nn.Linear(cfg.d_latent, cfg.n_head * cfg.head_dim, bias=False)
self.W_uv = nn.Linear(cfg.d_latent, cfg.n_head * cfg.head_dim, bias=False)
else:
self.W_q = nn.Linear(d, cfg.n_head * cfg.head_dim, bias=False)
self.W_k = nn.Linear(d, self.n_kv * cfg.head_dim, bias=False)
self.W_v = nn.Linear(d, self.n_kv * cfg.head_dim, bias=False)
self.proj = nn.Linear(cfg.n_head * cfg.head_dim, d, bias=False)
The forward pass is where the cache story shows up. For MHA/GQA/MQA, repeat_interleave broadcasts each shared KV head across its group of query heads. For MLA, the latent is computed once and both K and V are read out of it.
def forward(self, x, mask):
B, T, _ = x.shape
H, hd = self.n_head, self.head_dim
q = self.W_q(x).view(B, T, H, hd).transpose(1, 2) # (B, H, T, hd)
if self.cfg.attn == "mla":
c = self.W_dkv(x) # (B, T, d_latent) <- the cached vector
k = self.W_uk(c).view(B, T, H, hd).transpose(1, 2)
v = self.W_uv(c).view(B, T, H, hd).transpose(1, 2)
else:
k = self.W_k(x).view(B, T, self.n_kv, hd).transpose(1, 2)
v = self.W_v(x).view(B, T, self.n_kv, hd).transpose(1, 2)
if self.n_kv != H: # share KV across query heads
rep = H // self.n_kv
k, v = k.repeat_interleave(rep, 1), v.repeat_interleave(rep, 1)
att = (q @ k.transpose(-2, -1)) / math.sqrt(hd)
att = att.masked_fill(mask[:, :, :T, :T] == 0, float("-inf"))
y = (F.softmax(att, dim=-1) @ v).transpose(1, 2).reshape(B, T, H * hd)
return self.proj(y)
The cache arithmetic, made explicit
The cache size is pure counting. For everything except MLA you store keys and values for n_kv heads; MLA stores one latent vector.
def kv_cached_per_token_per_layer(cfg):
if cfg.attn == "mha": return 2 * cfg.n_head * cfg.head_dim # K and V, all heads
if cfg.attn == "gqa": return 2 * cfg.n_kv_head * cfg.head_dim # K and V, grouped
if cfg.attn == "mqa": return 2 * 1 * cfg.head_dim # K and V, one head
if cfg.attn == "mla": return cfg.d_latent # one latent, no K/V stored
With 4 heads and head dimension 32, MHA caches numbers per token per layer; MLA with a 32-dim latent caches 32. That 8x ratio is fixed by the architecture, not by training. It is the deterministic half of the story, and it is exactly what shrinks your memory bill.
The other half, quality, is the half that can surprise you, which is why we trained all four rather than trusting the arithmetic alone.
What the numbers say at production scale
The toy model makes the mechanics visible; the savings only matter at scale. Take a 7B-class model: 32 layers, 32 query heads, head dimension 128, BF16, a full 128K-token context. The same formulas give the cache size in gigabytes.

Full MHA would need 64 GB of KV cache for a single 128K request, four times the model weights. GQA with 8 KV heads (the Llama-3 configuration) brings that to 16 GB. MQA collapses it to 2 GB, and MLA with a 512-dim latent lands at 4 GB. The right panel shows why MLA is interesting even though MQA caches fewer bytes here: MQA buys its tiny cache by collapsing to a single KV head, which tends to dent quality at scale, whereas MLA keeps every head full-width and reconstructs them from the latent. You get most of MQA's memory win without MQA's quality risk. DeepSeek-V2 reports MLA matching or beating full MHA while cutting the cache by an order of magnitude.
MLA is a low-rank bottleneck, and you have seen it before
The mechanism inside MLA is a low-rank factorisation. Instead of a full-rank map from the residual stream to keys and values, MLA forces the information through a narrow latent of dimension , then expands it back out. Formally, with input :
Only (dimension ) is cached. At attention time, and reconstruct full keys and values. If is much smaller than , the cache shrinks accordingly. This is the same low-rank trick that makes LoRA fine-tuning 1000x cheaper: a big matrix is replaced by the product of two skinny ones because the useful information lives on a low-dimensional subspace. LoRA applies it to weight updates; MLA applies it to the KV representation.
There is one wrinkle real MLA has to handle that our minimal version sidesteps. Rotary position embeddings (RoPE) do not commute with the up-projection, so DeepSeek splits each key into a compressed part and a small "decoupled" RoPE part that is cached separately. We use learned positional embeddings instead, which keeps the latent path clean and the teaching point intact: cache a small latent, reconstruct K and V on demand.
When sharing goes too far
Sharing KV heads is not free in general, even though it looks free here. Two failure modes matter:
The first is scale-dependent quality loss. MQA's single KV head is the aggressive end, and at large scale it can underperform MHA on tasks that need diverse attention patterns. GQA exists precisely because the community found MQA gave up too much, and a middle ground recovered most of the quality. Our toy model is too small and the task too easy to expose this, which is the honest caveat: the 1% loss gap you see at 824K parameters is not a promise about a 7B model. The direction generalises (smaller cache, modest quality cost); the magnitude depends on scale and task.
The second is training, not retrofitting. You cannot take a trained MHA model and simply drop heads to get MQA. These variants are trained from scratch with the shared structure, or converted with a dedicated "uptraining" step (Ainslie et al. show GQA can be distilled from an MHA checkpoint with a small amount of extra training). The sharing has to be baked in while the weights are learned.
This is the same flavour of architectural lever as Mixture of Experts: MoE attacks the FLOPs side of LLM cost by activating only a few experts per token, while KV sharing attacks the memory side by caching less per token. Modern frontier models, DeepSeek-V3 among them, stack both.
Where This Comes From
The KV-sharing family has a clean lineage, each paper a response to the last.
Shazeer (2019), "Fast Transformer Decoding: One Write-Head is All You Need", introduced Multi-Query Attention. The motivation was decoding bandwidth: at each generation step you re-read the entire KV cache from memory, and that memory traffic, not arithmetic, is the bottleneck. Collapsing to a single KV head cuts the bytes you re-read by a factor of .
"We propose a variant called multi-query attention, where the keys and values are shared across all of the different attention heads, greatly reducing the size of these tensors and hence the memory bandwidth requirements of incremental decoding."
Ainslie et al. (2023), "GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints", introduced Grouped-Query Attention as the interpolation between MHA and MQA. They also showed you can uptrain an existing MHA checkpoint into GQA with about 5% of original pre-training compute, which is why GQA spread so fast: you did not have to retrain from scratch.
DeepSeek-AI (2024), the DeepSeek-V2 technical report, introduced Multi-Head Latent Attention. The low-rank latent compresses the KV cache far below GQA while, they report, improving on MHA quality. MLA is one of the two pillars (the other being their MoE design) behind DeepSeek's serving efficiency.
Pope et al. (2022), "Efficiently Scaling Transformer Inference", is the systems-level companion: it lays out the arithmetic of why KV-cache memory bandwidth dominates the cost of long-context, large-batch decoding, the constraint all of these tricks are designed to relax.
The thread connecting them is the same insight this post measured. The query heads carry the diversity worth paying for; the key-value cache is where the redundancy hides; and squeezing that cache, by sharing heads or by low-rank projection, is the cheapest lever in modern LLM serving. The matrices that get factorised here are the same Q, K, V projections whose gradients we derived in the backpropagation walkthrough, and the compression problem they create downstream is the one TurboQuant attacks with quantisation rather than architecture.
Further Reading
- Shazeer (2019), "Fast Transformer Decoding: One Write-Head is All You Need": Multi-Query Attention
- Ainslie et al. (2023), "GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints": Grouped-Query Attention
- DeepSeek-AI (2024), "DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Model": Multi-Head Latent Attention
- Pope et al. (2022), "Efficiently Scaling Transformer Inference": the memory-bandwidth case for all of the above
Interactive Tools
- Attention Visualizer: The K and V vectors this post is compressing, one head at a time. Step through the score matrix and the softmax to see exactly what a shared or latent key has to reproduce
- LLM Cost Calculator: Compare live pricing across 300+ APIs; the KV-cache reductions in this post are a large part of why some providers serve long context far cheaper than others
- Normal Distribution Calculator: Inspect the Gaussian-like activation distributions that the MLA latent projection has to compress without losing the directions attention depends on
Related Posts
- KV Cache Memory: Sizing LLM Inference: The prerequisite: how the KV cache works and why it becomes the memory wall this post tears down
- Mixture of Experts in LLMs: From Switch to DeepSeek-V3: The companion lever; MoE cuts FLOPs per token while KV sharing cuts memory per token, and DeepSeek-V3 stacks both
- LoRA from Scratch: Why LLM Fine-Tuning Got 1000x Cheaper: The same low-rank factorisation that powers MLA, applied to weight updates instead of the KV cache
- TurboQuant: How a Random Rotation Makes LLM Quantization Near-Optimal: The quantisation route to a smaller cache; architecture and quantisation are complementary, not rival, solutions
- Backpropagation Demystified: Neural Nets from First Principles: How the Q, K, and V projection matrices that these tricks reshape are learned in the first place
- Vision Transformers from Scratch in PyTorch: The same transformer block these attention tricks optimise, applied to images instead of text
- Parallel LLM Decoding: Speculative and Diffusion: A complementary inference-speed lever; KV sharing shrinks memory per step while parallel decoding cuts the number of sequential steps
- Beyond Attention: Linear Attention and Mamba SSMs: Where these tricks shrink the KV cache, linear attention and state-space models remove it, trading softmax attention for a recurrence with constant memory
- LLM Serving: Continuous Batching and PagedAttention: These tricks shrink the cache; the serving layer then pages and batches what remains across concurrent requests









