Track VI · Frontier Tech Reports · 04/20

DeepSeek-V3.2 — sparse attention과 RL 스케일링, 에이전트 과제 합성DeepSeek-V3.2 — sparse attention, RL scaling, agentic task synthesis

DeepSeek-V3.2 보고서를 읽는다. lightning indexer로 top-k 토큰만 고르는 DeepSeek Sparse Attention(DSA)과 그 indexer를 KL로 정렬하는 두 단계 continued pre-training, 사전학습 비용의 10%를 넘는 RL을 안정시킨 GRPO 수정(IS 보정 KL, off-policy sequence masking, Keep Routing/Sampling Mask), tool 사용 중 추론을 유지하는 context 관리와 1,800여 개 합성 환경을 식·코드·그림으로 따라간다.A reading of the DeepSeek-V3.2 report. With equations, code and figures we follow DeepSeek Sparse Attention (DSA), in which a lightning indexer picks only the top-k tokens, and the two-stage continued pre-training that aligns that indexer by KL; the GRPO fixes that kept RL stable at more than 10% of the pre-training cost (IS-corrected KL, off-policy sequence masking, Keep Routing/Sampling Mask); and the context management that keeps reasoning during tool use, together with some 1,800 synthesised environments.

If DeepSeek-V3 was “a large MoE trained cheaply” and DeepSeek-R1 was “RL that draws out long reasoning from verifiable rewards alone”, DeepSeek-V3.2 (December 2025) builds on both and goes after three bottlenecks. In the words of the report’s introduction: (1) vanilla attention is too expensive on long sequences, which holds back both deployment and post-training; (2) open models spend too little compute on post-training; and (3) they lag in generalisation and instruction following in agentic settings. The remedies are also three: DeepSeek Sparse Attention (DSA), stable RL scaling with a budget above 10% of the pre-training cost, and large-scale agentic task synthesis.

This lesson follows a report that is easy to read because it makes exactly one architectural change (DSA). We check with equations and code how that one change is trained, and which parts of the GRPO objective were modified so that RL can run for a long time. For anyone doing agentic post-training, sections 3 and 4 are especially practical.

At a glance

ItemDetails
LabDeepSeek-AI
ReleasearXiv 2512.02556 (2025-12-02). The official version of the experimental V3.2-Exp (evaluated 2025-09)
ModelsDeepSeek-V3.2 (thinking / non-thinking), DeepSeek-V3.2-Speciale (a high-compute, reasoning-only variant)
Size671B total / 37B active (V3.2-Base in V4 report Table 1), 61 layers — the same skeleton as V3
ArchitectureSame as DeepSeek-V3.1-Terminus + DSA. MLA, DeepSeekMoE (1 shared + 8 of 256 routed experts active), MTP
Context128K (starts from the 128K-extended checkpoint of V3.1-Terminus)
Pre-training tokensThe pre-training volume up to V3.1-Terminus is not in this report. Continued pre-training to introduce DSA: 2.1B (indexer warm-up) + 943.7B (sparse training)
OpennessWeights released (Hugging Face, MIT). The inference code is also released, which the report says specifies the details “without ambiguity”
LinksarXiv · HF: DeepSeek-V3.2

The number of layers, the number of experts and the indexer settings (64 heads, head dimension 128, top-k 2048) are not in the report body; they are taken from the released config.json. The report body states only top-k = 2048.

What is new

  • DSA: a light lightning indexer scores every preceding token, and the main attention is computed only over the k=2048k=2048 highest-scoring tokens. The main attention cost drops from O(L2)O(L^2) to O(Lk)O(Lk).
  • A training method that keeps the architecture and just slots in the indexer: first align the indexer (warm-up) so that it imitates the dense model’s attention distribution under a KL loss, then switch to sparse.
  • RL compute above 10% of pre-training: four GRPO fixes that keep it stable at that scale — an IS-corrected KL estimator, off-policy sequence masking, Keep Routing, and Keep Sampling Mask.
  • Thinking in tool-use: a context rule that does not discard reasoning while tool results go back and forth, a cold start that ties reasoning and tool calls into one trajectory, and agentic RL including 1,827 synthesised environments and 4,417 tasks.
  • Speciale: a variant with a reduced length penalty, trained with RL on reasoning data only, scored at gold-medal level in IMO and IOI 2025 (report Table 4).

Architecture

V3.2 makes one architectural change. Report §2.1: “Compared with DeepSeek-V3.1-Terminus … the only architectural modification of DeepSeek-V3.2 is the introduction of DeepSeek Sparse Attention (DSA) through continued training.” Everything else (MLA, DeepSeekMoE, MTP) is as in the V3 lesson.

Lightning indexer

The index score between a query token ht\mathbf h_t and a preceding token hs\mathbf h_s is (report eq. 1)

It,s=∑j=1HIwt,jI⋅ReLU⁡ ⁣(qt,jI⋅ksI)I_{t,s}=\sum_{j=1}^{H^I} w^I_{t,j}\cdot \operatorname{ReLU}\!\big(\mathbf q^I_{t,j}\cdot \mathbf k^I_s\big)

There are HIH^I indexer heads; the query side qt,jI∈RdI\mathbf q^I_{t,j}\in\mathbb R^{d^I} and the head weight wt,jI∈Rw^I_{t,j}\in\mathbb R come from ht\mathbf h_t, and the key ksI∈RdI\mathbf k^I_s\in\mathbb R^{d^I} comes from hs\mathbf h_s. It differs from the main attention in three ways.

  1. No softmax. The scores are used only for ranking, so there is no need to normalise them. ReLU is used instead, and the report gives only “throughput” as the reason (clipping negative scores to 0 leaves only multiply-accumulates).
  2. The key is shared across heads. ksI\mathbf k^I_s has no head index. The indexer cache per token is a single dId^I-dimensional vector.
  3. Small and low-precision. It has few heads, and the report says it can be implemented in FP8.

For each query, only the tokens with the top kk scores are kept and the main attention is computed over them (eq. 2).

ut=Attn⁡(ht, {cs  ∣  It,s∈Top-k⁡(It,:)})\mathbf u_t=\operatorname{Attn}\Big(\mathbf h_t,\ \big\{\mathbf c_s \;\big|\; I_{t,s}\in\operatorname{Top\text{-}k}(I_{t,:})\big\}\Big)

The selection is per query token: all attention heads of that token see the same kk entries. This fits together with the MQA mode of the next subsection.

DeepSeek-V3가 “싸게 학습하는 큰 MoE”였고 DeepSeek-R1이 “검증 가능한 보상만으로 긴 추론을 끌어내는 RL”이었다면, DeepSeek-V3.2(2025년 12월)는 그 둘 위에서 세 가지 병목을 짚는다. 보고서 서론의 진단을 그대로 옮기면 (1) vanilla attention이 긴 시퀀스에서 너무 비싸 배포와 사후학습을 모두 막고, (2) 공개 모델은 사후학습에 쓰는 계산이 부족하며, (3) 에이전트 상황에서 일반화와 instruction following이 뒤처진다. 처방도 셋이다. DeepSeek Sparse Attention(DSA), 사전학습 비용의 10%를 넘기는 안정적인 RL 스케일링, 그리고 대규모 에이전트 과제 합성이다.

이 레슨은 아키텍처 변화가 딱 하나(DSA)뿐이라는 점에서 읽기 좋은 보고서를 따라가며, 그 하나가 어떻게 학습되는지, RL을 오래 돌리기 위해 GRPO 식의 어디를 고쳤는지를 식과 코드로 확인한다. 에이전트 사후학습을 하는 사람에게는 3·4절이 특히 실용적이다.

한눈에

항목내용
연구실DeepSeek-AI
공개arXiv 2512.02556 (2025-12-02). 실험판 V3.2-Exp(2025-09 평가)의 정식판
모델DeepSeek-V3.2(thinking / non-thinking), DeepSeek-V3.2-Speciale(추론 전용 고계산 변형)
크기총 671B / 활성 37B (V4 보고서 Table 1의 V3.2-Base), 61층 — V3와 같은 뼈대
아키텍처DeepSeek-V3.1-Terminus와 동일 + DSA. MLA, DeepSeekMoE(공유 1 + routed 256 중 8개 활성), MTP
문맥 길이128K (V3.1-Terminus의 128K 확장 checkpoint에서 출발)
사전학습 토큰V3.1-Terminus까지의 사전학습량은 이 보고서에 없음. DSA 도입용 continued pre-training: 2.1B(indexer warm-up) + 943.7B(sparse 학습)
공개가중치 공개(Hugging Face, MIT). 추론 코드도 공개해 “세부를 모호함 없이” 명시한다고 적었다
링크arXiv · HF: DeepSeek-V3.2

층 수·expert 수·indexer 설정(head 64개, head 차원 128, top-k 2048)은 보고서 본문에 없고 공개 config.json에서 확인한 값이다. 보고서 본문은 top-k = 2048만 적는다.

무엇이 새로운가

  • DSA: 가벼운 lightning indexer가 앞선 모든 토큰에 점수를 매기고, 주 attention은 점수 상위 k=2048k=2048개 토큰에만 계산한다. 주 attention 비용이 O(L2)O(L^2)에서 O(Lk)O(Lk)로 내려간다.
  • 아키텍처는 그대로, indexer만 끼워 넣는 학습법: dense 모델의 attention 분포를 KL로 흉내 내도록 indexer를 먼저 정렬(warm-up)한 뒤 sparse로 전환한다.
  • RL 계산을 사전학습의 10% 이상으로: 그 규모에서 GRPO를 안정시킨 네 가지 수정 — IS로 보정한 KL 추정량, off-policy sequence masking, Keep Routing, Keep Sampling Mask.
  • Thinking in tool-use: tool 결과가 오가는 동안에는 추론을 버리지 않는 context 규칙, 추론과 tool 호출을 한 trajectory에 묶는 cold-start, 1,827개 합성 환경·4,417개 과제를 포함한 에이전트 RL.
  • Speciale: 길이 벌점을 줄이고 추론 데이터만으로 RL한 변형이 IMO·IOI 2025에서 금메달 수준 점수를 냈다(보고서 Table 4).

아키텍처

V3.2의 아키텍처 변경은 하나다. 보고서 2.1절: “Compared with DeepSeek-V3.1-Terminus … the only architectural modification of DeepSeek-V3.2 is the introduction of DeepSeek Sparse Attention (DSA) through continued training.” 나머지(MLA, DeepSeekMoE, MTP)는 V3 레슨의 내용 그대로다.

Lightning indexer

query 토큰 ht\mathbf h_t와 앞선 토큰 hs\mathbf h_s 사이의 index score는(보고서 식 1)

It,s=∑j=1HIwt,jI⋅ReLU⁡ ⁣(qt,jI⋅ksI)I_{t,s}=\sum_{j=1}^{H^I} w^I_{t,j}\cdot \operatorname{ReLU}\!\big(\mathbf q^I_{t,j}\cdot \mathbf k^I_s\big)

이다. HIH^I개의 indexer head가 있고, query 쪽 qt,jI∈RdI\mathbf q^I_{t,j}\in\mathbb R^{d^I}와 head 가중치 wt,jI∈Rw^I_{t,j}\in\mathbb R는 ht\mathbf h_t에서, key ksI∈RdI\mathbf k^I_s\in\mathbb R^{d^I}는 hs\mathbf h_s에서 나온다. 주 attention과 세 가지가 다르다.

  1. softmax가 없다. 점수는 순위를 매기는 데만 쓰이므로 정규화할 필요가 없다. 대신 ReLU를 쓰는데, 보고서는 이유를 “throughput”이라고만 적는다(음수 점수를 0으로 잘라 곱셈-누산만 남긴다).
  2. key는 head 사이에 공유된다. ksI\mathbf k^I_s에는 head 첨자가 없다. 토큰당 indexer 캐시는 dId^I차원 벡터 하나다.
  3. 작고 저정밀이다. head 수가 적고 FP8로 구현할 수 있다고 적었다.

각 query에 대해 상위 kk개 점수의 토큰만 남겨 주 attention을 계산한다(식 2).

ut=Attn⁡(ht, {cs  ∣  It,s∈Top-k⁡(It,:)})\mathbf u_t=\operatorname{Attn}\Big(\mathbf h_t,\ \big\{\mathbf c_s \;\big|\; I_{t,s}\in\operatorname{Top\text{-}k}(I_{t,:})\big\}\Big)

선택은 query 토큰 단위이고, 그 토큰의 모든 attention head가 같은 kk개 항목을 본다. 이것이 다음 소절의 MQA 모드와 맞물린다.

