Multi-Head Latent Attention
local graph
Chapter 12 — Multi-Head Latent Attention
Section titled “Chapter 12 — Multi-Head Latent Attention”Mixture-of-Experts fixed the cost of parameters. This chapter fixes the cost of memory. At inference, the dominant memory consumer is not the weights but the key/value cache — the stored keys and values of every previous token, reloaded at every step of generation. It grows with context length and with model depth, and it is why long-context inference is expensive. Multi-head Latent Attention (MLA), introduced by DeepSeek-V2 and central to V3, shrinks that cache by roughly an order of magnitude while matching or improving quality. It is, with MoE, one of the two innovations that define the DeepSeek architecture.
12.1 The KV-Cache Bottleneck
Section titled “12.1 The KV-Cache Bottleneck”During generation the model produces one token at a time, and at each step it must attend over all previous tokens. Recomputing their keys and values every step would be wasteful, so they are cached. The size of that cache, per token, is 2 · n_layers · n_heads · d_head values (keys and values, for every head, in every layer). For a deep model at long context this is enormous — often larger than the model weights themselves — and because generation is bottlenecked by reading it from memory, the cache size directly sets both the maximum context you can afford and the speed of decoding. Chapter 2’s roofline argument applies in full: decoding is memory-bound, and the cache is the memory.
12.2 From MHA to GQA to MLA
Section titled “12.2 From MHA to GQA to MLA”The field has attacked this cache in three escalating steps. Multi-head attention (MHA) stores a full set of keys and values for every head — the baseline, and the most expensive. Grouped-query attention (GQA), used by Llama, Qwen, and Mistral, shares one set of keys and values across a group of query heads, cutting the cache by the grouping factor (commonly 8×) at a small quality cost. MLA goes further and changes the representation entirely: rather than store keys and values at all, it stores a single small latent vector per token and reconstructs the keys and values from it on demand. The cache holds the compressed latent, not the expanded heads.
12.3 Low-Rank Compression of Keys and Values
Section titled “12.3 Low-Rank Compression of Keys and Values”The mechanism is the low-rank idea from Chapter 2. A down-projection maps the token to a small latent of dimension d_latent (512 in DeepSeek-V3, versus thousands for full keys and values); an up-projection reconstructs the per-head keys and values from that latent. Only the latent is cached. The simplified core is short:
import torch, torch.nn as nn, torch.nn.functional as F
class MLA(nn.Module): def __init__(self, d_model, n_heads, d_head, d_latent): super().__init__() self.n_heads, self.d_head = n_heads, d_head self.q_proj = nn.Linear(d_model, n_heads * d_head, bias=False) self.kv_down = nn.Linear(d_model, d_latent, bias=False) # cached self.kv_up = nn.Linear(d_latent, n_heads * 2 * d_head, bias=False) # K,V self.o_proj = nn.Linear(n_heads * d_head, d_model, bias=False)
def forward(self, x): # x: (B, T, d_model) B, T, _ = x.shape q = self.q_proj(x).view(B, T, self.n_heads, self.d_head).transpose(1, 2) c = self.kv_down(x) # cached latent kv = self.kv_up(c).view(B, T, self.n_heads, 2 * self.d_head).transpose(1, 2) k, v = kv.split(self.d_head, dim=-1) # split into K, V out = F.scaled_dot_product_attention(q, k, v, is_causal=True) return self.o_proj(out.transpose(1, 2).reshape(B, T, -1))Python — mla.py: Multi-head Latent Attention, simplified core (cache = the latent)
At training time this looks like ordinary attention with an extra bottleneck. The magic is at inference: because only c (size d_latent) is stored per token instead of the full keys and values (size 2 · n_heads · d_head), the cache shrinks dramatically. A further trick called weight absorption folds the up-projection into the query and output projections algebraically, so the expanded keys and values never even need to be materialized during decoding — the attention is computed directly against the cached latent.
12.4 The Wrinkle: Decoupled RoPE
Section titled “12.4 The Wrinkle: Decoupled RoPE”There is one complication, and it is instructive. Rotary position embeddings (Chapter 9) rotate the keys by an angle that depends on absolute position. That rotation cannot be commuted through the low-rank up-projection — if you compress first, you can no longer apply a position-dependent rotation cleanly, because the latent has lost the per-head structure RoPE needs. DeepSeek’s solution is decoupled RoPE: split each head into two parts. A larger content part is compressed through the latent as above and carries no position; a small rotary part (64 dimensions, shared across heads for the key) bypasses the compression and carries RoPE directly. The attention score sums the contributions of both parts. The cache therefore stores the latent plus this one small rotary key — still tiny compared to full keys and values. It is a clean example of an engineering constraint (RoPE and low-rank compression do not mix) producing a specific architectural design.
12.5 The Memory Math
Section titled “12.5 The Memory Math”The payoff is best seen numerically. Table 12.1 compares the per-token, per-layer cache for the three schemes on a representative large configuration. MLA stores only the latent and the small rotary key — a fraction of what even GQA needs, and a small fraction of MHA.
| Scheme | What is cached | Values / token / layer | Relative |
|---|---|---|---|
| MHA (128 heads) | full K and V, every head | ~32,800 | 1.00× |
| GQA (8 KV groups) | K and V for 8 grouped heads | ~2,050 | ~0.06× |
| MLA | one latent (512) + rotary key (64) | ~580 | ~0.018× |
Table 12.1 — Per-token, per-layer KV cache (representative large model, head dim 128)
Figures are illustrative; exact values depend on head count and latent rank. DeepSeek-V2 reports MLA cutting the KV cache to roughly one-thirteenth of an equivalent MHA model (about a 93% reduction) while matching or exceeding its quality — the rare optimization that is both cheaper and better.
MHA / GQA: cache the keys and values MLA: cache one small latent
[ token ] [ token ] | | project to K, V (per head) down-project to latent c (+ rope key) v v +-------------------------+ +--------+ +- - - - - - - + | large KV cache | | latent | -----> : reconstruct : | 2 · n_heads · d_head | +--------+ +- - - - - - - + | per token, per layer | d_latent (+64) K, V on the fly +-------------------------+ ~13× smaller cacheFigure 12.1. MHA stores full keys and values for every head; MLA stores only a small latent per token (plus a tiny rotary key) and reconstructs the keys and values when needed. The cached object is roughly an order of magnitude smaller, which is what makes long-context inference affordable.
12.6 Fast Decoding with FlashMLA
Section titled “12.6 Fast Decoding with FlashMLA”A smaller cache helps only if the attention kernel can exploit it. DeepSeek released FlashMLA, a decoding kernel tuned for MLA’s paged latent cache on modern NVIDIA GPUs (Hopper and Blackwell), giving the memory savings a matching speed-up. The pairing is deliberate: MLA reduces what must be moved, and FlashMLA moves it efficiently. We return to inference kernels in Chapters 14 and 27.
The simplified core above omits the one wrinkle Section 12.4 described: decoupled RoPE. Here is a faithful version that includes it — each head splits into a content part (compressed through the latent, carrying no position) and a small rotary part (carrying RoPE), with a single shared rotary key for the whole layer. This is the structure of DeepSeek-V3’s real MLA, condensed:
class MLA(nn.Module): def __init__(self, dim, n_heads, d_nope, d_rope, d_latent): super().__init__() self.h, self.dn, self.dr = n_heads, d_nope, d_rope self.d_latent = d_latent self.wq = nn.Linear(dim, n_heads * (d_nope + d_rope), bias=False) self.wkv_a = nn.Linear(dim, d_latent + d_rope, bias=False) # cached self.wkv_b = nn.Linear(d_latent, n_heads * 2 * d_nope, bias=False) self.wo = nn.Linear(n_heads * d_nope, dim, bias=False)
def forward(self, x, freqs): B, T, _ = x.shape q = self.wq(x).view(B, T, self.h, self.dn + self.dr) qc, qr = q.split([self.dn, self.dr], dim=-1) # content, rotary qr = apply_rope(qr, freqs) # position in qr only c, kr = self.wkv_a(x).split([self.d_latent, self.dr], dim=-1) kr = apply_rope(kr, freqs) # one shared rope key kc, v = self.wkv_b(c).view(B, T, self.h, 2 * self.dn).split( self.dn, dim=-1) # content K, V q = torch.cat([qc, qr], dim=-1) k = torch.cat([kc, kr[:, :, None].expand(-1, -1, self.h, -1)], -1) o = F.scaled_dot_product_attention( q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2), is_causal=True) return self.wo(o.transpose(1, 2).reshape(B, T, -1))Python — deepseek-ai/DeepSeek-V3 · MLA with decoupled RoPE, essence (reproduced, MIT licence)
Trace the dimensions and the design of Section 12.4 appears exactly. Only wkv_a’s output — the latent c of size d_latent plus the one rotary key kr of size d_rope — needs to be cached, because everything else is reconstructed from it on the fly: the content keys and values come back through wkv_b, and the single kr is shared (expanded) across all heads. The query and key each become the concatenation of a content half and a rotary half, so the attention score is automatically the sum of a content term (through the compressed path) and a positional term (through RoPE) — the two contributions Section 12.4 promised. DeepSeek-V3’s shipped MLA adds one more compression (the queries also pass through a low-rank latent, via a q_lora_rank) and the weight-absorption trick that fuses wkv_b into the surrounding projections so the full keys and values are never materialized at decode time; FlashMLA is the kernel that runs all of this efficiently. The essence, though — cache a small latent, reconstruct the rest, keep position in a tiny decoupled key — is exactly the code above.
Key point MoE and MLA are complementary. MoE lets the model hold vast knowledge while activating little of it per token; MLA lets the model attend over long contexts while caching little of it per token. Together they are why a 671-billion-parameter model with a 128K context can be served at a cost that, only a year or two earlier, would have been unthinkable.
Two of the three inefficiencies named at the end of Chapter 10 are now addressed: dense computation (by MoE) and the bloated cache (by MLA). The third — predicting only one token at a time — is the subject of the next chapter, where multi-token prediction densifies the training signal and, as a bonus, accelerates inference.
12.7 Worked Example: How MLA Shrinks the KV Cache
Section titled “12.7 Worked Example: How MLA Shrinks the KV Cache”Multi-Head Latent Attention earns its place through a single number: the size of the KV cache it must store. Where standard attention caches a full key and value vector for every head at every position, MLA caches a single low-rank latent and reconstructs the keys and values from it on the fly:
# compress once: store a small latent instead of full K, Vc = x @ W_down # [T, kv_lora_rank] e.g. 512 dims
# reconstruct keys and values from the cached latent when neededK = c @ W_up_k # expand to n_heads x head_dimV = c @ W_up_vPython — mla/cache.py: cache the latent, reconstruct K and V (illustrative)
Only the latent c — a few hundred dimensions per token per layer — lives in the cache, in place of the full keys and values across every head. For the configuration worked through in Section 27.7, this collapses a 335-gigabyte cache at 128K tokens to roughly twelve gigabytes, an almost thirty-fold reduction. The up-projection matrices that reconstruct K and V are part of the model’s fixed weights, paid for once, while the per-token cache — the quantity that grows without bound at long context — is what MLA compresses. That trade, a little extra compute to reconstruct in exchange for an order-of-magnitude smaller cache, is what makes long-context inference economically possible, and it is the reason MLA sits at the heart of both DeepSeek-V3 and GLM-5.2.
Cache the latent, rebuild the rest MLA stores a compressed latent per token and reconstructs full keys and values from it on demand. The fixed reconstruction weights cost nothing per token; the cache that grows with context shrinks by an order of magnitude. That is the whole win.
12.8 MLA and RoPE: The Decoupled Position Trick
Section titled “12.8 MLA and RoPE: The Decoupled Position Trick”Multi-Head Latent Attention compresses keys and values into a shared latent (Section 12.7), but this collides with rotary position embeddings (Chapter 9) in a way worth understanding, because the resolution is a genuine piece of frontier engineering rather than a tidy abstraction. RoPE rotates each key by an angle that depends on its position — but if keys are reconstructed from a position-independent compressed latent, there is no full key to rotate at cache time, and applying the rotation after reconstruction would defeat the compression.
DeepSeek’s solution is to decouple the position-carrying part of the key from the rest. Each cached entry is split: a compressed latent that holds the bulk of the key and value content (position-independent, and shared across heads), plus a small, separate key component that does carry RoPE’s rotation. Attention then combines the two — the reconstructed content from the latent and the rotary signal from the small decoupled key — recovering position-awareness without forcing the whole key to be stored uncompressed. The cache therefore holds a large shared latent and a small per-token rotary key, which is still dramatically smaller than full keys and values across every head (Section 27.7) while remaining compatible with the relative-position mechanism the model depends on. This detail rarely appears in high-level descriptions, but it is exactly the kind of careful reconciliation — between two techniques that individually work but jointly conflict — that distinguishes a real architecture from a sketch of one.
Carry position separately Compression and RoPE conflict, because a compressed latent has no full key to rotate. MLA splits off a small rotary key alongside the shared latent, keeping position-awareness and most of the cache savings — a reconciliation of two techniques that clash by default.
12.9 The KV Cache in Numbers
Section titled “12.9 The KV Cache in Numbers”MLA’s benefit is easiest to grasp as arithmetic. The KV cache stores, for every layer and every past token, the keys and values attention needs (Section 27.2). How much that is depends directly on the attention variant, and comparing the three side by side makes MLA’s advantage concrete:
| Variant | Cache size scales as |
|---|---|
| Multi-head (MHA) | 2 × layers × heads × head_dim × seq |
| Grouped-query (GQA) | 2 × layers × groups × head_dim × seq |
| Latent (MLA) | 2 × layers × latent_dim × seq |
Table 12.2 — KV cache size per sequence (schematic)
The story is in which quantity multiplies the rest. Standard multi-head attention pays for the full head count; grouped-query attention (Section 7.6) shrinks that by sharing key/value heads across groups, a factor of head count over group count. MLA instead stores a latent whose dimension is far smaller than heads times head dimension, so its cache is dramatically smaller than full multi-head attention — for configurations like DeepSeek-V3’s, roughly an order of magnitude. Because the cache grows linearly with sequence length and batch size, that constant factor is decisive at the limits that matter: at long context or high concurrency, an order-of-magnitude smaller cache is the difference between a workload fitting on a GPU and not (Section 27.10). The architecture of Chapter 12 is, in the end, a bet that compressing this one quantity unlocks the long-context, high-throughput regime — and the arithmetic above is why the bet pays off.
The cache is a constant factor that decides the limits MHA pays for every head, GQA for every group, MLA only for a small latent — roughly an order of magnitude less than MHA at DeepSeek-V3 scale. Since the cache grows with length and batch, that factor decides whether long-context, high-concurrency workloads fit.