AI Logic

Attention Mechanisms

Multi-head Latent Attention (MLA)

Updated:

Structure of MLA. The left side shows the computation: from the input h_t, one column compresses and restores the query and adds a part for RoPE, one column compresses keys and values into the latent vector c^KV and then restores them, and one column creates the RoPE key k^R shared by all heads; these feed multi-head attention and the output linear layer. Only c^KV and k^R are cached during inference. The right side compares the number of KV cache elements per token per layer (MHA 32,768, GQA 2,048, MQA 256, MLA 576).

What is Multi-head Latent Attention?

Multi-head Latent Attention (MLA) is an attention mechanism that compresses the keys and values together into a single low-dimensional "latent vector" and, at inference time, stores only that latent vector in the KV cache. DeepSeek-AI proposed it in 2024 in the paper on the DeepSeek-V2 language model, "DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Model."

A model that generates text one token at a time keeps the keys and values of past tokens in a KV cache. Standard multi-head attention (MHA) stores 2nhdh2 n_h d_h values per token in every layer (number of heads × head dimension × two for keys and values), so the cache limits both the number of requests that can be served at once and the context length.

Multi-query attention (MQA) and grouped-query attention (GQA) reduce the cache by sharing key and value heads, but in the paper's comparison they fell short of MHA. Instead of sharing heads, MLA compresses the keys and values into a low-rank form, and with a cache about the size of GQA with 2.25 groups it outperformed MHA.

As an analogy with storing goods: MHA lines up every item as is in the warehouse, GQA and MQA merge similar items into one to reduce their number, and MLA vacuum-packs each item into a small bundle for storage and restores it to full size when it is needed.

In the figure at the top of the article, the left side shows the computation in MLA (only the two items inside the yellow dashed box are cached), and the right side compares the size of the KV cache per token.

Theory