indexer top-k가 잡은 attention 질량attention mass captured by indexer top-k – oracle top-k – core attention 항목core attention entries –
A toy model (context of 600 tokens, dimension 24, 4 indexer heads). Grey bars are the true attention distribution pt,s of query token t (the head sum, L1-normalised — the target of eq. (3)); blue bars are the tokens picked by the top-k of the lightning indexer score It,s = Σj wj·ReLU(qIj·kIs). Drag a from 0 to 1 (how well the indexer queries line up with the true query direction ≈ the progress of the dense warm-up): the selected set moves from random to the oracle top-k, and the curve below (captured mass vs k) closes onto the oracle curve. A well-aligned indexer captures most of the mass even with a small k. The tall bars scattered around are "needle" tokens that match the query strongly. A gap to the oracle remains even at a = 1 because the true attention has a positional term favouring recent tokens, which this indexer cannot see. 장난감 모형이다(문맥 600 토큰, 차원 24, indexer head 4개). 회색 막대는 query 토큰 t의 진짜 attention 분포 pt,s(head 합을 L1 정규화한 것, 식 (3)의 target), 파란 막대는 lightning indexer 점수 It,s = Σj wj·ReLU(qIj·kIs)의 top-k로 뽑힌 토큰이다. a를 0에서 1로 끌어 보면(indexer query가 진짜 query 방향에 맞춰지는 정도 ≈ dense warm-up의 진행) 뽑힌 집합이 무작위에서 oracle top-k로 수렴하고, 아래 곡선(잡힌 질량 vs k)이 oracle 곡선에 붙는다. 정렬이 잘 되면 작은 k로도 질량 대부분을 잡는다. 곳곳의 키 큰 막대는 query와 강하게 맞는 "needle" 토큰이다. a = 1에서도 oracle과 틈이 남는 것은, 진짜 attention에는 최근 토큰을 선호하는 위치 항이 있는데 이 indexer는 위치를 보지 못하기 때문이다.

What to check in the figure:

  1. With a=0a=0 (an unaligned indexer), the blue bars are scattered at random and k=32k=32 captures only a bit over 10% of the mass. Raise aa above 0.6 and nearly all the needle tokens are caught and the curve hugs the oracle. Raising this aa is exactly what the dense warm-up of the next section does.
  2. Even at a=1a=1 a small gap to the oracle remains. The true attention in this toy has a positional term favouring recent tokens, but the indexer keys carry no positional information. It is the same kind of gap that explains why the follow-up V4 puts a separate sliding-window branch next to its sparse attention (V4 report §2.3.3).
  3. Lower the query position tt: when the context is short, kk is a large share of it and sparse attention gains little. The benefit of DSA comes from long contexts.

On top of MLA: MQA mode

Because DSA had to be trained on from V3.1-Terminus, it was implemented on top of MLA. For kernel efficiency, the report says, “each key-value entry must be shared across multiple queries” (a point made in NSA), so DSA was put on MLA’s MQA mode. What MQA mode is follows directly from the MLA equations of the V3 report. The attention logit of head ii is

qt,i⊤ks,i=(qt,iC)⊤WiUK csKV+(qt,iR)⊤ksR=(WiUK⊤qt,iC)⊤⏟per-head query (512-dim)csKV+(qt,iR)⊤ksR\mathbf q_{t,i}^\top \mathbf k_{s,i} = (\mathbf q^C_{t,i})^\top W^{UK}_i\,\mathbf c^{KV}_s + (\mathbf q^R_{t,i})^\top \mathbf k^R_s = \underbrace{\big(W^{UK\top}_i \mathbf q^C_{t,i}\big)^\top}_{\text{per-head query (512-dim)}}\mathbf c^{KV}_s + (\mathbf q^R_{t,i})^\top \mathbf k^R_s

Absorb WiUKW^{UK}_i into the query side and the key becomes a single [csKV;ksR][\mathbf c^{KV}_s;\mathbf k^R_s] (512 + 64 = 576 dimensions) shared by all heads; for the value, attend over the shared latent csKV\mathbf c^{KV}_s and then multiply by the per-head WiUVW^{UV}_i on the output side. In other words it is the same computation as MQA with a single KV head. According to report Appendix A, V3.1-Terminus uses MHA mode (expanding the latent into per-head K and V) for training and prefill, and MQA mode for decode. Because DSA takes this MQA mode, the 2048 latent entries chosen by the indexer are reused by all 128 heads at once. There is no need to do a sparse gather per head.

Cost: the indexer is still O(L2)O(L^2)

Report §2.3 says that the main attention goes from O(L2)→O(Lk)O(L^2)\to O(Lk) while the indexer remains O(L2)O(L^2), but is far cheaper than MLA. How much cheaper can be roughly counted from the public config (what follows is this lesson’s calculation, not a number from the report). For one query at position tt looking at one preceding token, the multiply-accumulates are

  • indexer: HIdI=64×128=8,192H^I d^I = 64\times128 = 8{,}192 (FP8)
  • MLA MQA-mode core attention: 128 heads × (key 576 + value 512) = 139,264 (BF16)

about a 17× difference. The per-query attention cost at position tt is then

costDSA(t)≈8,192 t+139,264 min⁡(t,2048),costdense(t)=139,264 t\text{cost}_{\text{DSA}}(t)\approx 8{,}192\,t + 139{,}264\,\min(t, 2048),\qquad \text{cost}_{\text{dense}}(t)=139{,}264\,t

and at t=128Kt=128\text{K} the ratio is 0.059+0.016≈0.0740.059 + 0.016 \approx 0.074. At long positions it is the indexer, not the main attention, that accounts for most of the remaining cost. This is why the follow-up V4 drops the indexer computation to FP4 and runs the indexer after compressing the KV. Actual time depends on memory bandwidth and kernels, so it does not convert directly into this ratio. The report shows the per-token-position cost curve on H800 serving (Figure 3) only as a plot. For short prefills it says a separately implemented masked MHA mode that emulates DSA is used.

→ Go deeper: Sparse attention puts DSA next to NSA, QSA and CSA/HCA; The DeepSeek lineage shows where V3.2 sits between V3 and V4.

Data

V3.2 is continued training from V3.1-Terminus, so it introduces no new pre-training corpus. Most of what it says about data concerns post-training, and especially agentic tasks.

Continued pre-training. Both stages use a data distribution “totally aligned with the 128K long context extension data used for DeepSeek-V3.1-Terminus”. That is, the switch to DSA was designed as an experiment that changes only the attention mechanism on the same data, not new data. This keeps the parity comparison below clean.

Post-training data. Domain specialists are built from the same V3.2 base checkpoint to generate data. Besides writing and general QA there are six domains — mathematics, programming, general logical reasoning, general agent, agentic coding and agentic search — all supporting thinking and non-thinking modes, and each specialist is trained with large-scale RL. Long-CoT data and direct-answer data are generated by different models.

Agentic RL tasks (report Table 1):

Task# tasksEnvironmentPrompts
code agent24,667realextracted
search agent50,275realsynthesised
general agent4,417synthesisedsynthesised
code interpreter5,908realextracted
  • Search agent: long-tail entities are pulled from a large web corpus, and a question-generation agent explores them with search tools to build QA pairs. Several answer agents with different configurations produce candidate answers, and a verification agent with search access checks several times, keeping only samples where the reference answer is correct and every candidate answer is wrong. This verifiable data is mixed with existing helpful RL data where search genuinely helps, and scored by a rubric-based generative reward model.
  • Code agent: millions of issue–PR pairs from GitHub are filtered with heuristics and LLM judgement, and a V3.2-based environment-building agent automates package installation, dependency resolution and test execution. An environment was accepted only if applying the gold patch gives at least one F2P (fail→pass) test and zero P2F (pass→fail). The result is tens of thousands of reproducible environments across Python, Java, JavaScript, TypeScript, C, C++, Go and PHP.
  • Code interpreter: solves math, logic and data-science problems with a Jupyter Notebook as the tool.
  • General agent: an environment-synthesis agent, in a sandbox with bash and search tools, (1) collects data for a task category (e.g. travel itineraries) and loads it into a DB, (2) builds task-specific tool functions, and (3) proposes an easy task together with its solution function and verification function (in Python), then repeatedly raises the difficulty. The solution function may only call tool functions and do logical operations, so a task can be solved only through the tool interface. Of the ⟨environment, tools, task, verifier⟩ bundles built this way, only those on which RL with V3.2 gives a nonzero pass@100 were kept, giving 1,827 environments and 4,417 tasks. The goal is tasks that are “hard to solve and easy to verify” — the report’s example is a 3-day travel plan with tangled constraints on cities, hotels, restaurants and budget.

The search agent’s filter “reference correct and every candidate wrong” and the general agent’s “pass@100 > 0” aim at the same goal from opposite sides. One removes tasks that are too easy, the other removes tasks that cannot be solved at all (no signal). It is the “you only learn from problems you sometimes get right” of the RLVR lesson, implemented as a data pipeline.

Training

Continued pre-training: dense warm-up → sparse

Stage 1: dense warm-up. The attention stays dense and only the indexer is trained (all other parameters frozen). For query token tt, the main attention scores are summed over all heads and L1-normalised along the sequence to form a target distribution pt,:∈Rtp_{t,:}\in\mathbb R^t, and the loss

LI=∑tDKL(pt,: ∥ Softmax⁡(It,:))\mathcal L^I=\sum_t D_{\text{KL}}\big(p_{t,:}\,\big\|\,\operatorname{Softmax}(I_{t,:})\big)

is minimised (eq. 3). The indexer output has no softmax, but during training only, a softmax is applied so that it can be treated as a distribution and matched. Learning rate 10−310^{-3}, 1,000 steps, 16 sequences of 128K tokens per step — 2.1B tokens in total.

Stage 2: sparse training. Top-k selection is switched on and all parameters are trained. The indexer keeps following the main attention, but is matched only on the selected set St\mathcal S_t.

LI=∑tDKL(pt,St ∥ Softmax⁡(It,St))\mathcal L^I=\sum_t D_{\text{KL}}\big(p_{t,\mathcal S_t}\,\big\|\,\operatorname{Softmax}(I_{t,\mathcal S_t})\big)

An important detail: the indexer input is detached from the computational graph. The indexer is trained only by LI\mathcal L^I, and the main model only by the language-modelling loss. Top-k selection is not differentiable, so there is no path for gradient to flow from the main model into the indexer in the first place; the detach blocks the other direction, so that the indexer loss cannot pull on the main model’s representations. Learning rate 7.3×10−67.3\times10^{-6} (the same as the final learning rate of V3 pre-training), 2,048 KV entries selected per query, 15,000 steps × 480 sequences of 128K = 943.7B tokens.

Parity evaluation. Comparing V3.2-Exp and V3.1-Terminus after the same post-training, the report says standard benchmarks and ChatbotArena Elo are similar, and that external long-context evaluations after release (a 4-point gain in reasoning mode on AA-LCR, Fiction.liveBench) showed no regression either (§2.2). Most comparisons in this section, however, are given only in prose, with no table.

Post-training: specialist distillation + one stage of mixed RL

The pipeline is the same as for V3.2-Exp. After SFT on the data produced by the specialists (the report says the distilled model is “only slightly” below the specialists, and that the gap disappears with subsequent RL), reasoning, agentic and human-alignment training are mixed into a single RL stage. This choice avoids the catastrophic forgetting that comes with splitting into several stages. Rewards are rule-based outcome rewards + a length penalty + a language-consistency reward for reasoning and agentic tasks, and for general tasks a generative reward model with a separate rubric for each prompt. The RL algorithm is GRPO; in this site’s notation (report eq. 5)

J(θ)=Ex,{yi}∼πold[1G∑i=1G1∣yi∣∑t=1∣yi∣(min⁡(ρi,tA^i,t, clip⁡(ρi,t,1−ε,1+ε)A^i,t)−β D^KL(i,t))],A^i,t=Ri−mean⁡(R)J(\theta)=\mathbb E_{x,\{y_i\}\sim\pi_{\text{old}}}\Bigg[\frac1G\sum_{i=1}^G\frac{1}{|y_i|}\sum_{t=1}^{|y_i|}\Big(\min\big(\rho_{i,t}\hat A_{i,t},\ \operatorname{clip}(\rho_{i,t},1-\varepsilon,1+\varepsilon)\hat A_{i,t}\big)-\beta\,\hat D_{\text{KL}}^{(i,t)}\Big)\Bigg],\qquad \hat A_{i,t}=R_i-\operatorname{mean}(R)

Unlike the R1 report, the text states that it does not divide by the std (a fix in the same direction as the difficulty bias pointed out by Dr. GRPO, though the report does not explain the reason). The report says the RL training budget exceeded 10% of the pre-training cost, and that performance rose steadily as the budget grew (§4.1).

V3.2-Speciale was trained with RL from the same base on reasoning data only, with a reduced length penalty, and adds the data and reward method of DeepSeekMath-V2 for proof ability.

Key methods in depth

1. Aligning the indexer with the main attention

The point of the dense warm-up is to make “the top-k chosen by the indexer overlap with where the main attention actually puts its mass”. Reducing KL(p ∥ softmax⁡(I))(p\,\|\,\operatorname{softmax}(I)) makes II large where pp is large, which raises the mass recall of the top-k. The code below builds the indexer of eq. (1) as is and fits it with Adam to the head-summed distribution of a fixed main attention as the target. The gradient is written by hand — from the softmax-KL gradient ∂L/∂I=softmax⁡(I)−p\partial\mathcal L/\partial I = \operatorname{softmax}(I)-p, through the ReLU and the head weights, down to the three projection matrices.

NumPy Lightning indexer and dense warm-up (eqs. 1, 3)
import numpy as np

rng = np.random.default_rng(0)
L, d = 256, 32                       # context length, hidden dimension
Hm, dm = 4, 16                       # main attention: 4 heads, head dim 16
HI, dI = 4, 8                        # lightning indexer: 4 heads, head dim 8 (small and cheap)

# context: hidden states h_s. Some tokens share a "topic" direction and attend strongly to each other.
topics = rng.normal(size=(6, d))
tid = rng.integers(0, 6, size=L)
Hs = 0.8 * rng.normal(size=(L, d)) + 1.2 * topics[tid]

