Abstract

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 4×–8×4\times\text{--}8\times 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][3] · DeepSeek-V2 (MLA) · 2024DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language ModelOpen arXiv:2405.04434 ↗) and DeepSeek-V3 (671B671\text{B} total parameters, 37B37\text{B} active per token, arXiv:2412.19437[4][4] · DeepSeek-V3 (DualPipe & FP8) · 2024DeepSeek-V3 Technical ReportOpen arXiv:2412.19437 ↗) answered yes with Multi-head Latent Attention (MLA). Instead of projecting hidden state ht∈Rdh_t \in \mathbb{R}^d directly to nhn_h heads of dimension dhd_h, MLA first projects hth_t down into a shared low-rank latent vector ctKV∈Rdcc_t^{KV} \in \mathbb{R}^{d_c} (where dc=512≪nhdh=128×128=16384d_c = 512 \ll n_h d_h = 128 \times 128 = 16384):

ctKV=htWDKV,kt,iC=ctKV(WiUK)⊤,vt,iC=ctKV(WiUV)⊤c_t^{KV} = h_t W^{DKV}, \qquad k_{t,i}^C = c_t^{KV} (W_i^{UK})^\top, \qquad v_{t,i}^C = c_t^{KV} (W_i^{UV})^\top
(1)

If we had to materialize kt,iCk_{t,i}^C and vt,iCv_{t,i}^C in HBM during decoding, no memory would be saved. The breakthrough of MLA is associative matrix absorption: during inference, the up-projection matrices WiUK,WiUV∈Rdh×dcW_i^{UK}, W_i^{UV} \in \mathbb{R}^{d_h \times d_c} are absorbed directly into the Query projection and Output projection!

Consider the unscaled attention score between head ii's query qt,i∈R1×dhq_{t,i} \in \mathbb{R}^{1 \times d_h} at step tt and historical key ks,iC=csKV(WiUK)⊤k_{s,i}^C = c_s^{KV} (W_i^{UK})^\top at step s≤ts \le t:

qt,i(ks,iC)⊤=qt,i(csKV(WiUK)⊤)⊤=(qt,iWiUK)⏟qt,iabs∈R1×dc(csKV)⊤q_{t,i} (k_{s,i}^C)^\top = q_{t,i} \Big(c_s^{KV} (W_i^{UK})^\top\Big)^\top = \underbrace{\big(q_{t,i} W_i^{UK}\big)}_{q_{t,i}^{\text{abs}} \in \mathbb{R}^{1 \times d_c}} (c_s^{KV})^\top
(2)

Similarly, for the value weighted sum across historical positions s≤ts \le t with attention weights αt,s(i)\alpha_{t,s}^{(i)}:

ot,i=∑s≤tαt,s(i)vt,sC=∑s≤tαt,s(i)(csKV(WiUV)⊤)=(∑s≤tαt,s(i)csKV)(WiUV)⊤o_{t,i} = \sum_{s \le t} \alpha_{t,s}^{(i)} v_{t,s}^C = \sum_{s \le t} \alpha_{t,s}^{(i)} \Big(c_s^{KV} (W_i^{UV})^\top\Big) = \left(\sum_{s \le t} \alpha_{t,s}^{(i)} c_s^{KV}\right) (W_i^{UV})^\top
(3)

Thus only the single compressed latent vector csKV∈Rdcc_s^{KV} \in \mathbb{R}^{d_c} is ever stored in the KV cache!

Why Decoupled RoPE is mandatory: If we applied position-dependent rotation Rm\mathcal{R}_m between WDKVW^{DKV} and WiUKW_i^{UK}, the intermediate matrix would become WiUKRt−sW_i^{UK} \mathcal{R}_{t - s}, which depends on ss and cannot be absorbed into qt,iq_{t,i} without recomputing keys for every historical token ss. DeepSeek-V2 solves this via Decoupled RoPE: it splits off a tiny shared rotary key ktR=Rt(htWKR)∈RdRk_t^R = \mathcal{R}_t(h_t W^{KR}) \in \mathbb{R}^{d_R} (dR=64d_R = 64) alongside per-head rotary queries qt,iR=Rt(qt,irope)q_{t,i}^R = \mathcal{R}_t(q_{t,i}^{\text{rope}}). The total cached state per token per layer is simply (ctKV,ktR)(c_t^{KV}, k_t^R) of width dc+dR=512+64=576d_c + d_R = 512 + 64 = \mathbf{576} elements—a 93.3%93.3\% KV cache reduction compared to MHA!

python
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_elems

