Shrinking the KV Cache: MQA, GQA, and Multi-Head Latent Attention

The KV cache is LLM serving's memory wall. MQA, GQA, and DeepSeek's Multi-Head Latent Attention shrink it 2 to 8x. We train all four and measure the cost.

Cover Image for Shrinking the KV Cache: MQA, GQA, and Multi-Head Latent Attention

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:

Open In Colab

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.

Animated line chart of validation loss over 3000 training steps for MHA, GQA-2, MQA, and MLA. All four curves drop from about 4.3 to roughly 1.55 and sit almost on top of each other by the end.

Here is what the cache costs at the end of training, and what it buys:

VariantKV cached / token / layerReductionVal lossVal accuracy
MHA (4 KV heads)2561x1.54653.8%
GQA (2 KV heads)1282x1.55754.1%
MQA (1 KV head)644x1.55254.0%
MLA (latent dim 32)328x1.56353.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.

Scatter plot of final validation loss against KV-cache reduction factor on a log-2 x-axis. MHA sits at 1x and loss 1.546, marked with a dashed reference line. GQA-2, MQA, and MLA sit at 2x, 4x, and 8x with losses between 1.552 and 1.563, all within a narrow band just above the MHA line.

What Just Happened?

The redundancy in multi-head attention

Multi-head attention gives every head its own query, key, and value projection. With HH heads, you compute HH separate sets of keys and values, and you cache all of them. For a token at position tt, every one of those 2H2H 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.

Diagram with four panels labelled MHA, GQA-2, MQA, and MLA. Each shows four blue query heads at the top. MHA connects them to four green KV heads, GQA-2 to two, MQA to one shared green KV head, and MLA connects all four to a single red latent vector. Captions read 4 KV heads, 2 KV heads, 1 KV head, and 1 small vector.

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 c\mathbf{c}, and that latent is the only thing cached. Keys and values for all heads are reconstructed from c\mathbf{c} 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 KK and VV 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 c\mathbf{c} 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 2×4×32=2562 \times 4 \times 32 = 256 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.

Two-panel bar chart. Left panel, cached elements per token per layer for the tiny model: MHA 256, GQA-2 128, MQA 64, MLA 32, annotated with 1x, 2x, 4x, 8x. Right panel, projected KV cache in GB for a 7B-scale model at 128K context: MHA 64 GB, GQA 16 GB, MQA 2 GB, MLA 4 GB.

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 dcd_c, then expands it back out. Formally, with input h\mathbf{h}:

c=WDKV h,k=WUK c,v=WUV c\mathbf{c} = W_{DKV}\,\mathbf{h}, \qquad \mathbf{k} = W_{UK}\,\mathbf{c}, \qquad \mathbf{v} = W_{UV}\,\mathbf{c}

Only c\mathbf{c} (dimension dcd_c) is cached. At attention time, WUKW_{UK} and WUVW_{UV} reconstruct full keys and values. If dcd_c is much smaller than 2H dhead2 H \, d_{\text{head}}, 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 HH.

"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

Stay in the loop

Get notified when new tutorials and deep-dives are published. No spam, unsubscribe anytime.

Related Posts

Frequently Asked Questions