# --- target distribution p_{t,:} from the main attention (eq. 3): sum per-head softmaxes, L1-normalise ---
Wq_m = rng.normal(size=(Hm, d, dm)) / np.sqrt(d)
Wk_m = rng.normal(size=(Hm, d, dm)) / np.sqrt(d)
T = np.arange(128, L)                # query positions 128..255 (each sees 0..t)
causal = np.arange(L)[None, :] <= T[:, None]          # (Q, L)

def main_target():
    q = np.einsum('td,hde->hte', Hs[T], Wq_m)           # (Hm, Q, dm)
    k = np.einsum('sd,hde->hse', Hs, Wk_m)              # (Hm, L, dm)
    z = np.einsum('hte,hse->hts', q, k) * 1.5
    z = np.where(causal[None], z, -np.inf)
    a = np.exp(z - z.max(-1, keepdims=True)); a /= a.sum(-1, keepdims=True)
    p = a.sum(0); return p / p.sum(-1, keepdims=True)   # sum over heads → L1-normalise
P = main_target()

# --- lightning indexer (eq. 1): I_{t,s} = sum_j w_{t,j} * ReLU(q^I_{t,j} . k^I_s) ---
params = {
    'Wq': rng.normal(size=(HI, d, dI)) / np.sqrt(d),
    'Wk': rng.normal(size=(d, dI)) / np.sqrt(d),
    'Ww': rng.normal(size=(d, HI)) / np.sqrt(d),
}

def indexer(pr):
    q = np.einsum('td,jde->tje', Hs[T], pr['Wq'])       # (Q, HI, dI)
    k = Hs @ pr['Wk']                                   # (L, dI)  key shared across heads
    w = Hs[T] @ pr['Ww']                                # (Q, HI)  head weights also come from the query
    a = q @ k.T                                         # (Q, HI, L)
    I = (w[:, :, None] * np.maximum(a, 0)).sum(1)
    return I, (q, k, w, a)

def masked_softmax(I):
    z = np.where(causal, I, -np.inf)
    e = np.exp(z - z.max(-1, keepdims=True)); return e / e.sum(-1, keepdims=True)

def kl_loss(I):                                         # eq. (3): sum_t KL(p_t || softmax(I_t))
    S = masked_softmax(I)
    return np.mean(np.sum(np.where(causal, P * (np.log(P + 1e-30) - np.log(S + 1e-30)), 0), -1)), S

def topk_recall(I, k):                                  # main-attention mass captured by the indexer top-k
    z = np.where(causal, I, -np.inf)
    idx = np.argsort(-z, axis=-1)[:, :k]
    return np.take_along_axis(P, idx, -1).sum(-1).mean()

def oracle_recall(k):
    return np.sort(P, -1)[:, ::-1][:, :k].sum(-1).mean()

# --- dense warm-up: main model frozen, only the indexer trained with KL (Adam, hand-written backprop) ---
m = {n: np.zeros_like(v) for n, v in params.items()}; v2 = {n: np.zeros_like(v) for n, v in params.items()}
lr, b1, b2 = 2e-2, 0.9, 0.999
I0, _ = indexer(params)
print(f"before training: KL={kl_loss(I0)[0]:.3f}  recall@16={topk_recall(I0,16):.3f}  recall@32={topk_recall(I0,32):.3f}")
for step in range(1, 201):
    I, (q, k, w, a) = indexer(params)
    loss, S = kl_loss(I)
    G = np.where(causal, S - P, 0) / len(T)            # dLoss/dI
    dw = (G[:, None, :] * np.maximum(a, 0)).sum(-1)
    da = G[:, None, :] * w[:, :, None] * (a > 0)
    dq = da @ k                                         # (Q, HI, dI)
    dk = da.reshape(-1, L).T @ q.reshape(-1, dI)       # (L, dI)
    grads = {'Wq': np.einsum('td,tje->jde', Hs[T], dq), 'Wk': Hs.T @ dk, 'Ww': Hs[T].T @ dw}
    for n in params:
        m[n] = b1 * m[n] + (1 - b1) * grads[n]; v2[n] = b2 * v2[n] + (1 - b2) * grads[n] ** 2
        params[n] -= lr * (m[n] / (1 - b1 ** step)) / (np.sqrt(v2[n] / (1 - b2 ** step)) + 1e-8)
    if step in (25, 75, 200):
        print(f"step {step:3d}: KL={loss:.3f}  recall@16={topk_recall(I,16):.3f}  recall@32={topk_recall(I,32):.3f}")
print(f"oracle  : recall@16={oracle_recall(16):.3f}  recall@32={oracle_recall(32):.3f}  (mean context length {causal.sum(1).mean():.0f})")
 

Picking only 16 of 192 tokens on average, the oracle captures 98% of the mass — attention is that peaked to begin with. The indexer captures about 8% before training and rises to the 70% range after 200 steps. This toy indexer has head dimension 8 and ranks with a single ReLU score, so it does not reach the oracle. The real V3.2, after a 2.1B-token warm-up, trains the main model too in sparse mode for 943.7B tokens, and in that stage the main model adapts to doing its attention inside the set the indexer picks. The fact that the main model also follows the indexer is what distinguishes this from a simple “attention approximation”.

확인 문제Check yourself

In DSA's sparse training stage, what is the best reason for detaching the indexer input from the computational graph?

The report states that the indexer’s only training signal is LI\mathcal L^I and that the main model is optimised only with the language-modelling loss. The indexer’s input is the main model’s hidden state ht\mathbf h_t. Without the detach, the gradient of LI\mathcal L^I would flow through ht\mathbf h_t into the main model’s parameters, pressuring the main model towards “representations the indexer finds easy to match”. The indexer keeps being trained during the sparse stage (so not option 4); this is not freezing. Non-differentiability of top-k concerns the main model → indexer direction; what the detach blocks is the indexer loss → main model direction.

2. GRPO fixes for running RL a long time

Spend RL compute above 10% of pre-training and the policy moves a lot over thousands of steps while the differences between the rollout engine and the training engine accumulate. All four fixes of report §3.1 deal with this off-policyness (exactly the subject of the training–inference mismatch lesson).

(a) IS-corrected KL estimator. GRPO uses the K3 estimator k3=πrefπθ−log⁡πrefπθ−1k_3 = \frac{\pi_{\text{ref}}}{\pi_\theta}-\log\frac{\pi_{\text{ref}}}{\pi_\theta}-1 for its KL term (KL estimators). But the sample yi,ty_{i,t} came from πold\pi_{\text{old}}, not πθ\pi_\theta. V3.2 corrects this by multiplying by the ratio (eq. 7).

D^KL(i,t)=πθ(yi,t∣⋅)πold(yi,t∣⋅)(πref(yi,t∣⋅)πθ(yi,t∣⋅)−log⁡πref(yi,t∣⋅)πθ(yi,t∣⋅)−1)\hat D_{\text{KL}}^{(i,t)}=\frac{\pi_\theta(y_{i,t}\mid\cdot)}{\pi_{\text{old}}(y_{i,t}\mid\cdot)}\left(\frac{\pi_{\text{ref}}(y_{i,t}\mid\cdot)}{\pi_\theta(y_{i,t}\mid\cdot)}-\log\frac{\pi_{\text{ref}}(y_{i,t}\mid\cdot)}{\pi_\theta(y_{i,t}\mid\cdot)}-1\right)

The expected value is Eπold[ρ k3]=Eπθ[k3]=DKL(πθ∥πref)\mathbb E_{\pi_{\text{old}}}[\rho\,k_3]=\mathbb E_{\pi_\theta}[k_3]=D_{\text{KL}}(\pi_\theta\|\pi_{\text{ref}}). What the report emphasises is the gradient. With r=πref/πθr=\pi_{\text{ref}}/\pi_\theta we have ∇r=−r∇log⁡πθ\nabla r=-r\nabla\log\pi_\theta, so

∇k3=(1−r) ∇log⁡πθ,∇(ρ k3)=ρ(k3+1−r)∇log⁡πθ=ρ log⁡πθπref ∇log⁡πθ.\nabla k_3=(1-r)\,\nabla\log\pi_\theta,\qquad \nabla(\rho\,k_3)=\rho\big(k_3+1-r\big)\nabla\log\pi_\theta=\rho\,\log\frac{\pi_\theta}{\pi_{\text{ref}}}\,\nabla\log\pi_\theta .

Two things stand out. First, the expectation of the corrected version is Eπθ[log⁡πθπref∇log⁡πθ]=∇DKL(πθ∥πref)\mathbb E_{\pi_\theta}[\log\frac{\pi_\theta}{\pi_{\text{ref}}}\nabla\log\pi_\theta]=\nabla D_{\text{KL}}(\pi_\theta\|\pi_{\text{ref}}): unbiased. Differentiating K3 as is, by contrast, gives even on-policy Eπθ[(1−r)∇log⁡πθ]=−∑yπref(y)∇log⁡πθ(y)=∇DKL(πref∥πθ)\mathbb E_{\pi_\theta}[(1-r)\nabla\log\pi_\theta]=-\sum_y\pi_{\text{ref}}(y)\nabla\log\pi_\theta(y)=\nabla D_{\text{KL}}(\pi_{\text{ref}}\|\pi_\theta) — the gradient of the KL in the opposite direction. Second, for tokens with πθ≪πref\pi_\theta\ll\pi_{\text{ref}} the K3 coefficient 1−r1-r grows without bound like −r-r, whereas the corrected one grows only at a log⁡\log rate. The “disproportionately large, unbounded weights to maximize the likelihood of these tokens” the report mentions is this −r-r.

(b) Off-policy sequence masking. The loss is multiplied by a binary mask Mi,tM_{i,t} (eqs. 8–9).

