DeepSeek-V2: Compressing the KV Cache with MLA and Cutting Training Cost with DeepSeekMoE
DeepSeek-V2 (DeepSeek-AI, 2024) is a 236B-parameter MoE model that activates 21B per token: Multi-head Latent Attention (MLA) shrinks the inference cache and DeepSeekMoE lowers training cost. This post rechecks 93.3%, 236B and 21B, and verifies MLA's absorption and decoupled RoPE numerically.
On this page
Why this paper matters
In May 2024 DeepSeek-AI released DeepSeek-V2 (arXiv 2405.04434): a mixture-of-experts (MoE) language model with 236B total parameters of which only 21B are active per token, pretrained on 8.1T tokens with a 128K context window. The three headline numbers are all comparisons with the company’s own previous dense model, DeepSeek 67B: 42.5% lower training cost, 93.3% smaller KV cache, and 5.76 times the maximum generation throughput.
It is worth reading because both cost-saving ideas carried over into V3 and R1. Multi-head Latent Attention (MLA) does not make heads share keys and values; it compresses them jointly into one low-dimensional latent vector and caches only that. DeepSeekMoE cuts experts into finer pieces, keeps some shared experts, and adds routing that limits communication plus three balance losses. The DeepSeek-V3 technical report builds on V2’s validated MLA and DeepSeekMoE, adding auxiliary-loss-free load balancing and multi-token prediction, so V2 is where to start if you want to understand V3 and R1.
This post does four things: (1) walks through the design choices of MLA and DeepSeekMoE in the paper’s order; (2) recomputes the paper’s numbers to see where 93.3%, 236B and 21B come from; (3) verifies MLA’s matrix absorption and decoupled RoPE numerically with a small float64 implementation; (4) computes a baseline for device-limited routing. The derivation of MLA and the comparison with GQA and MQA live in Efficient Attention: MQA, GQA, MLA and FlashAttention; here I stick to what the V2 paper chose and why.
Method
MLA: caching a single latent vector
Standard multi-head attention (MHA) caches the keys and values of all heads, numbers per token per layer. MQA and GQA let heads share keys and values to shrink the cache, but the paper’s comparison on 7B dense models (Appendix D.1, Table 8) shows MHA clearly ahead of GQA with 8 groups and of MQA on hard benchmarks; MMLU is 45.2, 41.2 and 37.9. MLA takes a different route: no sharing, but low-rank compression.
First project the hidden state down to a low-dimensional latent vector, then project up to the keys and values of every head:
Here with , and at inference only is cached. Better still, can be absorbed into the query projection and into the output projection , so keys and values never have to be materialized (the paper calls this matrix absorption; the code below checks it). The queries are low-rank compressed too (), which the paper says does nothing for the KV cache and is there to reduce activation memory during training.
Decoupled RoPE. Position encoding is where it gets awkward: RoPE acts on both queries and keys and depends on position. Apply it to and a position-dependent rotation lands between and ; matrix multiplication does not commute, so can no longer be folded into the query, and the keys of all prefix tokens must be recomputed. V2’s fix is to reserve a small slice of dimensions for position: one RoPE query per head and one RoPE key shared by all heads ( per head), concatenated with the position-free content part:
The attention scores are scaled by accordingly. Inference then caches two things: the latent ( numbers) and the shared RoPE key ( numbers), numbers per token per layer.
V2 sets and (with , ), so each layer caches 576 numbers per token. Table 1 of the paper points out that this equals the cache of GQA with only 2.25 groups:
| Attention | Cache per token (elements) | Value at V2’s depth and heads |
|---|---|---|
| MHA | 1,966,080 | |
| GQA | 122,880 for | |
| MQA | 15,360 | |
| MLA | 34,560 |
Here is the number of layers; the GQA and MQA values are my own application of the same formulas, not numbers from the paper.
DeepSeekMoE: fine-grained experts, shared experts and communication limits
The FFNs use DeepSeekMoE (Dai et al., 2024), with two ideas: cut experts into finer pieces so each one specializes more, and set aside some shared experts that every token passes through, to hold common knowledge and reduce redundancy among routed experts. The output is the input plus the outputs of the shared experts and of the selected routed experts:
where keeps the softmax affinity for the top experts and is zero elsewhere. V2’s setup: every layer except the first, which stays a dense FFN, is an MoE layer with 2 shared and 160 routed experts, an expert intermediate size of 1536, and 6 routed experts active per token.
Three further designs serve the training system:
- Device-limited routing. The routed experts live on devices, and a token’s communication cost is proportional to the number of devices its target experts cover. V2 first picks the devices holding the highest-affinity experts and then takes the top-6 only among experts on those devices. The paper says quality is roughly the same as unrestricted top-K once .
- Three auxiliary losses. Expert-level, device-level and communication balance losses (Eqs. 23 to 31), with coefficients , and . The first two even out the load on experts and devices; the third pushes every device towards receiving about tokens ( is the number of tokens in a sequence), so that no device gets swamped.
- Device-level token dropping. Balance losses cannot guarantee strict balance, so training gives each device a capacity factor of 1.0 and drops the lowest-affinity tokens beyond the budget, while guaranteeing that tokens of about 10% of the training sequences are never dropped. Nothing is dropped at evaluation.
Experiments and findings
Pretraining setup. 8.1T tokens (about 12% more Chinese than English tokens) with DeepSeek 67B’s BBPE tokenizer (about 100K entries); 60 layers and hidden size 5120. The optimizer is AdamW (, , weight decay 0.1) with a peak learning rate of , 2K warmup steps, and a factor of 0.316 applied at about 60% and 90% of the tokens; the batch size grows from 2304 to 9216 over the first 225B tokens; sequence length is 4K. The framework uses 16-way zero-bubble pipeline parallelism, 8-way expert parallelism and ZeRO-1 data parallelism, with no tensor parallelism: few parameters are active and some operators are recomputed to save activation memory.
Base-model results. The table is from the paper’s Table 2 (its own evaluation framework, the same settings for every model). The columns are DeepSeek 67B, Qwen1.5 72B, Mixtral 8x22B, LLaMA 3 70B and DeepSeek-V2:
| Benchmark | 67B | Qwen1.5 | Mixtral | LLaMA 3 | V2 |
|---|---|---|---|---|---|
| Active / total params | 67B / 67B | 72B / 72B | 39B / 141B | 70B / 70B | 21B / 236B |
| MMLU (5-shot) | 71.3 | 77.2 | 77.6 | 78.9 | 78.5 |
| BBH (3-shot) | 68.7 | 59.9 | 78.9 | 81.0 | 78.9 |
| GSM8K (8-shot) | 63.4 | 77.9 | 80.3 | 83.0 | 79.2 |
| MATH (4-shot) | 18.7 | 41.4 | 42.5 | 42.2 | 43.6 |
| HumanEval (0-shot) | 45.1 | 43.9 | 53.1 | 48.2 | 48.8 |
| C-Eval (5-shot) | 66.1 | 83.7 | 59.6 | 67.5 | 81.7 |
With only 21B active, V2 is clearly ahead of DeepSeek 67B on almost every benchmark (MMLU up 7.2 points, MATH from 18.7 to 43.6). Against LLaMA 3 70B it has a small gap in general English ability (MMLU 78.5 against 78.9, BBH 78.9 against 81.0, GSM8K 79.2 against 83.0) and does better in Chinese; the paper acknowledges the gap and notes that V2 saw fewer than a quarter of LLaMA 3’s English tokens. It treats scores within 0.3 of each other as the same level.
Efficiency. What the three numbers mean:
- Training cost. Per trillion tokens DeepSeek 67B needs 300.6K H800 GPU hours and V2 172.8K, a saving of 42.5%.
- KV cache. The paper says 93.3% smaller than DeepSeek 67B; the accounting is checked in the next section.
- Generation throughput. On a single node of 8 H800 GPUs, V2 generates more than 50K tokens per second, 5.76 times the maximum of 67B, and its prompt (prefill) throughput exceeds 100K tokens per second. The throughput uses the prompt and generation length distribution of the deployed DeepSeek 67B service; V2’s weights were converted to FP8 and its KV cache quantized to 6 bits on average.
Long context. After pretraining, YaRN extends the window from 4K to 128K and is applied only to the decoupled shared key , the part that carries RoPE: , , , target length 160K. Because the attention mechanism differs, the paper sets the length scaling factor to to minimize perplexity. It then trains 1000 more steps at sequence length 32K with 576 sequences per batch; although training only used 32K, the needle-in-a-haystack (NIAH) test is strong up to 128K. For YaRN itself see the YaRN breakdown.
Alignment. SFT uses 1.5M instruction examples (1.2M for helpfulness, 0.3M for safety), 2 epochs at a learning rate of . Reinforcement learning uses GRPO (see the DeepSeekMath and GRPO breakdown), which avoids a critic as large as the policy. Training has two stages: reasoning alignment first, with a reward model trained for code and math, then human-preference alignment with a weighted sum of a helpfulness reward model, a safety reward model and a rule-based reward model. Code preferences come from compiler feedback and math preferences from ground-truth answers. The paper also says online preference alignment clearly beats the offline kind, without elaborating the comparison. Table 4 has the English open-ended conversation results:
| Model | MT-Bench | AlpacaEval 2.0 (length-controlled) |
|---|---|---|
| DeepSeek 67B Chat | 8.35 | 16.6 |
| LLaMA 3 70B Instruct | 8.95 | 34.4 |
| DeepSeek-V2 Chat (SFT) | 8.62 | 30.0 |
| DeepSeek-V2 Chat (RL) | 8.97 | 38.9 |
RL lifts MT-Bench from 8.62 to 8.97 and AlpacaEval 2.0 from 30.0 to 38.9. The price is what the paper calls the alignment tax: BBH falls from 81.3 for the SFT model to 79.7 for the RL model (Table 3), and on IFEval V2 Chat scores 64.1 and 63.8, well below LLaMA 3 70B Instruct’s 79.7. The paper also observes that IFEval drops markedly when SFT data is below 10K examples and takes this to mean a model needs a certain amount of data to learn specific skills.
Ablations. Two are worth singling out:
- MHA, GQA and MQA (Table 8, 7B dense models). MHA is clearly better on hard benchmarks: BBH, MMLU, C-Eval and CMMLU are 37.0, 45.2, 42.9 and 43.5; GQA with 8 groups gets 35.6, 41.2, 37.7 and 38.4; MQA gets 33.2, 37.9, 30.0 and 34.6.
- MLA versus MHA (Table 9, MoE models). Small models (about 16B total parameters, 1.33T training tokens): MLA caches 15.6K numbers per token against MHA’s 110.6K (14%); BBH 39.0 against 37.9, MMLU 50.0 against 48.7, C-Eval 50.9 against 51.6, CMMLU 53.4 against 52.3. Large models (about 250B, only 420B training tokens): 34.6K against 860.2K (4%); BBH 50.7 against 46.6, MMLU 59.0 against 57.5, C-Eval 59.2 against 57.9, CMMLU 62.5 against 60.7.
Checking it with code
The script below has four parts, all on CPU and taking about a second:
- KV cache and 93.3%. It computes the cache of four attention variants at V2’s depth and head count, then reconstructs 93.3% using DeepSeek 67B’s configuration (95 layers, 8 KV heads, 128 dimensions per head, from Table 2 of the DeepSeek LLM paper), and checks 42.5% and the total GPU hours.
- 236B and 21B. It counts parameters from the paper’s hyperparameters plus two values from the public config (vocabulary 102,400; intermediate size 12,288 for the dense FFN of the first layer).
- Numerical checks of MLA. A complete MLA layer (with query compression and decoupled RoPE) in float64 at small size; it compares “rebuild keys and values first” with “absorbed, using only the cached and ”, then shows what happens if RoPE is applied directly to the keys, and finally computes the compute and memory traffic per cached token while decoding.
- Device-limited routing. With random affinities as a baseline, it counts how many devices a token’s experts land on and how many experts get replaced when routing is limited to 3 devices.
Environment: Apple M2 Max, CPU, Python 3.14.3, PyTorch 2.10.0. Parts 3 and 4 use fixed random seeds; with other seeds numbers such as the relative gaps change, the conclusions do not.
from math import comb
import torch
torch.set_default_dtype(torch.float64)
torch.manual_seed(0)
# ---- Part 1: the KV-cache arithmetic, and where 93.3% comes from ----
L, NH, DH, DC, DR = 60, 128, 128, 512, 64 # DeepSeek-V2, paper Sec. 3.1.2
V2 = {"MHA": 2 * NH * DH * L, "GQA-8": 2 * 8 * DH * L,
"MQA": 2 * DH * L, "MLA": (DC + DR) * L}
CTX = 128 * 1024
print("KV cache, V2 depth and heads, BF16: per token and per 128K sequence")
for name, n in V2.items():
print(f"{name:<6}{n:>10,} values {n * 2 / 1024:>7.1f} KiB "
f"{n * 2 * CTX / 2**30:>7.2f} GiB {n / V2['MHA']:.2%} of MHA")
print(f"MLA cache = GQA with {V2['MLA'] / (2 * DH * L):.2f} groups")
# DeepSeek 67B (DeepSeek LLM paper, Table 2): 95 layers, 8 KV heads, d_h=128
v67, mla = 2 * 8 * 128 * 95, V2["MLA"]
print(f"\n67B: {v67:,} values per token; V2 MLA: {mla:,} values")
print(f"Counting values only: {1 - mla / v67:.1%} smaller")
print(f"MLA at 6 bits, 67B at 16: {1 - mla * 6 / (v67 * 16):.1%} smaller")
print(f"Training cost: 1 - 172.8/300.6 = {1 - 172.8 / 300.6:.1%}; "
f"8.1T tokens ~ {172.8 * 8.1 / 1000:.2f}M GPU hours")
# ---- Part 2: can 236B and 21B be recomputed from the hyperparameters? ----
D, V, QC, FFD, FFE, NS, NR, TOPK = 5120, 102400, 1536, 12288, 1536, 2, 160, 6
attn = (D * QC + QC * NH * DH + QC * NH * DR # query: down, up, RoPE head
+ D * DC + 2 * DC * NH * DH + D * DR # key/value: down, up, RoPE key
+ NH * DH * D) # output projection
expert = 3 * D * FFE # SwiGLU has three matrices
dense, emb = 3 * D * FFD, 2 * V * D # dense layer 1; untied embeddings
moe = (NS + NR) * expert + NR * D # incl. router
moe_act = (NS + TOPK) * expert + NR * D
total = L * attn + dense + (L - 1) * moe + emb
active = L * attn + dense + (L - 1) * moe_act + emb
print(f"\ntotal {total / 1e9:.1f}B (paper: 236B); "
f"active per token {active / 1e9:.1f}B (paper: 21B)")
print(f"attention {L * attn / 1e9:.2f}B, embeddings and head "
f"{emb / 1e9:.2f}B, routed experts "
f"{(L - 1) * NR * expert / total:.1%} of the total")
# ---- Part 3: MLA matrix absorption and decoupled RoPE (float64, small) ----
d, nh, dh, dc, dr, dq, T = 48, 4, 16, 8, 8, 12, 10
def rope(x, pos): # x: (T, n, dim); adjacent pairs rotated by position
inv = 10000.0 ** (-torch.arange(0, x.shape[-1], 2) / x.shape[-1])
ang = pos[:, None, None] * inv
c, s = ang.cos(), ang.sin()
out = torch.empty_like(x)
out[..., 0::2] = x[..., 0::2] * c - x[..., 1::2] * s
out[..., 1::2] = x[..., 0::2] * s + x[..., 1::2] * c
return out
def w(i, o):
return torch.randn(i, o) / i ** 0.5
WDQ, WUQ, WQR = w(d, dq), w(dq, nh * dh), w(dq, nh * dr)
WDKV, WUK, WUV, WKR = w(d, dc), w(dc, nh * dh), w(dc, nh * dh), w(d, dr)
WO = w(nh * dh, d)
H = torch.randn(T, d)
POS = torch.arange(T, dtype=torch.float64)
MASK = torch.ones(T, T).triu(1).bool()
def parts(h, pos): # both query parts, and the two cached items c, k_R
cq = h @ WDQ
qc = (cq @ WUQ).view(T, nh, dh)
qr = rope((cq @ WQR).view(T, nh, dr), pos)
return qc, qr, h @ WDKV, rope((h @ WKR).view(T, 1, dr), pos)
def softmax_rows(s):
return s.masked_fill(MASK, float("-inf")).softmax(-1)
def explicit(h, pos): # rebuild K and V first, then plain attention
qc, qr, c, kr = parts(h, pos)
kc, v = (c @ WUK).view(T, nh, dh), (c @ WUV).view(T, nh, dh)
s = torch.einsum("tnd,jnd->ntj", qc, kc)
s = (s + torch.einsum("tnr,jor->ntj", qr, kr)) / (dh + dr) ** 0.5
o = torch.einsum("ntj,jnd->tnd", softmax_rows(s), v)
return o.reshape(T, nh * dh) @ WO
def absorbed(h, pos): # cached c, k_R only: W_UK into q, W_UV into W_O
qc, qr, c, kr = parts(h, pos)
q_lat = torch.einsum("tnd,cnd->tnc", qc, WUK.view(dc, nh, dh))
s = torch.einsum("tnc,jc->ntj", q_lat, c)
s = (s + torch.einsum("tnr,jor->ntj", qr, kr)) / (dh + dr) ** 0.5
o_lat = torch.einsum("ntj,jc->tnc", softmax_rows(s), c)
wuvo = torch.einsum("cnd,ndD->ncD", WUV.view(dc, nh, dh),
WO.view(nh, dh, d))
return torch.einsum("tnc,ncD->tD", o_lat, wuvo)
diff = (explicit(H, POS) - absorbed(H, POS)).abs().max().item()
print(f"\nmax abs error, explicit vs absorbed: {diff:.1e}")
# RoPE on the up-projected key: logit = q R(t-j) W^T c, R changes with t-j
q0, wk = torch.randn(1, dh), WUK.view(dc, nh, dh)[:, 0, :]
base = q0 @ wk.T
rel = []
for delta in range(1, T):
r = rope(torch.eye(dh).view(dh, 1, dh), torch.full((dh,), float(delta)))
rel.append(((q0 @ r[:, 0, :] @ wk.T - base).norm() / base.norm()).item())
print("RoPE directly on K: the absorbed query must change with t-j")
print(f"relative gap to distance 0, distances 1 to {T - 1}: "
f"{min(rel):.2f} to {max(rel):.2f}")
# decoupled RoPE: position only in q_R and k_R; logits depend on t-j only
def rope_logits(p):
qr, kr = parts(H, p)[1::2]
return torch.einsum("tnr,jor->ntj", qr, kr)
shift = (rope_logits(POS) - rope_logits(POS + 1000)).abs().max().item()
print(f"decoupled part, positions all shifted by 1000: max change {shift:.1e}")
# attention cost per cached token when decoding one token (one layer, BF16)
mha_f, mha_b = 4 * NH * DH, 2 * NH * DH * 2
mla_f, mla_b = 2 * NH * (2 * DC + DR), (DC + DR) * 2
print(f"MHA: {mha_f:,} FLOP and {mha_b:,} bytes per cached token, "
f"{mha_f / mha_b:.1f} FLOP/byte")
print(f"MLA (absorbed): {mla_f:,} FLOP and {mla_b:,} bytes, "
f"{mla_f / mla_b:.1f} FLOP/byte")
# ---- Part 4: device-limited routing and expert combinations ----
NDEV, PER, N, M = 8, 20, 100_000, 3
g = torch.Generator().manual_seed(1)
sc = torch.rand(N, NR, generator=g) # random affinities, a baseline only
def n_devices(idx): # number of devices holding a token's experts
s = (idx // PER).sort(1).values
return 1 + (s[:, 1:] != s[:, :-1]).sum(1)
top = sc.topk(TOPK, 1).indices
exact = NDEV * (1 - comb(NR - PER, TOPK) / comb(NR, TOPK))
nd = n_devices(top)
print(f"\nrandom top-{TOPK}: {nd.double().mean():.2f} devices on average "
f"(exact {exact:.2f}), at most {nd.max().item()}")
keep = sc.view(N, NDEV, PER).max(2).values.topk(M, 1).indices
ok = torch.zeros(N, NDEV, dtype=torch.bool).scatter_(1, keep, True)
masked = sc.masked_fill(~ok.repeat_interleave(PER, 1), -1.0)
top_m = masked.topk(TOPK, 1).indices
same = (top.unsqueeze(2) == top_m.unsqueeze(1)).any(2).sum(1).double()
print(f"limited to {M} devices: {n_devices(top_m).double().mean():.2f} on "
f"average, at most {n_devices(top_m).max().item()}")
print(f"same experts as unrestricted top-{TOPK}: {same.mean():.2f} of {TOPK}")
print("expert combinations")
print(f" 2 of 16: {comb(16, 2):,}; 8 of 64: {comb(64, 8):,}")
print(f" {TOPK} of {NR} (V2): {comb(NR, TOPK):,}")
Output:
KV cache, V2 depth and heads, BF16: per token and per 128K sequence
MHA 1,966,080 values 3840.0 KiB 480.00 GiB 100.00% of MHA
GQA-8 122,880 values 240.0 KiB 30.00 GiB 6.25% of MHA
MQA 15,360 values 30.0 KiB 3.75 GiB 0.78% of MHA
MLA 34,560 values 67.5 KiB 8.44 GiB 1.76% of MHA
MLA cache = GQA with 2.25 groups
67B: 194,560 values per token; V2 MLA: 34,560 values
Counting values only: 82.2% smaller
MLA at 6 bits, 67B at 16: 93.3% smaller
Training cost: 1 - 172.8/300.6 = 42.5%; 8.1T tokens ~ 1.40M GPU hours
total 235.7B (paper: 236B); active per token 21.4B (paper: 21B)
attention 8.95B, embeddings and head 1.05B, routed experts 94.5% of the total
max abs error, explicit vs absorbed: 1.3e-15
RoPE directly on K: the absorbed query must change with t-j
relative gap to distance 0, distances 1 to 9: 0.37 to 1.43
decoupled part, positions all shifted by 1000: max change 4.8e-14
MHA: 65,536 FLOP and 65,536 bytes per cached token, 1.0 FLOP/byte
MLA (absorbed): 278,528 FLOP and 1,152 bytes, 241.8 FLOP/byte
random top-6: 4.46 devices on average (exact 4.46), at most 6
limited to 3 devices: 2.99 on average, at most 3
same experts as unrestricted top-6: 4.37 of 6
expert combinations
2 of 16: 120; 8 of 64: 4,426,165,368
6 of 160 (V2): 21,193,254,160
How to read these numbers:
- The cache arithmetic. MLA caches 34,560 numbers per token, 1.76% of MHA with the same heads and exactly the cache of GQA with 2.25 groups, in line with the paper’s Table 1. In BF16 one 128K sequence needs 8.44 GiB with MLA and 480 GiB with MHA. Against GQA with 8 groups MLA’s cache is 28%, against MHA 1.76%. In practice the baseline is often GQA already, so when someone quotes a saving, ask what it is measured against.
- 93.3% is architecture, depth and quantization combined. Against DeepSeek 67B (which already uses GQA, with 194,560 numbers per token), counting values alone gives 82.2%; quantizing V2’s cache to an average of 6 bits and counting 67B at 16 bits gives exactly 93.3%. Section 3.2.3 says the deployed model quantizes its KV cache to 6 bits on average but does not give this calculation, so it is my reconstruction: it matches to one decimal, which does not prove it is how the paper computed it. Nor is the 82.2% all MLA: per layer the cache is 28% of 67B’s (576 against 2,048 numbers), and multiplying by the layer ratio 60/95 (V2 is shallower) gives 17.8%, a reduction of 82.2%.
- Training cost against the theoretical gap. 172.8/300.6 gives 42.5%, matching the paper; at 172.8K GPU hours per trillion tokens, 8.1T tokens come to about 1.40M H800 GPU hours (my extrapolation: the paper gives no total and this excludes context extension and post-training). By active parameters alone, matrix-multiply work per token is about 31% of 67B’s (21B/67B), yet the saving is only 42.5%. My reading is that communication and irregular computation eat part of the theoretical gain; the paper says only that MoE adds communication overhead and gives no breakdown.
- 236B and 21B check out. I get 235.7B in total and 21.4B active. The 21.4B includes the input embedding table, which is only a lookup (about 0.52B); without it the count is about 20.9B, and both round to 21B. Routed experts hold 94.5% of the parameters and each token uses 6 of 160 of them, which is where “large total, small active” comes from.
- Absorption and decoupled RoPE both hold. The largest absolute difference between the outputs before and after absorption is 1.3e-15, float64 rounding. If RoPE is applied directly to the up-projected key, the absorbed query becomes and changes with the distance : at distances 1 to 9 it differs from the distance-0 query by a relative 0.37 to 1.43, so there is no single matrix to fold in ahead of time. With decoupling, position lives only in and ; shifting all positions by 1000 changes those logits by at most 4.8e-14, so they depend on relative distance only.
- MLA is not free: it trades compute for memory traffic. After absorption, the attention compute per cached token while decoding is 4.25 times MHA’s (278,528 against 65,536 FLOP) while the bytes read are 1/56.9 of MHA’s (1,152 against 65,536). The arithmetic intensity rises from 1.0 to about 242 FLOP per byte: MHA decoding attention is a textbook memory-bound workload, and MLA moves it towards a regime where compute and memory are closer to balanced. This comparison is my own derivation, the paper has no such table, and whether it turns into throughput depends on the kernel and the hardware.
- Baseline for device-limited routing. With random affinities, 6 experts land on 4.46 devices on average (exact value 4.46) and up to 6; limited to 3 devices they touch at most 3, but share only 4.37 experts with the unrestricted top-6, so about 1.6 experts per token are swapped. This is a random-affinity baseline: a trained router has structured affinities, and how many experts are swapped depends on the learned distribution. The paper gives no such statistic and says only that quality is roughly unchanged once .
- Combination counts only measure routing flexibility. Choosing 2 of 16 experts gives 120 combinations, 8 of 64 gives 4.4 billion, and V2’s 6 of 160 gives 21.2 billion. The argument for fine-grained experts is more flexible combinations and more specialized experts; I only counted combinations and did not test whether they improve quality (that is what the DeepSeekMoE paper’s experiments are for).
I did not tune anything in this script. Between the first run and the page I only shortened lines to 80 columns and tidied the output format; every number comes from one complete run of the code on this page.
Limitations and what to keep in mind
- The efficiency numbers come from the authors’ own deployment. The 5.76 times throughput uses their online service’s prompt and generation length distribution, and V2 combines FP8 weights with a 6-bit KV cache; the paper does not say whether the 67B baseline had the same optimizations. Outside readers cannot reproduce the ratio from the paper, and it should not be credited to MLA alone.
- 93.3% and 42.5% are each tied to their own accounting. The first stacks the depth difference and quantization (see the check above); the second is measured H800 GPU hours, not a FLOPs ratio.
- The MLA ablation is thin. Table 9 has two scales, one training run each and no error bars; the large models trained on only 420B tokens; the activated parameters also differ (25.0B against 21.5B for the large pair), so it is not a strictly parameter-matched comparison. On the small models MLA is slightly lower on C-Eval (50.9 against 51.6). “MLA is no worse than MHA” is a safer reading than “MLA is better”.
- Evaluation uses the authors’ own framework. Every baseline was rerun in the same internal framework, which helps comparability but is hard for outsiders to audit item by item; the paper treats gaps under 0.3 as equal.
- Alignment has trade-offs. RL improved open-ended conversation and also brought an alignment tax, and on IFEval V2 trails LLaMA 3 70B Instruct by about 16 points; details such as the reward-model data and the coefficients are not published.
- Language coverage. The authors say the data is mostly Chinese and English, so other languages need care.
- Limits of my code. Tiny dimensions (tens), float64 and no training: it shows algebraic equivalence and orders of magnitude, nothing more. Production uses BF16 or FP8, with different rounding and kernels. The routing baseline uses random affinities, not a trained router.
What to take from this paper
- The inference bottleneck is often the bytes of cache, not only the parameter count. MLA cuts the cache per token from to by joint low-rank compression, and the paper reports quality no worse than MHA.
- Keep position encoding apart from low-rank compression. RoPE depends on position and breaks matrix absorption; decoupled RoPE carries position in a small shared key and leaves the content part position-free.
- Ask what each number is measured against. 93.3% is architecture, depth and quantization combined (my reconstruction), 42.5% is measured H800 GPU hours, and 5.76 times is throughput under their online distribution.
- MoE saves active parameters, and turning that into real savings takes a whole package: device-limited routing, three balance losses, device-level token dropping, and a parallelism scheme with no tensor parallelism.
- It is the starting point of the V3 and R1 line. MLA and DeepSeekMoE are validated in V2, V3 adds auxiliary-loss-free balancing and multi-token prediction on top, and the GRPO used for V2’s RL comes from DeepSeekMath.
Further reading
- Paper: DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Model; weights and code in the authors’ GitHub repository.
- Prior work it relies on: Dai et al., DeepSeekMoE (arXiv:2401.06066); DeepSeek-AI, DeepSeek LLM (arXiv:2401.02954, the source of the 67B configuration used here, its Table 2); Shazeer, Fast Transformer Decoding: One Write-Head is All You Need (arXiv:1911.02150, MQA).
- Related paper breakdowns on this site: DeepSeek-V3, GQA, Mixtral, YaRN, DeepSeekMath and GRPO.
- Related Wiki on this site: Efficient Attention: MQA, GQA, MLA and FlashAttention, Mixture of Experts (MoE): Routing, Load Balancing and Sparse Activation, KV Cache and Inference Performance.
- Glossary: MLA, Decoupled RoPE, Shared expert, Device-limited routing, KV cache.
FAQ
- Why does DeepSeek-V2's MLA decouple RoPE from the compressed keys?
- RoPE depends on position. If it is applied to the up-projected keys, a position-dependent rotation sits between the query projection and the key up-projection, so the up-projection can no longer be absorbed into the query and the keys of every prefix token would have to be recomputed at each step. V2 instead gives position its own small slice: a RoPE query per head plus one 64-dimensional RoPE key shared by all heads, cached next to the latent, which makes 512 + 64 = 576 cached values per token per layer. In a small float64 implementation the outputs before and after absorption differ by at most about 1.3e-15; with RoPE applied directly to the keys, the absorbed query at distances 1 to 9 differs from the one at distance 0 by a relative 0.37 to 1.43.
- Where does the 93.3% KV-cache reduction come from?
- The abstract states it against DeepSeek 67B. With 67B's configuration (95 layers, 8 KV heads, 128 dimensions per head) and V2's MLA (60 layers, 576 values per layer), counting values alone gives 82.2%; quantizing V2's cache to an average of 6 bits while counting 67B at 16 bits gives 93.3%. Section 3.2.3 does say the deployed model quantizes its KV cache to 6 bits on average, but the paper does not write out the 93.3% calculation, so this is my reconstruction. The 82.2% also includes the difference in depth (60 versus 95 layers). So 93.3% is architecture, depth and quantization combined, not MLA alone.
- Can DeepSeek-V2's 236B total and 21B active parameters be recomputed from its hyperparameters?
- Yes. Using the paper's hyperparameters (60 layers, hidden size 5120, 128 heads, 2 shared plus 160 routed experts with intermediate size 1536, 6 routed experts per token) and two values from the public config (vocabulary 102,400; intermediate size 12,288 for the dense FFN of the first layer), I get 235.7B parameters in total and 21.4B active per token, including the embedding table and output head. Routed experts hold 94.5% of all parameters and attention about 8.95B.
- What is device-limited routing, and how many devices does it allow per token?
- V2 spreads its 160 routed experts evenly over 8 devices (20 each). Plain top-6 routing can scatter a token's experts across many devices, and communication under expert parallelism grows with the number of devices touched. V2 first picks the M=3 devices that hold the highest-affinity experts and then takes the top-6 only among experts on those devices, so a token is sent to at most 3 devices. With purely random affinities, unrestricted routing touches 4.46 devices on average and up to 6; the restricted version touches at most 3 but shares only 4.37 of the 6 experts with the unrestricted choice. A trained router's affinities are not random, so that overlap does not describe training; the paper says that with M of at least 3 quality is roughly the same as unrestricted top-K.