Standard MHA takes the input of the tt-th token, ht∈Rdh_t \in \mathbb{R}^d, computes qt=WQhtq_t = W^Q h_t, kt=WKhtk_t = W^K h_t, and vt=WVhtv_t = W^V h_t (each of dimension nhdhn_h d_h), and splits them into nhn_h heads to compute attention (Eqs. (1)–(8) in the paper). MLA computes attention in the following steps (Eqs. (9)–(19)).

  1. Compress keys and values jointly: A down-projection WDKVW^{DKV} maps hth_t to a dcd_c-dimensional latent vector ctKVc_t^{KV} (dc≪dhnhd_c \ll d_h n_h). This ctKVc_t^{KV} is what is cached during inference.
  2. Restore keys and values: Up-projections WUK,WUVW^{UK}, W^{UV} produce each head's key ktCk_t^C and value vtCv_t^C from ctKVc_t^{KV}.
  3. Compress the queries as well: To reduce activation memory during training, the query is also compressed to ctQ=WDQhtc_t^Q = W^{DQ} h_t (dc′d'_c dimensions) and then restored as qtC=WUQctQq_t^C = W^{UQ} c_t^Q. This does not reduce the KV cache.
  4. Carry positional information separately: A separate query qt,iRq_{t,i}^R (per head) and a key ktRk_t^R shared by all heads (length dhRd_h^R) are created for applying RoPE. ktRk_t^R is cached as well.
  5. Concatenate and compute attention: With qt,i=[qt,iC;qt,iR]q_{t,i} = [q_{t,i}^C; q_{t,i}^R] and kt,i=[kt,iC;ktR]k_{t,i} = [k_{t,i}^C; k_t^R], attention is computed per head and the output projection WOW^O is applied.

Steps 1–2 correspond to the following equations (Eqs. (9)–(11)).

ctKV=WDKVht,ktC=WUKctKV,vtC=WUVctKVc_t^{KV} = W^{DKV} h_t, \qquad k_t^C = W^{UK} c_t^{KV}, \qquad v_t^C = W^{UV} c_t^{KV}

Steps 4–5 correspond to the following equations (Eqs. (14)–(18)).

qtR=RoPE(WQRctQ),ktR=RoPE(WKRht)q_t^R = \mathrm{RoPE}(W^{QR} c_t^Q), \qquad k_t^R = \mathrm{RoPE}(W^{KR} h_t) ot,i=∑j=1tSoftmaxj ⁣(qt,i⊤kj,idh+dhR)vj,iC,ut=WO[ot,1;ot,2;… ;ot,nh]o_{t,i} = \sum_{j=1}^{t} \mathrm{Softmax}_j\!\left(\frac{q_{t,i}^\top k_{j,i}}{\sqrt{d_h + d_h^R}}\right) v_{j,i}^C, \qquad u_t = W^O [o_{t,1}; o_{t,2}; \dots; o_{t,n_h}]

Because only ctKVc_t^{KV} and ktRk_t^R are cached during inference, the cache per token holds (dc+dhR) l(d_c + d_h^R)\, l elements (ll is the number of layers).

DeepSeek-V2 uses nh=128n_h = 128 heads, head dimension dh=128d_h = 128, KV compression dimension dc=512d_c = 512 (=4dh= 4 d_h), query compression dimension dc′=1536d'_c = 1536, and RoPE dimension dhR=64d_h^R = 64 (=dh/2= d_h / 2). An RMSNorm follows the compressed latent vectors to stabilize training.

Why the cache can be made smaller

Attention can be computed without materializing keys and values: At inference time, the restoring projections can be merged into the projections before and after them (Section 2.1.2 of the paper). The compressed part of the score for head ii can be rewritten as follows.

qt,iC⊤kj,iC=qt,iC⊤WiUKcjKV=(WiUK⊤qt,iC)⊤cjKV{q_{t,i}^C}^\top k_{j,i}^C = {q_{t,i}^C}^\top W_i^{UK} c_j^{KV} = \bigl({W_i^{UK}}^\top q_{t,i}^C\bigr)^\top c_j^{KV}

In other words, if WUKW^{UK} is absorbed into the query-side projection WUQW^{UQ}, the dot product can be taken directly with the cached cjKVc_j^{KV}. Likewise, WUVW^{UV} can be absorbed into the output projection WOW^O. As a result, inference does not even need to restore the keys and values of past tokens.

Why RoPE is decoupled: RoPE applies a position-dependent rotation matrix to the queries and keys. If RoPE were applied to ktCk_t^C, a rotation matrix determined by the position of the token currently being generated would sit between WUKW^{UK} and the query in the equation above. Since matrix multiplication is not commutative, WUKW^{UK} could no longer be absorbed into the query side, and the keys of all past tokens would have to be recomputed at every inference step. MLA therefore provides a separate small part (qR,kRq^R, k^R) to carry positional information and does not apply RoPE to the compressed part.

Comparing cache sizes: The number of KV cache elements per token is as follows (Table 1 in the paper; ngn_g is the number of GQA groups).

MethodKV cache per tokenPerformance in the paper
Multi-head attention (MHA)2nhdhl2 n_h d_h lStrong
Grouped-query attention (GQA)2ngdhl2 n_g d_h lModerate
Multi-query attention (MQA)2dhl2 d_h lWeak
MLA(dc+dhR) l≈92dhl(d_c + d_h^R)\, l \approx \tfrac{9}{2} d_h lStronger

With the DeepSeek-V2 settings, dc+dhR=4dh+dh/2=4.5 dhd_c + d_h^R = 4d_h + d_h/2 = 4.5\,d_h, so the MLA cache is the same size as GQA with 2.25 groups.

MLA can also be seen as a kind of low-rank factorization that splits the key and value projections into two matrices, "down × up." Its goal, however, is not to reduce parameters but to let the KV cache, which persists across layers, be stored at the compressed dimension.

Experimental results

Comparison with MHA: The paper trained MoE models of two sizes that differ only in the attention part and compared them on hard benchmarks (Appendix D.2, Table 9). The small model has about 16B total parameters trained on 1.33T tokens, and the large model has about 250B parameters trained on 420B tokens.

ModelKV cache per token (elements)BBHMMLUC-EvalCMMLU
Small MoE, MHA110.6K37.948.751.652.3
Small MoE, MLA15.6K39.050.050.953.4
Large MoE, MHA860.2K46.657.557.960.7
Large MoE, MLA34.6K50.759.059.262.5

MLA outperformed MHA everywhere except C-Eval for the small model, while its KV cache was 14% of MHA's for the small model and 4% for the large model.

Comparing MHA, GQA, and MQA: For dense models of about 7B parameters trained on the same 1.33T tokens, MHA clearly outperformed GQA (8 groups) and MQA (Appendix D.1, Table 8). On MMLU, for example, MQA scored 37.9, GQA 41.2, and MHA 45.2. The paper uses this result as evidence that "existing methods for reducing the cache degrade performance."

DeepSeek-V2 as a whole: DeepSeek-V2 (236B total parameters, 21B activated per token) reduced the KV cache by 93.3% and raised the maximum generation throughput 5.76-fold compared with the dense DeepSeek 67B. These figures, however, reflect not only MLA but also the MoE architecture, FP8 weights, and KV cache quantization (6 bits on average) combined (Section 3.2.3 of the paper).

Practical considerations

MLA changes the model architecture itself. It is not a way to make inference cheaper for an existing MHA model.

To realize the benefits of MLA during inference, the implementation must absorb the up-projections WUK,WUVW^{UK}, W^{UV} into the query and output projections and compute directly with the cached latent vector cKVc^{KV}. If all keys and values are restored every step as during training, the cache is small but each step pays a restoring cost proportional to the number of past tokens.

Keep the following points in mind when using MLA.

  • Apply RoPE only to the decoupled part: Applying RoPE to the compressed part makes absorbing the projections impossible. Positional information is carried by qR,kRq^R, k^R.
  • The compression dimension sets the trade-off between performance and cache size: DeepSeek-V2 uses dc=4dhd_c = 4 d_h and dhR=dh/2d_h^R = d_h/2. The paper does not compare other values, so other settings need to be verified independently.
  • Add normalization after compression: Because low-rank compression changes the scale of layer outputs, the paper adds RMSNorm after the latent vectors and applies scaling factors at the width bottlenecks to stabilize training.
  • Independent of how the cache is laid out: MLA makes the cache itself smaller. It can be combined with methods such as PagedAttention that eliminate waste in how the cache is laid out in memory.

Comparison with other methods

Attention mechanisms that reduce the KV cache are compared below by "what they reduce and how."

MethodHow the cache is reducedElements per token per layer (example with nh=dh=128n_h = d_h = 128)Performance in the paper's evaluation
Multi-head attention (Vaswani et al., 2017)Not reduced32,768Baseline
Grouped-query attention (Ainslie et al., 2023)K/V heads shared within ngn_g groups2,048 (ng=8n_g = 8)Lower than MHA
Multi-query attention (Shazeer, 2019)A single K/V head for all heads256Lower than GQA
MLA (DeepSeek-AI, 2024)K/V compressed into a low-dimensional latent vector (dc=512d_c = 512), plus a key for RoPE (dhR=64d_h^R = 64)576Higher than MHA

(The element counts plug the DeepSeek-V2 settings into the formulas in Table 1 of the paper. The performance comparison is based on the experiments in Appendix D of the paper.)

GQA and MQA shrink the cache by reducing the number of heads, so the diversity of per-head representations is lost. MLA keeps a key and value for every head while storing the underlying information in compressed form, so each head can still have different keys and values.

As a rough guide to choosing among them:

  • Building a new language model and wanting a large cut in the inference cache: MLA is a candidate. Its implementation is more complex than GQA's.
  • Prioritizing ease of implementation, or converting an existing MHA model: GQA is widely used. The GQA paper also shows how to convert an MHA checkpoint into GQA with a small amount of additional training.
  • Reducing waste in how the cache is laid out: Use PagedAttention, which can be combined with any of these methods.

PyTorch example

Show code
python
import math
import torch
import torch.nn as nn
import torch.nn.functional as F


def rope(x, pos, base=10000.0):
    """RoPE (rotary position embedding). x: [..., T, d] (d is even), pos: [T]"""
    d = x.shape[-1]
    inv = base ** (-torch.arange(0, d, 2, dtype=x.dtype) / d)
    ang = pos[:, None].to(x.dtype) * inv[None, :]          # [T, d/2]
    cos, sin = ang.cos(), ang.sin()
    x1, x2 = x[..., 0::2], x[..., 1::2]
    return torch.stack([x1 * cos - x2 * sin, x1 * sin + x2 * cos], dim=-1).flatten(-2)


class MLA(nn.Module):
    """Multi-head Latent Attention (Eqs. (9)-(19) of DeepSeek-V2), with a causal mask"""

    def __init__(self, d, n_h, d_h, d_c, d_cq, d_hr):
        super().__init__()
        self.n_h, self.d_h, self.d_hr = n_h, d_h, d_hr
        self.w_dkv = nn.Linear(d, d_c, bias=False)          # Eq. (9): compress K and V jointly
        self.kv_norm = nn.RMSNorm(d_c)                       # RMSNorm after compression (Sec. 3.1.2)
        self.w_uk = nn.Linear(d_c, n_h * d_h, bias=False)   # Eq. (10)
        self.w_uv = nn.Linear(d_c, n_h * d_h, bias=False)   # Eq. (11)
        self.w_dq = nn.Linear(d, d_cq, bias=False)          # Eq. (12): compress the query
        self.q_norm = nn.RMSNorm(d_cq)
        self.w_uq = nn.Linear(d_cq, n_h * d_h, bias=False)  # Eq. (13)
        self.w_qr = nn.Linear(d_cq, n_h * d_hr, bias=False) # Eq. (14): query for RoPE (per head)
        self.w_kr = nn.Linear(d, d_hr, bias=False)          # Eq. (15): key for RoPE (shared by all heads)
        self.w_o = nn.Linear(n_h * d_h, d, bias=False)      # Eq. (19)

    def forward(self, h):
        B, T, _ = h.shape
        pos = torch.arange(T)
        c_kv = self.kv_norm(self.w_dkv(h))                   # [B, T, d_c]   ← cached during inference
        k_r = rope(self.w_kr(h), pos)                        # [B, T, d_hr]  ← cached during inference
        c_q = self.q_norm(self.w_dq(h))
        heads = lambda x, n: x.view(B, T, self.n_h, n).transpose(1, 2)
        q_c = heads(self.w_uq(c_q), self.d_h)                # [B, n_h, T, d_h]
        q_r = rope(heads(self.w_qr(c_q), self.d_hr), pos)    # [B, n_h, T, d_hr]
        k_c = heads(self.w_uk(c_kv), self.d_h)
        v_c = heads(self.w_uv(c_kv), self.d_h)
        q = torch.cat([q_c, q_r], dim=-1)                    # Eq. (16)
        k = torch.cat([k_c, k_r[:, None].expand(-1, self.n_h, -1, -1)], dim=-1)  # Eq. (17)
        o = F.scaled_dot_product_attention(q, k, v_c, is_causal=True)  # Eq. (18): scale is 1/√(d_h + d_hr)
        return self.w_o(o.transpose(1, 2).reshape(B, T, -1)), (c_kv, k_r)


mla = MLA(d=512, n_h=8, d_h=64, d_c=256, d_cq=384, d_hr=32)
h = torch.randn(2, 16, 512)
u, (c_kv, k_r) = mla(h)
print(u.shape, c_kv.shape, k_r.shape)  # cache is d_c + d_hr = 288 elements per token (2 × 8 × 64 = 1024 for MHA)

# Absorption at inference: merging W^UK into the query side gives dot products with the cache c_kv directly, without restoring keys
i = 0                                                     # check with head 0
w_uk_i = mla.w_uk.weight.view(8, 64, 256)[i]              # [d_h, d_c]
q_c_i = mla.w_uq(mla.q_norm(mla.w_dq(h)))[..., i * 64:(i + 1) * 64]  # [B, T, d_h]
s_full = q_c_i @ (c_kv @ w_uk_i.T).transpose(1, 2)        # restore keys, then dot product
s_absorbed = (q_c_i @ w_uk_i) @ c_kv.transpose(1, 2)      # absorbed form (no restoring)
print(torch.allclose(s_full, s_absorbed, atol=1e-4))      # True

FAQ

Q. How does MLA differ from GQA?
A.

GQA reduces the number of heads by sharing key and value heads among several query heads. MLA keeps the number of heads, stores the information underlying the keys and values compressed into a dcd_c-dimensional latent vector, and restores each head's keys and values from it. In the paper's comparison, GQA performed worse than MHA, while MLA performed better.

Q. Why is RoPE split off into a separate part?
A.

During inference, the key-restoring projection WUKW^{UK} is merged into the query side so that dot products are taken directly with the cached latent vectors. Applying RoPE to the compressed part would insert a position-dependent rotation matrix in between and prevent this merge. Positional information is therefore carried by a small separate query and key (dhRd_h^R dimensions), and RoPE is not applied to the compressed part.

Q. How much smaller does the cache per token become?
A.

With the DeepSeek-V2 settings (nh=128n_h = 128, dh=128d_h = 128, dc=512d_c = 512, dhR=64d_h^R = 64), each layer stores dc+dhR=576d_c + d_h^R = 576 elements, about 1.8% of MHA's 2nhdh=32,7682 n_h d_h = 32{,}768 elements. In the paper's comparison of MoE models, the KV cache was 14% (small model) and 4% (large model) of MHA's.

References

  1. DeepSeek-AI, "DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Model," arXiv:2405.04434, 2024.
  2. J. Ainslie, J. Lee-Thorp, M. de Jong, Y. Zemlyanskiy, F. Lebrón, and S. Sanghai, "GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints," EMNLP, 2023.
  3. N. Shazeer, "Fast Transformer Decoding: One Write-Head is All You Need," arXiv:1911.02150, 2019.