Mi,t={0A^i,t<0  and  1∣yi∣∑t=1∣yi∣log⁡πold(yi,t∣⋅)πθ(yi,t∣⋅)>δ1otherwiseM_{i,t}=\begin{cases}0 & \hat A_{i,t}<0\ \text{ and }\ \dfrac{1}{|y_i|}\displaystyle\sum_{t=1}^{|y_i|}\log\dfrac{\pi_{\text{old}}(y_{i,t}\mid\cdot)}{\pi_\theta(y_{i,t}\mid\cdot)}>\delta\\[4pt] 1 & \text{otherwise}\end{cases}

The sum on the left of the condition is a sequence-level estimate of DKL(πold∥πθ)D_{\text{KL}}(\pi_{\text{old}}\|\pi_\theta). Here πold\pi_{\text{old}} is the sampling probability returned by the inference engine, so this value measures, together, the off-policyness from several mini-batch updates and the implementation differences between engines. And only sequences with negative advantage are masked. The report’s explanation is “the model benefits the most by learning from its own mistakes, whereas highly off-policy negative samples can be detrimental”. Pushing down further the probability of a sequence the current policy would hardly produce carries little information, and since πθ\pi_\theta for those tokens is already small, it combines with the large coefficient of (a) above and easily becomes unstable.

(c) Keep Routing. In an MoE, the same input can choose different experts in the inference engine and the training engine, and more so once the policy is updated. A sudden change in the active parameter subspace magnifies the off-policy problem. So the routing path from sampling is saved and enforced during training. The report says this was “crucial” for the stability of MoE RL and has been used since DeepSeek-V3-0324.

(d) Keep Sampling Mask. With top-p/top-k sampling, the action space of πold\pi_{\text{old}} is a truncated vocabulary while πθ\pi_\theta is computed over the full vocabulary, which breaks the premise of importance sampling. The truncation mask from sampling is saved and applied to πθ\pi_\theta as well. Top-p plus this mask was reported to be effective at keeping language consistency during RL.

그림에서 확인할 것:

  1. a=0a=0(정렬 안 된 indexer)이면 파란 막대가 무작위로 흩어지고 k=32k=32로 잡는 질량이 10%대다. aa를 0.6 이상으로 올리면 needle 토큰이 거의 다 잡히고 곡선이 oracle에 붙는다. 다음 절의 dense warm-up이 하는 일이 이 aa를 올리는 것이다.
  2. a=1a=1이어도 oracle과 약간의 차이가 남는다. 이 장난감의 진짜 attention에는 최근 토큰을 선호하는 위치 항이 있는데, indexer key에는 위치 정보를 넣지 않았기 때문이다. 후속작 V4가 sparse attention 옆에 sliding window 가지를 따로 두는 이유와 같은 종류의 틈이다(V4 보고서 2.3.3절).
  3. query 위치 tt를 줄여 보면 문맥이 짧을 때는 kk가 문맥의 큰 몫이라 sparse의 이득이 작다. DSA의 이득은 긴 문맥에서 나온다.

MLA 위에 얹기: MQA 모드

DSA를 V3.1-Terminus에서 이어 학습해야 했기 때문에 DSA는 MLA 위에 구현됐다. 보고서는 kernel 효율상 “each key-value entry must be shared across multiple queries”(NSA의 논점)라며, MLA의 MQA 모드에 DSA를 얹었다고 쓴다. MQA 모드가 무엇인지는 V3 보고서의 MLA 식에서 바로 유도된다. head ii의 attention logit은

qt,i⊤ks,i=(qt,iC)⊤WiUK csKV+(qt,iR)⊤ksR=(WiUK⊤qt,iC)⊤⏟head별 query (512차원)csKV+(qt,iR)⊤ksR\mathbf q_{t,i}^\top \mathbf k_{s,i} = (\mathbf q^C_{t,i})^\top W^{UK}_i\,\mathbf c^{KV}_s + (\mathbf q^R_{t,i})^\top \mathbf k^R_s = \underbrace{\big(W^{UK\top}_i \mathbf q^C_{t,i}\big)^\top}_{\text{head별 query (512차원)}}\mathbf c^{KV}_s + (\mathbf q^R_{t,i})^\top \mathbf k^R_s

이다. WiUKW^{UK}_i를 query 쪽으로 흡수하면 key는 모든 head가 공유하는 [csKV;ksR][\mathbf c^{KV}_s;\mathbf k^R_s](512 + 64 = 576차원) 하나가 되고, value도 공유 latent csKV\mathbf c^{KV}_s에 attention을 건 뒤 head별 WiUVW^{UV}_i를 출력 쪽에서 곱하면 된다. 즉 KV head가 하나인 MQA와 같은 계산이다. 보고서 부록 A에 따르면 V3.1-Terminus는 학습·prefill에 MHA 모드(latent를 head별 K, V로 풀어서 계산), decode에 MQA 모드를 쓴다. DSA는 이 MQA 모드를 택했기 때문에 indexer가 고른 latent 항목 2048개를 128개 head가 한꺼번에 재사용한다. sparse gather를 head마다 따로 할 필요가 없다.

비용: indexer는 여전히 O(L2)O(L^2)

보고서 2.3절은 주 attention이 O(L2)→O(Lk)O(L^2)\to O(Lk)가 되고 indexer는 여전히 O(L2)O(L^2)이지만 MLA보다 훨씬 싸다고 쓴다. 얼마나 싼지는 공개 config로 대략 셀 수 있다(아래는 이 레슨의 계산이고 보고서 숫자가 아니다). 위치 tt의 query 하나가 앞선 토큰 하나를 볼 때 드는 곱셈-누산은

  • indexer: HIdI=64×128=8,192H^I d^I = 64\times128 = 8{,}192 (FP8)
  • MLA MQA 모드 core attention: 128 head × (key 576 + value 512) = 139,264 (BF16)

로 약 17배 차이다. 그러면 위치 tt에서 query당 attention 비용은

costDSA(t)≈8,192 t+139,264 min⁡(t,2048),costdense(t)=139,264 t\text{cost}_{\text{DSA}}(t)\approx 8{,}192\,t + 139{,}264\,\min(t, 2048),\qquad \text{cost}_{\text{dense}}(t)=139{,}264\,t

이고, t=128Kt=128\text{K}에서 비는 0.059+0.016≈0.0740.059 + 0.016 \approx 0.074다. 긴 위치에서는 주 attention이 아니라 indexer가 남은 비용의 대부분이다. 이것이 후속작 V4가 indexer 계산을 FP4로 내리고 KV를 압축한 뒤에 indexer를 돌리는 이유다. 실제 시간은 메모리 대역폭과 kernel에 달려 있어서 이 비로 바로 환산되지는 않는다. 보고서는 H800 서비스 기준 토큰 위치별 비용 곡선(Figure 3)을 그림으로만 보여 준다. 짧은 prefill에는 DSA를 흉내 낸 masked MHA 모드를 따로 구현해 쓴다고 적었다.

→ 더 깊이: Sparse attention은 DSA를 NSA·QSA·CSA/HCA와 나란히 놓고, DeepSeek 계보는 V3.2가 V3와 V4 사이 어디에 있는지 보여 준다.

데이터

V3.2는 V3.1-Terminus에서 출발한 continued training이라 새 사전학습 말뭉치를 소개하지 않는다. 데이터에 관한 내용은 대부분 사후학습, 그중에서도 에이전트 과제에 있다.

Continued pre-training. 두 단계 모두 데이터 분포를 *“totally aligned with the 128K long context extension data used for DeepSeek-V3.1-Terminus”*로 맞췄다. 즉 DSA 전환은 새 데이터가 아니라 같은 데이터에서 attention 방식만 바꾸는 실험으로 설계됐다. 덕분에 이후의 parity 비교(아래)가 깨끗하다.

사후학습 데이터. 같은 V3.2 base checkpoint에서 도메인별 specialist를 만들어 데이터를 생성한다. 글쓰기·일반 QA에 더해 여섯 도메인 — 수학, 프로그래밍, 일반 논리 추론, 일반 에이전트, 에이전트 코딩, 에이전트 검색 — 이 있고, 모두 thinking과 non-thinking 모드를 지원하며 각 specialist가 대규모 RL로 학습된다. 긴 CoT 데이터와 직답 데이터는 서로 다른 모델이 생성한다.

에이전트 RL 과제(보고서 Table 1):

과제과제 수환경프롬프트
code agent24,667실제추출
search agent50,275실제합성
general agent4,417합성합성
code interpreter5,908실제추출
  • Search agent: 대규모 웹 말뭉치에서 long-tail 엔티티를 뽑고, 질문 생성 agent가 검색 도구로 엔티티를 탐색해 QA를 만든다. 설정이 다른 여러 답변 agent가 후보 답을 내고, 검색이 가능한 검증 agent가 여러 번 확인해 정답은 맞고 후보 답은 모두 틀린 샘플만 남긴다. 검증 가능한 이 데이터에, 검색이 실제로 도움이 되는 기존 helpful RL 데이터를 섞고 rubric 기반 generative reward model로 채점한다.
  • Code agent: GitHub의 issue–PR 쌍 수백만 개를 휴리스틱과 LLM 판정으로 거르고, V3.2 기반 환경 구축 agent가 패키지 설치·의존성 해결·테스트 실행을 자동화한다. gold patch를 적용했을 때 F2P(실패→통과) 테스트가 하나 이상이고 P2F(통과→실패)가 0일 때만 환경을 채택했다. Python, Java, JavaScript, TypeScript, C, C++, Go, PHP에 걸쳐 수만 개의 재현 가능한 환경이 나왔다.
  • Code interpreter: Jupyter Notebook을 도구로 수학·논리·데이터 과학 문제를 푼다.
  • General agent: 환경 합성 agent가 bash와 검색 도구가 있는 sandbox에서 (1) 과제 범주(예: 여행 일정)에 맞는 데이터를 수집해 DB에 넣고, (2) 과제 전용 도구 함수를 만들고, (3) 쉬운 과제와 그 풀이 함수·검증 함수(Python)를 함께 제안한 뒤 난이도를 반복해서 올린다. 풀이 함수는 도구 함수 호출과 논리 연산만 할 수 있어서 과제는 반드시 도구 인터페이스로만 풀린다. 이렇게 만든 ⟨환경, 도구, 과제, 검증기⟩ 묶음 가운데 V3.2로 RL을 돌려 pass@100이 0이 아닌 것만 남긴 결과가 1,827개 환경, 4,417개 과제다. “풀기는 어렵고 검증은 쉬운” 과제가 목표다 — 보고서의 예시는 도시·호텔·식당·예산 조건이 얽힌 3일 여행 계획이다.

검색 agent의 필터 “정답은 맞고 모든 후보는 틀린”과 general agent의 “pass@100 > 0”은 정반대 방향에서 같은 목적을 겨냥한다. 하나는 너무 쉬운 과제를, 다른 하나는 아예 풀 수 없는(신호가 없는) 과제를 뺀다. RLVR 레슨에서 본 “가끔은 맞히는 문제에서만 배운다”를 데이터 파이프라인으로 구현한 것이다.

학습

Continued pre-training: dense warm-up → sparse

1단계: dense warm-up. attention은 dense 그대로 두고 indexer만 학습한다(나머지 파라미터 동결). query 토큰 tt에 대해 주 attention 점수를 모든 head에 걸쳐 더하고 시퀀스 방향으로 L1 정규화해 target 분포 pt,:∈Rtp_{t,:}\in\mathbb R^t를 만든 뒤

LI=∑tDKL(pt,: ∥ Softmax⁡(It,:))\mathcal L^I=\sum_t D_{\text{KL}}\big(p_{t,:}\,\big\|\,\operatorname{Softmax}(I_{t,:})\big)

를 최소화한다(식 3). indexer 출력에는 softmax가 없지만, 학습할 때만 softmax를 씌워 분포로 보고 맞춘다. 학습률 10−310^{-3}, 1,000 step, step당 128K 토큰 시퀀스 16개 — 총 2.1B 토큰이다.

2단계: sparse training. top-k 선택을 켜고 모든 파라미터를 학습한다. indexer는 계속 주 attention을 따라가되 선택된 집합 St\mathcal S_t 위에서만 맞춘다.

LI=∑tDKL(pt,St ∥ Softmax⁡(It,St))\mathcal L^I=\sum_t D_{\text{KL}}\big(p_{t,\mathcal S_t}\,\big\|\,\operatorname{Softmax}(I_{t,\mathcal S_t})\big)

중요한 세부: indexer 입력을 계산 그래프에서 떼어낸다(detach). indexer는 LI\mathcal L^I로만, 주 모델은 언어모델링 손실로만 학습된다. top-k 선택은 미분이 되지 않으니 주 모델에서 indexer로 gradient가 흐를 길이 원래 없고, 반대로 indexer 손실이 주 모델 표현을 끌어당기지도 못하게 막은 것이다. 학습률 7.3×10−67.3\times10^{-6}(V3 사전학습의 마지막 학습률과 같은 값), query당 KV 2,048개 선택, 15,000 step × 128K 시퀀스 480개 = 943.7B 토큰.

Parity 평가. 같은 사후학습을 거친 V3.2-Exp와 V3.1-Terminus를 비교해 표준 벤치마크와 ChatbotArena Elo가 비슷하고, 공개 후 외부 장문 평가(AA-LCR에서 reasoning 모드 4점 상승, Fiction.liveBench)에서도 퇴보가 없었다고 보고한다(2.2절). 다만 이 절의 비교는 대부분 문장으로만 적혀 있고 표가 없다.

사후학습: specialist distillation + 한 단계 mixed RL

V3.2-Exp와 같은 파이프라인이다. specialist로 만든 데이터로 SFT한 뒤(distill된 모델은 specialist보다 “약간만” 낮고 그 차이는 이후 RL로 사라진다고 적었다), 추론·에이전트·human alignment를 한 RL 단계에 섞는다. 여러 단계로 나누면 생기는 catastrophic forgetting을 피하려는 선택이다. 보상은 추론·에이전트 과제에 규칙 기반 결과 보상 + 길이 벌점 + 언어 일관성 보상, 일반 과제에 프롬프트마다 rubric이 따로 있는 generative reward model이다. RL 알고리즘은 GRPO이고, 사이트 표기로 옮기면(보고서 식 5)

J(θ)=Ex,{yi}∼πold[1G∑i=1G1∣yi∣∑t=1∣yi∣(min⁡(ρi,tA^i,t, clip⁡(ρi,t,1−ε,1+ε)A^i,t)−β D^KL(i,t))],A^i,t=Ri−mean⁡(R)J(\theta)=\mathbb E_{x,\{y_i\}\sim\pi_{\text{old}}}\Bigg[\frac1G\sum_{i=1}^G\frac{1}{|y_i|}\sum_{t=1}^{|y_i|}\Big(\min\big(\rho_{i,t}\hat A_{i,t},\ \operatorname{clip}(\rho_{i,t},1-\varepsilon,1+\varepsilon)\hat A_{i,t}\big)-\beta\,\hat D_{\text{KL}}^{(i,t)}\Big)\Bigg],\qquad \hat A_{i,t}=R_i-\operatorname{mean}(R)

이다. R1 보고서와 달리 std로 나누지 않는다고 본문에 적혀 있다(Dr. GRPO가 지적한 난이도 편향과 같은 방향의 수정이지만 보고서는 이유를 설명하지 않는다). 보고서는 RL 학습 예산이 사전학습 비용의 10%를 넘었고, 예산을 늘릴수록 성능이 꾸준히 올랐다고 쓴다(4.1절).

V3.2-Speciale은 같은 base에서 추론 데이터만, 길이 벌점을 줄여 RL했고, 증명 능력을 위해 DeepSeekMath-V2의 데이터와 보상 방법을 더했다.

핵심 method 깊게 보기

1. indexer를 주 attention에 맞추기

dense warm-up의 요점은 “indexer가 고른 top-k가 주 attention이 실제로 질량을 두는 곳과 겹치게” 만드는 것이다. KL(p ∥ softmax⁡(I))(p\,\|\,\operatorname{softmax}(I))를 줄이면 pp가 큰 곳에서 II가 커지고, 그러면 top-k의 질량 회수율(recall)이 오른다. 아래 코드는 식 (1)의 indexer를 그대로 만들고, 고정된 주 attention의 head-합 분포를 target으로 Adam으로 맞춘다. gradient는 손으로 쓴다 — softmax-KL의 ∂L/∂I=softmax⁡(I)−p\partial\mathcal L/\partial I = \operatorname{softmax}(I)-p에서 ReLU와 head 가중치를 거쳐 세 투영 행렬로 내려간다.

NumPy lightning indexer와 dense warm-up (식 1, 3)
import numpy as np

rng = np.random.default_rng(0)
L, d = 256, 32                       # 문맥 길이, hidden 차원
Hm, dm = 4, 16                       # main attention: head 4개, head 차원 16
HI, dI = 4, 8                        # lightning indexer: head 4개, head 차원 8 (작고 싸다)

# 문맥: hidden state h_s. 일부 토큰은 "주제" 방향을 공유해 서로 강하게 attend 한다.
topics = rng.normal(size=(6, d))
tid = rng.integers(0, 6, size=L)
Hs = 0.8 * rng.normal(size=(L, d)) + 1.2 * topics[tid]

# --- main attention이 만드는 target 분포 p_{t,:} (식 3): head별 softmax를 합하고 L1 정규화 ---
Wq_m = rng.normal(size=(Hm, d, dm)) / np.sqrt(d)
Wk_m = rng.normal(size=(Hm, d, dm)) / np.sqrt(d)
T = np.arange(128, L)                # query 위치: 128..255 (각자 0..t를 본다)
causal = np.arange(L)[None, :] <= T[:, None]          # (Q, L)

def main_target():
    q = np.einsum('td,hde->hte', Hs[T], Wq_m)           # (Hm, Q, dm)
    k = np.einsum('sd,hde->hse', Hs, Wk_m)              # (Hm, L, dm)
    z = np.einsum('hte,hse->hts', q, k) * 1.5
    z = np.where(causal[None], z, -np.inf)
    a = np.exp(z - z.max(-1, keepdims=True)); a /= a.sum(-1, keepdims=True)
    p = a.sum(0); return p / p.sum(-1, keepdims=True)   # head 합 → L1 정규화
P = main_target()

# --- lightning indexer (식 1): I_{t,s} = sum_j w_{t,j} * ReLU(q^I_{t,j} . k^I_s) ---
params = {
    'Wq': rng.normal(size=(HI, d, dI)) / np.sqrt(d),
    'Wk': rng.normal(size=(d, dI)) / np.sqrt(d),
    'Ww': rng.normal(size=(d, HI)) / np.sqrt(d),
}

def indexer(pr):
    q = np.einsum('td,jde->tje', Hs[T], pr['Wq'])       # (Q, HI, dI)
    k = Hs @ pr['Wk']                                   # (L, dI)  key는 head 사이에 공유
    w = Hs[T] @ pr['Ww']                                # (Q, HI)  head 가중치도 query에서 나온다
    a = q @ k.T                                         # (Q, HI, L)
    I = (w[:, :, None] * np.maximum(a, 0)).sum(1)
    return I, (q, k, w, a)

def masked_softmax(I):
    z = np.where(causal, I, -np.inf)
    e = np.exp(z - z.max(-1, keepdims=True)); return e / e.sum(-1, keepdims=True)

def kl_loss(I):                                         # 식 (3): sum_t KL(p_t || softmax(I_t))
    S = masked_softmax(I)
    return np.mean(np.sum(np.where(causal, P * (np.log(P + 1e-30) - np.log(S + 1e-30)), 0), -1)), S

def topk_recall(I, k):                                  # indexer top-k가 잡는 main attention 질량
    z = np.where(causal, I, -np.inf)
    idx = np.argsort(-z, axis=-1)[:, :k]
    return np.take_along_axis(P, idx, -1).sum(-1).mean()

def oracle_recall(k):
    return np.sort(P, -1)[:, ::-1][:, :k].sum(-1).mean()

# --- dense warm-up: main 모델은 고정, indexer만 KL로 학습 (Adam, 손으로 쓴 역전파) ---
m = {n: np.zeros_like(v) for n, v in params.items()}; v2 = {n: np.zeros_like(v) for n, v in params.items()}
lr, b1, b2 = 2e-2, 0.9, 0.999
I0, _ = indexer(params)
print(f"학습 전: KL={kl_loss(I0)[0]:.3f}  recall@16={topk_recall(I0,16):.3f}  recall@32={topk_recall(I0,32):.3f}")
for step in range(1, 201):
    I, (q, k, w, a) = indexer(params)
    loss, S = kl_loss(I)
    G = np.where(causal, S - P, 0) / len(T)            # dLoss/dI
    dw = (G[:, None, :] * np.maximum(a, 0)).sum(-1)
    da = G[:, None, :] * w[:, :, None] * (a > 0)
    dq = da @ k                                         # (Q, HI, dI)
    dk = da.reshape(-1, L).T @ q.reshape(-1, dI)       # (L, dI)
    grads = {'Wq': np.einsum('td,tje->jde', Hs[T], dq), 'Wk': Hs.T @ dk, 'Ww': Hs[T].T @ dw}
    for n in params:
        m[n] = b1 * m[n] + (1 - b1) * grads[n]; v2[n] = b2 * v2[n] + (1 - b2) * grads[n] ** 2
        params[n] -= lr * (m[n] / (1 - b1 ** step)) / (np.sqrt(v2[n] / (1 - b2 ** step)) + 1e-8)
    if step in (25, 75, 200):
        print(f"step {step:3d}: KL={loss:.3f}  recall@16={topk_recall(I,16):.3f}  recall@32={topk_recall(I,32):.3f}")
print(f"oracle  : recall@16={oracle_recall(16):.3f}  recall@32={oracle_recall(32):.3f}  (평균 문맥 길이 {causal.sum(1).mean():.0f})")
 

평균 192개 토큰 중 16개만 골라도 oracle은 질량의 98%를 잡는다 — attention은 원래 이만큼 뾰족하다. 학습 전 indexer는 8% 정도만 잡다가 200 step 후 70%대로 오른다. 이 장난감 indexer는 head 차원이 8이고 ReLU 점수 하나로 순위를 매기므로 oracle까지는 못 간다. 실제 V3.2는 2.1B 토큰 warm-up 뒤에 943.7B 토큰 동안 sparse로 주 모델까지 함께 학습하는데, 이 단계에서 주 모델은 indexer가 고른 집합 안에서 attention을 쓰도록 적응한다. indexer를 따라가는 쪽이 주 모델이기도 하다는 점이 단순한 “attention 근사”와 다르다.

확인 문제Check yourself

DSA의 sparse 학습 단계에서 indexer 입력을 계산 그래프에서 떼어낸(detach) 이유로 가장 적절한 것은?

보고서는 indexer의 학습 신호는 LI\mathcal L^I뿐이고 주 모델은 언어모델링 손실로만 최적화된다고 명시한다. indexer의 입력은 주 모델의 hidden state ht\mathbf h_t다. detach하지 않으면 LI\mathcal L^I의 gradient가 ht\mathbf h_t를 거쳐 주 모델 파라미터로 흘러, 주 모델이 “indexer가 맞히기 쉬운 표현”으로 바뀌는 압력을 받는다. indexer는 sparse 단계에서도 계속 학습되므로(4번 아님) 동결과는 다르다. top-k가 미분 불가능한 것은 주 모델→indexer 방향의 이야기이고, detach가 막는 것은 indexer 손실→주 모델 방향이다.

2. RL을 오래 돌리기 위한 GRPO 수정

RL 계산을 사전학습의 10% 넘게 쓰면 수천 step 동안 정책이 크게 움직이고, rollout 엔진과 학습 엔진의 차이가 누적된다. 보고서 3.1절의 네 가지 수정은 모두 이 off-policy성을 다룬다(학습–추론 불일치 레슨의 주제와 정확히 겹친다).

(a) IS로 보정한 KL 추정량. GRPO는 KL 항으로 K3 추정량 k3=πrefπθ−log⁡πrefπθ−1k_3 = \frac{\pi_{\text{ref}}}{\pi_\theta}-\log\frac{\pi_{\text{ref}}}{\pi_\theta}-1을 쓴다(KL 추정량). 그런데 샘플 yi,ty_{i,t}는 πθ\pi_\theta가 아니라 πold\pi_{\text{old}}에서 왔다. V3.2는 ratio를 곱해 보정한다(식 7).

D^KL(i,t)=πθ(yi,t∣⋅)πold(yi,t∣⋅)(πref(yi,t∣⋅)πθ(yi,t∣⋅)−log⁡πref(yi,t∣⋅)πθ(yi,t∣⋅)−1)\hat D_{\text{KL}}^{(i,t)}=\frac{\pi_\theta(y_{i,t}\mid\cdot)}{\pi_{\text{old}}(y_{i,t}\mid\cdot)}\left(\frac{\pi_{\text{ref}}(y_{i,t}\mid\cdot)}{\pi_\theta(y_{i,t}\mid\cdot)}-\log\frac{\pi_{\text{ref}}(y_{i,t}\mid\cdot)}{\pi_\theta(y_{i,t}\mid\cdot)}-1\right)

값의 기대값은 Eπold[ρ k3]=Eπθ[k3]=DKL(πθ∥πref)\mathbb E_{\pi_{\text{old}}}[\rho\,k_3]=\mathbb E_{\pi_\theta}[k_3]=D_{\text{KL}}(\pi_\theta\|\pi_{\text{ref}})이다. 보고서가 강조하는 것은 gradient다. r=πref/πθr=\pi_{\text{ref}}/\pi_\theta로 두면 ∇r=−r∇log⁡πθ\nabla r=-r\nabla\log\pi_\theta이므로

∇k3=(1−r) ∇log⁡πθ,∇(ρ k3)=ρ(k3+1−r)∇log⁡πθ=ρ log⁡πθπref ∇log⁡πθ.\nabla k_3=(1-r)\,\nabla\log\pi_\theta,\qquad \nabla(\rho\,k_3)=\rho\big(k_3+1-r\big)\nabla\log\pi_\theta=\rho\,\log\frac{\pi_\theta}{\pi_{\text{ref}}}\,\nabla\log\pi_\theta .

두 가지가 보인다. 첫째, 보정판의 기대값은 Eπθ[log⁡πθπref∇log⁡πθ]=∇DKL(πθ∥πref)\mathbb E_{\pi_\theta}[\log\frac{\pi_\theta}{\pi_{\text{ref}}}\nabla\log\pi_\theta]=\nabla D_{\text{KL}}(\pi_\theta\|\pi_{\text{ref}})로 편향이 없다. 반면 K3를 그대로 미분하면 on-policy에서도 Eπθ[(1−r)∇log⁡πθ]=−∑yπref(y)∇log⁡πθ(y)=∇DKL(πref∥πθ)\mathbb E_{\pi_\theta}[(1-r)\nabla\log\pi_\theta]=-\sum_y\pi_{\text{ref}}(y)\nabla\log\pi_\theta(y)=\nabla D_{\text{KL}}(\pi_{\text{ref}}\|\pi_\theta) — 방향이 반대인 KL의 gradient가 된다. 둘째, πθ≪πref\pi_\theta\ll\pi_{\text{ref}}인 토큰에서 K3의 계수 1−r1-r은 −r-r로 무한히 커지지만 보정판은 log⁡\log 속도로만 커진다. 보고서가 말한 *“disproportionately large, unbounded weights to maximize the likelihood of these tokens”*가 이 −r-r이다.

(b) Off-policy sequence masking. 손실에 이진 마스크 Mi,tM_{i,t}를 곱한다(식 8–9).

Mi,t={0A^i,t<0  이고  1∣yi∣∑t=1∣yi∣log⁡πold(yi,t∣⋅)πθ(yi,t∣⋅)>δ1그 외M_{i,t}=\begin{cases}0 & \hat A_{i,t}<0\ \text{ 이고 }\ \dfrac{1}{|y_i|}\displaystyle\sum_{t=1}^{|y_i|}\log\dfrac{\pi_{\text{old}}(y_{i,t}\mid\cdot)}{\pi_\theta(y_{i,t}\mid\cdot)}>\delta\\[4pt] 1 & \text{그 외}\end{cases}

조건의 왼쪽 합은 시퀀스 단위의 DKL(πold∥πθ)D_{\text{KL}}(\pi_{\text{old}}\|\pi_\theta) 추정치다. 여기서 πold\pi_{\text{old}}는 추론 엔진이 돌려준 샘플링 확률이라서, 이 값은 mini-batch 여러 번 업데이트로 생긴 off-policy성과 엔진 구현 차이를 함께 잰다. 그리고 음의 advantage인 시퀀스만 마스크한다. 보고서의 설명은 *“the model benefits the most by learning from its own mistakes, whereas highly off-policy negative samples can be detrimental”*이다. 현재 정책이 거의 내지 않을 시퀀스의 확률을 더 깎는 것은 정보가 적고, 그 토큰들의 πθ\pi_\theta가 이미 작으니 위 (a)의 큰 계수와 겹쳐 불안정해지기 쉽다.

(c) Keep Routing. MoE는 같은 입력이라도 추론 엔진과 학습 엔진에서 expert 선택이 달라질 수 있고, 정책이 업데이트되면 더 달라진다. 활성 파라미터 부분공간이 갑자기 바뀌면 off-policy 문제가 커진다. 그래서 샘플링 때의 routing 경로를 저장해 학습 때 강제한다. 보고서는 이것이 MoE RL 안정성에 “crucial”했고 DeepSeek-V3-0324부터 써 왔다고 적었다.

(d) Keep Sampling Mask. top-p/top-k로 샘플링하면 πold\pi_{\text{old}}의 행동 공간이 잘린 어휘가 되는데 πθ\pi_\theta는 전체 어휘에서 계산되어 importance sampling의 전제가 깨진다. 샘플링 때의 truncation mask를 저장해 πθ\pi_\theta에도 똑같이 적용한다. top-p + 이 마스크가 RL 중 언어 일관성 유지에 효과적이었다고 한다.

K3 계수K3 coefficient – 보정 계수corrected coefficient – mask된 시퀀스masked sequences – 음(−) advantage 중 비율share of negative (−) advantage –
Left: the coefficient c when the gradient of the KL term is written as c·∇log πθ(y). The original K3 has c = 1 − πref/πθ, so for tokens with πθ ≪ πref it grows without bound in the negative direction (move the first slider left). The corrected version multiplied by πθ/πold (eq. 7) has c = (πθ/πold)·log(πθ/πref) and grows only logarithmically. Right (toy data): each dot is one sequence; the horizontal axis is the sequence-mean log(πold/πθ), the vertical axis the advantage. Raise the off-policy degree and the cloud spreads to the right; lower δ and the red region (Â<0 with divergence above δ) widens, so more negative sequences drop out of the loss. Positive-advantage sequences stay no matter how off-policy they are. 왼쪽: KL 항의 gradient를 c·∇log πθ(y)로 쓸 때 계수 c. 원래 K3는 c = 1 − πref/πθ라서 πθ ≪ πref인 토큰에서 음의 방향으로 끝없이 커진다(첫 슬라이더를 왼쪽으로). πθ/πold를 곱한 보정판(식 7)은 c = (πθ/πold)·log(πθ/πref)로 로그 속도로만 자란다. 오른쪽(장난감 데이터): 점 하나가 시퀀스 하나, 가로축은 시퀀스 평균 log(πold/πθ), 세로축은 advantage. off-policy 정도를 키우면 분포가 오른쪽으로 퍼지고, δ를 낮추면 빨간 영역(Â<0 이면서 발산이 δ보다 큰 시퀀스)이 넓어져 더 많은 음의 시퀀스가 손실에서 빠진다. 양의 advantage 시퀀스는 아무리 off-policy여도 남는다.
NumPy IS-corrected K3 is unbiased in both value and gradient (eq. 7)
import numpy as np
rng = np.random.default_rng(1)
V = 12                                               # vocabulary at one token position (toy)
def softmax(z): e = np.exp(z - z.max()); return e / e.sum()

z_ref = rng.normal(size=V)
z_th  = z_ref + rng.normal(scale=1.0, size=V)        # policy being trained: has moved well away from ref
z_old = z_th + rng.normal(scale=0.5, size=V)         # policy that produced the rollout (a few steps ago + engine differences)
p_ref, p_th, p_old = softmax(z_ref), softmax(z_th), softmax(z_old)

kl_true = np.sum(p_th * np.log(p_th / p_ref))        # KL(π_θ || π_ref)
k3  = lambda y: p_ref[y] / p_th[y] - np.log(p_ref[y] / p_th[y]) - 1
rho = lambda y: p_th[y] / p_old[y]                   # π_θ / π_old

# 1) expected value: the key point is that samples come from π_old
ys = np.arange(V)
print(f"true KL(π_θ||π_ref)            = {kl_true:.4f}")
print(f"E_old[K3]        (uncorrected) = {np.sum(p_old * k3(ys)):.4f}   ← off, because it is w.r.t. π_old")
print(f"E_old[ρ·K3]      (eq. 7)       = {np.sum(p_old * rho(ys) * k3(ys)):.4f}   ← exact match")

# 2) Monte Carlo check too (4096 tokens)
y = rng.choice(V, size=4096, p=p_old)
print(f"MC 4096: K3 {k3(y).mean():.4f} ± {k3(y).std()/64:.4f} | ρ·K3 {(rho(y)*k3(y)).mean():.4f} ± {(rho(y)*k3(y)).std()/64:.4f}")

# 3) expected gradient (w.r.t. the logits z_θ of θ).  ∇_z log π_θ(y) = e_y − π_θ
def grad_logp(y): g = -p_th.copy(); g[y] += 1; return g
true_grad = p_th * (np.log(p_th / p_ref) - kl_true)  # ∇_z KL(π_θ||π_ref) (closed form)
g_k3   = sum(p_old[y] * (1 - p_ref[y] / p_th[y]) * grad_logp(y) for y in ys)            # coefficient (1 − π_ref/π_θ)
g_corr = sum(p_old[y] * rho(y) * np.log(p_th[y] / p_ref[y]) * grad_logp(y) for y in ys) # coefficient ρ·log(π_θ/π_ref)
print(f"\n|E[∇K3] − ∇KL|   = {np.abs(g_k3 - true_grad).max():.4f}")
print(f"|E[∇ρK3] − ∇KL|  = {np.abs(g_corr - true_grad).max():.2e}")
# even on-policy (π_old = π_θ), differentiating K3 as is gives the gradient of a different KL
g_k3_on = sum(p_th[y] * (1 - p_ref[y] / p_th[y]) * grad_logp(y) for y in ys)
print(f"on-policy E[∇K3] − ∇KL(π_θ||π_ref) = {np.abs(g_k3_on - true_grad).max():.4f},"
      f"  − ∇KL(π_ref||π_θ) = {np.abs(g_k3_on - (p_th - p_ref)).max():.2e}")

# 4) size of the two coefficients for tokens with π_θ ≪ π_ref
for r in [0.5, 0.1, 0.01, 0.001]:                    # r = π_θ/π_ref
    print(f"π_θ/π_ref={r:<6} K3 coef {1 - 1/r:9.1f} | corrected coef (ρ=1) {np.log(r):6.2f}")
 

How to read the output: in value, the uncorrected K3 lands near 0.24, off from the true KL of 0.21; in gradient, even on-policy, K3 matches ∇DKL(πref∥πθ)\nabla D_{\text{KL}}(\pi_{\text{ref}}\|\pi_\theta) to numerical precision. In other words, the common implementation that “differentiates the K3 loss” was minimising the KL in a different direction from the one intended. The last block of lines traces the two curves in the left panel of the figure.

The report adds that the KL strength should differ by domain, and that in domains like mathematics it was better to weaken the KL or drop it altogether. Fixing the KL term and deciding whether to use a KL at all are separate questions.

Below is a PyTorch version that puts (a) and (b), the two of the four fixes that show up in the loss, into one function. (c) and (d) are not part of the loss but state the rollout engine saves and hands to the training forward pass (routing indices, truncation mask), so they appear only in comments.

PyTorch V3.2-style GRPO loss (PyTorch, read-only) 로컬에서 실행run locally (pip install torch)
import torch

def grpo_v32_loss(logp, old_logp, ref_logp, tok_mask, rewards,
                  beta=1e-3, eps=0.2, delta=0.1):
    """
    logp     : (G, T) current policy log π_θ(y_t | ·). Assumed to be computed with the rollout's expert path
               (Keep Routing) and the rollout's top-p-truncated vocabulary (Keep Sampling Mask).
    old_logp : (G, T) log π_old returned by the inference engine at sampling time (not recomputed by the training engine)
    ref_logp : (G, T) log π_ref
    tok_mask : (G, T) 1 for response tokens, 0 for padding
    rewards  : (G,)   rewards of the G responses to one prompt
    """
    n_tok = tok_mask.sum(-1).clamp(min=1)                       # |y_i|
    adv = (rewards - rewards.mean()).detach()                   # Â_i = R_i − mean(R) (no division by std)
    A = adv[:, None]

    ratio = torch.exp(logp - old_logp)                          # ρ_{i,t}
    surr = torch.min(ratio * A, ratio.clamp(1 - eps, 1 + eps) * A)

    with torch.no_grad():                                       # (b) off-policy sequence masking, eq. (9)
        seq_div = ((old_logp - logp) * tok_mask).sum(-1) / n_tok    # mean log(π_old/π_θ)
        keep = ~((adv < 0) & (seq_div > delta))                 # drop only negative-advantage, high-divergence sequences
    M = keep[:, None].to(logp.dtype)

    log_r = ref_logp - logp                                     # log(π_ref/π_θ)
    k3 = torch.exp(log_r) - log_r - 1
    kl = ratio * k3                                             # (a) eq. (7): gradient also flows through the ratio

    per_tok = surr * M - beta * kl
    per_seq = (per_tok * tok_mask).sum(-1) / n_tok              # 1/|y_i| Σ_t
    return -per_seq.mean()                                      # maximise 1/G Σ_i → loss has the opposite sign
 

→ Go deeper: Engineering away the training–inference mismatch — Keep Routing, Keep Sampling Mask and their counterparts at other labs, side by side. The frontier RL landscape writes V3.2’s full objective (unbiased KL, off-policy sequence masking) into the same per-token template as every other lab’s.

3. Using tools while reasoning: context management

R1 discarded the previous reasoning whenever the next message arrived. In an agent, where every tool call appends a message, this rule forces the model to rethink the problem from scratch at every call. V3.2’s rule (§3.2.1) is two lines.

  • Past reasoning is discarded only when a new user message arrives. While only tool-related messages (tool results etc.) are appended, it is kept.
  • Even when reasoning is discarded, the record of tool calls and their results is kept.

The report also notes a side effect. Frameworks that emulate tool interaction with user messages, such as Roo Code or Terminus, discard the reasoning every time and get no benefit, so the non-thinking model is recommended for such environments. Indeed, the thinking score of 46.4 on Terminal Bench 2.0 was measured with the Claude Code framework; on Terminus it was 39.3 with non-thinking.

→ Go deeper: Long-horizon RL — context management, credit and budgets over long agent trajectories.

NumPy IS 보정 K3는 값과 gradient 모두 불편이다 (식 7)
import numpy as np
rng = np.random.default_rng(1)
V = 12                                               # 한 토큰 위치의 어휘 (장난감)
def softmax(z): e = np.exp(z - z.max()); return e / e.sum()

z_ref = rng.normal(size=V)
z_th  = z_ref + rng.normal(scale=1.0, size=V)        # 학습 중 정책: ref에서 꽤 멀어짐
z_old = z_th + rng.normal(scale=0.5, size=V)         # rollout을 만든 정책 (몇 step 전 + 추론 엔진 차이)
p_ref, p_th, p_old = softmax(z_ref), softmax(z_th), softmax(z_old)

kl_true = np.sum(p_th * np.log(p_th / p_ref))        # KL(π_θ || π_ref)
k3  = lambda y: p_ref[y] / p_th[y] - np.log(p_ref[y] / p_th[y]) - 1
rho = lambda y: p_th[y] / p_old[y]                   # π_θ / π_old

# 1) 값의 기대값: 샘플이 π_old에서 왔다는 점이 핵심
ys = np.arange(V)
print(f"진짜 KL(π_θ||π_ref)          = {kl_true:.4f}")
print(f"E_old[K3]        (보정 없음)  = {np.sum(p_old * k3(ys)):.4f}   ← π_old 기준이라 어긋남")
print(f"E_old[ρ·K3]      (식 7)       = {np.sum(p_old * rho(ys) * k3(ys)):.4f}   ← 정확히 일치")

# 2) 몬테카를로로도 확인 (토큰 4096개)
y = rng.choice(V, size=4096, p=p_old)
print(f"MC 4096: K3 {k3(y).mean():.4f} ± {k3(y).std()/64:.4f} | ρ·K3 {(rho(y)*k3(y)).mean():.4f} ± {(rho(y)*k3(y)).std()/64:.4f}")

# 3) gradient(θ의 logit z_θ에 대해)의 기대값.  ∇_z log π_θ(y) = e_y − π_θ
def grad_logp(y): g = -p_th.copy(); g[y] += 1; return g
true_grad = p_th * (np.log(p_th / p_ref) - kl_true)  # ∇_z KL(π_θ||π_ref) (해석해)
g_k3   = sum(p_old[y] * (1 - p_ref[y] / p_th[y]) * grad_logp(y) for y in ys)            # 계수 (1 − π_ref/π_θ)
g_corr = sum(p_old[y] * rho(y) * np.log(p_th[y] / p_ref[y]) * grad_logp(y) for y in ys) # 계수 ρ·log(π_θ/π_ref)
print(f"\n|E[∇K3] − ∇KL|   = {np.abs(g_k3 - true_grad).max():.4f}")
print(f"|E[∇ρK3] − ∇KL|  = {np.abs(g_corr - true_grad).max():.2e}")
# on-policy(π_old = π_θ)여도 K3를 그대로 미분하면 다른 KL의 gradient가 나온다
g_k3_on = sum(p_th[y] * (1 - p_ref[y] / p_th[y]) * grad_logp(y) for y in ys)
print(f"on-policy E[∇K3] − ∇KL(π_θ||π_ref) = {np.abs(g_k3_on - true_grad).max():.4f},"
      f"  − ∇KL(π_ref||π_θ) = {np.abs(g_k3_on - (p_th - p_ref)).max():.2e}")

# 4) π_θ ≪ π_ref 인 토큰에서 두 계수의 크기
for r in [0.5, 0.1, 0.01, 0.001]:                    # r = π_θ/π_ref
    print(f"π_θ/π_ref={r:<6} K3 계수 {1 - 1/r:9.1f} | 보정 계수(ρ=1) {np.log(r):6.2f}")
 

결과를 읽는 법: 값으로는 보정 없는 K3가 0.24 근처로 진짜 KL 0.21에서 벗어나고, gradient로는 on-policy에서조차 K3가 ∇DKL(πref∥πθ)\nabla D_{\text{KL}}(\pi_{\text{ref}}\|\pi_\theta)와 수치 오차 수준으로 일치한다. 즉 “K3 손실을 미분해 쓰는” 흔한 구현은 의도와 다른 방향의 KL을 최소화하고 있었다. 마지막 줄이 그림 왼쪽 패널의 두 곡선이다.

보고서는 덧붙여 도메인마다 KL 세기가 달라야 한다고, 수학 같은 도메인에서는 KL을 약하게 하거나 아예 빼는 편이 나았다고 쓴다. KL 항을 고치는 일과 KL을 쓸지 말지는 별개라는 뜻이다.

아래는 네 수정 중 손실에 드러나는 (a)와 (b)를 한 함수에 넣은 PyTorch 버전이다. (c)와 (d)는 손실이 아니라 rollout 엔진이 저장해 학습 forward에 넘겨 주는 상태(routing 인덱스, truncation mask)라서 주석으로만 표시했다.

PyTorch V3.2식 GRPO 손실 (PyTorch, 읽기 전용) 로컬에서 실행run locally (pip install torch)
import torch

def grpo_v32_loss(logp, old_logp, ref_logp, tok_mask, rewards,
                  beta=1e-3, eps=0.2, delta=0.1):
    """
    logp     : (G, T) 현재 정책 log π_θ(y_t | ·). Keep Routing으로 rollout 때의 expert 경로를,
               Keep Sampling Mask로 rollout 때의 top-p 잘린 어휘를 그대로 써서 계산했다고 가정.
    old_logp : (G, T) 추론 엔진이 샘플링할 때 돌려준 log π_old (학습 엔진에서 다시 계산한 값이 아님)
    ref_logp : (G, T) log π_ref
    tok_mask : (G, T) 응답 토큰이면 1, padding이면 0
    rewards  : (G,)   한 프롬프트에 대한 G개 응답의 보상
    """
    n_tok = tok_mask.sum(-1).clamp(min=1)                       # |y_i|
    adv = (rewards - rewards.mean()).detach()                   # Â_i = R_i − mean(R) (std로 나누지 않음)
    A = adv[:, None]

    ratio = torch.exp(logp - old_logp)                          # ρ_{i,t}
    surr = torch.min(ratio * A, ratio.clamp(1 - eps, 1 + eps) * A)

    with torch.no_grad():                                       # (b) off-policy sequence masking, 식 (9)
        seq_div = ((old_logp - logp) * tok_mask).sum(-1) / n_tok    # 평균 log(π_old/π_θ)
        keep = ~((adv < 0) & (seq_div > delta))                 # 음의 advantage + 발산 큰 시퀀스만 제외
    M = keep[:, None].to(logp.dtype)

    log_r = ref_logp - logp                                     # log(π_ref/π_θ)
    k3 = torch.exp(log_r) - log_r - 1
    kl = ratio * k3                                             # (a) 식 (7): ratio를 통해서도 gradient가 흐른다

    per_tok = surr * M - beta * kl
    per_seq = (per_tok * tok_mask).sum(-1) / n_tok              # 1/|y_i| Σ_t
    return -per_seq.mean()                                      # 1/G Σ_i 를 최대화 → 손실은 부호 반대
 

→ 더 깊이: 학습–추론 불일치 엔지니어링 — Keep Routing, Keep Sampling Mask와 다른 lab의 대응책을 나란히 비교한다. 프론티어 RL 목적함수 지도는 V3.2의 목적함수 전체(불편 KL, off-policy 시퀀스 mask)를 다른 lab과 같은 토큰별 틀에 적어 넣는다.

3. 추론하면서 tool 쓰기: context 관리

R1은 다음 메시지가 오면 이전 추론을 버렸다. tool 호출마다 메시지가 하나씩 붙는 에이전트에서는 이 규칙 때문에 모델이 호출할 때마다 문제를 처음부터 다시 생각해야 한다. V3.2의 규칙(3.2.1절)은 두 줄이다.

  • 과거 추론은 새 user 메시지가 올 때만 버린다. tool 관련 메시지(tool 결과 등)만 붙는 동안에는 유지한다.
  • 추론을 버릴 때도 tool 호출과 그 결과의 기록은 남긴다.

부작용도 적었다. Roo Code나 Terminus처럼 tool 상호작용을 user 메시지로 흉내 내는 프레임워크에서는 매번 추론이 버려져 이득을 못 보므로, 그런 환경에는 non-thinking 모델을 권한다. 실제로 Terminal Bench 2.0의 thinking 점수 46.4는 Claude Code 프레임워크로 잰 값이고, Terminus에서는 non-thinking으로 39.3이었다.

→ 더 깊이: Long-horizon RL — 긴 agent 궤적의 context 관리, credit, 예산.

총 생성 토큰total generated tokens – 최대 문맥peak context – 총 prefill(입력) 토큰total prefill (input) tokens –
All numbers are toy values (user message 150, tool call 60, tool result 900, fresh reasoning needed per call 800 tokens, 3 user turns). Each bar is one model call; the lower part is that call's input context (grey = user and tool messages, light violet = past reasoning still kept), the upper part (blue) is the reasoning newly generated in that call. Pick R1-style and past reasoning disappears every time, so we assume the model must re-think α times the reasoning it lost; the blue part grows as the calls pile up. V3.2 keeps reasoning while tool results are appended and clears it only at a new user message (dashed line). The tool-calling path of V4 does not clear it even at user-turn boundaries — the least generation, but the longest context. 숫자는 모두 장난감 값이다(user 메시지 150, tool 호출 60, tool 결과 900, 호출 한 번에 새로 필요한 추론 800 토큰, user 턴 3개). 막대 하나가 모델 호출 한 번이고, 아래 칸은 그 호출의 입력 문맥(회색 = user·tool 메시지, 연보라 = 남아 있는 과거 추론), 위 칸(파랑)은 그 호출에서 새로 생성한 추론이다. R1식을 고르면 과거 추론이 매번 사라지므로, 사라진 추론의 α배를 다시 생각해야 한다고 가정했다. 그래서 호출이 거듭될수록 파란 칸이 커진다. V3.2는 tool 결과가 붙는 동안 추론을 유지하고 새 user 메시지에서만 비운다(점선). V4의 tool-calling 경로는 user 턴 경계에서도 비우지 않는다 — 생성은 가장 적지만 문맥이 가장 길다.

This rule is paired with training. In the cold start (§3.2.2) there is reasoning data (a system prompt telling the model to think first inside <think>) and non-reasoning agentic data (a system prompt specifying the tool-call format), but no trajectory that combines the two. So a system prompt saying “call the Python tool multiple times (up to 20) during reasoning” (Appendix Table 8) gets the model to produce a trajectory of the desired shape occasionally, and those become the starting point for RL. The report candidly says the trajectories at this stage “may not be robust” — quality comes from RL.

Experimental results

Main benchmarks

이 규칙은 학습과 짝을 이룬다. Cold-start(3.2.2절)에서는 추론 데이터(시스템 프롬프트가 <think> 안에서 먼저 생각하라고 지시)와 비추론 에이전트 데이터(도구 호출 형식을 지시)를 갖고 있을 뿐, 둘을 합친 trajectory는 없다. 그래서 “추론 중에 Python 도구를 여러 번(최대 20회) 부르라”는 시스템 프롬프트(부록 Table 8)로 모델이 가끔 원하는 형태의 trajectory를 내게 하고, 그것을 RL의 출발점으로 삼는다. 보고서는 이 단계의 trajectory가 “robust하지 않을 수 있다”고 솔직히 적었다 — 품질은 RL이 만든다.

실험 결과

주요 벤치마크

Pick an area, and click a model name in the legend to switch it on or off. Bar lengths are relative within each row, scaled to that row's best score (because percentages and ratings are mixed); the number next to each bar is the raw value from the report. An empty slot means the report gives no value. Source: report Table 2 (BrowseComp* = with context management). 분야를 고르고, 범례의 모델 이름을 눌러 켜고 끌 수 있다. 막대 길이는 행마다 그 행의 최고점을 기준으로 맞춘 상대값이고(% 지표와 rating이 섞여 있기 때문), 막대 옆 숫자가 보고서에 적힌 원래 값이다. 빈칸은 보고서에 값이 없는 경우다. 출처: 보고서 Table 2 (BrowseComp* = context 관리 적용).

Evaluation settings (§4.1): temperature 1.0, 128K context, the standard function-call format of thinking mode for tool benchmarks, and MCP benchmarks measured in internal environments. Three things to read off.

  • Reasoning is similar to GPT-5 High and below Gemini-3.0-Pro. The report says as much. These scores are with the length-constraint reward on; lifting the constraint (Speciale) pushes them higher.
  • On agentic benchmarks the gap to open models is large. τ²-Bench 80.3 (with V3.2 itself in the user role as well; airline 63.8, retail 81.1, telecom 96.2), MCP-Mark 38.0 and Tool-Decathlon 35.2 put it well ahead of Kimi-K2-Thinking and MiniMax-M2. The report cites the fact that these benchmarks’ environments and tool sets were never seen in RL as evidence of generalisation.
  • The context limit costs points. On BrowseComp, more than 20% of cases exceed 128K. The report also says that on the GitHub and Playwright tasks of MCP-Mark, V3.2 often went past 128K by lengthening its trajectory with redundant self-verification.

Non-thinking mode (Appendix Table 9) is a little below thinking but competitive: Terminal Bench 2.0 37.1 vs 46.4, SWE Verified 72.1 vs 73.1, τ²-bench 77.2 vs 80.3, MCP-Mark 26.5 vs 38.0. SWE Verified was steady at 72–74 in every setting: internal framework, Claude Code, RooCode, and non-thinking.

Accuracy and tokens: Speciale

평가 설정(4.1절): 온도 1.0, 문맥 128K, tool 벤치마크는 thinking 모드의 표준 function call 형식, MCP 벤치마크는 내부 환경에서 재었다. 읽을 점은 셋이다.

  • 추론은 GPT-5 High와 비슷하고 Gemini-3.0-Pro보다 낮다. 보고서도 그렇게 쓴다. 이 점수는 길이 제약 보상을 건 상태이고, 제약을 풀면(Speciale) 더 오른다.
  • 에이전트 벤치마크에서 공개 모델 대비 격차가 크다. τ²-Bench 80.3(user 역할도 V3.2 자신; 항공 63.8, 소매 81.1, 통신 96.2), MCP-Mark 38.0, Tool-Decathlon 35.2로 Kimi-K2-Thinking·MiniMax-M2를 크게 앞선다. 보고서는 이 벤치마크의 환경·도구 세트가 RL에서 본 적 없다는 점을 일반화의 근거로 든다.
  • context 한계가 점수를 깎는다. BrowseComp에서 20% 이상의 사례가 128K를 넘는다. MCP-Mark의 GitHub·Playwright 과제에서도 V3.2가 중복 자기검증으로 trajectory를 늘려 128K를 넘는 일이 잦았다고 적었다.

Non-thinking 모드(부록 Table 9)는 thinking보다 조금 낮지만 경쟁력이 있다: Terminal Bench 2.0 37.1 vs 46.4, SWE Verified 72.1 vs 73.1, τ²-bench 77.2 vs 80.3, MCP-Mark 26.5 vs 38.0. SWE Verified는 내부 프레임워크·Claude Code·RooCode·non-thinking 어느 설정에서도 72–74로 일정했다.

정확도와 토큰: Speciale

The numbers of report Table 3, plotted as they are. The horizontal axis is the mean number of output tokens (thousands), the vertical axis accuracy (Pass@1; rating for CodeForces). Switch benchmarks: V3.2-Speciale (the variant with a reduced length penalty) is always up and to the right of V3.2 — more tokens for higher accuracy — and on the math benchmarks it even passes Gemini-3.0-Pro. Gemini-3.0-Pro, by contrast, usually reaches similar or higher accuracy with far fewer tokens (token efficiency). Kimi-K2-Thinking is also on the token-hungry side. Kimi-K2-Thinking's CodeForces value is not in the report. 보고서 Table 3의 숫자를 그대로 찍었다. 가로축은 평균 출력 토큰 수(천 단위), 세로축은 정확도(Pass@1, CodeForces는 rating). 벤치마크를 바꿔 보면 V3.2-Speciale(길이 벌점을 줄인 변형)이 언제나 V3.2보다 오른쪽 위 — 더 많은 토큰으로 더 높은 정확도 — 에 있고, 수학 벤치마크에서는 Gemini-3.0-Pro를 넘기도 한다. 반면 Gemini-3.0-Pro는 비슷하거나 더 높은 정확도를 대개 훨씬 적은 토큰으로 낸다(토큰 효율). Kimi-K2-Thinking도 많은 토큰을 쓰는 쪽이다. Kimi-K2-Thinking의 CodeForces 값은 보고서에 없다.
Competition (report Table 4)ScoreMedal
IMO 202535/42 (full marks on P1–P5, 0 on P6)Gold
CMO 2025102/126Gold
IOI 2025492/600 (10th)Gold
ICPC WF 202510/12 problems (2nd)Gold

On every benchmark in Table 3, Speciale uses 1.4–2.3× more tokens than V3.2 (CodeForces: 42k → 77k) to raise accuracy. The report itself admits that Speciale’s token efficiency is “significantly inferior” to Gemini-3.0-Pro’s, and says it deliberately put a stronger length constraint on the deployed V3.2. For IOI, 500 candidates were drawn per problem, samples failing the sample tests, the length constraint, or saying “cannot be solved” were filtered out, and the 50 with the longest reasoning were submitted (Appendix D; the rules allow 50 submissions per problem). The competition scores include this submission strategy.

Are the synthetic agentic tasks hard, and do they generalise?

Report §4.3 asks two questions about the synthetic tasks.

Pass@K (Table 5, 50 general synthetic tasks)V3.2-ExpSonnet-4.5Gemini-3.0-ProGPT-5-Thinking
112%34%51%62%
218%47%65%75%
426%62%74%82%

The model used for synthesis solves only 12% itself, and the best model 62% — hard enough to be worth RL. Generalisation is tested by an experiment that runs RL from V3.2’s SFT checkpoint on the general-agent synthetic tasks alone, in non-thinking mode (Figure 5). This RL raised τ²-Bench, MCP-Mark and MCP-Universe substantially, whereas V3.2-Exp, trained with RL only in code and search environments, did not improve on these three benchmarks. There is only a figure, with no table of numbers.

Test-time context management for the search agent

When token usage passes 80% of the context, one of three strategies is applied: (1) Summary: summarise the overflowing trajectory and restart; (2) Discard-75%: drop the first 75% of the tool-call history; (3) Discard-all: drop the entire tool-call history (similar to a new-context tool). The baseline is parallel scaling, which picks the trajectory with the fewest steps out of N independent ones. On BrowseComp the score of 51.4 without management rose to at most 60.2 with Summary (stretching to an average of 364 steps, but with low efficiency) and to 67.6 with Discard-all, matching parallel scaling with far fewer steps (§4.4, Figure 6). Worth noticing: the simplest strategy was the best, and the report itself concludes that “benchmark scores should be reported together with the actual compute cost”.

확인 문제Check yourself

Why does V3.2's off-policy sequence masking never mask positive-advantage sequences, however large their divergence? Which is closest to the report's explanation?

The report’s sentence: “the model benefits the most by learning from its own mistakes, whereas highly off-policy negative samples can be detrimental.” The mask is 0 only for sequences that have negative advantage and whose sequence-mean log⁡(πold/πθ)\log(\pi_{\text{old}}/\pi_\theta) exceeds δ\delta. Intuitively, a signal to lower further the probability of a sequence the current policy already hardly produces carries little information, and since πθ\pi_\theta is small for those tokens the gradient coefficients tend to be large. Conversely, a sequence that led to a good outcome is judged worth reinforcing even if it is off-policy. Clipping only bounds the token ratio; it does not create this asymmetry.

Reading critically

  • The DSA ablations are thin. Parity with dense is supported only by a sentence saying it is “similar” and by mentions of ChatbotArena Elo and external long-context evaluations; there are no ablations varying top-k or indexer size, and no comparison with other sparse attention (NSA etc.) under the same conditions. Even basic settings such as the number and dimension of indexer heads have to be looked up in the public config rather than the text.
  • The cost claim is a figure only. Figure 3, the basis for the “significant end-to-end speedup”, is a per-token-position cost curve on H800 serving, with no table. As computed above, at long positions the indexer is most of the remaining cost, so the gain can vary a lot with the implementation (FP8 indexer, kernels).
  • The effect of the RL fixes is not quantified. All four GRPO fixes are described qualitatively (“helped stability”, “was crucial”). There are no learning curves or on/off comparisons, and the values of δ\delta, β\beta, ε\varepsilon are not given. Dropping the std from the advantage also appears only in an equation, without explanation.
  • The denominator of “RL compute above 10%” is unclear. The report does not say whether it means the total pre-training cost up to V3.1-Terminus, or in what unit. Whether the specialists’ RL compute is included is also unknown.
  • Differences in agentic evaluation settings. MCP-Universe and MCP-Mark were measured in internal environments, the headline SWE Verified number in the internal framework, and Terminal Bench 2.0 in the Claude Code framework. In τ²-Bench the user simulator is also V3.2 itself. Whether the other models’ numbers came from the same harness cannot be confirmed from the table alone. BrowseComp 67.6 includes test-time context management.
  • Possible contamination of synthetic environments. The search-agent data is QA built from long-tail web entities, and BrowseComp is also long-tail web questions. The report says only that the RL environments do not overlap with the evaluation environments, without describing any question- or entity-level overlap check.
  • Interpreting Speciale’s competition scores. As the IOI submission strategy (500 samples → filters → the 50 longest) shows, competition results include a sampling budget and selection rules. The sentence “a general model without competition-specific training” is true, but it is not the same as single-sample ability.

Summary

  • DSA ranks the preceding tokens with a lightning indexer (eq. 1: a weighted sum of per-head ReLU scores, keys shared across heads, FP8-capable) and computes the main attention only over the top-k=2048k=2048. It sits on MLA’s MQA mode, so the selected latents are shared by all 128 heads.
  • The indexer is first fitted by KL to the head-summed distribution of dense attention (2.1B tokens), then trained further in the sparse regime with KL over the selected set, with its input detached so that its loss is separated from the main model (943.7B tokens). The main attention becomes O(Lk)O(Lk), but the indexer remains O(L2)O(L^2).
  • For RL beyond 10% of pre-training, GRPO was fixed in four places: IS-corrected K3 (unbiased in value and gradient, with a coefficient that grows only at a log⁡\log rate), masking that drops only negative-advantage, high-divergence sequences, Keep Routing, and Keep Sampling Mask.
  • On the agentic side, the key pieces are the “keep reasoning during tool results” context rule, a cold-start prompt that interleaves reasoning and tool calls, and 1,827 environments synthesised together with solution and verification functions and filtered by pass@100 > 0; RL on the synthetic tasks alone generalised to unseen tool benchmarks.
  • The results are GPT-5 High level in reasoning and the best among open models in agentic tasks, but token efficiency and the 128K context remain limits. The follow-up V4 goes after exactly these two points (long-context cost, how far reasoning is kept).
대회 (보고서 Table 4)점수메달
IMO 202535/42 (P1–P5 만점, P6 0점)Gold
CMO 2025102/126Gold
IOI 2025492/600 (10위)Gold
ICPC WF 202510/12 문제 (2위)Gold

Speciale은 Table 3의 모든 벤치마크에서 V3.2보다 1.4–2.3배 많은 토큰을 쓰며(CodeForces는 42k → 77k) 정확도를 올린다. 보고서도 Speciale의 토큰 효율이 Gemini-3.0-Pro보다 “significantly inferior”하다고 인정하고, 배포판 V3.2에는 일부러 더 강한 길이 제약을 걸었다고 적었다. IOI는 문제당 후보 500개를 뽑아 샘플 테스트·길이 제약·“풀 수 없다”고 말한 샘플을 걸러낸 뒤 추론이 가장 긴 50개를 제출했다(부록 D, 규정상 문제당 50회 제출 가능). 대회 점수는 이런 제출 전략까지 포함한 값이다.

합성 에이전트 과제는 어렵고, 일반화되는가

보고서 4.3절은 합성 과제에 두 가지를 묻는다.

Pass@K (Table 5, general 합성 과제 50개)V3.2-ExpSonnet-4.5Gemini-3.0-ProGPT-5-Thinking
112%34%51%62%
218%47%65%75%
426%62%74%82%

합성에 쓴 모델 자신은 12%만 풀고, 최고 모델도 62%다 — RL에 쓸 만큼 어렵다. 일반화는 V3.2의 SFT checkpoint에 general agent 합성 과제만으로, non-thinking 모드로 RL한 실험으로 본다(Figure 5). 이 RL은 τ²-Bench, MCP-Mark, MCP-Universe를 크게 올린 반면, 코드·검색 환경에서만 RL한 V3.2-Exp는 이 세 벤치마크에서 오르지 않았다. 그림만 있고 표 숫자는 없다.

검색 에이전트의 test-time context 관리

토큰 사용이 context의 80%를 넘으면 (1) Summary: 넘친 trajectory를 요약하고 다시 시작, (2) Discard-75%: 앞쪽 tool 호출 기록 75%를 버림, (3) Discard-all: tool 호출 기록을 모두 버림(새 context 도구와 비슷) 중 하나를 쓴다. 비교 기준은 독립 trajectory N개 중 step이 가장 적은 것을 고르는 병렬 스케일링이다. BrowseComp에서 관리 없이 51.4이던 점수가 Summary로 최대 60.2(평균 364 step까지 늘어나지만 효율은 낮음), Discard-all로 67.6이 되어 병렬 스케일링과 비슷한 점수를 훨씬 적은 step으로 냈다(4.4절, Figure 6). 가장 단순한 전략이 가장 좋았다는 것, 그리고 보고서 스스로 “벤치마크 점수에는 실제 계산 비용을 함께 적어야 한다”고 결론 내린 것이 눈여겨볼 점이다.

확인 문제Check yourself

V3.2의 off-policy sequence masking이 양(+)의 advantage 시퀀스는 아무리 발산이 커도 마스크하지 않는 이유로 보고서의 설명에 가장 가까운 것은?

보고서 문장: “the model benefits the most by learning from its own mistakes, whereas highly off-policy negative samples can be detrimental.” 마스크는 음의 advantage 이면서 시퀀스 평균 log⁡(πold/πθ)\log(\pi_{\text{old}}/\pi_\theta)가 δ\delta를 넘는 경우에만 0이다. 직관적으로, 현재 정책이 이미 거의 내지 않는 시퀀스의 확률을 더 낮추라는 신호는 정보가 적고, 그 토큰들은 πθ\pi_\theta가 작아 gradient 계수가 커지기 쉽다. 반대로 off-policy여도 좋은 결과를 낸 시퀀스는 강화할 가치가 있다고 본 것이다. clip은 토큰 ratio 범위만 제한할 뿐 이 비대칭을 만들지 않는다.

비판적으로 읽기

  • DSA의 ablation이 얇다. dense 대비 parity는 “비슷하다”는 문장과 ChatbotArena Elo·외부 장문 평가 언급으로만 뒷받침되고, top-k나 indexer 크기를 바꾼 ablation, 같은 조건의 다른 sparse attention(NSA 등)과의 비교가 없다. indexer head 수·차원 같은 기본 설정조차 본문이 아니라 공개 config에서 찾아야 한다.
  • 비용 주장은 그림뿐이다. “significant end-to-end speedup”의 근거인 Figure 3은 H800 서비스 기준 토큰 위치별 비용 곡선이고 표가 없다. 위에서 계산했듯 긴 위치에서는 indexer가 남은 비용의 대부분이므로, 구현(FP8 indexer, kernel)에 따라 이득이 크게 달라질 수 있다.
  • RL 수정의 효과가 정량화되지 않았다. 네 가지 GRPO 수정은 모두 “안정성에 도움이 됐다”, “crucial했다”는 정성적 서술이다. 학습 곡선이나 on/off 비교가 없고, δ\delta·β\beta·ε\varepsilon 값도 적혀 있지 않다. advantage에서 std를 뺀 것도 설명 없이 식으로만 나타난다.
  • “10% 이상의 RL 계산”의 분모가 불분명하다. V3.1-Terminus까지의 총 사전학습 비용인지, 어떤 단위인지 밝히지 않는다. specialist들의 RL 계산이 포함되는지도 알 수 없다.
  • 에이전트 평가의 설정 차이. MCP-Universe·MCP-Mark는 내부 환경에서, SWE Verified 대표값은 내부 프레임워크에서, Terminal Bench 2.0은 Claude Code 프레임워크에서 쟀다. τ²-Bench는 user 시뮬레이터도 V3.2 자신이다. 다른 모델의 숫자가 같은 harness에서 나왔는지는 표만으로 확인할 수 없다. BrowseComp 67.6은 test-time context 관리가 들어간 값이다.
  • 합성 환경의 오염 가능성. search agent 데이터는 웹 long-tail 엔티티에서 만든 QA이고 BrowseComp도 웹 long-tail 질문이다. 보고서는 RL 환경이 평가 환경과 겹치지 않는다고만 말할 뿐, 질문·엔티티 수준의 중복 검사는 설명하지 않는다.
  • Speciale의 대회 점수 해석. IOI 제출 전략(500개 샘플 → 필터 → 가장 긴 50개)처럼 대회 결과에는 샘플링 예산과 선택 규칙이 들어 있다. “범용 모델이 대회 특화 학습 없이”라는 문장은 맞지만, 단일 샘플 능력과는 다르다.

정리

  • DSA는 lightning indexer(식 1: head별 ReLU 점수의 가중합, key는 head 공유, FP8 가능)로 앞선 토큰의 순위를 매기고 주 attention은 top-k=2048k=2048에만 계산한다. MLA의 MQA 모드 위에 얹어 선택된 latent를 128개 head가 공유한다.
  • indexer는 먼저 dense attention의 head-합 분포에 KL로 맞추고(2.1B 토큰), 이어 sparse 상태에서 선택 집합 위의 KL로 계속 학습하되 입력을 detach해 주 모델과 손실을 분리했다(943.7B 토큰). 주 attention은 O(Lk)O(Lk)가 되지만 indexer는 O(L2)O(L^2)로 남는다.
  • 사전학습의 10%를 넘는 RL을 위해 GRPO를 네 군데 고쳤다: IS로 보정한 K3(값·gradient 모두 불편, 계수가 log⁡\log 속도로만 증가), 음의 advantage + 큰 발산 시퀀스만 버리는 masking, Keep Routing, Keep Sampling Mask.
  • 에이전트 쪽은 “tool 결과 동안 추론 유지” context 규칙, 추론과 tool 호출을 섞는 cold-start 프롬프트, 풀이·검증 함수를 함께 합성하고 pass@100 > 0으로 거른 1,827개 환경이 핵심이며, 합성 과제만으로 한 RL이 처음 보는 tool 벤치마크로 일반화됐다.
  • 결과는 추론에서 GPT-5 High 수준, 에이전트에서 공개 모델 최고 수준이지만 토큰 효율과 128K 문맥이 한계로 남는다. 후속작 V4는 바로 이 두 지점(긴 문맥 비용, 추론 유지 범위)을 이어서 공략한다.

더 읽을거리Further reading