In our companion CPU verification (labs/llm/deepseek-mla-grpo), forward_explicit and forward_absorbed match to within 10−1210^{-12} in float64 while compressing the cached tensor footprint by more than an order of magnitude.

Figure 1: Per-token per-layer KV cache comparison across MHA, GQA, and DeepSeek MLA alongside colocated interference versus DistServe Prefill-Decode disaggregation.
Figure 1: Per-token per-layer KV cache comparison across MHA, GQA, and DeepSeek MLA alongside colocated interference versus DistServe Prefill-Decode disaggregation.

2.DeepSeek-V3: Auxiliary-Loss-Free MoE, DualPipe, and FP8 Co-Design#

Training the 671B671\text{B}-parameter DeepSeek-V3 model on just 2.788M2.788\text{M} H800 GPU hours (∼USD 5.57M\sim \text{USD } 5.57\text{M}) required three additional systems breakthroughs:

  1. Fine-Grained DeepSeekMoE with Auxiliary-Loss-Free Load Balancing: Instead of 8 coarse experts, DeepSeek-V3 uses 11 shared expert and 256256 routed experts per layer (88 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 bib_i added only during Top-KK selection (Top-⁡K(si,t+bi)\operatorname{Top-}K(s_{i,t} + b_i)) while weighting the output by the unperturbed affinity si,ts_{i,t}. After every step, bib_i is decremented by γ\gamma for overloaded experts and incremented by γ\gamma for underloaded experts—achieving balanced expert routing with zero gradient interference!
  2. DualPipe Bidirectional Pipeline Parallelism: Cross-node Expert Parallelism (EP) introduces heavy Dispatch and Combine All-to-All network communication across InfiniBand. DualPipe feeds micro-batches from both ends of the pipeline simultaneously and splits backward computation into input gradients (BB) and weight gradients (WW), completely overlapping bidirectional All-to-All communication inside fine-grained compute chunks while cutting pipeline bubbles in half.
  3. Fine-Grained FP8 Mixed-Precision Training: To double Tensor Core throughput over bfloat16 without activation outliers causing overflow in E4M3 FP8, DeepSeek-V3 quantizes activations in 1×1281 \times 128 tile blocks and weights in 128×128128 \times 128 blocks, periodically accumulating partial sums from Tensor Cores into FP32 CUDA registers every NC=128N_C = 128 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][2] · DistServe (PD Disaggregation) · 2024DistServe: 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 B=1B = 1.
  • Decode optimizes for Time-Per-Output-Token (TPOT) and is Memory-bound, requiring large batches.

When a continuous batching scheduler injects a 40964096-token prefill into an active decoding batch, the compute-bound prefill monopolizes the GPU for 100ms+100\text{ms}+, 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:

  1. Prefill Instances configured with higher Tensor Parallelism to minimize single-request TTFT near the compute roofline.
  2. 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 93.3%93.3\%), 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 2.0×–4.48×2.0\times\text{--}4.48\times.

4.Speculative Decoding: Turning GEMV into parallel GEMM#

At low batch sizes (B=1…4B = 1 \dots 4), Decode remains memory-bound because streaming 2N2N bytes of target model weights from HBM yields only 11 token. Speculative Decoding (Leviathan et al., arXiv:2211.17192[1][1] · Speculative Decoding · 2022Fast Inference from Transformers via Speculative DecodingOpen arXiv:2211.17192 ↗) breaks this bottleneck without altering the output distribution:

  1. A lightweight draft model q(xt∣x<t)q(x_t \mid x_{<t}) rapidly proposes γ\gamma candidate tokens x~1,…,x~γ\tilde{x}_1, \dots, \tilde{x}_\gamma.
  2. The large target model p(xt∣x<t)p(x_t \mid x_{<t}) evaluates all γ+1\gamma + 1 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 11 up to γ+1\gamma + 1 along the flat memory-bound slope of the Roofline!
  3. Using rejection sampling, each drafted token x~t\tilde{x}_t is accepted with probability min⁡ ⁣(1, p(x~t)q(x~t))\min\!\big(1,\, \frac{p(\tilde{x}_t)}{q(\tilde{x}_t)}\big); if rejected at step tt, a corrected token is sampled from the residual distribution norm⁡ ⁣(max⁡(0, p(x)−q(x)))\operatorname{norm}\!\big(\max(0,\, p(x) - q(x))\big), guaranteeing exact mathematical equivalence to sampling from p(x)p(x) alone while delivering 2×–3×2\times\text{--}3\times wall-clock speedups.

5.References and next chapter#

References

  1. [1]
  2. [2]
  3. [3]
  4. [4]

Share