kbyy Personal Blog

Back

KV cache 能够加速推理,但需要占用大量显存空间.MHA、MQA、GQA 到 MLA 的演变历程,是对模型性能和显存占用的折中. 本文将从设计动机与实际代码优化层面来介绍 MLA:Multi-head Latent Attention.

参数约定#

本文均以 DeepSeek V3 671B ↗ 的参数为基础进行讨论.可以参考下表:

参数符号取值说明
dimdd7168隐藏层维度
n_layersLL61Transformer 层数
n_headshh128注意力头数
q_lora_rankdcqd_{cq}1536Query 的低秩压缩维度
kv_lora_rankdckvd_{ckv}512KV 的压缩隐向量维度,也是 KV cache 的主体
qk_nope_head_dimdnd_n128Q/K 中不带 RoPE 的部分,每头维度
qk_rope_head_dimdrd_r64Q/K 中携带 RoPE 的部分,每头维度
v_head_dimdvd_v128V 的每头维度

动机#

如果使用 GQA(以 8 个 KV 头为例),单层每个 token 的 KV cache 需要

2×8×128×2 Bytes=4096 Bytes=4 KiB2 \times 8 \times 128 \times 2\, \text{Bytes} = 4096 \,\text{Bytes} = 4 \,\text{KiB}

乘以 61 层与 128k 上下文,需要 30.530.5 GiB.

MLA 提出将 KV 压缩成隐向量并存储,以此来减少 KV cache 的压力.MLA 中,单层每个 token 需要

(512+64)×2 Bytes=1152 Bytes=1.125 KiB(512 + 64) \times 2\, \text{Bytes} = 1152 \,\text{Bytes} = 1.125 \,\text{KiB}

节省了 71.8%71.8\% 的显存空间.

代码#

DeepSeek V3 官方代码 ↗将 Attention 分为了 naive 与 absorb 两种模式.我们先学习容易理解的 naive 模式.

Naive#

将一些条件分支与多卡并行的代码删去后,naive 部分主干代码:

class MLA(nn.Module):
    """
    Multi-Head Latent Attention (MLA) Layer.

    Attributes:
        dim (int): Dimensionality of the input features.
        n_heads (int): Number of attention heads.
        n_local_heads (int): Number of local attention heads for distributed systems.
        q_lora_rank (int): Rank for low-rank query projection.
        kv_lora_rank (int): Rank for low-rank key/value projection.
        qk_nope_head_dim (int): Dimensionality of non-positional query/key projections.
        qk_rope_head_dim (int): Dimensionality of rotary-positional query/key projections.
        qk_head_dim (int): Total dimensionality of query/key projections.
        v_head_dim (int): Dimensionality of value projections.
        softmax_scale (float): Scaling factor for softmax in attention computation.
    """
    def __init__(self, args: ModelArgs):
        super().__init__()
        self.dim = args.dim # 7168
        self.n_heads = args.n_heads # 128
        self.n_local_heads = args.n_heads // world_size # 不考虑多卡并行,world_size = 1
        self.q_lora_rank = args.q_lora_rank # 1536
        self.kv_lora_rank = args.kv_lora_rank # 512
        self.qk_nope_head_dim = args.qk_nope_head_dim # 128
        self.qk_rope_head_dim = args.qk_rope_head_dim # 64
        self.qk_head_dim = args.qk_nope_head_dim + args.qk_rope_head_dim # 128 + 64 = 192
        self.v_head_dim = args.v_head_dim # 128

        self.wq_a = Linear(self.dim, self.q_lora_rank)
        self.q_norm = RMSNorm(self.q_lora_rank) 
        self.wq_b = Linear(self.q_lora_rank, self.n_heads * self.qk_head_dim)
        self.wkv_a = Linear(self.dim, self.kv_lora_rank + self.qk_rope_head_dim)
        self.kv_norm = RMSNorm(self.kv_lora_rank)
        self.wkv_b = Linear(self.kv_lora_rank, self.n_heads * (self.qk_nope_head_dim + self.v_head_dim))
        self.wo = Linear(self.n_heads * self.v_head_dim, self.dim)
        self.softmax_scale = self.qk_head_dim ** -0.5

        self.register_buffer("k_cache", torch.zeros(args.max_batch_size, args.max_seq_len, self.n_local_heads, self.qk_head_dim), persistent=False)
        self.register_buffer("v_cache", torch.zeros(args.max_batch_size, args.max_seq_len, self.n_local_heads, self.v_head_dim), persistent=False)

    def forward(self, x: torch.Tensor, start_pos: int, freqs_cis: torch.Tensor, mask: Optional[torch.Tensor]):
        """
        Forward pass for the Multi-Head Latent Attention (MLA) Layer.

        Args:
            x (torch.Tensor): Input tensor of shape (batch_size, seq_len, dim).
            start_pos (int): Starting position in the sequence for caching.
            freqs_cis (torch.Tensor): Precomputed complex exponential values for rotary embeddings.
            mask (Optional[torch.Tensor]): Mask tensor to exclude certain positions from attention.

        Returns:
            torch.Tensor: Output tensor with the same shape as the input.
        """
        bsz, seqlen, _ = x.size()
        end_pos = start_pos + seqlen

        q = self.wq_b(self.q_norm(self.wq_a(x)))
        q = q.view(bsz, seqlen, self.n_local_heads, self.qk_head_dim)
        q_nope, q_pe = torch.split(q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1)
        q_pe = apply_rotary_emb(q_pe, freqs_cis)
        kv = self.wkv_a(x)
        kv, k_pe = torch.split(kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1)
        k_pe = apply_rotary_emb(k_pe.unsqueeze(2), freqs_cis)

        q = torch.cat([q_nope, q_pe], dim=-1)
        kv = self.wkv_b(self.kv_norm(kv))
        kv = kv.view(bsz, seqlen, self.n_local_heads, self.qk_nope_head_dim + self.v_head_dim)
        k_nope, v = torch.split(kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1)
        k = torch.cat([k_nope, k_pe.expand(-1, -1, self.n_local_heads, -1)], dim=-1)
        self.k_cache[:bsz, start_pos:end_pos] = k
        self.v_cache[:bsz, start_pos:end_pos] = v
        scores = torch.einsum("bshd,bthd->bsht", q, self.k_cache[:bsz, :end_pos]) * self.softmax_scale

        if mask is not None:
            # mask: [S, T] --> [S, 1, T] -(broadcast)-> [B, S, 1, T]
            scores += mask.unsqueeze(1)
        scores = scores.softmax(dim=-1, dtype=torch.float32).type_as(x)
        x = torch.einsum("bsht,bthd->bshd", scores, self.v_cache[:bsz, :end_pos])
        x = self.wo(x.flatten(2))
        return x
