DeepSeek-V2: MLA Explained
·2 min read

MLA is a novel attention mechanism designed for Transformer-based Large Language Models, aiming to boost inference efficiency by massively compressing how Key-Value (KV) cache is stored and accessed during generation. Conventional Multi-Head Attention (MHA) keeps a heavy cache of keys and values per token, which limits batch sizes and sequence lengths for LLMs. MLA replaces this with a joint, low-rank compression of keys and values (and optionally queries), dramatically reducing memory footprint while maintaining or improving performance.
MLA also introduces decoupled Rotary Position Embedding (RoPE) to address the incompatibility between standard RoPE and low-rank compression.
MLA Full Formulas#
Below are the complete step-by-step formulas of MLA, as defined in the DeepSeek-V2 paper (Appendix C):
1. Query Compression
-
Compress the attention input for queries:
where is the compressed latent vector for queries, is the input at time , and is the down-projection matrix.
-
Up-project to produce query candidates:
-
Apply Rotary Position Embedding (RoPE) to decoupled queries:
-
Concatenate compressed and RoPE queries for each head:
2. Key-Value Joint Compression
-
Compress the attention input for keys and values:
-
Up-project keys:
-
Apply RoPE to the decoupled key:
-
Concatenate compressed and RoPE keys for each head:
-
Up-project values:
3. Attention Calculation
-
For each head, compute attention output:
where is the per-head dimension, and is the decoupled per-head dimension for RoPE.
-
Concatenate all heads and project:
where is the output projection matrix.
Caching Strategy
- During inference, only compressed latent vectors (, ) need to be cached, greatly reducing memory requirements compared to MHA.
Optimization Note
- Due to distributive properties in matrix multiplication, some projection matrices (e.g., ) can be merged with other projections during inference, avoiding redundant computation of keys and values for each query.
Summary Table of MLA vs Other Attention Mechanisms#
| Mechanism | KV Cache Per Token (# elements) | Performance |
|---|---|---|
| MHA | Strong | |
| GQA | Moderate | |
| MQA | Weak | |
| MLA (Ours) | () | Stronger |
Where:
- : # of attention heads
- : per-head dimension
- : # of layers
- : # of groups (GQA)
- : compression dimension (MLA)
- : decoupled query/key dimension (MLA)
For DeepSeek-V2, typically, , , making MLA's cache much leaner.
Source: [DeepSeek-V2 Paper](https://arxiv.org/pdf/2405.04434