Prove how Multi-head Latent Attention (MLA) absorbs decompression matrices into Query and Output projections to slash KV cache by 93.3%, overlap all-to-all MoE traffic with DualPipe, and disaggregate Prefill from Decode.
1.Why GQA was not the final word on KV cache compression#
In Chapter 1, Grouped-Query Attention (GQA) reduced the KV cache of an 8B/70B model by by forcing groups of query heads to share identical Key and Value heads. Yet sharing heads reduces the expressive rank of the attention kernel. Can we give every single attention head its own distinct Key and Value representations while caching even fewer bytes than GQA?
DeepSeek-V2 (arXiv:2405.04434[3]DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language ModelOpen arXiv:2405.04434 ↗) and DeepSeek-V3 ( total parameters, active per token, arXiv:2412.19437[4]DeepSeek-V3 Technical ReportOpen arXiv:2412.19437 ↗) answered yes with Multi-head Latent Attention (MLA). Instead of projecting hidden state directly to heads of dimension , MLA first projects down into a shared low-rank latent vector (where ):
If we had to materialize and in HBM during decoding, no memory would be saved. The breakthrough of MLA is associative matrix absorption: during inference, the up-projection matrices are absorbed directly into the Query projection and Output projection!
Consider the unscaled attention score between head 's query at step and historical key at step :
Similarly, for the value weighted sum across historical positions with attention weights :
Thus only the single compressed latent vector is ever stored in the KV cache!
Why Decoupled RoPE is mandatory: If we applied position-dependent rotation between and , the intermediate matrix would become , which depends on and cannot be absorbed into without recomputing keys for every historical token . DeepSeek-V2 solves this via Decoupled RoPE: it splits off a tiny shared rotary key () alongside per-head rotary queries . The total cached state per token per layer is simply of width elements—a KV cache reduction compared to MHA!
class MultiHeadLatentAttention(nn.Module):
"""
Demonstrates the algebraic equivalence between:
1. Explicit Up-Projection (training path): materialize K = c_kv @ W_uk^T, V = c_kv @ W_uv^T
2. Matrix-Absorbed Inference (decoding path): cache only c_kv (dimension d_c << H * d_h),
absorb W_uk into q_absorbed = q @ W_uk, and absorb W_uv after softmax.
"""
def __init__(self, d_model: int, num_heads: int, head_dim: int, d_c: int):
super().__init__()
self.num_heads = num_heads
self.head_dim = head_dim
self.d_c = d_c
self.wq = nn.Linear(d_model, num_heads * head_dim, bias=False)
self.w_dkv = nn.Linear(d_model, d_c, bias=False)
# Per-head up-projection weights stored as [H, head_dim, d_c]
self.w_uk = nn.Parameter(torch.randn(num_heads, head_dim, d_c) / math.sqrt(d_c))
self.w_uv = nn.Parameter(torch.randn(num_heads, head_dim, d_c) / math.sqrt(d_c))
self.wo = nn.Linear(num_heads * head_dim, d_model, bias=False)
def forward_explicit(self, x: Tensor) -> tuple[Tensor, int]:
b, s, _ = x.shape
q = self.wq(x).view(b, s, self.num_heads, self.head_dim).transpose(1, 2) # [B, H, S, D]
c_kv = self.w_dkv(x) # [B, S, d_c]
# Materialize full per-head K and V: [B, H, S, D]
k = torch.einsum("bsd,hcd->bhsc", c_kv, self.w_uk)
v = torch.einsum("bsd,hcd->bhsc", c_kv, self.w_uv)
explicit_cache_elems = 2 * k.numel()
scores = (q @ k.transpose(-2, -1)) / math.sqrt(self.head_dim)
mask = torch.triu(torch.full((s, s), float("-inf"), device=x.device), diagonal=1)
probs = F.softmax(scores + mask, dim=-1)
out = (probs @ v).transpose(1, 2).contiguous().view(b, s, -1)
return self.wo(out), explicit_cache_elems
def forward_absorbed(self, x: Tensor) -> tuple[Tensor, int]:
b, s, _ = x.shape
q = self.wq(x).view(b, s, self.num_heads, self.head_dim).transpose(1, 2) # [B, H, S, D]
c_kv = self.w_dkv(x) # [B, S, d_c] -- ONLY this compressed latent tensor is cached!
compressed_cache_elems = c_kv.numel()
# Absorb W_uk into Q: q_abs [B, H, S, d_c] = q [B, H, S, D] @ W_uk [H, D, d_c]
q_abs = torch.einsum("bhsd,hdc->bhsc", q, self.w_uk)
# Dot product directly against shared latent cache c_kv [B, S, d_c]
scores = torch.einsum("bhsc,btc->bhst", q_abs, c_kv) / math.sqrt(self.head_dim)
mask = torch.triu(torch.full((s, s), float("-inf"), device=x.device), diagonal=1)
probs = F.softmax(scores + mask, dim=-1)
# Aggregate latent vectors first: [B, H, S, d_c], then project up with W_uv
latent_context = torch.einsum("bhst,btc->bhsc", probs, c_kv)
head_out = torch.einsum("bhsc,hdc->bhsd", latent_context, self.w_uv)
out = head_out.transpose(1, 2).contiguous().view(b, s, -1)
return self.wo(out), compressed_cache_elemsIn our companion CPU verification (labs/llm/deepseek-mla-grpo), forward_explicit and forward_absorbed match to within in float64 while compressing the cached tensor footprint by more than an order of magnitude.
2.DeepSeek-V3: Auxiliary-Loss-Free MoE, DualPipe, and FP8 Co-Design#
Training the -parameter DeepSeek-V3 model on just H800 GPU hours () required three additional systems breakthroughs:
- Fine-Grained DeepSeekMoE with Auxiliary-Loss-Free Load Balancing: Instead of 8 coarse experts, DeepSeek-V3 uses shared expert and routed experts per layer ( routed active per token). Traditional MoE models add an auxiliary load-balancing loss to prevent routing collapse, but large auxiliary penalties degrade language modeling quality. DeepSeek-V3 introduces a dynamic per-expert bias term added only during Top- selection () while weighting the output by the unperturbed affinity . After every step, is decremented by for overloaded experts and incremented by for underloaded experts—achieving balanced expert routing with zero gradient interference!
- DualPipe Bidirectional Pipeline Parallelism: Cross-node Expert Parallelism (EP) introduces heavy
DispatchandCombineAll-to-Allnetwork communication across InfiniBand. DualPipe feeds micro-batches from both ends of the pipeline simultaneously and splits backward computation into input gradients () and weight gradients (), completely overlapping bidirectionalAll-to-Allcommunication inside fine-grained compute chunks while cutting pipeline bubbles in half. - Fine-Grained FP8 Mixed-Precision Training: To double Tensor Core throughput over
bfloat16without activation outliers causing overflow in E4M3 FP8, DeepSeek-V3 quantizes activations in tile blocks and weights in blocks, periodically accumulating partial sums from Tensor Cores into FP32 CUDA registers every elements.
3.DistServe: Prefill-Decode (PD) Disaggregation#
Even with MLA and PagedAttention, colocating Prefill and Decode requests on the same GPU pool creates severe latency interference (Zhong et al., DistServe, arXiv:2401.09670[2]DistServe: Disaggregating Prefill and Decoding for Goodput-optimized LLM ServingOpen arXiv:2401.09670 ↗):
- Prefill optimizes for Time-To-First-Token (TTFT) and is Compute-bound even at .
- Decode optimizes for Time-Per-Output-Token (TPOT) and is Memory-bound, requiring large batches.
When a continuous batching scheduler injects a -token prefill into an active decoding batch, the compute-bound prefill monopolizes the GPU for , stalling every active user's streaming token generation (TPOT spike). Worse, colocated instances must use identical Tensor/Pipeline parallelism for both phases.
DistServe physically disaggregates serving into two specialized pools:
- Prefill Instances configured with higher Tensor Parallelism to minimize single-request TTFT near the compute roofline.
- Decode Instances configured with higher Pipeline/Data Parallelism to maximize concurrent batch capacity and KV cache bandwidth.
Once a Prefill instance computes the prompt's KV cache (which MLA shrinks by ), it streams the KV blocks over high-speed NVLink or RDMA directly into the Decode instance's PagedAttention pool—improving goodput (requests/sec meeting strict TTFT and TPOT SLOs) by .
4.Speculative Decoding: Turning GEMV into parallel GEMM#
At low batch sizes (), Decode remains memory-bound because streaming bytes of target model weights from HBM yields only token. Speculative Decoding (Leviathan et al., arXiv:2211.17192[1]Fast Inference from Transformers via Speculative DecodingOpen arXiv:2211.17192 ↗) breaks this bottleneck without altering the output distribution:
- A lightweight draft model rapidly proposes candidate tokens .
- The large target model evaluates all positions in a single parallel forward pass—costing nearly the exact same HBM weight read time as generating 1 token, because arithmetic intensity moves from up to along the flat memory-bound slope of the Roofline!
- Using rejection sampling, each drafted token is accepted with probability ; if rejected at step , a corrected token is sampled from the residual distribution , guaranteeing exact mathematical equivalence to sampling from alone while delivering wall-clock speedups.
5.References and next chapter#
- DeepSeek-AI, DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Model (2024).
- DeepSeek-AI, DeepSeek-V3 Technical Report (2024).
- Zhong et al., DistServe: Disaggregating Prefill and Decoding for Goodput-optimized LLM Serving (2024).
- Leviathan et al., Fast Inference from Transformers via Speculative Decoding (2022).
- Continue to Chapter 6: Beyond Fixed-Context Text: Ring Attention, Native Sparse Attention, Mamba-2, Agents, and Physical AI.
References
- [1]
- [2]
- [3]
- [4]