DeepSeek-V3.2: Sparse Attention, Scaled-Up Reinforcement Learning and Synthetic Agent Tasks
DeepSeek-V3.2 adds DeepSeek Sparse Attention to V3.1-Terminus by continued training: a lightning indexer picks 2048 tokens per query, so core attention drops from O(L²) to O(Lk). Then scaled-up GRPO and 1,800+ synthetic environments. I recompute the numbers and rebuild DSA in miniature.
On this page
- Why this paper is worth reading
- Background: two bills for attention in long contexts
- The structure of DSA
- Two-stage continued pre-training
- Checking parameters, tokens, FLOPs and the paper’s tables
- Checking the gradient of the “unbiased KL estimate”
- Rebuilding DSA in miniature
- The paper’s post-training: scaled-up GRPO and agent tasks
- Specialist distillation and mixed reinforcement learning
- Four tricks for scaling GRPO
- Bringing thinking into tool calls
- Large-scale synthetic agent tasks
- The paper’s results
- Limits and open questions
- What to take from this paper
- Further reading
- FAQ
DeepSeek-V3.2: Pushing the Frontier of Open Large Language Models (DeepSeek-AI, December 2025; the V3.2 paper below) reports a mixture-of-experts model whose checkpoint on Hugging Face holds 685,355,329,792 parameters (including the MTP layer and the indexers). Its architecture differs from DeepSeek-V3.1-Terminus in one place: continued training adds DeepSeek Sparse Attention (DSA). DSA uses a tiny “lightning indexer” to score every earlier token for each query token and lets only the top 2048 into core attention, so core attention drops from to . The paper’s other two contributions are scaling reinforcement learning to more than 10% of the pre-training cost, and training “thinking while using tools” on synthetic agent tasks (over 1,800 environments and 85,000 prompts). It reports that V3.2 is on par with GPT-5 High on reasoning benchmarks, and that V3.2-Speciale, with the length limit relaxed, reaches gold-medal level at IMO 2025, IOI 2025, CMO 2025 and the ICPC World Finals 2025.
The paper appeared on arXiv on 2 December 2025 (v1; this post uses v1). A model of this size cannot be retrained on a laptop, so I did the three things that can be checked. First, I recomputed the indexer’s parameter count, the continued-pre-training token budgets and the per-token attention FLOPs from the parameter tallies of two Hub checkpoints, the paper’s step counts and batch sizes, and the model config, and checked the numbers in the paper’s Tables 1, 3 and 4. They all agree; only the average in τ²-Bench needs rounding error to explain. Second, I tested the mathematical claim behind the paper’s “unbiased KL estimate” by exact enumeration: the corrected gradient equals the KL gradient to machine precision, while the K3 estimator the paper corrects, even on-policy, has the gradient of the reverse KL. Third, I rebuilt DSA’s two training stages on a tiny byte-level model (train the indexer first, then train sparse), the learned indexer ends 0.003 bpb above the oracle and 0.023 bpb below the sliding window at , and 300 steps of sparse training shrink the gap to a dense control from 0.0248 to 0.0048; at toy scale this shows the direction, not the magnitude, and it measures no speed.
Why this paper is worth reading
- It is a complete recipe for sparse attention in a large MoE. Not just an attention variant: the paper shows how to retrofit an already-trained dense model into a sparse one (945.8B tokens of continued training), how to train the indexer, and what the cost curves look like, for a model that is served in production.
- The post-training half is just as substantial. The paper writes up how to scale reinforcement-learning compute without collapse and how to bring thinking into tool calling as reusable practices; read it next to GDPO, DAPO and GSPO on this site.
- It states its own limits. Less world knowledge than the closed models, poor token efficiency and weaker complex-task performance are all in the conclusion; DSA is only evaluated as “on par with V3.1-Terminus”, with no ablation, which this post points out too.
- Neighbouring pages. MLA and DeepSeekMoE are in the DeepSeek-V2 walkthrough, V3’s overall architecture in the DeepSeek-V3 walkthrough, and GRPO in the DeepSeekMath walkthrough; the concept pages are efficient attention, long context and reasoning reinforcement learning.
Background: two bills for attention in long contexts
Dense attention makes every query token take dot products with all earlier tokens, so core attention costs for sequence length , and decoding re-reads the whole KV cache at every step. MLA compresses each token’s cache to a 512-dimension latent plus a 64-dimension position part, which shrinks the cache, but core attention still touches every earlier token. At a 128K context that term dominates everything else: in the estimate below, dense attention takes 96.8% of each token’s compute.
Sparse attention lets each query look at only a small part of the past. Fixed patterns (a sliding window plus a few global tokens) are simple, but position decides which tokens matter, not content; learned selection is more flexible, and its difficulties are the cost of the selection itself and how to turn an already-trained dense model into a sparse one without damage. DSA answers with a very cheap scorer, trained by distillation to match dense attention, followed by letting the main model adapt. DeepSeek’s earlier NSA (Yuan et al., ACL 2025) is a natively trainable sparse-attention route, and the V3.2 paper cites it for the kernel-level requirement.
The structure of DSA
For the query token’s hidden state and an earlier token , the lightning indexer computes an index score (the paper’s Eq. 1):
is the number of indexer heads, and come from the query token, and from the earlier token. The paper picks ReLU for throughput and stresses that the indexer has few heads and can run in FP8. With in hand, only the key-value entries with the highest scores go to attention (Eq. 2):
In V3.2, . Because training continues from V3.1-Terminus, DSA is built on MLA, specifically on MLA’s MQA mode: each latent vector is shared by all heads of a query token, so the indexer selects one set of entries per token, not one per head. The paper says this is a kernel-efficiency requirement (each key-value entry must be shared by several queries to be read efficiently). The MHA and MQA modes of MLA are in the paper’s Appendix A; V3.1-Terminus uses the MHA mode for training and prefilling and the MQA mode for decoding.
The model config and the official reference implementation add sizes the paper does not state: the indexer has 64 heads of 128 dimensions each; queries come from MLA’s low-rank query vector (1536 dimensions), keys come from the hidden state (7168 dimensions projected to 128, then LayerNorm), and the weights come from a linear projection of the hidden state; only the first 64 dimensions of the queries and keys get rotary position encoding, and a Hadamard transform is applied before scoring. These details come from inference/model.py of V3.2-Exp on Hugging Face, not from the paper’s text.
Two-stage continued pre-training
Starting from the V3.1-Terminus base with its 128K context, with training data distributed exactly like V3.1-Terminus’s 128K long-context extension data, there are two stages.
Dense warm-up. Keep dense attention, freeze every parameter except the lightning indexer, and train only the indexer. The goal is to make the indexer’s output distribution match the main attention distribution: for the -th query token, sum the attention scores over all heads and L1-normalize along the sequence to get a target distribution , then minimize a KL divergence (Eq. 3):
The learning rate is , for only 1000 steps of 16 sequences of 128K tokens each, 2.1B tokens in total.
Sparse training. Introduce fine-grained token selection and update all parameters so the model adapts to the sparse pattern. The indexer still aligns to the main attention, but only on the selected set (Eq. 4):
The indexer’s input is detached from the computational graph and optimized separately: the indexer is driven only by , the main model only by the language-modeling loss. The learning rate is , with 2048 key-value tokens selected, and the main model and the indexer train together for 15000 steps of 480 sequences of 128K tokens, 943.7B tokens in total. Post-training keeps using the same sparse attention.
Two properties of this design are worth noting. First, in the warm-up the main attention is a ready-made teacher, so the indexer only has to imitate; it does not have to discover from scratch what matters. Second, in the sparse stage the indexer and the main model are decoupled: the selection itself has no gradient (top-k is not differentiable), so the indexer can improve only through the KL distillation path, and the main model learns, through the language-modeling loss, to work with the tokens it is given.
Checking parameters, tokens, FLOPs and the paper’s tables
The script below fetches the config.json and the parameter tallies of two checkpoints from Hugging Face (network required) and does five things: it checks the indexer’s parameter count against the difference between the two checkpoints’ tallies; it recomputes the token budgets of both stages from steps, batch sizes and sequence length; it estimates per-token attention FLOPs from the config and compares dense with DSA; it checks the output-token counts in the paper’s Table 3; and it checks the sums in Table 4, Table 1 and the introduction. The numbers of Tables 3 and 4 were copied by me from the PDF. The FLOPs model is my own estimate, not the paper’s: core attention costs per attended token ( heads, keys of 576 dimensions and values of 512 in MQA mode), the indexer costs per candidate token (64 heads, 128 dimensions), and all other layers are counted as twice the activated parameters.
Full code (about 170 lines)
"""Checking DeepSeek-V3.2: indexer size, token budgets, FLOPs, tables"""
import json
import math
import urllib.request
HUB = "https://huggingface.co"
OLD = "deepseek-ai/DeepSeek-V3.1-Terminus"
NEW = "deepseek-ai/DeepSeek-V3.2"
def fetch(url):
with urllib.request.urlopen(url, timeout=60) as r:
return json.load(r)
def hub(repo):
cfg = fetch(f"{HUB}/{repo}/resolve/main/config.json")
st = fetch(f"{HUB}/api/models/{repo}")["safetensors"]
return cfg, st["parameters"], st["total"]
cfg_o, par_o, tot_o = hub(OLD)
cfg, par_n, tot_n = hub(NEW)
print("== 1. Indexer parameters (difference of two Hub checkpoints)")
d, qr = cfg["hidden_size"], cfg["q_lora_rank"]
hi, di = cfg["index_n_heads"], cfg["index_head_dim"]
n_idx = cfg["num_hidden_layers"] + cfg["num_nextn_predict_layers"]
per = {"wq_b": qr * hi * di, "wk": d * di,
"k_norm": 2 * di, "weights_proj": d * hi}
for k, v in per.items():
print(f" {k:13s}{v:>12,}")
one = sum(per.values())
print(f" per layer {one:,}; ×{n_idx} layers (incl. MTP)"
f" = {one * n_idx:,}")
want = {"F8_E4M3": (per["wq_b"] + per["wk"]) * n_idx,
"BF16": per["weights_proj"] * n_idx,
"F32": per["k_norm"] * n_idx}
print(f" {'dtype':9s}{'V3.1-Terminus':>16s}{'V3.2':>16s}"
f"{'diff':>13s}{'indexer':>13s}{'rest':>13s}")
for k, w in want.items():
diff = par_n[k] - par_o[k]
print(f" {k:9s}{par_o[k]:>16,}{par_n[k]:>16,}{diff:>13,}"
f"{w:>13,}{diff - w:>13,}")
print(f" {'total':9s}{tot_o:>16,}{tot_n:>16,}{tot_n - tot_o:>13,}"
f"{one * n_idx:>13,}{tot_n - tot_o - one * n_idx:>13,}")
print(f" indexer share of V3.2 parameters "
f"{one * n_idx / tot_n:.4%}")
blocks = par_o["F8_E4M3"] // 128**2
print(f" V3.1 FP8 weights / (128*128) ≈ scale count:"
f" {blocks:,}")
print(" scale_fmt: V3.1 =",
cfg_o["quantization_config"].get("scale_fmt"),
"; V3.2 =", cfg["quantization_config"]["scale_fmt"])
print("\n== 2. Continued pre-training token budgets")
K = 128 * 1024
warm, sparse = 1000 * 16 * K, 15000 * 480 * K
print(f" dense warm-up 1000 x 16 x 128K = {warm:,} "
f"({warm / 1e9:.2f}B)")
print(f" sparse stage 15000 x 480 x 128K = {sparse:,} "
f"({sparse / 1e9:.1f}B)")
print(f" total {warm + sparse:,} ({(warm + sparse) / 1e9:.1f}B)")
print("\n== 3. Attention FLOPs per token (my estimate)")
H, topk = cfg["num_attention_heads"], cfg["index_topk"]
kvl, dr = cfg["kv_lora_rank"], cfg["qk_rope_head_dim"]
dn, dv = cfg["qk_nope_head_dim"], cfg["v_head_dim"]
core = 2 * H * ((kvl + dr) + kvl) # per attended token: QK and PV
idx = 2 * hi * di # per candidate token: indexer score
idx_proj = 2 * (qr * hi * di + d * di + d * hi)
print(f" core attention per attended token {core:,}"
f" FLOPs/layer")
print(f" indexer per candidate token {idx:,}"
f" FLOPs/layer = {idx / core:.2%} of core")
nl = cfg["num_hidden_layers"]
attn_w = (d * qr + qr * H * (dn + dr) + d * (kvl + dr)
+ kvl * H * (dn + dv) + H * dv * d)
ffn = 3 * d * cfg["intermediate_size"]
moe = (3 * d * cfg["moe_intermediate_size"]
* (cfg["num_experts_per_tok"] + cfg["n_shared_experts"])
+ d * cfg["n_routed_experts"])
nd = cfg["first_k_dense_replace"]
act = nl * attn_w + nd * ffn + (nl - nd) * moe + d * cfg["vocab_size"]
other = 2 * act
print(f" activated matmul params per token"
f" {act / 1e9:.2f}B -> {other / 1e9:.1f} GFLOPs")
def dense(t):
return nl * core * t, other
def dsa(t):
return nl * (idx * t + core * min(t, topk) + idx_proj), other
print(f" {'t':>7s}{'dense attn':>20s}{'DSA':>14s}"
f"{'attn ratio':>18s}{'total ratio':>18s}")
rows = {}
for t in (1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072):
(a, o), (b, _) = dense(t), dsa(t)
rows[t] = (a / b, (a + o) / (b + o))
print(f" {t // 1024:>6d}K{a / 1e9:>17.1f} G{b / 1e9:>11.1f} G"
f"{a / b:>17.2f}x{(a + o) / (b + o):>17.2f}x")
t0 = next(t for t in range(1, 131073)
if sum(dsa(t)) < sum(dense(t)))
print(f" DSA becomes cheaper from position {t0:,}")
a, o = dense(131072)
print(f" attention share at 128K"
f" {a / (a + o):.1%}")
# read off Figure 3 (USD per million tokens, about ±0.02)
fig3 = {"prefill": (0.67, 0.19), "decode": (2.15, 0.25)}
for k, (v1, v2) in fig3.items():
print(f" Fig. 3 read-off {k} 128K: {v1:.2f} vs {v2:.2f} "
f"USD = {v1 / v2:.1f}x")
print("\n== 4. Paper Table 3: output tokens")
# (acc, ktokens): GPT-5 High, Gemini-3.0 Pro, K2 Thinking, V3.2, Speciale
T3 = {
"AIME 2025": [(94.6, 13), (95.0, 15), (94.5, 24), (93.1, 16), (96.0, 23)],
"HMMT Feb 2025": [(88.3, 16), (97.5, 16), (89.4, 31), (92.5, 19),
(99.2, 27)],
"HMMT Nov 2025": [(89.2, 20), (93.3, 15), (89.2, 29), (90.2, 18),
(94.4, 25)],
"IMOAnswerBench": [(76.0, 31), (83.3, 18), (78.6, 37), (78.3, 27),
(84.5, 45)],
"LiveCodeBench": [(84.5, 13), (90.7, 13), (82.6, 29), (83.3, 16),
(88.7, 27)],
"Codeforces": [(2537, 29), (2708, 22), None, (2386, 42), (2701, 77)],
"GPQA Diamond": [(85.7, 8), (91.9, 8), (84.5, 12), (82.4, 7),
(85.7, 16)],
"HLE": [(26.3, 15), (37.7, 15), (23.9, 24), (25.1, 21), (30.6, 35)],
}
pairs = {"V3.2/K2": (3, 2), "V3.2/GPT5": (3, 0),
"Spec/Gem": (4, 1), "V3.2/Spec": (3, 4)}
print(" cell: k tokens of the 1st / 2nd = ratio")
print(" K2 = Kimi-K2 Thinking, GPT5 = GPT-5 High,")
print(" Gem = Gemini-3.0 Pro, Spec = V3.2-Speciale")
print(f" {'':16s}" + "".join(f"{n:>14s}" for n in pairs))
logs = {n: [] for n in pairs}
for b, row in T3.items():
cells = []
for n, (i, j) in pairs.items():
if row[j] is None:
cells.append(f"{'-':>14s}")
continue
r = row[i][1] / row[j][1]
logs[n].append(math.log(r))
cells.append(f"{row[i][1]}/{row[j][1]}={r:.2f}".rjust(14))
print(f" {b:16s}" + "".join(cells))
print(f" {'geo. mean':16s}" + "".join(
f"{math.exp(sum(v) / len(v)):>14.2f}" for v in logs.values()))
print(" benchmarks:", [len(v) for v in logs.values()])
print("\n== 5. Sums in paper Tables 4 and 1")
comp = {"IMO 2025": ([7, 7, 7, 7, 7, 0], 35, 42),
"CMO 2025": ([18, 18, 9, 21, 18, 18], 102, 126),
"IOI 2025": ([100, 82, 72, 100, 55, 83], 492, 600)}
for k, (ps, tot, full) in comp.items():
print(f" {k}: {sum(ps)} (paper {tot}/{full}) "
f"{'ok' if sum(ps) == tot else 'MISMATCH'}")
icpc = "3 - 1 1 2 2 - 1 1 1 1 1".split()
print(f" ICPC WF 2025: solved "
f"{sum(x != '-' for x in icpc)}/12 (paper 10/12)")
tasks = {"code agent": 24667, "search agent": 50275,
"general agent": 4417, "code interpreter": 5908}
print(f" Table 1: {' + '.join(f'{v:,}' for v in tasks.values())}"
f" = {sum(tasks.values()):,} (intro 85,000)")
tau = (63.8 + 81.1 + 96.2) / 3
print(f" tau2-bench: (63.8 + 81.1 + 96.2) / 3 = {tau:.2f} "
f"(Table 2 80.3)")
Output:
== 1. Indexer parameters (difference of two Hub checkpoints)
wq_b 12,582,912
wk 917,504
k_norm 256
weights_proj 458,752
per layer 13,959,424; ×62 layers (incl. MTP) = 865,484,288
dtype V3.1-Terminus V3.2 diff indexer rest
F8_E4M3 680,571,043,840 681,408,069,632 837,025,792 837,025,792 0
BF16 3,917,742,080 3,946,184,704 28,442,624 28,442,624 0
F32 42,600,080 1,075,456 -41,524,624 15,872 -41,540,496
total 684,531,386,000 685,355,329,792 823,943,792 865,484,288 -41,540,496
indexer share of V3.2 parameters 0.1263%
V3.1 FP8 weights / (128*128) ≈ scale count: 41,538,760
scale_fmt: V3.1 = None ; V3.2 = ue8m0
== 2. Continued pre-training token budgets
dense warm-up 1000 x 16 x 128K = 2,097,152,000 (2.10B)
sparse stage 15000 x 480 x 128K = 943,718,400,000 (943.7B)
total 945,815,552,000 (945.8B)
== 3. Attention FLOPs per token (my estimate)
core attention per attended token 278,528 FLOPs/layer
indexer per candidate token 16,384 FLOPs/layer = 5.88% of core
activated matmul params per token 36.62B -> 73.2 GFLOPs
t dense attn DSA attn ratio total ratio
1K 17.4 G 20.1 G 0.86x 0.97x
2K 34.8 G 38.5 G 0.90x 0.97x
4K 69.6 G 40.6 G 1.71x 1.25x
8K 139.2 G 44.7 G 3.11x 1.80x
16K 278.4 G 52.9 G 5.26x 2.79x
32K 556.7 G 69.2 G 8.04x 4.42x
64K 1113.5 G 102.0 G 10.92x 6.77x
128K 2226.9 G 167.5 G 13.30x 9.55x
DSA becomes cheaper from position 2,283
attention share at 128K 96.8%
Fig. 3 read-off prefill 128K: 0.67 vs 0.19 USD = 3.5x
Fig. 3 read-off decode 128K: 2.15 vs 0.25 USD = 8.6x
== 4. Paper Table 3: output tokens
cell: k tokens of the 1st / 2nd = ratio
K2 = Kimi-K2 Thinking, GPT5 = GPT-5 High,
Gem = Gemini-3.0 Pro, Spec = V3.2-Speciale
V3.2/K2 V3.2/GPT5 Spec/Gem V3.2/Spec
AIME 2025 16/24=0.67 16/13=1.23 23/15=1.53 16/23=0.70
HMMT Feb 2025 19/31=0.61 19/16=1.19 27/16=1.69 19/27=0.70
HMMT Nov 2025 18/29=0.62 18/20=0.90 25/15=1.67 18/25=0.72
IMOAnswerBench 27/37=0.73 27/31=0.87 45/18=2.50 27/45=0.60
LiveCodeBench 16/29=0.55 16/13=1.23 27/13=2.08 16/27=0.59
Codeforces - 42/29=1.45 77/22=3.50 42/77=0.55
GPQA Diamond 7/12=0.58 7/8=0.88 16/8=2.00 7/16=0.44
HLE 21/24=0.88 21/15=1.40 35/15=2.33 21/35=0.60
geo. mean 0.66 1.12 2.09 0.60
benchmarks: [7, 8, 8, 8]
== 5. Sums in paper Tables 4 and 1
IMO 2025: 35 (paper 35/42) ok
CMO 2025: 102 (paper 102/126) ok
IOI 2025: 492 (paper 492/600) ok
ICPC WF 2025: solved 10/12 (paper 10/12)
Table 1: 24,667 + 50,275 + 4,417 + 5,908 = 85,267 (intro 85,000)
tau2-bench: (63.8 + 81.1 + 96.2) / 3 = 80.37 (Table 2 80.3)
Reading it item by item:
- The indexer’s parameter count checks out (section 1). The indexer has four groups of parameters per layer (
wq_b,wk,k_norm,weights_proj), 13,959,424 in total; V3.2 has 61 main layers plus one MTP layer, each with an indexer, so 865,484,288 in all. On the Hub, V3.2 has 837,025,792 more FP8 parameters and 28,442,624 more BF16 parameters than V3.1-Terminus, and both numbers equal the corresponding indexer parts digit for digit. The F32 column drops by 41,524,624, and the indexers do not cause that: V3.2’sconfig.jsonhasscale_fmt: ue8m0, which V3.1-Terminus lacks. V3.1’s F32 column should include the block scales of its FP8 weights (FP8 parameters ÷ 128² is about 41,538,760 of them), while V3.2’s tally has no such entry, and the size of the gap fits; I did not check tensor by tensor, so this is an inference. The indexers are 0.1263% of all parameters, a very cheap component. - The token budgets check out (section 2). 1000 × 16 × 128K is 2,097,152,000, which the paper writes as 2.1B; 15000 × 480 × 128K is 943,718,400,000, which the paper writes as 943.7B.
- The attention FLOPs estimate (section 3). The “attn ratio” is dense core attention divided by “indexer plus core attention over the 2048 selected tokens”, per token; the “total ratio” also counts the other layers (36.62B activated parameters, about 73.2 GFLOPs). At 1K and 2K DSA is slightly more expensive (attention ratios 0.86 and 0.90, total 0.97): the indexer still scores every earlier token, but there are no tokens to save; for the whole model DSA becomes cheaper only from position 2,283. At 128K dense core attention takes 96.8% of each token’s compute, and DSA cuts total FLOPs to 1/9.55, core attention alone to 1/13.30. The indexer costs only 5.88% of core attention per candidate token, but it is still : for infinitely long sequences the per-token FLOPs ratio tends to 278,528 ÷ 16,384 = 17.
- A FLOPs ratio is not a cost ratio. The paper’s Figure 3 is measured serving cost on H800s (at 2 USD per GPU-hour). Reading it, I get about 0.67 against 0.19 USD at 128K for prefilling (3.5x) and about 2.15 against 0.25 USD for decoding (8.6x). The whole-model FLOPs ratio of 9.55 is close to the measured decoding ratio of 8.6 and far from the prefilling 3.5. I do not count the first as a confirmation: decoding is limited by memory bandwidth and depends on how much cache is read per step, prefilling is limited by compute but sparse-attention kernels are usually less efficient than dense matrix multiplies, and the paper also says short-sequence prefilling simulates DSA with masked MHA. The paper gives no cost breakdown, so the above is my guess, not a conclusion.
- Table 3: token efficiency (section 4). The paper says V3.2 matches K2-Thinking with far fewer output tokens. On the 7 benchmarks they share, the geometric mean of the output-token ratio (V3.2 over K2) is 0.66, from 0.55 (LiveCodeBench) to 0.88 (HLE). Against GPT-5 High it goes the other way: the geometric mean over 8 benchmarks is 1.12, so V3.2 uses about a tenth more tokens. Speciale uses 2.09 times as many tokens as Gemini-3.0 Pro, most on Codeforces (77k against 22k, 3.50 times), in line with the paper’s admission that its token efficiency is clearly below Gemini-3.0-Pro. V3.2 against Speciale is 0.60: the length penalty cuts tokens by about 40%, and the price is accuracy, for example 93.1 against 96.0 on AIME 2025. The token counts in the table are rounded to thousands, so the ratios carry rounding error, and there are only 7 to 8 benchmarks.
- Tables 4 and 1 and the introduction agree (section 5). The six IMO 2025 problem scores add up to 35, CMO to 102, IOI to 492, and ICPC World Finals has 10 problems solved, all matching the paper’s totals. The four task counts in Table 1 add up to 85,267, and the introduction says “85,000 prompts”. The τ²-Bench average of the three categories (airline 63.8, retail 81.1, telecom 96.2) is 80.37, and Table 2 says 80.3, which agrees only within the rounding error of the category scores.
Checking the gradient of the “unbiased KL estimate”
The first trick in the paper’s “Scaling GRPO” section is an unbiased KL estimate: the K3 estimator (with ) commonly used in GRPO is biased when the samples come from the old policy , and the paper multiplies it by the importance ratio (Eq. 7; all probabilities are conditioned on and , omitted below):
The paper says the gradient is then unbiased, while the original K3 gives “disproportionately large, unbounded weights” to tokens with . That is a mathematical claim that can be tested exactly. The script below computes exact expectations (no sampling) on a 6-token vocabulary, with random old, current and reference distributions, and compares the gradient of , the gradient of the original K3 and the gradient of the corrected estimator, then checks the coefficient each sample puts on . (In the script cur, old and ref are the current, old and reference policies.)
"""Checking V3.2's unbiased KL: exact expectations and gradients"""
import torch
torch.manual_seed(0)
V = 6
old, cur, ref = (torch.randn(V, dtype=torch.float64) for _ in range(3))
p_old, p_ref = old.softmax(0), ref.softmax(0)
z = cur.clone().requires_grad_(True)
def losses(z, p_old):
p = z.softmax(0)
r = p_ref / p
k3 = r - r.log() - 1 # K3 per token
return {
"KL(cur||ref)": (p * (p / p_ref).log()).sum(),
"KL(ref||cur)": (p_ref * (p_ref / p).log()).sum(),
"E_old[K3]": (p_old * k3).sum(),
"E_old[(cur/old) K3]": (p_old * (p / p_old) * k3).sum(),
"E_old[sg(cur/old) K3]": (p_old * (p / p_old).detach() * k3).sum(),
}
def grads(z, p_old):
out = {}
for k, v in losses(z, p_old).items():
out[k] = torch.autograd.grad(v, z, retain_graph=True)[0]
return out
print("== 1. Sampling from the old policy (exact expectations)")
val, g = losses(z, p_old), grads(z, p_old)
for k, v in val.items():
print(f" {k:22s} {v.item():.6f} grad {g[k].numpy().round(4)}")
t = g["KL(cur||ref)"]
for k in ("E_old[K3]", "E_old[(cur/old) K3]", "E_old[sg(cur/old) K3]"):
print(f" max|grad {k} - grad KL(cur||ref)| = "
f"{(g[k] - t).abs().max().item():.2e}")
d = (g["E_old[sg(cur/old) K3]"] - g["KL(ref||cur)"]).abs().max().item()
print(f" max|grad E_old[sg(cur/old) K3] - grad KL(ref||cur)| = {d:.2e}")
print(" sg = stop-gradient (detach)")
print("\n== 2. On-policy (old = current)")
g2 = grads(z, z.softmax(0).detach())
for ref_k in ("KL(cur||ref)", "KL(ref||cur)"):
d = (g2["E_old[K3]"] - g2[ref_k]).abs().max().item()
print(f" max|grad K3 - grad {ref_k}| = {d:.2e}")
print("\n== 3. Per-sample coefficient on grad log pi (on-policy)")
print(f" {'cur/ref':>9s}{'K3: 1-ref/cur':>16s}{'fixed: log(cur/ref)':>22s}")
for x in (1e3, 1e2, 10, 1, 0.1, 0.01, 0.001):
print(f" {x:>9g}{1 - 1 / x:>16.1f}{torch.tensor(x).log().item():>22.2f}")
err = 0.0
for i in range(V):
def one(z):
p = z.softmax(0)
r = p_ref[i] / p[i]
return (p[i] / p_old[i]) * (r - r.log() - 1)
a = torch.autograd.grad(one(z), z)[0]
b = torch.autograd.grad(z.log_softmax(0)[i], z)[0]
p = z.softmax(0).detach()
coef = (p[i] / p_old[i]) * (p[i] / p_ref[i]).log()
err = max(err, (a - coef * b).abs().max().item())
print(" fixed per-sample gradient = (cur/old) log(cur/ref) grad log cur,")
print(f" max error {err:.1e}")
Output:
== 1. Sampling from the old policy (exact expectations)
KL(cur||ref) 0.157771 grad [ 0.2526 -0.1342 0.0163 -0.065 -0.0129 -0.0568]
KL(ref||cur) 0.117068 grad [ 0.1616 -0.0898 0.0231 -0.0638 0. -0.0311]
E_old[K3] 0.372081 grad [ 0.3716 -0.1144 -0.0143 -0.1696 -0.0213 -0.052 ]
E_old[(cur/old) K3] 0.157771 grad [ 0.2526 -0.1342 0.0163 -0.065 -0.0129 -0.0568]
E_old[sg(cur/old) K3] 0.157771 grad [ 0.1616 -0.0898 0.0231 -0.0638 0. -0.0311]
max|grad E_old[K3] - grad KL(cur||ref)| = 1.19e-01
max|grad E_old[(cur/old) K3] - grad KL(cur||ref)| = 8.33e-17
max|grad E_old[sg(cur/old) K3] - grad KL(cur||ref)| = 9.10e-02
max|grad E_old[sg(cur/old) K3] - grad KL(ref||cur)| = 4.16e-17
sg = stop-gradient (detach)
== 2. On-policy (old = current)
max|grad K3 - grad KL(cur||ref)| = 9.10e-02
max|grad K3 - grad KL(ref||cur)| = 4.16e-17
== 3. Per-sample coefficient on grad log pi (on-policy)
cur/ref K3: 1-ref/cur fixed: log(cur/ref)
1000 1.0 6.91
100 1.0 4.61
10 0.9 2.30
1 0.0 0.00
0.1 -9.0 -2.30
0.01 -99.0 -4.61
0.001 -999.0 -6.91
fixed per-sample gradient = (cur/old) log(cur/ref) grad log cur,
max error 6.7e-16
- The corrected gradient equals the KL gradient to machine precision (section 1). With samples from the old policy, the expectation of the original K3 is 0.372081 while is 0.157771, so the value is biased, and its gradient differs from the KL gradient by up to 1.19e-01. After multiplying by the importance ratio the expectation is exactly 0.157771 and the gradient error is at most 8.33e-17. The paper’s claim holds, with one precondition: the equality needs the importance ratio to be differentiated too. The paper does not say whether its implementation does that; the
sgrow of the output treats it as a constant (stop-gradient), and the expectation is still 0.157771, but the gradient is off the KL gradient by 9.10e-02 and within 4.16e-17 of the gradient of , which means it falls back to the reverse KL. - The original K3’s gradient belongs to the reverse KL (section 2). On-policy (old policy equal to the current one), the gradient of the original K3 differs from the gradient of by only 4.16e-17 and from that of by 9.10e-02. The reason is that on-policy the K3 gradient is , which is exactly the gradient of the reverse KL. This is my derivation plus a numerical check, and the paper does not discuss it; it shows that “the value of K3 is unbiased” does not mean “the gradient of K3 is the gradient of the KL you think it is”.
- The “unbounded” weights check out (section 3). The original K3 puts the coefficient on : at it is -999.0, linear and unbounded. The corrected coefficient is (the first factor is 1 on-policy), which is -6.91 at the same ratio and grows only logarithmically. The maximum error between the per-sample gradient and this closed form is 6.7e-16. The paper’s remark that unbounded weights make gradient noise accumulate holds on paper; whether that is what destabilizes their training can only be seen in training runs, not here.
Environment: Apple M2 Max, Python 3.14.3, PyTorch 2.10.0, NumPy 2.4.2, CPU only; each check script runs in a few seconds, and the second uses torch.manual_seed(0) with no sampling, only exact expectations. The first script’s parameters and configs are the values Hugging Face returned on 13 November 2026, and they may differ after the repositories are updated.
Rebuilding DSA in miniature
DSA’s central claim is that a cheap learned scorer plus top-k lets attention look at a small part of the past with almost no loss in quality. This section reproduces its two-stage training on a laptop and adds a control the paper does not give. The setup follows, with every difference from the paper stated.
- Model and data. A byte-level language model with 4 layers, width 128, 4 heads and sequence length 512; the data is the first 6,000,000 bytes of the top-level
*.pyfiles of the Python standard library, concatenated (95% train, 5% validation), the validation set is the first 192 windows of 512 bytes, and the metric is bits per byte (bpb). The paper has a 685B MoE with a 128K context and MLA, several orders of magnitude larger; here attention is ordinary multi-head attention, and the selection for a query token is shared by its 4 heads, matching the paper’s “one set of entries for all heads”. - Indexer. 2 heads of 16 dimensions per layer, with the same form as the paper’s Eq. 1: ; the input is the layer’s normalized hidden state, detached.
- Three stages. Stage 0 is dense pre-training for 1200 steps (the stand-in for the paper’s already-trained V3.1-Terminus); stage 1 is a dense warm-up of 400 steps that trains only the indexer against the head-averaged attention distribution (equivalent to the paper’s “sum over heads, then L1-normalize”); stage 2 is 300 steps of sparse training, where the main model sees only the language-modeling loss and the indexer only the KL computed on the selected set, with .
- Control. Fork the same stage-1 checkpoint into one branch that trains sparse and one that continues dense for the same number of steps on the same batches. The paper has no such control.
- Comparing selectors. On the dense model after stage 1, four selectors are evaluated at : the learned indexer (index), an oracle (the highest-attention sources of the dense model itself, an unreachable upper bound), a sliding window (window, the nearest ) and random. Besides bpb the output reports “recall”: the share of the dense model’s own attention mass that falls on the selected sources (only queries with count).
- No speed-up. The implementation masks a dense attention, so it compares quality only, not speed, and cannot show DSA’s cost advantage.
- Three seeds. The seed fixes the initialization; batch sampling uses separate seeds (the seed plus 1000, 2000 and 3000).
Full code (about 290 lines)
"""DSA in miniature: warm up a lightning indexer, then train sparse"""
import copy
import glob
import json
import math
import sysconfig
import time
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
dev = "mps" if torch.backends.mps.is_available() else "cpu"
D, LAYERS, HEADS, T, B = 128, 4, 4, 512, 16
HI, DI = 2, 16 # indexer heads and width
KS = (16, 32, 64, 128)
STEPS0, STEPS1, STEPS2 = 1200, 400, 300
LR0, LR1, LR2 = 3e-3, 3e-3, 3e-4
KTRAIN = 64
SEEDS = (0, 1, 2)
files = sorted(glob.glob(sysconfig.get_paths()["stdlib"] + "/*.py"))
raw = b"".join(open(f, "rb").read() for f in files)[:6_000_000]
data = torch.tensor(np.frombuffer(raw, dtype=np.uint8).astype(np.int64))
cut = int(len(data) * 0.95)
train, val = data[:cut], data[cut:]
CAUSAL = torch.ones(T, T, dtype=torch.bool, device=dev).tril()
NEG = float("-inf")
class RMS(nn.Module):
def __init__(self, d):
super().__init__()
self.g = nn.Parameter(torch.ones(d))
def forward(self, x):
return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + 1e-6) * self.g
def topk_mask(score, k):
# top-k sources per query; all valid ones when fewer than k
idx = score.topk(min(k, score.shape[-1]), dim=-1).indices
m = torch.zeros_like(score, dtype=torch.bool).scatter_(-1, idx, True)
return m & CAUSAL
class Layer(nn.Module):
def __init__(self):
super().__init__()
self.n1, self.n2 = RMS(D), RMS(D)
self.qkv = nn.Linear(D, 3 * D, bias=False)
self.proj = nn.Linear(D, D, bias=False)
self.up = nn.Linear(D, 4 * D, bias=False)
self.down = nn.Linear(4 * D, D, bias=False)
# lightning indexer: I[t,s] = sum_j w[t,j] * relu(q[t,j] . k[s])
self.iq = nn.Linear(D, HI * DI, bias=False)
self.ik = nn.Linear(D, DI, bias=False)
self.iw = nn.Linear(D, HI, bias=False)
def index(self, h):
b, t, _ = h.shape
q = self.iq(h).view(b, t, HI, DI)
s = torch.einsum("bthd,bsd->bths", q, self.ik(h)).relu()
return torch.einsum("bth,bths->bts", self.iw(h), s)
def forward(self, x, mode="dense", k=KTRAIN, out=None):
b, t, _ = x.shape
h = self.n1(x)
q, kk, v = self.qkv(h).view(b, t, 3, HEADS, D // HEADS).unbind(2)
q, kk, v = (z.transpose(1, 2) for z in (q, kk, v))
att = (q @ kk.transpose(-1, -2)) / math.sqrt(D // HEADS)
att = att.masked_fill(~CAUSAL, NEG)
sel = None
if mode != "dense":
if mode == "index":
score = self.index(h.detach())
elif mode == "oracle":
score = att.softmax(-1).sum(1)
elif mode == "window":
dist = torch.arange(t, device=x.device)
score = -(dist[:, None] - dist[None, :]).float().expand(b, t, t)
else:
score = torch.rand(b, t, t, device=x.device)
sel = topk_mask(score.masked_fill(~CAUSAL, NEG), k)
att = att.masked_fill(~sel[:, None], NEG)
p = att.softmax(-1)
if out is not None:
out["p"] = p.mean(1) # head-averaged attention
out["sel"] = sel
out["idx"] = self.index(h.detach())
y = (p @ v).transpose(1, 2).reshape(b, t, D)
x = x + self.proj(y)
return x + self.down(F.gelu(self.up(self.n2(x))))
class Net(nn.Module):
def __init__(self):
super().__init__()
self.emb, self.pos = nn.Embedding(256, D), nn.Embedding(T, D)
self.layers = nn.ModuleList([Layer() for _ in range(LAYERS)])
self.fn, self.head = RMS(D), nn.Linear(D, 256, bias=False)
for n, p in self.named_parameters():
if p.dim() == 2:
nn.init.normal_(p, 0, 0.02)
def forward(self, x, mode="dense", k=KTRAIN, outs=None):
h = self.emb(x) + self.pos(torch.arange(x.shape[1], device=x.device))
for i, layer in enumerate(self.layers):
o = {} if outs is not None else None
h = layer(h, mode, k, o)
if outs is not None:
outs.append(o)
return self.head(self.fn(h))
def kl_index(o, selected_only):
# KL(p ‖ softmax(I)); on the selected sources only in the sparse stage
I = o["idx"].masked_fill(~(o["sel"] if selected_only else CAUSAL), NEG)
p = o["p"].detach()
logq = I.log_softmax(-1).masked_fill(p == 0, 0.0)
return (p * (torch.log(p + 1e-9) - logq)).sum(-1).mean()
def batch(rng):
ix = rng.integers(0, len(train) - T - 1, B)
x = torch.stack([train[i:i + T] for i in ix])
y = torch.stack([train[i + 1:i + T + 1] for i in ix])
return x.to(dev), y.to(dev)
starts = list(range(0, len(val) - T - 1, T))[:192]
VX = torch.stack([val[i:i + T] for i in starts])
VY = torch.stack([val[i + 1:i + T + 1] for i in starts])
@torch.no_grad()
def bpb(model, mode="dense", k=KTRAIN):
tot, n = 0.0, 0
for j in range(0, len(VX), 16):
x, y = VX[j:j + 16].to(dev), VY[j:j + 16].to(dev)
lg = model(x, mode, k)
tot += F.cross_entropy(lg.reshape(-1, 256), y.reshape(-1),
reduction="sum").item()
n += y.numel()
return tot / n / math.log(2)
@torch.no_grad()
def recall(model, mode, k):
# share of the dense model's own attention mass
# on the selected sources (queries with t >= k only)
num, cnt = 0.0, 0
for j in range(0, len(VX), 16):
outs = []
model(VX[j:j + 16].to(dev), "dense", k, outs)
for layer, o in zip(model.layers, outs):
if mode == "oracle":
score = o["p"]
elif mode == "index":
score = o["idx"]
elif mode == "window":
d = torch.arange(T, device=dev)
score = -(d[:, None] - d[None, :]).float().expand_as(o["p"])
else:
score = torch.rand_like(o["p"])
m = topk_mask(score.masked_fill(~CAUSAL, NEG), k)
mass = (o["p"] * m).sum(-1)[:, k:]
num += mass.sum().item()
cnt += mass.numel()
return num / cnt
def lr_at(step, steps, peak, warm=50):
cos = 0.5 * (1 + math.cos(math.pi * step / steps))
return peak * min(1, (step + 1) / warm) * (0.1 + 0.9 * cos)
def fit(model, groups, steps, peak, rng, lossfn):
# groups: parameter groups, each clipped on its own
params = [p for g in groups for p in g]
opt = torch.optim.AdamW(params, lr=peak, betas=(0.9, 0.95),
weight_decay=0.0)
for step in range(steps):
for g in opt.param_groups:
g["lr"] = lr_at(step, steps, peak)
x, y = batch(rng)
loss = lossfn(model, x, y)
opt.zero_grad(set_to_none=True)
loss.backward()
for g in groups:
nn.utils.clip_grad_norm_(g, 1.0)
opt.step()
def lm_loss(model, x, y):
return F.cross_entropy(model(x).reshape(-1, 256), y.reshape(-1))
def warm_loss(model, x, y):
outs = []
model(x, "dense", KTRAIN, outs)
return sum(kl_index(o, False) for o in outs)
def sparse_loss(model, x, y):
outs = []
lg = model(x, "index", KTRAIN, outs)
kl = sum(kl_index(o, True) for o in outs)
return F.cross_entropy(lg.reshape(-1, 256), y.reshape(-1)) + kl
def is_idx(name):
return name.split(".")[-2] in ("iq", "ik", "iw")
res = {}
t0 = time.time()
for seed in SEEDS:
torch.manual_seed(seed)
model = Net().to(dev)
main = [p for n, p in model.named_parameters() if not is_idx(n)]
idx = [p for n, p in model.named_parameters() if is_idx(n)]
# stage 0: dense pre-training (batches use their own seed)
fit(model, [main], STEPS0, LR0, np.random.default_rng(seed + 1000),
lm_loss)
# stage 1: dense warm-up, indexers only
fit(model, [idx], STEPS1, LR1, np.random.default_rng(seed + 2000),
warm_loss)
x, _ = batch(np.random.default_rng(seed + 4000))
with torch.no_grad():
gap = (model(x, "index", T) - model(x)).abs().max().item()
print(f"seed {seed}: k=T gives dense logits, max diff {gap:.1e}")
r = {"dense": bpb(model)}
for mode in ("index", "oracle", "window", "random"):
for k in KS:
r[f"{mode}-{k}"] = bpb(model, mode, k)
r[f"rec-{mode}-{k}"] = recall(model, mode, k)
# stage 2: sparse training vs dense continuation of the same length
ctrl = copy.deepcopy(model)
fit(model, [main, idx], STEPS2, LR2, np.random.default_rng(seed + 3000),
sparse_loss)
cmain = [p for n, p in ctrl.named_parameters() if not is_idx(n)]
fit(ctrl, [cmain], STEPS2, LR2, np.random.default_rng(seed + 3000),
lm_loss)
r["sparse-trained"] = bpb(model, "index", KTRAIN)
r["sparse-trained-dense-eval"] = bpb(model)
r["ctrl-dense"] = bpb(ctrl)
r["ctrl-sparse-eval"] = bpb(ctrl, "index", KTRAIN)
res[seed] = r
print(f"seed {seed} done, {(time.time() - t0) / 60:.1f} min", flush=True)
json.dump(res, open("dsa.json", "w"))
def stat(key, base=None):
v = np.array([res[s][key] - (res[s][base] if base else 0) for s in SEEDS])
return v.mean(), v.std(ddof=1)
print("\nDense model after stage 1, val bpb: %.4f ± %.4f" % stat("dense"))
print("Each query sees k sources: bpb above dense / attention-mass recall")
print(f"{'selector':8s}" + "".join(f" k={k:<3d} dbpb rec" for k in KS))
for mode in ("index", "oracle", "window", "random"):
row = f"{mode:8s}"
for k in KS:
d = stat(f"{mode}-{k}", "dense")[0]
row += f" {d:+6.3f} {stat(f'rec-{mode}-{k}')[0]:.3f}"
print(row)
print("\nPaired differences (same model, same windows), mean ± std of 3 seeds:")
for k in KS:
a = [res[s][f"index-{k}"] - res[s][f"window-{k}"] for s in SEEDS]
b = [res[s][f"index-{k}"] - res[s][f"oracle-{k}"] for s in SEEDS]
print(f"k={k:<3d} index - window {np.mean(a):+.3f} ± "
f"{np.std(a, ddof=1):.3f} index - oracle {np.mean(b):+.3f} ± "
f"{np.std(b, ddof=1):.3f}")
print("\nStage 2 (k=%d), bpb above the dense model of stage 1:" % KTRAIN)
for key, name in (("index-%d" % KTRAIN, "sparse eval, no sparse training"),
("sparse-trained", "sparse-trained, sparse eval"),
("sparse-trained-dense-eval", "sparse-trained, dense eval"),
("ctrl-dense", "control (dense), dense eval"),
("ctrl-sparse-eval", "control (dense), sparse eval")):
m, sd = stat(key, "dense")
print(f" {name:36s} {m:+.4f} ± {sd:.4f}")
d = [res[s]["sparse-trained"] - res[s]["ctrl-dense"] for s in SEEDS]
print("sparse-trained sparse eval - control dense eval:", end=" ")
print("%+.4f ± %.4f" % (np.mean(d), np.std(d, ddof=1)))
Output:
seed 0: k=T gives dense logits, max diff 0.0e+00
seed 0 done, 9.2 min
seed 1: k=T gives dense logits, max diff 0.0e+00
seed 1 done, 18.2 min
seed 2: k=T gives dense logits, max diff 0.0e+00
seed 2 done, 27.7 min
Dense model after stage 1, val bpb: 2.5383 ± 0.0595
Each query sees k sources: bpb above dense / attention-mass recall
selector k=16 dbpb rec k=32 dbpb rec k=64 dbpb rec k=128 dbpb rec
index +0.243 0.694 +0.075 0.823 +0.025 0.916 +0.007 0.970
oracle +0.199 0.712 +0.068 0.837 +0.022 0.925 +0.005 0.975
window +0.310 0.597 +0.144 0.734 +0.047 0.860 +0.012 0.945
random +2.736 0.111 +2.303 0.184 +1.781 0.296 +1.143 0.461
Paired differences (same model, same windows), mean ± std of 3 seeds:
k=16 index - window -0.067 ± 0.017 index - oracle +0.045 ± 0.005
k=32 index - window -0.069 ± 0.007 index - oracle +0.007 ± 0.002
k=64 index - window -0.023 ± 0.003 index - oracle +0.003 ± 0.002
k=128 index - window -0.005 ± 0.002 index - oracle +0.002 ± 0.001
Stage 2 (k=64), bpb above the dense model of stage 1:
sparse eval, no sparse training +0.0248 ± 0.0022
sparse-trained, sparse eval -0.0951 ± 0.0030
sparse-trained, dense eval -0.0856 ± 0.0086
control (dense), dense eval -0.1000 ± 0.0037
control (dense), sparse eval -0.0708 ± 0.0074
sparse-trained sparse eval - control dense eval: +0.0048 ± 0.0007
Figure 3 plots the selector comparison from the table.
Read these results against the noise first. The dense model after stage 1 has a validation bpb of 2.5383 ± 0.0595 across the three seeds, so the seeds differ a lot, and every comparison below is a paired difference on the same model and the same validation windows (the ± is the standard deviation of the paired difference over the three seeds). The Chinese edition of this page ran the same seeds once more and differs in the third decimal (for example, the sparse-trained model’s sparse eval is -0.0951 here and -0.0962 there; runs on MPS are not bit-reproducible), so differences below 0.001 bpb are not interpreted. Every number on this page comes from the one full run of its own language.
- The learned indexer nearly catches the oracle. An indexer trained for 400 steps on the KL objective alone, with only 2 heads of 16 dimensions per layer, ends +0.025 bpb above the dense model at ; the oracle ends +0.022, a paired difference of +0.003 ± 0.002, and the recall is 0.916 against 0.925. At the paired difference is +0.007 ± 0.002 and at it is +0.002 ± 0.001. Only at is the gap clear (+0.045 ± 0.005): each query keeps just 16 sources, so one wrong pick costs the most.
- It beats “just the nearest ”, by more than the noise. The paired difference to the sliding window is -0.067 ± 0.017 (), -0.069 ± 0.007 (), -0.023 ± 0.003 () and -0.005 ± 0.002 (). The data is Python source code with strong locality, so the window is a fairly strong baseline here; whether the gap would be larger on data that needs long-range retrieval was not tested.
- The selection itself decides everything. Picking 64 sources at random adds +1.781 bpb at a recall of just 0.296. Sparse attention is not free; all of its value is in the selector.
- Sparse training shrinks the remaining gap (stage 2). Switching the stage-1 model to a sparse evaluation at adds +0.0248 ± 0.0022 bpb; after 300 steps of sparse training, the sparse-evaluated model is only +0.0048 ± 0.0007 behind the dense control (dense eval) that trained the same 300 steps, about one fifth of the former. If the dense control is also evaluated sparsely (its indexer was not updated along with it), its score drops from -0.1000 to -0.0708. For the sparse-trained model, the dense eval (-0.0856) is slightly worse than the sparse eval (-0.0951), but the two have standard deviations of 0.0086 and 0.0030, so the difference is of the order of the noise and I draw no conclusion from it.
- What toy scale can and cannot say. The sequence is only 512 long, so means each query sees an eighth of its past, while the paper selects 2,048 of 131,072 positions (a sixty-fourth); the model has 4 layers, and the stage-1 dense model trained for only 1200 steps (validation bpb 2.5383, far from converged); no speed was measured. The direction agrees with the paper: a light learned scorer can approach the oracle, and sparse training recovers most of the loss. The magnitudes do not extrapolate to the paper’s model.
Environment: Apple M2 Max, MPS backend, Python 3.14.3, PyTorch 2.10.0, NumPy 2.4.2, 27.7 minutes for the three seeds (other experiments were running on the same GPU, so a solo run would be faster).
The paper’s post-training: scaled-up GRPO and agent tasks
DSA addresses “long sequences are too expensive”; the paper’s other two parts address “too little post-training investment” and “weak agent generalization”.
Specialist distillation and mixed reinforcement learning
A specialist is first trained for each domain: mathematics, programming, general logical reasoning, general agent tasks, agentic coding and agentic search, plus writing and general question answering; every domain supports both thinking and non-thinking modes. Each specialist starts from the same pre-trained V3.2 base and goes through large-scale reinforcement learning, and the specialists then generate data for each domain to train the final checkpoint. The paper says models trained on the distilled data come out only marginally below the specialists, and the gap is closed by the reinforcement learning that follows.
The final reinforcement learning is a single mixed stage: reasoning, agent and human-preference alignment are merged into one stage with GRPO, to avoid the catastrophic forgetting common in multi-stage training. Reasoning and agent tasks use rule-based outcome rewards, a length penalty and a language-consistency reward; general tasks use a generative reward model with per-prompt rubrics. The released V3.2 went through thousands of steps of continued reinforcement learning; V3.2-Speciale was trained only on reasoning data with a relaxed length penalty, plus the data and reward of DeepSeekMath-V2 to improve mathematical proofs.
Four tricks for scaling GRPO
The paper writes the advantage as : subtract the group mean, do not divide by the standard deviation. On top of that come four stabilizing practices:
| Practice | Problem it addresses | What the paper does |
|---|---|---|
| Unbiased KL estimate | With samples from the old policy, the K3 estimator is biased, and gradient weights are unbounded on tokens with | Multiply by the importance ratio (Eq. 7); different domains need different KL strengths, and for mathematics it can be weak or absent |
| Off-policy sequence masking | A batch of rollouts is split into several mini-batches, and the inference and training frameworks differ in implementation, which makes training off-policy | Mask whole sequences whose advantage is negative and whose sequence-average exceeds a threshold (Eq. 9) |
| Keep Routing | MoE expert routing differs between inference and training, so the active parameter subspace jumps | Store the routing paths used at sampling and force them in training; used in the reinforcement-learning pipeline since DeepSeek-V3-0324 |
| Keep Sampling Mask | Top-p and top-k truncation make the action spaces of and differ, which breaks importance sampling | Store the truncation masks used at sampling and apply them in training; together with top-p it keeps the language consistent |
Off-policy sequence masking masks only sequences with negative advantage, and the paper’s reason is that a model learns most from its own mistakes, while highly off-policy negative samples can mislead the optimization. The paper describes these tricks only qualitatively (“improves stability in certain scenarios that would otherwise be unstable”) and does not ablate them one by one, so this post cannot tell you which matters most; comparable ablations are in DAPO and GSPO.
Bringing thinking into tool calls
R1 discards the reasoning content when the second round of messages arrives, and the paper found that this wastes many tokens in tool calling: after every tool return the model has to rethink the whole problem. V3.2’s context-management rule is: historical reasoning content is discarded only when a new user message arrives; if only tool outputs are appended, the reasoning stays; and when reasoning is dropped, the tool calls and their results stay in the context. The paper warns that frameworks such as Roo Code and Terminus simulate tool interaction with user messages, cannot benefit from this rule, and are better served by the non-thinking model.
The cold-start stage relies on prompts, not extra training: the paper’s appendix Tables 6 to 8 give three kinds of system prompts (reasoning data with <think> tags, non-reasoning agent data with tool-call guidance, and a prompt that asks the model to interleave several tool calls into its reasoning), so that the model “occasionally” writes the desired trajectories, which serve as the starting point for the reinforcement learning that follows.
Large-scale synthetic agent tasks
The paper’s Table 1 lists four kinds of reinforcement-learning tasks:
| Task type | Number | Environment | Prompts |
|---|---|---|---|
| Code agent | 24,667 | real | extracted from the internet |
| Search agent | 50,275 | real | synthesized |
| General agent | 4,417 | synthesized | synthesized |
| Code interpreter | 5,908 | real | extracted from the internet |
General-agent tasks are generated automatically by an “environment-synthesis agent”. Given a task category (say, planning a trip) and a sandbox with bash and search tools, the agent first retrieves data into a sandbox database and synthesizes a set of task-specific tool functions; it then proposes a simple task together with a Python solution function and verification function, and raises the difficulty round by round, extending the toolset when needed. The solution function may only call tool functions or do logical computation, never touch the database directly, which guarantees that the task can be solved only through the tool interface. The result is thousands of ⟨environment, tools, task, verifier⟩ tuples; the paper runs reinforcement learning on them with DeepSeek-V3.2 and keeps only instances with non-zero pass@100, ending with 1,827 environments and 4,417 tasks. The trip-planning example in the paper is “hard to solve, easy to verify”: finding an itinerary that satisfies all constraints (no repeated cities, hotel tier setting the budget cap for restaurants and attractions, and so on) in a huge combinatorial space is hard, while checking a given itinerary against the constraints is easy.
The paper runs two checks. First, on 50 randomly sampled general synthetic tasks V3.2-Exp reaches only 12% pass@1, while Claude Sonnet 4.5, Gemini-3.0 Pro and GPT-5-Thinking reach 34%, 51% and 62%, so the tasks are hard even for frontier models. Second, the SFT checkpoint of V3.2 is trained with reinforcement learning on synthetic tasks only, in non-thinking mode, and τ²-Bench, MCP-Mark and MCP-Universe all improve clearly; a control trained with reinforcement learning only in code and search environments does not improve on these three benchmarks (the paper’s Figure 5, whose numbers are in the figure and not quoted here). This is the main evidence that synthetic tasks transfer, but it rests on three benchmarks the paper chose and gives no run-to-run variance.
The paper’s results
The paper’s Table 2 compares V3.2 with Claude-4.5-Sonnet, GPT-5 High, Gemini-3.0 Pro, Kimi-K2 Thinking and MiniMax M2. A few rows, all self-reported by the paper:
| Benchmark | V3.2 | GPT-5 High | Gemini-3.0 Pro | Kimi-K2 Thinking |
|---|---|---|---|---|
| AIME 2025 | 93.1 | 94.6 | 95.0 | 94.5 |
| HMMT Feb 2025 | 92.5 | 88.3 | 97.5 | 89.4 |
| GPQA Diamond | 82.4 | 85.7 | 91.9 | 84.5 |
| HLE (text) | 25.1 | 26.3 | 37.7 | 23.9 |
| SWE-bench Verified | 73.1 | 74.9 | 76.2 | 71.3 |
| Terminal Bench 2.0 | 46.4 | 35.2 | 54.2 | 35.7 |
| BrowseComp | 51.4 (67.6 with context management) | 54.9 | none | none (60.2 with context management) |
| τ²-Bench | 80.3 | 80.2 | 85.4 | 74.3 |
| MCP-Universe | 45.9 | 47.9 | 50.7 | 35.6 |
| Tool-Decathlon | 35.2 | 29.0 | 36.4 | 17.6 |
Three footnotes matter when reading the table. First, the 46.4 on Terminal Bench 2.0 was obtained under the Claude Code framework, because the thinking-mode context management is incompatible with Terminus; with Terminus in non-thinking mode the score is 39.3. Second, about 20% or more of the BrowseComp cases exceed the 128K context, so the main score uses context management, and without it the score is 51.4. Third, MCP-Universe and MCP-Mark were evaluated in the paper’s own environment, whose search and browser setups may differ slightly from the official ones; the paper also observed that V3.2 often makes redundant self-verification, so trajectories grow too long and exceed 128K, which drags down the MCP benchmarks.
Section 4.4 of the paper studies context management for search agents: when token usage exceeds 80% of the context window, three strategies extend the budget, namely Summary (summarize the overflowed trajectory and restart), Discard-75% (drop the first 75% of the tool-call history) and Discard-all (drop all tool-call history); the baseline is parallel scaling, sampling N trajectories and keeping the one with the fewest steps. Summary stretches the average to 364 steps and lifts BrowseComp to 60.2, but is not very efficient; Discard-all is simple and effective, reaching 67.6, comparable to parallel scaling with far fewer steps. The paper’s conclusion is that test-time compute can be scaled serially (context management) or in parallel, and that evaluations should account for actual compute cost.
The results of V3.2-Speciale, with the length limit relaxed, are in the paper’s Tables 3 and 4: 35/42 at IMO 2025, 102/126 at CMO 2025, 492/600 at IOI 2025 and 10/12 problems at the ICPC World Finals 2025, all at the gold line; the caption of Table 4 also says it ranked 2nd at the ICPC World Finals 2025 and 10th at IOI 2025. The paper notes that its mathematical-proof ability borrows the data and reward of DeepSeekMath-V2, that the English version of CMO 2025 was evaluated, and that the IMO and CMO problems and the inference code are public in the DeepSeek-Math-V2 repository.
Limits and open questions
- DSA is evaluated as “on par”, not ablated. Section 2.2 of the paper only says that V3.2-Exp performs similarly to V3.1-Terminus on a suite of standard benchmarks, that their ChatbotArena Elo scores are close, that AA-LCR is four points higher and that several Fiction.liveBench metrics are better; apart from the “four points”, this paper gives no numbers. There is no top-k sweep, no control that keeps training dense on the same data, and no measurement of indexer recall. The miniature above fills in all three, but its scale is many orders of magnitude from the paper’s, so it can show the mechanism, not vouch for the paper.
- Cost is one plot, not a table. Figure 3 is an estimate from the authors’ own H800 deployment, with no absolute numbers, batch sizes or implementation details, so I can only read it off. Why prefilling and decoding differ so much from the FLOPs ratio is not broken down.
- The reinforcement-learning tricks are not ablated one by one. The contribution of each of the four cannot be separated, nor is it known whether other models need them equally.
- Agent evaluations are not on one footing. Some benchmarks use internal environments, the Terminal Bench score comes from a different framework, thinking mode is incompatible with some frameworks, and the 128K context is a hard limit that BrowseComp gets around only with context management.
- The three limitations the paper admits: fewer total training FLOPs, so world knowledge lags behind the leading closed models; poor token efficiency, with longer generations needed to reach Gemini-3.0-Pro’s quality; and complex tasks still behind frontier models.
What to take from this paper
- DSA is sparse attention you can retrofit. A very cheap scorer, aligned to dense attention by KL distillation, warmed up first and then released with all parameters to adapt to the sparse pattern, turns an existing dense model into a sparse one; on the cost side attention is the main expense in long contexts, so pushing it down is close to an order of magnitude in FLOPs at 128K, but measured cost and the FLOPs ratio are not the same thing.
- Scaling reinforcement learning is a stability engineering problem. Unbiased KL, off-policy masking, Keep Routing and Keep Sampling Mask all deal with the mismatch between the sampling-time distribution and the training-time distribution, which is especially severe in MoE models and heavily optimized inference frameworks.
- “Hard to solve, easy to verify” synthetic tasks are a scalable raw material. Environments, tools, tasks and verifiers are generated together and a strong model filters out the too-easy ones; the paper’s ablation shows transfer to unseen agent benchmarks, but the evidence is only the three benchmarks the paper chose.
Further reading
- Paper: DeepSeek-V3.2: Pushing the Frontier of Open Large Language Models (DeepSeek-AI, 2025).
- Reference implementation and weights: deepseek-ai/DeepSeek-V3.2 and deepseek-ai/DeepSeek-V3.2-Exp on Hugging Face (the latter’s
inference/model.pyhas the full indexer). - Neighbouring walkthroughs: DeepSeek-V2 (MLA and DeepSeekMoE), DeepSeek-V3, DeepSeekMath and GRPO, DeepSeek-R1, GDPO; for what came after the sparse attention, see DeepSeek-V4.1-Flash (CSA2: cross-layer sharing of cache and selection, global KV down to 890 bytes per token).
- Concept pages: efficient attention, long context, KV cache, mixture of experts, reasoning reinforcement learning.
FAQ
- What is DeepSeek Sparse Attention (DSA), and how does it differ from a sliding window?
- DSA is the sparse attention introduced in DeepSeek-V3.2. A small "lightning indexer" (64 heads of 128 dimensions, ReLU scoring, FP8-capable) scores every earlier token for each query token, the top 2048 are kept, and core attention runs only on them, so its cost drops from O(L²) to O(Lk). Unlike a sliding window, the selected tokens depend on content and can be arbitrarily far away, and the indexer is learned (it is trained with a KL divergence to match the dense attention distribution). The price is that the indexer itself is still O(L²), at roughly 5.9% of core attention's cost per token pair (estimated here from the config).
- How do DeepSeek-V3.2, V3.2-Exp and V3.1-Terminus relate?
- V3.1-Terminus is the last V3.1 release, with its context already extended to 128K. V3.2 starts from its base checkpoint, adds DSA by continued pre-training (2.1B tokens of dense warm-up, 943.7B tokens of sparse training) and then post-trains. The paper says V3.2 has exactly the architecture of V3.2-Exp and keeps V3.2-Exp's post-training pipeline of specialist distillation plus mixed reinforcement learning, and it stresses a post-training budget above 10% of the pre-training cost. V3.2-Exp is the experimental release the paper evaluated in September 2025, finding it on par with V3.1-Terminus. V3.2-Speciale is a high-compute variant trained only on reasoning data with a relaxed length penalty.
- How much compute and cost does DSA save?
- Estimated from the model config (278,528 FLOPs per attended token for core attention, 16,384 FLOPs per candidate token for the indexer, k=2048), core attention FLOPs at position 128K fall to about 1/13.3, and the whole model to about 1/9.55; below position 2,283 DSA is not cheaper. The paper's Figure 3 plots measured serving cost on H800s, and from it I read a cost gap at 128K of about 3.5x for prefilling and about 8.6x for decoding (read-off error about 0.02 USD). A FLOPs ratio is not a cost ratio, and the paper does not break the difference down.
- Why is DSA built on the MQA mode of MLA?
- The paper's reason is kernel efficiency: each key-value entry has to be shared by several queries to be read efficiently. In the MQA mode of MLA, each latent vector (512 dimensions plus a 64-dimension position part) is shared by all 128 heads of a query token, so the indexer only has to pick one set of 2048 entries per token, not per head. V3.1-Terminus uses the MHA mode for training and prefilling and the MQA mode for decoding; the paper says short-sequence prefilling simulates DSA with masked MHA.
- Which parts of V3.2's post-training are worth borrowing?
- Four tricks for stable reinforcement learning (an unbiased KL estimate, off-policy sequence masking, Keep Routing and Keep Sampling Mask), a rule for keeping thinking inside tool calls (drop old reasoning only when a new user message arrives, never for tool outputs), and "hard to solve, easy to verify" synthetic agent tasks (1,827 environments and 4,417 general tasks, with all agent prompts adding up to over 85,000). The paper ablates none of these tricks individually, so their separate contributions are unknown.