python

搭配上数据流图(来自 ChatGPT):

MLA naive 模式的数据流与张量形状,展示 Q 与 KV 投影、RoPE、KV cache、注意力计算及输出投影
MLA naive 模式的数据流与张量形状

Q 投影#

做 QQ 投影时,先将其转化为低维的中间表示(低秩分解思想),再投影成多头,这减少了参数量和计算量.

  • 普通 MHA:投影矩阵为 WQT∈R7168×(128×192)W_{\text{Q}}^T \in \mathbb{R}^{7168 \times (128 \times 192)},参数量约 176M;
  • MLA:下采样矩阵 WQaT∈R7168×1536W_{\text{Qa}}^T \in \mathbb{R}^{7168 \times 1536},上采样矩阵 WQbT∈R1536×(128×192)W_{\text{Qb}}^T \in \mathbb{R}^{1536 \times(128 \times 192)},参数量约 49M.

KV 投影#

MLA 先将输入用 WKVaW_{\text{KVa}} 下采样成 KVKV 共用的隐向量,再用 WKVbW_{\text{KVb}} 上采样成多头的 KVKV 向量,再 split 成 KK 和 VV,同样减少了参数量和计算量.

QK RoPE#

与先前架构不同的是,RoPE 不直接加入 Q、KQ、K,而是作为额外的投影部分 concat 到最后一维,期中 KK 的 RoPE 在各个头之间共享.在 absorb 版本会解释为什么这么做.

KV cache#

经过上采样和 split、RoPE 后,将得到的 [B, S, h, 192 / 128] 维的 K、VK、V 存入 cache.

MHA#

K、VK、V 和 QQ 具有相同的头数,最后等价于做了普通 MHA.


Naive 版本相对先前架构而言,主要改进是将投影得到 Q、K、VQ、K、V 的过程用一个中间低秩矩阵分解,从而减少参数量.

但我们发现存储的 KV cache 并不是低秩的,甚至由于最后等效为 MHA、KK 需要额外的 64 维 RoPE,其 KV cache 存储远超过 GQA:

128×(192+128)×2 Bytes=80 KiB128 \times (192 + 128) \times 2\, \text{Bytes}=80\,\text{KiB}

是 GQA 的 20倍,与我们的预期背道而驰.

于是有一个很自然的想法:既然 K、VK、V 都由同一个低维隐向量生成,能否只缓存这个隐向量,同时完成相同的注意力计算?

Absorb#

矩阵吸收#

在 naive 版本,我们有

Q=[Qnope:QR]=[Qnope:RoPE⁡(Qpe)]\begin{aligned} Q &= \begin{bmatrix} Q_\text{nope} : Q_{\text{R}} \end{bmatrix} \\ &= \begin{bmatrix} Q_\text{nope} : \operatorname{RoPE}(Q_\text{pe}) \end{bmatrix} \end{aligned}

以及

K=[Knope:KR]=[cKVWKT:RoPE⁡(Kpe)]\begin{aligned} K &= \begin{bmatrix} K_\text{nope} : K_{\text{R}} \end{bmatrix} \\ &= \begin{bmatrix} c^{\mathrm{KV}} W_{\text{K}}^T : \operatorname{RoPE}(K_\text{pe}) \end{bmatrix} \end{aligned} V=cKVWVTV = c^{\mathrm{KV}} W_{\text{V}}^T

其中

  • 分块矩阵中的 :: 表示横向拼接,上下排列表示纵向拼接;
  • [WKT:WVT]=WKVbT\begin{bmatrix} W_{\text{K}}^T : W_{\text{V}}^T \end{bmatrix} = W_{\text{KVb}}^T,即最后一维前半段得到 KnopeK_\text{nope},后半段得到 VV;
  • QQ 和 KK 的维度都是 [B, S, h, 192];VV 为 [B, S, h, 128]

在 naive 版本中,维度的变化为 bshd,bthd->bsht,b 和 h 维度不变,只是做 sd @ td -> st 的矩阵乘法.由分块矩阵乘法

QKT=[Qnope:QR][KnopeTKRT]=QnopeKnopeT+QRKRT=Qnope(cKVWKT)T+QRKRT=QnopeWK(cKV)T+QRKRT=(QnopeWK)(cKV)T+QRKRT\begin{aligned} QK^T &= \begin{bmatrix} Q_\text{nope} : Q_{\text{R}} \end{bmatrix} \begin{bmatrix} K_{\mathrm{nope}}^T \\ K_{\text{R}}^T \end{bmatrix} \\ &= Q_\text{nope}K_{\mathrm{nope}}^T + Q_{\text{R}}K_{\text{R}}^T \\ &= Q_\text{nope}(c^{\mathrm{KV}} W_{\text{K}}^T)^T + Q_{\text{R}} K_{\text{R}}^T \\ &= Q_\text{nope} W_{\text{K}} (c^{\mathrm{KV}})^T + Q_{\text{R}} K_{\text{R}}^T \\ &= (Q_\text{nope} W_{\text{K}}) (c^{\mathrm{KV}})^T + Q_{\text{R}} K_{\text{R}}^T \end{aligned}

由于一层中 WKW_\text{K} 是一个固定的矩阵,因此我们可以在得到 QnopeQ_\text{nope} 后乘以 WKW_{\text{K}},并用结果处理 cKVc^{\mathrm{KV}},与之前计算的结果完全等价.

按照这种方法,除了 cKVc^{\mathrm{KV}} 外,我们还需要存储 KRK_\text{R}.此时每层单个 token 的 KV cache 变为

(512+64)×2 Bytes=1.125 KiB(512 + 64) \times 2\, \text{Bytes}=1.125\,\text{KiB}

这也解释了需要使用拼接的 RoPE 而不是直接作和:拼接使内容分支和位置分支在点积中保持分离.

假设两部分具有相同维度,并改为直接作和:

Q=Qnope+QRK=Knope+KR=cKVWKT+KR\begin{aligned} Q &= Q_\text{nope} + Q_{\text{R}} \\ K &= K_\text{nope} + K_{\text{R}} \\ &= c^{\mathrm{KV}} W_{\text{K}}^T + K_{\text{R}} \end{aligned}

此时点积展开为

QKT=(Qnope+QR)(Knope+KR)T=QnopeKnopeT+QnopeKRT+QRKnopeT+QRKRT\begin{aligned} QK^T &= (Q_\text{nope} + Q_{\text{R}}) (K_\text{nope} + K_{\text{R}})^T \\ &= Q_\text{nope}K_\text{nope}^T + Q_\text{nope}K_{\text{R}}^T \\ &\quad + Q_{\text{R}}K_\text{nope}^T + Q_{\text{R}}K_{\text{R}}^T \end{aligned}

相比拼接,多出了 QnopeKRTQ_\text{nope}K_{\text{R}}^T 和 QRKnopeTQ_{\text{R}}K_\text{nope}^T 两项内容与位置的耦合项,不方便进行矩阵吸收.

VV 的矩阵也可以吸收.设 softmax 后的注意力权重为

A=softmax⁡(QKTdn+dr)A = \operatorname{softmax}\left(\frac{QK^T}{\sqrt{d_n + d_r}}\right)

在 naive 版本中,O=AVO = AV 的维度变化为 bsht,bthd->bshd,即每个头做 st @ td -> sd 的矩阵乘法.代入 V=cKVWVTV = c^{\mathrm{KV}} W_{\text{V}}^T,由矩阵乘法结合律

O=AV=A(cKVWVT)=(AcKV)WVT\begin{aligned} O &= AV \\ &= A\left(c^{\mathrm{KV}} W_{\text{V}}^T\right) \\ &= \left(Ac^{\mathrm{KV}}\right)W_{\text{V}}^T \end{aligned}

由于一层中 WVW_{\text{V}} 是一个固定的矩阵,因此我们可以先用注意力权重对 cKVc^{\mathrm{KV}} 加权求和,得到 [B, S, h, 512] 的结果,再乘以 WVTW_{\text{V}}^T 投影成 [B, S, h, 128].

MQA#

通过矩阵吸收,我们可以认为将多头的 QQ 与只有单头的 KVKV 隐向量 cKVc^{\mathrm{KV}} 进行了注意力,可以看作是一种 MQA.我们保留了类似 MHA 的结果,但 KV cache 确实 MQA 级别的.

class MLA(nn.Module):
    """
    Multi-Head Latent Attention (MLA) Layer.

    Attributes:
        dim (int): Dimensionality of the input features.
        n_heads (int): Number of attention heads.
        n_local_heads (int): Number of local attention heads for distributed systems.
        q_lora_rank (int): Rank for low-rank query projection.
        kv_lora_rank (int): Rank for low-rank key/value projection.
        qk_nope_head_dim (int): Dimensionality of non-positional query/key projections.
        qk_rope_head_dim (int): Dimensionality of rotary-positional query/key projections.
        qk_head_dim (int): Total dimensionality of query/key projections.
        v_head_dim (int): Dimensionality of value projections.
        softmax_scale (float): Scaling factor for softmax in attention computation.
    """
    def __init__(self, args: ModelArgs):
        super().__init__()
        self.dim = args.dim # 7168
        self.n_heads = args.n_heads # 128
        self.n_local_heads = args.n_heads // world_size # 不考虑多卡并行,world_size = 1
        self.q_lora_rank = args.q_lora_rank # 1536
        self.kv_lora_rank = args.kv_lora_rank # 512
        self.qk_nope_head_dim = args.qk_nope_head_dim # 128
        self.qk_rope_head_dim = args.qk_rope_head_dim # 64
        self.qk_head_dim = args.qk_nope_head_dim + args.qk_rope_head_dim # 128 + 64 = 192
        self.v_head_dim = args.v_head_dim # 128

        self.wq_a = Linear(self.dim, self.q_lora_rank)
        self.q_norm = RMSNorm(self.q_lora_rank) 
        self.wq_b = Linear(self.q_lora_rank, self.n_heads * self.qk_head_dim)
        self.wkv_a = Linear(self.dim, self.kv_lora_rank + self.qk_rope_head_dim)
        self.kv_norm = RMSNorm(self.kv_lora_rank)
        self.wkv_b = Linear(self.kv_lora_rank, self.n_heads * (self.qk_nope_head_dim + self.v_head_dim))
        self.wo = Linear(self.n_heads * self.v_head_dim, self.dim)
        self.softmax_scale = self.qk_head_dim ** -0.5
        
        self.register_buffer("kv_cache", torch.zeros(args.max_batch_size, args.max_seq_len, self.kv_lora_rank), persistent=False)
        self.register_buffer("pe_cache", torch.zeros(args.max_batch_size, args.max_seq_len, self.qk_rope_head_dim), persistent=False)

    def forward(self, x: torch.Tensor, start_pos: int, freqs_cis: torch.Tensor, mask: Optional[torch.Tensor]):
        """
        Forward pass for the Multi-Head Latent Attention (MLA) Layer.

        Args:
            x (torch.Tensor): Input tensor of shape (batch_size, seq_len, dim).
            start_pos (int): Starting position in the sequence for caching.
            freqs_cis (torch.Tensor): Precomputed complex exponential values for rotary embeddings.
            mask (Optional[torch.Tensor]): Mask tensor to exclude certain positions from attention.

        Returns:
            torch.Tensor: Output tensor with the same shape as the input.
        """
        bsz, seqlen, _ = x.size()
        end_pos = start_pos + seqlen
     
        q = self.wq_b(self.q_norm(self.wq_a(x)))
        q = q.view(bsz, seqlen, self.n_local_heads, self.qk_head_dim)
        q_nope, q_pe = torch.split(q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1)
        q_pe = apply_rotary_emb(q_pe, freqs_cis)
        kv = self.wkv_a(x)
        kv, k_pe = torch.split(kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1)
        k_pe = apply_rotary_emb(k_pe.unsqueeze(2), freqs_cis)
        
        wkv_b = self.wkv_b.weight if self.wkv_b.scale is None else weight_dequant(self.wkv_b.weight, self.wkv_b.scale, block_size) 
        wkv_b = wkv_b.view(self.n_local_heads, -1, self.kv_lora_rank)
        q_nope = torch.einsum("bshd,hdc->bshc", q_nope, wkv_b[:, :self.qk_nope_head_dim])
        self.kv_cache[:bsz, start_pos:end_pos] = self.kv_norm(kv)
        self.pe_cache[:bsz, start_pos:end_pos] = k_pe.squeeze(2)
        scores = (torch.einsum("bshc,btc->bsht", q_nope, self.kv_cache[:bsz, :end_pos]) +
                    torch.einsum("bshr,btr->bsht", q_pe, self.pe_cache[:bsz, :end_pos])) * self.softmax_scale

        if mask is not None:
            # mask: [S, T] --> [S, 1, T] -(broadcast)-> [B, S, 1, T]
            scores += mask.unsqueeze(1)
        scores = scores.softmax(dim=-1, dtype=torch.float32).type_as(x)
        x = torch.einsum("bsht,btc->bshc", scores, self.kv_cache[:bsz, :end_pos])
        x = torch.einsum("bshc,hdc->bshd", x, wkv_b[:, -self.v_head_dim:])
        x = self.wo(x.flatten(2))
        return x
python
MLA absorb 模式的数据流与张量形状,展示 Q 与 KV 投影、RoPE、KV cache、注意力计算及输出投影
MLA naive 模式的数据流与张量形状

两种版本的选择#

以上是 DeepSeek 官方的代码实现.其两种版本选择是一个全局变量控制的:

attn_impl: Literal["naive", "absorb"] = "absorb"
python

因为在其源代码中,两个版本创建的 KV cache 是不一样的,因此不能在推理过程中切换版本.

然而,仅考虑显存占用与访存,absorb 版本肯定优于 naive.但从计算量角度(忽略 BB 和 hh,假设 query 长度为 SS,历史长度为 TT),由于注意力点积与加权为 sd,td->st、st,td->sd,因此总计算量为 2ST(dQK+dV)2ST(d_{QK} + d_{V})

  • naive:dQK=192,dV=128d_{QK} = 192,d_V = 128
  • absorb:dQK=576,dV=512d_{QK} = 576,d_V = 512

而线性层的计算量是一样的,总体而言 absorb 的计算量高于 naive 版本.由于低计算量的 naive 版本适合 compute-bound 的 Prefill,低访存的 absorb 版本适合 memory-bound 的 Decode,将这二者混合使用才能更好发挥价值.

将这二者统一也很简单,把 naive 版本写入的 KV cache 改为与 absorb 一致即可.

vllm ↗也是这么组合的:

MLA has two possible ways of computing, a data-movement friendly approach and a compute friendly approach. We generally want to use the compute friendly approach for “prefill” (i.e. the ratio Sq / Skv is relatively large, often near 1) and the data-movement friendly approach for “decode” (i.e. the ratio Sq / Skv is small, often near 0).

参考资料#

  1. vLLM 文档:MLA Attention 实现说明 ↗
  2. 知乎:图解 · 彻底理解MLA的计算过程 ↗
  3. DeepSeek-V3 官方仓库 ↗
  4. 苏剑林:缓存与效果的极限拉扯:从 MHA、MQA、GQA 到 MLA ↗
DeepSeek MLA:从 Naive Attention 到高效推理实现
https://kbyylin-blog.vercel.app/notes/mla
Author 空白阴影
Published at
Comment seems to stuck. Try to refresh?✨