Track VI · Frontier Tech Reports · 05/20

DeepSeek-V4 — 백만 토큰 문맥을 싸게 만드는 법 (+V4.1-Flash)DeepSeek-V4 — how to make a million-token context cheap (+V4.1-Flash)

KV를 시퀀스 방향으로 압축한 뒤 sparse하게 읽는 CSA, 128토큰을 한 항목으로 묶는 HCA, 잔차 행렬을 doubly stochastic 다양체에 가두는 mHC, Muon의 하이브리드 Newton–Schulz, 다중 교사 on-policy distillation을 식과 코드로 따라가고, KV를 토큰당 890바이트까지 줄인 후속작 V4.1-Flash의 CED·CSA2까지 계산해 본다.We follow, in equations and code, CSA (compress the KV along the sequence, then read it sparsely), HCA (pack 128 tokens into one entry), mHC (confine the residual matrix to the doubly stochastic manifold), Muon's hybrid Newton–Schulz and multi-teacher on-policy distillation, and then compute the CED and CSA2 of the follow-up V4.1-Flash, which cuts the KV to 890 bytes per token.

DeepSeek-V3 shrank the entry size of the KV cache with MLA, and V3.2 used DSA to cut the number of entries a query reads to a top-k. Even so, V3.2 stores the KV of every token in every layer, and its indexer still scans the whole context. Once reasoning models and agents began producing trajectories hundreds of thousands of tokens long, this became the bottleneck. DeepSeek-V4 (April 2026, preview) alternates two kinds of attention that compress the KV along the sequence (CSA and HCA) so that a 1M-token context is routine, and it replaces the residual connection with mHC and the optimizer with Muon. V4.1-Flash, released five months later, goes one step further in the same direction: it shares KV across layers as well and brings the global KV down to 890 bytes per token. This lesson derives the architecture of both reports in equations and recomputes their numbers ourselves.

At a glance

DeepSeek-V4-FlashDeepSeek-V4-ProDeepSeek-V4.1-Flash
Release2026-04 (preview)2026-04 (preview)2026-09
Parameters (total / active)284B / 13B1.6T / 49B552B backbone + 196B Engram / prefill 8B, decode 16B
Layers / hidden43 / 409661 / 716840 (encoder 20 + decoder 20) / 5120
Attention2 SWA layers + alternating CSA·HCA2 HCA layers + alternating CSA·HCA2 SWA layers + CSA2 (Full/Reindex/Reuse)
MoE1 shared + 6 of 256 routed1 shared + 6 of 384 routed1 shared + 6 of 384 routed
Context1M1M1M
Pre-training tokens32T33T45T (multimodal)
OptimizerMuon + AdamWMuon + AdamWMuon (head-wise) + AdamW + Sinkhorn-balanced
Opennessweights released (Hugging Face)weights releasedweights released
LinkarXiv 2606.19348samearXiv 2609.19969

(V4 report §4.2.1, §4.2.2; V4.1 report §2.1, §4.2. Neither report states the licence terms in its body.)

What is new

  • CSA + HCA hybrid attention. CSA compresses 4 tokens into one KV entry and then reads only a top-k of them with V3.2’s lightning indexer; HCA compresses 128 tokens into one entry and reads all of them. Every layer also has a 128-token sliding-window branch. At 1M context the report gives V4-Pro 27% of V3.2’s single-token inference FLOPs and 10% of its KV cache (abstract, §1).
  • mHC. In Hyper-Connections, which widen the residual stream 4×, the residual matrix is constrained to be doubly stochastic so that the signal does not blow up as layers are stacked.
  • Muon. Most matrix parameters are trained with Muon, and the Newton–Schulz iteration becomes “8 fast steps + 2 stabilising steps”.
  • On-policy distillation instead of RL for the merge stage of post-training. Domain experts are grown with SFT + GRPO and then merged into a single model by minimising a full-vocabulary reverse KL against more than ten teachers (§5.1).
  • V4.1-Flash: a Causal Encoder-Decoder in which half the decoder builds its KV from the encoder’s last layer, CSA2 which reuses KV and top-k indices across layers, and FP4 main KV bring the global KV to about 1/4 of V4-Flash’s.

Architecture

V4 keeps V3’s skeleton of Transformer + DeepSeekMoE + MTP (§2.1). The MoE changes in three places. The affinity function changes from Sigmoid⁡\operatorname{Sigmoid} to Softplus⁡(⋅)\sqrt{\operatorname{Softplus}(\cdot)}; V3’s node-limited routing constraint (at most 4 nodes per token) is dropped; and the early layers, where V3 used dense FFNs, become hash-routing MoE. Hash routing picks the expert by feeding the token ID into a fixed hash function (Roller et al. 2021). It reads as a judgement that in the early layers a token’s contextual representation is still shallow, so a learned router gains little (the report gives no reason). Auxiliary-loss-free load balancing, a very small sequence-wise balance loss and MTP depth 1 are unchanged from V3.

What is new is the attention and the residual connection.

→ Go deeper: The DeepSeek lineage — the V2 → V3 → V3.2 → V4 → V4.1 path that leads to this attention.

Why compress along the sequence

The size of the KV cache is a product of three axes.

KV bytes=(bytes per entry)⏟MHA→GQA→MLA×(entries stored)⏟sequence compression×(layers with KV)⏟cross-layer sharing\text{KV bytes} = \underbrace{(\text{bytes per entry})}_{\text{MHA→GQA→MLA}} \times \underbrace{(\text{entries stored})}_{\text{sequence compression}} \times \underbrace{(\text{layers with KV})}_{\text{cross-layer sharing}}

The V4.1 report uses this framing explicitly (V4.1 §2.3). GQA and MLA shrink the first axis, V4’s CSA/HCA the second, and V4.1’s CSA2 the third. V3.2’s DSA shrinks none of them: it cuts only the amount read (compute) to a top-k, and storage is unchanged.

CSA: compress, then read sparsely

From the input hidden states H∈Rn×dH\in\mathbb{R}^{n\times d}, CSA builds two sets of KV candidates and two sets of compression weights (report Eqs. 9–10).

Ca=HWaKV,Cb=HWbKV,Za=HWaZ,Zb=HWbZ,W⋅∈Rd×cC^a = HW^{aKV},\quad C^b = HW^{bKV},\qquad Z^a = HW^{aZ},\quad Z^b = HW^{bZ},\qquad W^{\cdot}\in\mathbb{R}^{d\times c}

The ii-th compressed entry is a weighted sum over 2m2m tokens: CaC^a of its own block [mi, m(i+1)−1][mi,\,m(i+1)-1] and CbC^b of the immediately preceding block [m(i−1), mi−1][m(i-1),\,mi-1] (Eqs. 11–12).

[Smi:m(i+1)−1a; Sm(i−1):mi−1b]=Softmax⁡row([Zmi:m(i+1)−1a+Ba; Zm(i−1):mi−1b+Bb])[S^a_{mi:m(i+1)-1};\,S^b_{m(i-1):mi-1}] = \operatorname{Softmax}_{\text{row}}\big([Z^a_{mi:m(i+1)-1}+B^a;\ Z^b_{m(i-1):mi-1}+B^b]\big)CiComp=∑j=mim(i+1)−1Sja⊙Cja+∑j=m(i−1)mi−1Sjb⊙CjbC^{\text{Comp}}_i = \sum_{j=mi}^{m(i+1)-1} S^a_j\odot C^a_j + \sum_{j=m(i-1)}^{mi-1} S^b_j\odot C^b_j

The softmax normalises over the 2m2m positions separately for each channel (which is why ⊙\odot is a Hadamard product), and Ba,Bb∈Rm×cB^a, B^b\in\mathbb{R}^{m\times c} are learned biases for each position inside the block. The window is 2m2m, but it overlaps half of each neighbouring entry, so the number of entries is n/mn/m. The overlap appears to be there so that information straddling a block boundary is not cut off from one of the entries.

Next, V3.2’s lightning indexer is run over the compressed entries. The indexer keys are compressed in the same way to give KIComp∈Rnm×cIK^{\text{IComp}}\in\mathbb{R}^{\frac nm\times c^I}, and the query side is made low-rank (Eqs. 13–16).

ctQ=htWDQ,qtI=ctQWIUQ,wtI=htWw,It,s=∑h=1nhIwt,hI ReLU⁡(qt,hI⋅KsIComp)\mathbf c^Q_t = \mathbf h_t W^{DQ},\quad \mathbf q^I_t = \mathbf c^Q_t W^{IUQ},\quad \mathbf w^I_t = \mathbf h_t W^{w},\qquad I_{t,s} = \sum_{h=1}^{n^I_h} w^I_{t,h}\,\operatorname{ReLU}\big(\mathbf q^I_{t,h}\cdot K^{\text{IComp}}_s\big)

Only the kk compressed entries with the highest scores are kept (Eq. 17). The causality condition is s<⌊t/m⌋s<\lfloor t/m\rfloor: an entry whose block is not yet full may contain future tokens, so it cannot be seen.

The core attention is MQA. A compressed entry is both key and value (a single head), and all query heads share it (Eqs. 18–19). The low-rank query latent ctQ\mathbf c^Q_t is shared with the indexer query. Because the output cnhcn_h — the number of heads nhn_h times the head dimension c=512c=512 — is large (512×128=65,536512\times128=65{,}536 in V4-Pro), the output projection is also split in two. The nhn_h heads are grouped into gg groups, each group is reduced to dgd_g dimensions, and the gdggd_g dimensions are then mapped to dd (grouped output projection). Counting with V4-Pro’s setting (g=16, dg=1024, d=7168g=16,\ d_g=1024,\ d=7168), the projection parameters drop from 65,536×7,168≈47065{,}536\times7{,}168\approx470 million for a single projection to 16×4,096×1,024+16,384×7,168≈18516\times4{,}096\times1{,}024 + 16{,}384\times7{,}168\approx185 million (our calculation).

HCA: compress heavily and read everything

HCA applies the same compression without overlap and at a much larger ratio m′=128m'=128 (Eqs. 20–23).

Sm′i:m′(i+1)−1=Softmax⁡row(Zm′i:m′(i+1)−1+B),CiComp=∑j=m′im′(i+1)−1Sj⊙CjS_{m'i:m'(i+1)-1}=\operatorname{Softmax}_{\text{row}}(Z_{m'i:m'(i+1)-1}+B),\qquad C^{\text{Comp}}_i=\sum_{j=m'i}^{m'(i+1)-1}S_j\odot C_j

It then reads all compressed entries densely, with no sparse selection. At 1M context there are about 8 thousand entries, so dense reading is cheap. The same query effectively alternates between “pick and read at 4-token resolution” in CSA layers and “scan everything at 128-token resolution” in HCA layers.

Small parts

  • q·KV normalisation. Just before the core attention, RMSNorm is applied to each query head and to the KV entries. It keeps attention logits from blowing up, so Muon does not need QK-Clip (§2.3.3, §2.4).
  • Partial RoPE and counter-rotation of the output. RoPE is applied only to the last 64 dimensions of the queries and KV entries. But since a KV entry also serves as the value, the output ot=∑jstjR(j)vj\mathbf o_t=\sum_j s_{tj}R(j)\mathbf v_j carries the rotation of the absolute position jj. So RoPE for position −t-t is applied once more to the last 64 dimensions of the output.
R(−t) ot=∑jstj R(−t)R(j) vj=∑jstj R(j−t) vjR(-t)\,\mathbf o_t=\sum_j s_{tj}\,R(-t)R(j)\,\mathbf v_j=\sum_j s_{tj}\,R(j-t)\,\mathbf v_j

Because rotation matrices satisfy R(a)R(b)=R(a+b)R(a)R(b)=R(a+b), only the relative distance j−tj-t remains in the output.

  • Sliding-window branch. Alongside the compressed entries, each query also sees the uncompressed KV of the most recent nwin=128n_{\text{win}}=128 tokens. This covers the stretch where its own block is not yet full (the part it cannot see as compressed entries because of causality) and fine-grained dependencies in the nearby context.
  • Attention sink. A sink logit zh′z'_h, learned per head, is added to the denominator (Eq. 27). It lets a head decide that “there is nothing to look at” — that is, the attention weights can sum to less than 1.
sh,i,j=exp⁡(zh,i,j)∑kexp⁡(zh,i,k)+exp⁡(zh′)s_{h,i,j}=\frac{\exp(z_{h,i,j})}{\sum_k\exp(z_{h,i,k})+\exp(z'_h)}

The figure below shows, as a scaled-down toy, how these components fit together for one query.

DeepSeek-V3는 MLA로 KV cache의 항목 크기를 줄였고, V3.2는 DSA로 query가 읽는 항목 수를 top-k로 줄였다. 그래도 V3.2는 모든 토큰의 KV를 모든 층에 저장하고, indexer는 여전히 문맥 전체를 훑는다. 추론 모델과 agent가 수십만 토큰짜리 궤적을 만들기 시작하면서 이것이 병목이 되었다. DeepSeek-V4(2026년 4월, preview)는 KV를 시퀀스 방향으로 압축하는 두 종류의 attention(CSA, HCA)을 교대로 쌓아 1M 토큰 문맥을 일상적으로 지원하고, 잔차 연결을 mHC로, optimizer를 Muon으로 바꿨다. 다섯 달 뒤 나온 V4.1-Flash는 같은 방향으로 한 걸음 더 가서 층 방향까지 KV를 공유해 global KV를 토큰당 890바이트로 줄였다. 이 레슨은 두 보고서의 구조를 식으로 유도하고, 숫자를 직접 다시 계산해 본다.

한눈에

DeepSeek-V4-FlashDeepSeek-V4-ProDeepSeek-V4.1-Flash
발표2026-04 (preview)2026-04 (preview)2026-09
파라미터 (총 / 활성)284B / 13B1.6T / 49B552B backbone + 196B Engram / prefill 8B, decode 16B
층 / hidden43 / 409661 / 716840 (인코더 20 + 디코더 20) / 5120
AttentionSWA 2층 + CSA·HCA 교대HCA 2층 + CSA·HCA 교대SWA 2층 + CSA2 (Full/Reindex/Reuse)
MoE공유 1 + routed 256 중 6공유 1 + routed 384 중 6공유 1 + routed 384 중 6
문맥1M1M1M
사전학습 토큰32T33T45T (멀티모달)
OptimizerMuon + AdamWMuon + AdamWMuon(head-wise) + AdamW + Sinkhorn-balanced
공개가중치 공개 (Hugging Face)가중치 공개가중치 공개
링크arXiv 2606.19348같음arXiv 2609.19969

(V4 보고서 §4.2.1, §4.2.2; V4.1 보고서 §2.1, §4.2. 라이선스 조건은 두 보고서 본문에 적혀 있지 않다.)

무엇이 새로운가

  • CSA + HCA 하이브리드 attention. CSA는 4토큰을 한 KV 항목으로 압축한 뒤 V3.2의 lightning indexer로 top-k만 읽고, HCA는 128토큰을 한 항목으로 압축해 전부 읽는다. 모든 층에 128토큰 sliding window 가지가 붙는다. 1M 문맥에서 V4-Pro는 V3.2 대비 단일 토큰 추론 FLOPs 27%, KV cache 10%라고 보고한다(초록, §1).
  • mHC. 잔차 스트림을 4배로 넓히는 Hyper-Connections에서 잔차 행렬을 doubly stochastic 행렬로 제한해, 깊이 쌓아도 신호가 폭발하지 않게 했다.
  • Muon. 대부분의 행렬 파라미터를 Muon으로 학습하고, Newton–Schulz 반복을 “빠른 8회 + 안정화 2회”로 바꿨다.
  • 사후학습의 통합 단계를 RL 대신 on-policy distillation으로. 도메인별 전문가를 SFT + GRPO로 키운 뒤, 열 개가 넘는 교사로부터 full-vocabulary reverse KL을 줄여 하나의 모델로 합친다(§5.1).
  • V4.1-Flash: 디코더 절반이 인코더 마지막 층에서 KV를 만드는 Causal Encoder-Decoder, 층 사이에 KV와 top-k 인덱스를 재사용하는 CSA2, FP4 main KV로 global KV를 V4-Flash의 약 1/4로 줄였다.

아키텍처

V4는 Transformer + DeepSeekMoE + MTP라는 V3의 뼈대를 유지한다(§2.1). MoE는 세 군데가 바뀌었다. affinity 함수가 Sigmoid⁡\operatorname{Sigmoid}에서 Softplus⁡(⋅)\sqrt{\operatorname{Softplus}(\cdot)}로 바뀌었고, V3의 node-limited routing(토큰당 최대 4노드) 제약을 없앴으며, V3가 dense FFN을 쓰던 앞쪽 층을 Hash routing MoE로 바꿨다. Hash routing은 토큰 ID를 고정된 hash 함수에 넣어 expert를 정한다(Roller et al. 2021). 앞쪽 층에서는 토큰의 문맥 표현이 아직 얕으니 학습된 router가 얻는 것이 적다는 판단으로 읽힌다(보고서는 이유를 따로 적지 않는다). auxiliary-loss-free 부하 균형과 아주 작은 sequence-wise balance loss, MTP 깊이 1은 V3 그대로다.

새로운 것은 attention과 잔차 연결이다.

→ 더 깊이: DeepSeek 계보 — 이 attention에 이르는 V2 → V3 → V3.2 → V4 → V4.1의 흐름.

왜 시퀀스 방향 압축인가

KV cache의 크기는 세 축의 곱이다.

KV bytes=(항목당 바이트)⏟MHA→GQA→MLA×(저장하는 항목 수)⏟시퀀스 압축×(KV를 가진 층 수)⏟층 간 공유\text{KV bytes} = \underbrace{(\text{항목당 바이트})}_{\text{MHA→GQA→MLA}} \times \underbrace{(\text{저장하는 항목 수})}_{\text{시퀀스 압축}} \times \underbrace{(\text{KV를 가진 층 수})}_{\text{층 간 공유}}

V4.1 보고서가 이 틀을 명시적으로 쓴다(V4.1 §2.3). GQA와 MLA는 첫째 축을, V4의 CSA/HCA는 둘째 축을, V4.1의 CSA2는 셋째 축을 줄인다. V3.2의 DSA는 어느 축도 줄이지 않는다. 읽는 양(연산)만 top-k로 줄이고 저장은 그대로다.

CSA: 압축한 뒤 sparse하게 읽기

입력 hidden state H∈Rn×dH\in\mathbb{R}^{n\times d}에서 CSA는 KV 후보 두 벌과 압축 가중치 두 벌을 만든다(보고서 식 9–10).

Ca=HWaKV,Cb=HWbKV,Za=HWaZ,Zb=HWbZ,W⋅∈Rd×cC^a = HW^{aKV},\quad C^b = HW^{bKV},\qquad Z^a = HW^{aZ},\quad Z^b = HW^{bZ},\qquad W^{\cdot}\in\mathbb{R}^{d\times c}

ii번째 압축 항목은 자기 블록 [mi, m(i+1)−1][mi,\,m(i+1)-1]의 CaC^a와 바로 앞 블록 [m(i−1), mi−1][m(i-1),\,mi-1]의 CbC^b, 합쳐 2m2m개 토큰의 가중합이다(식 11–12).

[Smi:m(i+1)−1a; Sm(i−1):mi−1b]=Softmax⁡row([Zmi:m(i+1)−1a+Ba; Zm(i−1):mi−1b+Bb])[S^a_{mi:m(i+1)-1};\,S^b_{m(i-1):mi-1}] = \operatorname{Softmax}_{\text{row}}\big([Z^a_{mi:m(i+1)-1}+B^a;\ Z^b_{m(i-1):mi-1}+B^b]\big)CiComp=∑j=mim(i+1)−1Sja⊙Cja+∑j=m(i−1)mi−1Sjb⊙CjbC^{\text{Comp}}_i = \sum_{j=mi}^{m(i+1)-1} S^a_j\odot C^a_j + \sum_{j=m(i-1)}^{mi-1} S^b_j\odot C^b_j

softmax는 2m2m개 위치에 걸쳐 채널마다 따로 정규화되고(⊙\odot가 Hadamard 곱인 이유), Ba,Bb∈Rm×cB^a, B^b\in\mathbb{R}^{m\times c}는 블록 안 위치별 학습 bias다. 창이 2m2m이지만 이웃 항목과 절반씩 겹치므로 항목 수는 n/mn/m이다. 겹치게 만든 이유는 블록 경계에 걸친 정보가 한쪽 항목에서 잘리지 않게 하기 위해서로 보인다.

다음은 V3.2의 lightning indexer를 압축 항목 위에서 돌리는 것이다. indexer key도 같은 방식으로 압축해 KIComp∈Rnm×cIK^{\text{IComp}}\in\mathbb{R}^{\frac nm\times c^I}를 만들고, query 쪽은 저랭크로 만든다(식 13–16).

ctQ=htWDQ,qtI=ctQWIUQ,wtI=htWw,It,s=∑h=1nhIwt,hI ReLU⁡(qt,hI⋅KsIComp)\mathbf c^Q_t = \mathbf h_t W^{DQ},\quad \mathbf q^I_t = \mathbf c^Q_t W^{IUQ},\quad \mathbf w^I_t = \mathbf h_t W^{w},\qquad I_{t,s} = \sum_{h=1}^{n^I_h} w^I_{t,h}\,\operatorname{ReLU}\big(\mathbf q^I_{t,h}\cdot K^{\text{IComp}}_s\big)

점수가 높은 kk개 압축 항목만 남긴다(식 17). 인과성 조건은 s<⌊t/m⌋s<\lfloor t/m\rfloor다. 블록이 다 차지 않은 항목은 미래 토큰을 포함할 수 있으니 볼 수 없다.

core attention은 MQA다. 압축 항목 하나가 key이자 value이고(head가 하나), 모든 query head가 그것을 공유한다(식 18–19). query 저랭크 latent ctQ\mathbf c^Q_t는 indexer query와 같이 쓴다. head 수 nhn_h와 head 차원 c=512c=512를 곱한 출력 cnhcn_h가 크므로(V4-Pro에서 512×128=65,536512\times128=65{,}536), 출력 투영도 둘로 나눈다. nhn_h개 head를 gg개 그룹으로 묶어 그룹마다 dgd_g차원으로 줄인 뒤, gdggd_g차원을 dd로 보낸다(grouped output projection). V4-Pro 설정(g=16, dg=1024, d=7168g=16,\ d_g=1024,\ d=7168)으로 세어 보면 투영 파라미터가 한 번에 보낼 때의 65,536×7,168≈4.7065{,}536\times7{,}168\approx4.70억 개에서 16×4,096×1,024+16,384×7,168≈1.8516\times4{,}096\times1{,}024 + 16{,}384\times7{,}168\approx1.85억 개로 줄어든다(우리 계산).

HCA: 크게 압축하고 전부 읽기

HCA는 같은 압축을 겹침 없이, 훨씬 큰 비율 m′=128m'=128로 한다(식 20–23).

Sm′i:m′(i+1)−1=Softmax⁡row(Zm′i:m′(i+1)−1+B),CiComp=∑j=m′im′(i+1)−1Sj⊙CjS_{m'i:m'(i+1)-1}=\operatorname{Softmax}_{\text{row}}(Z_{m'i:m'(i+1)-1}+B),\qquad C^{\text{Comp}}_i=\sum_{j=m'i}^{m'(i+1)-1}S_j\odot C_j

그리고 sparse 선택 없이 모든 압축 항목을 dense하게 읽는다. 1M 문맥이면 항목이 약 8천 개라 dense로 읽어도 싸다. 같은 query가 CSA 층에서는 “4토큰 해상도로 골라 읽기”, HCA 층에서는 “128토큰 해상도로 전부 훑기”를 번갈아 하는 셈이다.

작은 부품들

  • q·KV 정규화. core attention 직전에 query의 각 head와 KV 항목에 RMSNorm을 건다. attention logit 폭발을 막아 Muon에서 QK-Clip을 쓰지 않아도 되게 한다(§2.3.3, §2.4).
  • 부분 RoPE와 출력의 역회전. query와 KV 항목의 마지막 64차원에만 RoPE를 건다. 그런데 KV 항목이 value로도 쓰이므로 출력 ot=∑jstjR(j)vj\mathbf o_t=\sum_j s_{tj}R(j)\mathbf v_j가 절대 위치 jj의 회전을 품게 된다. 그래서 출력의 마지막 64차원에 위치 −t-t의 RoPE를 한 번 더 건다.
R(−t) ot=∑jstj R(−t)R(j) vj=∑jstj R(j−t) vjR(-t)\,\mathbf o_t=\sum_j s_{tj}\,R(-t)R(j)\,\mathbf v_j=\sum_j s_{tj}\,R(j-t)\,\mathbf v_j

회전행렬이 R(a)R(b)=R(a+b)R(a)R(b)=R(a+b)를 만족하므로 출력에는 상대 거리 j−tj-t만 남는다.

  • Sliding window 가지. 각 query는 압축 항목과 함께 최근 nwin=128n_{\text{win}}=128개 토큰의 압축하지 않은 KV도 본다. 자기 블록이 덜 찬 구간(인과성 때문에 압축 항목으로 못 보는 부분)과 가까운 문맥의 세밀한 의존성을 메운다.
  • Attention sink. head마다 학습되는 sink logit zh′z'_h를 분모에 더한다(식 27). 한 head가 “볼 것이 없다”는 판단을 할 수 있게, 즉 attention 합이 1보다 작아질 수 있게 한다.
sh,i,j=exp⁡(zh,i,j)∑kexp⁡(zh,i,k)+exp⁡(zh′)s_{h,i,j}=\frac{\exp(z_{h,i,j})}{\sum_k\exp(z_{h,i,k})+\exp(z'_h)}

아래 그림은 이 구성 요소들이 한 query에서 어떻게 맞물리는지를 축소된 장난감으로 보여 준다.

full attention – CSA – HCA – 관련 토큰 중 CSA+SWA가 닿은 수relevant tokens reached by CSA+SWA –
A 192-token toy context (a scaled-down version of the real setting: SWA window nwin=12, HCA m′=16). Dark cells in the top row are the relevant tokens the query "needs". Drag t and the KV each query actually reads changes: light green is the most recent nwin uncompressed tokens (the SWA branch), blue cells in the middle row are the CSA compressed entries chosen by the lightning indexer, and the bottom row is the HCA compressed entries (all read densely). Click a CSA cell to show above it the 2m raw tokens (the overlapping window) used to build that entry. A query cannot see tokens whose block has not finished as compressed entries (s < ⌊t/m⌋); SWA fills that gap. The readouts are counted on the toy, and the scores are fake indexer scores made by adding noise to the relevant-token positions. 192토큰짜리 장난감 문맥(실제 설정의 축소판: SWA 창 nwin=12, HCA m′=16). 맨 위 줄의 진한 칸은 query가 "필요로 하는" 관련 토큰이다. t를 끌면 각 query가 실제로 읽는 KV가 바뀐다: 연두색은 압축하지 않은 최근 nwin개 토큰(SWA 가지), 가운데 줄의 파란 칸은 lightning indexer가 고른 CSA 압축 항목, 아래 줄은 HCA 압축 항목(전부 dense로 읽음). CSA 칸을 클릭하면 그 항목을 만드는 데 쓰인 2m개 원시 토큰(겹치는 창)이 위에 표시된다. query는 자기 블록이 끝나지 않은 토큰을 압축 항목으로 볼 수 없다(s < ⌊t/m⌋). 그 틈을 SWA가 메운다. 지표는 장난감에서 센 값이고, 점수는 관련 토큰 위치에 잡음을 섞은 가짜 indexer 점수다.
  1. As you move t, the grey (not yet visible) region of the CSA row never reaches right up to the query. That gap is always covered by the light-green SWA window.
  2. Reduce top-k to 1 and some relevant tokens are missed. The real CSA has a trained indexer and k=1024 in V4-Pro, far more generous than the toy.
  3. Increase m and one CSA entry covers more tokens. The same k reaches further, but more tokens are mixed into each entry, so resolution drops. HCA is the extreme of this.

How much smaller: computing the KV cache

The report’s storage format (§2.3.4) keeps the 64 RoPE dimensions of a KV entry in BF16 and the remaining 448 dimensions in FP8. One entry is then 448+64×2=576448+64\times2=576 bytes. The CSA indexer key (cI=128c^I=128) is stored in MXFP4 after post-training QAT (§5.2.1), so we count it as 6464 bytes + 1 byte of scale per 32 elements, i.e. 6868 bytes. With these, V4-Pro’s global KV per token is

30×576+684⏟CSA, m=4+31×576128⏟HCA, m′=128≈4,830+140=4,970 B/token\underbrace{30\times\frac{576+68}{4}}_{\text{CSA, }m=4}+\underbrace{31\times\frac{576}{128}}_{\text{HCA, }m'=128}\approx 4{,}830+140=4{,}970\ \text{B/token}

(our estimate, assuming 2 HCA layers followed by 59 layers alternating and starting with CSA; the report does not give the alternation order or the FP8 scale overhead). Stacking BF16 GQA8 (head dim 128) to the same 61 layers gives 61×2×8×128×2=249,85661\times2\times8\times128\times2=249{,}856 B/token, so the ratio is about 2.0%. This matches the report’s “about 2% of a BF16 GQA8 baseline at 1M context” (§2.3.4). Compared with V3’s MLA (61 layers × 576 dimensions × BF16 = 70,272 B/token) it is about 7%.

→ Go deeper: Sparse attention compares CSA/HCA with NSA, DSA and QSA; Long-context serving covers what compressed KV and the sliding-window branch mean when serving 1M tokens.

  1. t를 움직이면 CSA 줄의 회색(아직 볼 수 없는) 영역이 query 바로 앞까지 오지 않는다. 그 빈틈은 항상 연두색 SWA 창이 덮는다.
  2. top-k를 1로 줄이면 관련 토큰 중 일부를 놓친다. 실제 CSA는 indexer가 학습되어 있고 V4-Pro에서 k=1024라, 장난감보다 훨씬 넉넉하다.
  3. m을 키우면 CSA 항목 하나가 더 많은 토큰을 덮는다. 같은 k로 더 넓게 보지만 항목 하나에 섞이는 토큰이 많아져 해상도가 떨어진다. HCA는 그 극단이다.

얼마나 줄었나: KV cache 계산

보고서의 저장 형식(§2.3.4)은 KV 항목의 RoPE 64차원은 BF16, 나머지 448차원은 FP8이다. 그러면 항목 하나가 448+64×2=576448+64\times2=576바이트다. CSA indexer key(cI=128c^I=128)는 사후학습의 QAT 이후 MXFP4로 저장되니(§5.2.1) 6464바이트 + 32원소마다 1바이트 scale로 6868바이트로 잡는다. 이것으로 V4-Pro의 토큰당 global KV를 세면

30×576+684⏟CSA, m=4+31×576128⏟HCA, m′=128≈4,830+140=4,970 B/토큰\underbrace{30\times\frac{576+68}{4}}_{\text{CSA, }m=4}+\underbrace{31\times\frac{576}{128}}_{\text{HCA, }m'=128}\approx 4{,}830+140=4{,}970\ \text{B/토큰}

이다(앞 2층 HCA 뒤 59층이 CSA부터 교대한다고 가정한 우리 추정. 보고서는 교대 순서와 FP8 scale 오버헤드를 적지 않는다). BF16 GQA8(head dim 128)을 같은 61층으로 쌓으면 61×2×8×128×2=249,85661\times2\times8\times128\times2=249{,}856 B/토큰이니 비율은 약 2.0%다. 보고서가 말하는 “1M 문맥에서 BF16 GQA8 기준선의 약 2%”(§2.3.4)와 맞는다. V3의 MLA(61층 × 576차원 × BF16 = 70,272 B/토큰)와 비교하면 약 7%다.

→ 더 깊이: Sparse attention은 CSA/HCA를 NSA·DSA·QSA와 비교하고, 긴 문맥 서빙은 압축 KV와 sliding window 가지가 1M 토큰 서빙에서 무엇을 뜻하는지 다룬다.

선택selected – global KV/토큰token – 요청 하나one request – GQA8 대비vs GQA8 – V3 MLA 대비vs V3 MLA –
Click a bar to show that model's KV composition below. Drag N from 4K to 1M: at short contexts the SWA state (green, a fixed block independent of length) takes a large share even for the V4 family, and as the context grows the CSA terms (blue, violet) dominate. HCA (amber) packs 128 tokens into one entry and is barely visible even at 1M. Only V4.1-Flash's 890 B/token is a reported value; V4-Flash/Pro and the SWA sizes are our estimates computed from the report's configuration (§2.3, §4.2.1) (the CSA/HCA alternation order and the FP8 scale overhead are not in the report, so they are assumed). The GQA8 baseline assumes 61 layers, head dim 128, BF16. 막대를 클릭하면 아래에 그 모델의 KV 구성이 나온다. N을 4K→1M으로 끌어 보면 짧은 문맥에서는 V4 계열에서도 SWA 상태(초록, 길이와 무관한 고정 블록)가 큰 비중을 차지하다가, 문맥이 길어질수록 CSA 항(파랑·보라)이 지배하는 것이 보인다. HCA(호박색)는 128토큰을 한 항목으로 묶어 1M에서도 거의 보이지 않는다. V4.1-Flash의 890 B/토큰만 보고서 값이고, V4-Flash/Pro와 SWA 크기는 보고서 설정(§2.3, §4.2.1)으로 우리가 계산한 추정치다(CSA/HCA 교대 순서와 FP8 scale 오버헤드는 보고서에 없어 가정). GQA8 기준선은 61층·head dim 128·BF16으로 가정했다.

At short contexts, the green in the figure — the SWA state — makes up most of the V4 family’s KV. The 128 uncompressed tokens of KV per layer are a fixed cost independent of context length, so the shorter the context, the larger their share. The V4 report also notes that when stored on disk the SWA KV is about 8× larger than the compressed CSA/HCA entries, and it provides three storage strategies for it (store everything, periodic checkpoints, or store nothing and recompute nwin⋅Ln_{\text{win}}\cdot L tokens) (§3.5.2). This problem comes back in V4.1.

mHC: widen the residual stream without blowing up

Hyper-Connections (HC) widen the residual stream from Rd\mathbb{R}^d to Rnhc×d\mathbb{R}^{n_{\text{hc}}\times d}. The layer function Fl\mathcal F_l (attention or MoE) still takes and returns dd dimensions, and three small matrices connect the stream and the layer (Eq. 1).

Xl+1=BlXl+Cl Fl(AlXl),Al∈R1×nhc, Bl∈Rnhc×nhc, Cl∈Rnhc×1X_{l+1}=B_lX_l+C_l\,\mathcal F_l(A_lX_l),\qquad A_l\in\mathbb{R}^{1\times n_{\text{hc}}},\ B_l\in\mathbb{R}^{n_{\text{hc}}\times n_{\text{hc}}},\ C_l\in\mathbb{R}^{n_{\text{hc}}\times1}

With nhc=1, A=B=C=1n_{\text{hc}}=1,\ A=B=C=1 this is the ordinary residual xl+1=xl+Fl(xl)x_{l+1}=x_l+\mathcal F_l(x_l). Since nhcn_{\text{hc}} is much smaller than dd (4 in V4), compute barely grows while a new scaling axis — residual width — appears. The problem is depth. Leaving out the layer-function contributions, the residual path after LL layers is BL⋯B1B_L\cdots B_1, and if the spectral norm of BlB_l is even slightly above 1 the product grows exponentially. The report notes that stacking many HC layers often made training numerically unstable (§2.2).

mHC constrains BlB_l to the set of doubly stochastic matrices (the Birkhoff polytope) (Eq. 2).

M={M∈Rn×n∣M1=1, 1⊤M=1⊤, M≥0}\mathcal M=\{M\in\mathbb R^{n\times n}\mid M\mathbf 1=\mathbf 1,\ \mathbf 1^\top M=\mathbf 1^\top,\ M\ge0\}

The properties this constraint gives are proved in three lines.

  • Row and column sums are 1 and the entries are non-negative, so ∥M∥1=∥M∥∞=1\|M\|_1=\|M\|_\infty=1. Since ∥M∥2≤∥M∥1∥M∥∞=1\|M\|_2\le\sqrt{\|M\|_1\|M\|_\infty}=1, it is non-expansive. The signal grows neither in the forward pass nor in the backward pass, where the transpose is applied.
  • If M1,M2∈MM_1,M_2\in\mathcal M, then M1M21=M11=1M_1M_2\mathbf 1=M_1\mathbf 1=\mathbf 1, 1⊤M1M2=1⊤\mathbf 1^\top M_1M_2=\mathbf 1^\top, and the entries are non-negative, so M1M2∈MM_1M_2\in\mathcal M. It is closed under multiplication, so however many layers are stacked, the whole residual path is still non-expansive.
  • 1⊤(BlXl)=1⊤Xl\mathbf 1^\top(B_lX_l)=\mathbf 1^\top X_l. The residual path exactly preserves the sum of the streams and only mixes mass between them.

AlA_l and ClC_l are made non-negative and bounded with a sigmoid (Al=σ(A~l), Cl=2σ(C~l)A_l=\sigma(\tilde A_l),\ C_l=2\sigma(\tilde C_l); Eqs. 6–7), to keep signals from cancelling each other. All three matrices depend on the input. From X^l\hat X_l, the flattened and RMS-normalised XlX_l, a linear map produces a dynamic component, which is multiplied by a gate α\alpha initialised to a small value and added to a static bias SS (Eqs. 3–5).

B~l=αlres⋅Mat⁡(X^lWlres)+Slres,Bl=Sinkhorn⁡(exp⁡(B~l))\tilde B_l=\alpha^{\text{res}}_l\cdot\operatorname{Mat}(\hat X_lW^{\text{res}}_l)+S^{\text{res}}_l,\qquad B_l=\operatorname{Sinkhorn}\big(\exp(\tilde B_l)\big)

After exp⁡\exp makes the entries positive, the Sinkhorn–Knopp iteration M(t)=Tr(Tc(M(t−1)))M^{(t)}=\mathcal T_r(\mathcal T_c(M^{(t-1)})), alternating column and row normalisation, is run for tmax⁡=20t_{\max}=20 steps (Eq. 8). For a positive matrix this iteration converges to a doubly stochastic matrix.

→ Go deeper: Stability components — mHC next to other residual variants and norm placements.

짧은 문맥에서는 그림의 초록색, 즉 SWA 상태가 V4 계열 KV의 대부분이다. 층마다 128토큰의 압축 안 된 KV는 문맥 길이와 무관한 고정 비용이라, 문맥이 짧을수록 비중이 커진다. V4 보고서도 디스크에 저장할 때 SWA KV가 압축된 CSA/HCA 항목보다 약 8배 크다고 적고, 이를 위한 저장 전략 세 가지(전체 저장, 주기적 checkpoint, 저장하지 않고 nwin⋅Ln_{\text{win}}\cdot L 토큰 재계산)를 둔다(§3.5.2). 이 문제는 V4.1에서 다시 등장한다.

mHC: 잔차 스트림을 넓히되 폭발하지 않게

Hyper-Connections(HC)는 잔차 스트림을 Rd\mathbb{R}^d에서 Rnhc×d\mathbb{R}^{n_{\text{hc}}\times d}로 넓힌다. 층 함수 Fl\mathcal F_l(attention이나 MoE)은 여전히 dd차원을 받고 내보내며, 세 개의 작은 행렬이 스트림과 층을 잇는다(식 1).

Xl+1=BlXl+Cl Fl(AlXl),Al∈R1×nhc, Bl∈Rnhc×nhc, Cl∈Rnhc×1X_{l+1}=B_lX_l+C_l\,\mathcal F_l(A_lX_l),\qquad A_l\in\mathbb{R}^{1\times n_{\text{hc}}},\ B_l\in\mathbb{R}^{n_{\text{hc}}\times n_{\text{hc}}},\ C_l\in\mathbb{R}^{n_{\text{hc}}\times1}

nhc=1, A=B=C=1n_{\text{hc}}=1,\ A=B=C=1이면 보통의 residual xl+1=xl+Fl(xl)x_{l+1}=x_l+\mathcal F_l(x_l)이다. nhcn_{\text{hc}}는 dd보다 훨씬 작으니(V4는 4) 연산은 거의 늘지 않으면서 잔차 폭이라는 새 스케일링 축이 생긴다. 문제는 깊이다. 층 함수 기여를 빼면 LL층 뒤의 잔차 경로는 BL⋯B1B_L\cdots B_1이고, BlB_l의 spectral norm이 1보다 조금만 커도 곱은 지수적으로 커진다. 보고서는 HC를 여러 층 쌓으면 학습이 자주 수치적으로 불안정해졌다고 적는다(§2.2).

mHC는 BlB_l을 doubly stochastic 행렬의 집합(Birkhoff polytope)으로 제한한다(식 2).

M={M∈Rn×n∣M1=1, 1⊤M=1⊤, M≥0}\mathcal M=\{M\in\mathbb R^{n\times n}\mid M\mathbf 1=\mathbf 1,\ \mathbf 1^\top M=\mathbf 1^\top,\ M\ge0\}

이 제약이 주는 성질은 세 줄로 증명된다.

  • 행 합과 열 합이 1이고 원소가 음수가 아니므로 ∥M∥1=∥M∥∞=1\|M\|_1=\|M\|_\infty=1이다. ∥M∥2≤∥M∥1∥M∥∞=1\|M\|_2\le\sqrt{\|M\|_1\|M\|_\infty}=1이므로 비확장(non-expansive) 이다. 순전파에서도, 전치가 곱해지는 역전파에서도 신호가 커지지 않는다.
  • M1,M2∈MM_1,M_2\in\mathcal M이면 M1M21=M11=1M_1M_2\mathbf 1=M_1\mathbf 1=\mathbf 1, 1⊤M1M2=1⊤\mathbf 1^\top M_1M_2=\mathbf 1^\top, 원소도 음수가 아니므로 M1M2∈MM_1M_2\in\mathcal M이다. 곱에 대해 닫혀 있으니 몇 층을 쌓아도 잔차 경로 전체가 여전히 비확장이다.
  • 1⊤(BlXl)=1⊤Xl\mathbf 1^\top(B_lX_l)=\mathbf 1^\top X_l이다. 잔차 경로는 스트림들의 합을 정확히 보존하고, 스트림 사이에 질량을 섞기만 한다.

AlA_l과 ClC_l은 sigmoid로 음이 아니고 유계가 되게 한다(Al=σ(A~l), Cl=2σ(C~l)A_l=\sigma(\tilde A_l),\ C_l=2\sigma(\tilde C_l); 식 6–7). 신호가 서로 상쇄되는 것을 막기 위해서다. 세 행렬은 입력에 따라 달라진다. XlX_l을 펼쳐 RMSNorm한 X^l\hat X_l에서 선형 사상으로 동적 성분을 만들고, 작은 값으로 초기화한 게이트 α\alpha를 곱해 정적 bias SS에 더한다(식 3–5).

B~l=αlres⋅Mat⁡(X^lWlres)+Slres,Bl=Sinkhorn⁡(exp⁡(B~l))\tilde B_l=\alpha^{\text{res}}_l\cdot\operatorname{Mat}(\hat X_lW^{\text{res}}_l)+S^{\text{res}}_l,\qquad B_l=\operatorname{Sinkhorn}\big(\exp(\tilde B_l)\big)

exp⁡\exp로 양수를 만든 뒤 열 정규화와 행 정규화를 번갈아 하는 Sinkhorn–Knopp 반복 M(t)=Tr(Tc(M(t−1)))M^{(t)}=\mathcal T_r(\mathcal T_c(M^{(t-1)}))을 tmax⁡=20t_{\max}=20회 돌린다(식 8). 양수 행렬에서 이 반복은 doubly stochastic 행렬로 수렴한다.

→ 더 깊이: 안정화 부품 — mHC를 다른 residual 변형, norm 위치와 함께 본다.

‖B‖₂ – max |행 합row sum−1| – max |열 합col sum−1| – 61층 후after 61 layers ‖∏B‖₂: HC – · mHC –
The left panel is one layer's residual matrix Bl. At t=0 it is exp(Braw) as is (positive, but with arbitrary row and column sums); as t increases, alternating column and row normalisation converges to a doubly stochastic matrix whose row and column sums are all 1 (the report uses tmax=20). Then ‖B‖₂ ≤ 1. The right panel is the spectral norm (log axis) of the whole residual path ∏Bl over a 61-layer stack. For unconstrained HC (B=I+εG, red), raising ε turns a small per-layer growth into an exponential blow-up, while mHC (blue, current t) stays near 1. Lower t to 1–2 and you can see it leak a little, because the matrix is not yet exactly doubly stochastic. The matrices are random toys (raw logit = 3εG + 2I, G standard normal). 왼쪽은 한 층의 잔차 행렬 Bl이다. t=0은 exp(Braw) 그대로(양수지만 행·열 합이 제각각)이고, t를 올리면 열 정규화와 행 정규화를 번갈아 하며 행 합·열 합이 모두 1인 doubly stochastic 행렬로 수렴한다(보고서는 tmax=20). 그러면 ‖B‖₂ ≤ 1이 된다. 오른쪽은 61층을 쌓았을 때 잔차 경로 전체 ∏Bl의 spectral norm(로그 축)이다. 제약 없는 HC(B=I+εG, 빨강)는 ε를 키우면 층마다 조금씩 커지던 것이 지수적으로 폭발하고, mHC(파랑, 현재 t)는 1 근처에 머문다. t를 1–2로 낮추면 아직 정확히 doubly stochastic이 아니어서 조금씩 새는 것이 보인다. 행렬은 무작위 장난감(raw logit = 3εG + 2I, G는 표준정규)이다.

The Sinkhorn iteration is a differentiable operation, so backpropagation passes straight through it. The price is a small computation per layer — 20 normalisations of an nhc×nhcn_{\text{hc}}\times n_{\text{hc}} matrix — and memory traffic for residual activations that are nhcn_{\text{hc}} times larger. V4 absorbs this with recomputation and fused kernels (§3.4.2), and V4.1 halves that traffic again (see the V4.1 section below).

Data

V3V4V4.1-Flash
Pre-training tokens14.8T32T (Flash) / 33T (Pro), corpus over 32T45T, text + images
Tokenizerbyte-level BPE 128KV3 tokenizer + special tokens for context construction, still 128Knot described separately in the body
Document packingpacking, no cross-sample maskingpacking + sample-level attention maskingsample-level masking
Noteslarger share of math and code, FIM 0.1auto-generated and templated web documents removed (to prevent model collapse), long documents (papers, technical reports) prioritised, more languages, agentic data in mid-trainingmultimodal data from the start of pre-training

(V3 report §4.1, V4 §4.1, V4.1 §4.1–4.2.) That is about all the V4 report reveals about data. There are no domain ratios, deduplication criteria, amounts of synthetic data, or length distributions of long documents. For a model that supports 1M context, nothing about the composition of long-context data is disclosed beyond the fact that the pre-training context was extended 4K → 16K → 64K → 1M (§4.2.2).

The scale of the post-training data is not given either. What is disclosed is the structure. An expert is built for each domain (math, code, agents, instruction following, etc.); easily verified tasks are graded by rules and test cases, and hard-to-verify tasks by RL data with rubrics and a generative reward model (GRM) (§5.1.1).

Training

Pre-training recipe

V4-FlashV4-Pro
OptimizerMuon (most matrices) + AdamW (embedding, output head, RMSNorm weights, mHC static biases and gates)same
AdamWβ=(0.9,0.95)\beta=(0.9,0.95), ϵ=10−20\epsilon=10^{-20}, weight decay 0.1same
Muonmomentum 0.95, weight decay 0.1, update RMS rescaled to 0.18same
Tokens / max batch32T / 75.5M tokens33T / 94.4M tokens
LR2000-step warmup → hold at 2.7×10−42.7\times10^{-4} → cosine to 2.7×10−52.7\times10^{-5} at the endpeak 2.0×10−42.0\times10^{-4}, final 2.0×10−52.0\times10^{-5}
Context4K → 16K → 64K → 1Msame
Sparse attentiondense for the first 1T tokens, sparse after indexer warm-up at 64Klonger dense phase, same method
Load balancingbias update speed 0.001, balance loss weight 0.0001same
MTP loss weight0.3 → 0.1 from the start of LR decaysame

(V4 §4.2.2.) Compared with V3, the shape of the LR schedule (warmup → long constant phase → cosine decay at the end), the batch-size ramp and the lowered MTP weight are unchanged; the optimizer and the context-length schedule differ. V3 pre-trained at 4K and then extended to 128K with YaRN, whereas V4 reaches 1M within pre-training.

Muon and the hybrid Newton–Schulz

Muon updates matrix parameters by orthogonalising their momentum. The report’s Algorithm 1 is:

Gt=∇WLt(Wt−1),Mt=μMt−1+GtOt′=HybridNewtonSchulz⁡(μMt+Gt)(Nesterov)Ot=Ot′⋅max⁡(n,m)⋅γ,Wt=Wt−1(1−ηλ)−η Ot\begin{aligned} G_t&=\nabla_W\mathcal L_t(W_{t-1}),\qquad M_t=\mu M_{t-1}+G_t\\ O'_t&=\operatorname{HybridNewtonSchulz}(\mu M_t+G_t)\qquad(\text{Nesterov})\\ O_t&=O'_t\cdot\sqrt{\max(n,m)}\cdot\gamma,\qquad W_t=W_{t-1}(1-\eta\lambda)-\eta\,O_t \end{aligned}

For M=UΣV⊤M=U\Sigma V^\top the ideal result is UV⊤UV^\top, the matrix with every singular value set to 1. SVD is expensive, so we start from M0=M/∥M∥FM_0=M/\|M\|_F (so that the singular values are at most 1) and iterate an odd polynomial (Eq. 28).

Mk=aMk−1+b (Mk−1Mk−1⊤)Mk−1+c (Mk−1Mk−1⊤)2Mk−1M_k=aM_{k-1}+b\,(M_{k-1}M_{k-1}^\top)M_{k-1}+c\,(M_{k-1}M_{k-1}^\top)^2M_{k-1}

Substituting Mk−1=UΣV⊤M_{k-1}=U\Sigma V^\top gives (MM⊤)M=UΣ3V⊤(MM^\top)M=U\Sigma^3V^\top, so the iteration applies the scalar polynomial σ↦aσ+bσ3+cσ5\sigma\mapsto a\sigma+b\sigma^3+c\sigma^5 to each singular value independently. A one-dimensional graph therefore tells the whole story. V4 uses (a,b,c)=(3.4445,−4.7750,2.0315)(a,b,c)=(3.4445,-4.7750,2.0315) for the first 8 steps to lift small singular values quickly, then switches to (2,−1.5,0.5)(2,-1.5,0.5) for the last 2 steps to pin them exactly at 1 (§2.4). The second polynomial f(σ)=2σ−1.5σ3+0.5σ5f(\sigma)=2\sigma-1.5\sigma^3+0.5\sigma^5 has f(1)=1, f′(1)=2−4.5+2.5=0f(1)=1,\ f'(1)=2-4.5+2.5=0, so it converges quadratically near 1.

→ Go deeper: the derivations behind Muon and Newton–Schulz iterations are in Muon and orthogonalised optimisers.

Sinkhorn 반복이 미분 가능한 연산이라 역전파가 그대로 통과한다. 대가는 층마다 nhc×nhcn_{\text{hc}}\times n_{\text{hc}} 행렬에 20번의 정규화를 하는 작은 연산과, nhcn_{\text{hc}}배로 늘어난 잔차 activation의 메모리 트래픽이다. V4는 재계산과 fused kernel로 이것을 감당하고(§3.4.2), V4.1은 이 트래픽을 다시 절반으로 줄인다(아래 V4.1 절).

데이터

V3V4V4.1-Flash
사전학습 토큰14.8T32T(Flash) / 33T(Pro), 코퍼스 32T 이상45T, 텍스트+이미지
토크나이저byte-level BPE 128KV3 토크나이저 + 문맥 구성용 special token, 128K 유지본문에 별도 서술 없음
문서 packingpacking, cross-sample masking 없음packing + sample-level attention maskingsample-level masking
특기 사항수학·코드 비중 확대, FIM 0.1자동 생성·템플릿 웹 문서 제거(model collapse 방지), 긴 문서(논문·기술 보고서) 우선, 다국어 확대, mid-training에 agentic 데이터멀티모달 데이터를 사전학습 처음부터

(V3 보고서 §4.1, V4 §4.1, V4.1 §4.1–4.2.) V4 보고서가 데이터에 대해 밝히는 것은 이 정도다. 도메인 비율, 중복 제거 기준, 합성 데이터의 양, 긴 문서의 길이 분포는 없다. 1M 문맥을 지원하는 모델인데 사전학습 문맥을 4K → 16K → 64K → 1M으로 늘렸다는 것(§4.2.2) 말고는 긴 문맥 데이터 구성이 공개되지 않았다.

사후학습 데이터도 규모가 적혀 있지 않다. 공개된 것은 구조다. 도메인(수학, 코드, agent, instruction following 등)마다 전문가를 만들고, 쉽게 검증되는 과제는 규칙·테스트 케이스로, 검증이 어려운 과제는 rubric이 붙은 RL 데이터와 생성형 보상모델(GRM)로 채점한다(§5.1.1).

학습

사전학습 레시피

V4-FlashV4-Pro
OptimizerMuon(대부분의 행렬) + AdamW(embedding, 출력 head, RMSNorm 가중치, mHC의 정적 bias·게이트)같음
AdamWβ=(0.9,0.95)\beta=(0.9,0.95), ϵ=10−20\epsilon=10^{-20}, weight decay 0.1같음
Muonmomentum 0.95, weight decay 0.1, update RMS를 0.18로 재조정같음
토큰 / 최대 배치32T / 75.5M 토큰33T / 94.4M 토큰
LR2000 step warmup → 2.7×10−42.7\times10^{-4} 유지 → 끝에서 cosine으로 2.7×10−52.7\times10^{-5}피크 2.0×10−42.0\times10^{-4}, 끝 2.0×10−52.0\times10^{-5}
문맥4K → 16K → 64K → 1M같음
Sparse attention처음 1T 토큰은 dense, 64K에서 indexer warm-up 후 sparsedense 구간이 더 김, 방법은 같음
부하 균형bias update 속도 0.001, balance loss 가중치 0.0001같음
MTP loss 가중치0.3 → LR decay 시작부터 0.1같음

(V4 §4.2.2.) V3와 비교하면 LR 스케줄의 모양(warmup → 긴 상수 구간 → 끝의 cosine decay)과 batch size 증가 스케줄, MTP 가중치 낮추기가 그대로이고, optimizer와 문맥 길이 스케줄이 다르다. V3는 4K로 사전학습한 뒤 YaRN으로 128K까지 늘렸지만, V4는 사전학습 안에서 1M까지 간다.

Muon과 하이브리드 Newton–Schulz

Muon은 행렬 파라미터의 momentum을 직교화해서 업데이트한다. 보고서의 Algorithm 1은 다음과 같다.

Gt=∇WLt(Wt−1),Mt=μMt−1+GtOt′=HybridNewtonSchulz⁡(μMt+Gt)(Nesterov)Ot=Ot′⋅max⁡(n,m)⋅γ,Wt=Wt−1(1−ηλ)−η Ot\begin{aligned} G_t&=\nabla_W\mathcal L_t(W_{t-1}),\qquad M_t=\mu M_{t-1}+G_t\\ O'_t&=\operatorname{HybridNewtonSchulz}(\mu M_t+G_t)\qquad(\text{Nesterov})\\ O_t&=O'_t\cdot\sqrt{\max(n,m)}\cdot\gamma,\qquad W_t=W_{t-1}(1-\eta\lambda)-\eta\,O_t \end{aligned}

M=UΣV⊤M=U\Sigma V^\top일 때 이상적인 결과는 UV⊤UV^\top, 즉 모든 특이값을 1로 만든 행렬이다. SVD는 비싸므로 M0=M/∥M∥FM_0=M/\|M\|_F(특이값이 1 이하가 되게)에서 시작해 홀수 다항식을 반복한다(식 28).

Mk=aMk−1+b (Mk−1Mk−1⊤)Mk−1+c (Mk−1Mk−1⊤)2Mk−1M_k=aM_{k-1}+b\,(M_{k-1}M_{k-1}^\top)M_{k-1}+c\,(M_{k-1}M_{k-1}^\top)^2M_{k-1}

Mk−1=UΣV⊤M_{k-1}=U\Sigma V^\top을 대입하면 (MM⊤)M=UΣ3V⊤(MM^\top)M=U\Sigma^3V^\top이므로, 이 반복은 특이값마다 독립적으로 스칼라 다항식 σ↦aσ+bσ3+cσ5\sigma\mapsto a\sigma+b\sigma^3+c\sigma^5를 적용한다. 그래서 1차원 그래프로 전부 이해할 수 있다. V4는 처음 8회에 (a,b,c)=(3.4445,−4.7750,2.0315)(a,b,c)=(3.4445,-4.7750,2.0315)로 작은 특이값을 빠르게 끌어올리고, 마지막 2회를 (2,−1.5,0.5)(2,-1.5,0.5)로 바꿔 1에 정확히 고정한다(§2.4). 두 번째 다항식 f(σ)=2σ−1.5σ3+0.5σ5f(\sigma)=2\sigma-1.5\sigma^3+0.5\sigma^5는 f(1)=1, f′(1)=2−4.5+2.5=0f(1)=1,\ f'(1)=2-4.5+2.5=0이라 1 근처에서 이차 수렴한다.

→ 더 깊이: Muon과 Newton–Schulz 반복의 유도는 Muon과 직교화 옵티마이저에 있다.

하이브리드 σ 범위hybrid σ range – quintic만quintic only –
The horizontal axis is the singular value σ₀ of the normalised momentum matrix M₀ = M/‖M‖F (log axis, 10⁻³–1); the vertical axis is its value after k iterations. Ideal orthogonalisation sends every σ to 1 (dashed). Raise k from 0 to 8: the quintic coefficients (3.4445, −4.7750, 2.0315) lift small singular values quickly but stall near 1, oscillating between 0.68 and 1.13 (red). V4 switches the last 2 steps to (2, −1.5, 0.5). This polynomial has value 1 and slope 0 at σ=1, so it removes the remaining oscillation with quadratic convergence (blue, [1.000, 1.001] at k=10). Change the number of quintic steps to move the hybrid's switch point. 가로축은 정규화된 모멘텀 행렬 M₀ = M/‖M‖F의 특이값 σ₀(로그 축, 10⁻³–1), 세로축은 k번 반복한 뒤의 값이다. 이상적인 직교화는 모든 σ를 1로 보낸다(점선). k를 0에서 8까지 올리면 quintic 계수 (3.4445, −4.7750, 2.0315)가 작은 특이값을 빠르게 끌어올리지만 1 근처에서 0.68–1.13 사이를 출렁이며 멈춘다(빨강). V4는 마지막 2번을 (2, −1.5, 0.5)로 바꾼다. 이 다항식은 σ=1에서 값 1, 기울기 0이라 남은 출렁임을 이차 수렴으로 없앤다(파랑, k=10에서 [1.000, 1.001]). quintic 단계 수를 바꿔 하이브리드의 전환 시점을 옮겨 볼 수 있다.

The max⁡(n,m)⋅γ\sqrt{\max(n,m)}\cdot\gamma factor that sets the update RMS to 0.180.18 is the trick from Liu et al. (2025). The element RMS of an orthogonal matrix depends on its shape; matching it to the typical RMS of an AdamW update lets the learning rate and weight decay tuned for AdamW be reused as is.

NumPy Hybrid Newton–Schulz: where do the singular values go?
import numpy as np

QU, ST = (3.4445, -4.7750, 2.0315), (2.0, -1.5, 0.5)

def newton_schulz(M, steps=10, n_quintic=8):
    X = M / np.linalg.norm(M)                  # Frobenius normalisation → singular values ≤ 1
    tall = X.shape[0] > X.shape[1]
    if tall: X = X.T                           # keep it (small dim) x (large dim) so X Xᵀ is small
    out = {}
    for k in range(steps):
        a, b, c = QU if k < n_quintic else ST
        A = X @ X.T
        X = a * X + (b * A + c * A @ A) @ X
        out[k + 1] = X.T if tall else X
    return out

rng = np.random.default_rng(0)
U, _ = np.linalg.qr(rng.standard_normal((256, 64)))
V, _ = np.linalg.qr(rng.standard_normal((64, 64)))
s = np.logspace(0, -3, 64)                     # momentum matrix with condition number 1000
M = (U * s) @ V.T
target = U @ V.T                               # the ideal orthogonalised result

for name, nq in [("hybrid 8+2", 8), ("quintic only", 10)]:
    res = newton_schulz(M, 10, nq)
    for k in (5, 8, 10):
        sv = np.linalg.svd(res[k], compute_uv=False)
        err = np.linalg.norm(res[k] - target) / np.linalg.norm(target)
        print(f"{name:12s} k={k:2d}  σ ∈ [{sv.min():.4f}, {sv.max():.4f}]   ‖X−UVᵀ‖/‖UVᵀ‖ = {err:.3f}")
 

With the quintic alone, after 10 steps the singular values still sit between 0.68 and 1.13 and the relative error to UV⊤UV^\top stays at about 0.21. The hybrid all but removes that wobble in its last 2 steps. The smallest singular value (σ0=10−3\sigma_0=10^{-3}), however, only just reaches about 0.68 during the 8 quintic steps, so sending even very small singular values to 1 is not the goal. In practical Muon, too, the point is to make “most directions roughly the same size” rather than to orthogonalise exactly.

Training instabilities: two remedies

V3 reported no irrecoverable loss spikes throughout training, but the 1.6T V4 did hit spikes (§4.2.3). The report diagnoses the spikes as linked to outliers in the MoE layers and amplified by routing, and it discloses two techniques. It admits that it has no theory for why either one works.

  • Anticipatory Routing. At step tt, features are computed with the current parameters θt\theta_t, but the routing indices are computed with past parameters θt−Δt\theta_{t-\Delta t}. The interpretation is that this breaks the loop “router changes expert assignment → that expert is updated → router changes again”. The data for step tt is read ahead at time t−Δtt-\Delta t to precompute the routing, which keeps the extra cost to about 20%. It is not on all the time: when a spike is detected, training rolls back briefly and the technique is switched on for a while.
  • SwiGLU clamping. The linear component of SwiGLU is clipped to [−10,10][-10,10] and the gate component is capped at 10. This removes the outliers directly.

From an RL practitioner’s point of view the first is familiar. It tackles the same problem as V3.2’s Keep Routing (forcing the rollout-time expert assignment during training) — instability that arises because routing moves along with the parameters — in a different way.

Post-training: grow experts, then merge with on-policy distillation

V4’s post-training is almost the same as V3.2’s, but one stage has been replaced wholesale. V3.2 did SFT on data produced by experts and finished with a single stage of mixed RL; V4 puts On-Policy Distillation (OPD) in that slot (§5.1).

Stage 1: experts. For each domain — math, code, agents, instruction following and so on — an expert is built from the base with SFT → GRPO RL. For the GRPO hyperparameters the report only says they were “closely aligned” with previous work. Writing the form summarised for V3.2 in this site’s notation:

J(θ)=E[1G∑i=1G1∣yi∣∑t=1∣yi∣(min⁡(ρi,tA^i, clip⁡(ρi,t,1−ε,1+ε)A^i)Mi,t−β D^KL(i,t))],A^i=ri−mean⁡(r1..G)J(\theta)=\mathbb E\left[\frac1G\sum_{i=1}^G\frac1{|y_i|}\sum_{t=1}^{|y_i|}\Big(\min\big(\rho_{i,t}\hat A_i,\ \operatorname{clip}(\rho_{i,t},1-\varepsilon,1+\varepsilon)\hat A_i\big)M_{i,t}-\beta\,\hat D^{(i,t)}_{\text{KL}}\Big)\right],\qquad \hat A_i=r_i-\operatorname{mean}(r_{1..G})

Here D^KL\hat D_{\text{KL}} is the k3 estimator corrected with an importance ratio for samples from πold\pi_{\text{old}}, and Mi,tM_{i,t} is the off-policy mask that switches off sequences with negative advantage that have drifted far from πold\pi_{\text{old}} (V3.2 lesson). The same GRPO is used to build different experts for each reasoning effort: three modes trained with different length penalties and context windows (Tables 2–3).

ModeFormatDifference during RLEval context
Non-think</think> summary—8K
Think High<think> thinking </think> summarymedium length penalty and context window128K
Think Maxa “maximum reasoning” instruction before the system prompt + the format abovelonger context, weaker length penalty384K

For hard-to-verify tasks the scalar reward model is dropped in favour of a rubric-based GRM, and there is no separate GRM: the actor itself is the judge. In other words, the policy model learns to grade through RL as well (§5.1.1). The report claims this works well with little human annotation, but gives no numbers.

There are format changes on the agent side too. Tool calls are now written with a |DSML| special token in an XML format (the report says JSON string-escaping failures went down). And in conversations that call tools, earlier reasoning is not deleted even when a new user message arrives (interleaved thinking). V3.2 kept the reasoning while tool results kept coming but deleted it at a new user message. Now that there is a 1M context, V4 chooses to keep the continuity of thought in long-horizon agent tasks. In ordinary conversations it is still deleted. Auxiliary tasks — deciding whether to search, titling a conversation, generating search queries — are handled by appending a Quick Instruction special token (<|action|>, <|title|>, <|query|>, etc.) to the end of the input and running on the already-computed KV cache. There is no longer any need to prefill the same prompt again with a separate small model.

Stage 2: merging with OPD. With NN experts (N>10N>10) as teachers, the student πθ\pi_\theta minimises the reverse KL to the teachers on trajectories it generated itself (Eq. 29).

LOPD(θ)=∑i=1Nwi DKL(πθ ∥ πEi),DKL(πθ∥πE)=Ey∼πθ∑t∑v∈Vπθ(v∣x,y<t)log⁡πθ(v∣x,y<t)πE(v∣x,y<t)\mathcal L_{\text{OPD}}(\theta)=\sum_{i=1}^Nw_i\,D_{\text{KL}}\big(\pi_\theta\,\|\,\pi_{E_i}\big),\qquad D_{\text{KL}}(\pi_\theta\|\pi_E)=\mathbb E_{y\sim\pi_\theta}\sum_t\sum_{v\in V}\pi_\theta(v\mid x,y_{<t})\log\frac{\pi_\theta(v\mid x,y_{<t})}{\pi_E(v\mid x,y_{<t})}

Reverse KL is mode-seeking. The student is heavily penalised for putting probability where the teacher puts almost none, so it attaches to the behaviour of the teacher suited to the task (distillation lesson). Earlier implementations reused the RL framework and made a token-level estimate, using sg⁡[log⁡πE(yt)−log⁡πθ(yt)]\operatorname{sg}[\log\pi_E(y_t)-\log\pi_\theta(y_t)] of the single sampled token like an advantage; V4 says this is unstable because of high gradient variance and computes the KL exactly over the logits of the whole vocabulary. Storing the logits of a dozen-plus teachers with vocabularies over 100K is impossible, so only the teachers’ last hidden states are stored, the teacher’s output head is re-applied during training to recover the logits, and samples are sorted by teacher so that only one teacher’s head is on the GPU at a time (§5.2.2). The difference between the two estimators is computed in “Going deeper” below.

Going deeper into the core methods

1. CSA compression and causality

We transcribe Eqs. 11–12 to build the compressed entries and check three things. (1) There are n/mn/m entries. (2) Each channel’s softmax weights sum to 1 over the 2m2m positions. (3) Changing one token changes exactly two compressed entries (its own block, used as CaC^a, and the next block, used as CbC^b), and none of the entries visible to the query at that token’s position (s<⌊t/m⌋s<\lfloor t/m\rfloor) changes.

NumPy CSA compression (Eqs. 11–12), causality, indexer top-k
import numpy as np
rng = np.random.default_rng(0)
n, d, c, m = 64, 32, 16, 4                     # tokens, hidden, KV head dim, compression ratio

H = rng.standard_normal((n, d))
Wa, Wb, Wza, Wzb = [rng.standard_normal((d, c)) / np.sqrt(d) for _ in range(4)]
Ba, Bb = 0.1 * rng.standard_normal((m, c)), 0.1 * rng.standard_normal((m, c))

def csa_compress(H):
    Ca, Cb, Za, Zb = H @ Wa, H @ Wb, H @ Wza, H @ Wzb
    nb = len(H) // m
    out, S_all = np.zeros((nb, c)), []
    for i in range(nb):
        za, ca = Za[m*i:m*(i+1)] + Ba, Ca[m*i:m*(i+1)]
        if i == 0:                             # no previous block: pad with -inf / 0
            zb, cb = np.full((m, c), -np.inf), np.zeros((m, c))
        else:
            zb, cb = Zb[m*(i-1):m*i] + Bb, Cb[m*(i-1):m*i]
        z, cc = np.vstack([za, zb]), np.vstack([ca, cb])
        S = np.exp(z - z.max(0)); S /= S.sum(0)   # softmax over the 2m positions, per channel
        out[i] = (S * cc).sum(0); S_all.append(S)
    return out, S_all

C, S_all = csa_compress(H)
print("compressed entries shape:", C.shape, f"(= n/m = {n//m})")
print("per-channel weight sums (entry 5):", np.round(S_all[5].sum(0)[:6], 6), "...")

# Which compressed entries change if token 37 changes?
H2 = H.copy(); H2[37] += 1.0
C2, _ = csa_compress(H2)
changed = np.where(np.abs(C2 - C).max(1) > 1e-12)[0]
print("token 37 changed → entries changed:", changed.tolist(), f"(block {37//m} via C^a, block {37//m+1} via C^b)")
t = 37
print(f"entries visible to query t={t}: s < {t//m} → 0..{t//m-1}; changed among them:",
      [s for s in changed if s < t // m], "→ causality holds")

# lightning indexer: I[t,s] = Σ_h w_h · ReLU(q_h · K_s)
nI, cI, k = 4, 8, 3
Wiq = rng.standard_normal((d, nI * cI)) / np.sqrt(d)
Wik = rng.standard_normal((c, cI)) / np.sqrt(c)   # (toy) indexer keys built from the compressed entries
Ww  = rng.standard_normal((d, nI)) / np.sqrt(d)
t = n - 1
q = (H[t] @ Wiq).reshape(nI, cI); w = H[t] @ Ww
K = C[: t // m] @ Wik
I = (w[:, None] * np.maximum(q @ K.T, 0)).sum(0)
top = np.sort(np.argsort(-I)[:k])
print(f"\nquery t={t}: top-{k} of the {t//m} visible compressed entries = {top.tolist()}")

# KV entries read by one query under the real V4-Pro settings
for N in [8_192, 131_072, 1_048_576]:
    print(f"N={N:>9,}: dense {N:>9,} | CSA {min(1024, N//4) + 128:>5,} | HCA {N//128 + 128:>5,} | CSA indexer scoring {N//4:>7,}")
 

The last column is the linear cost that remains in CSA. Compression cut the entries the indexer must score from V3.2’s NN to N/4N/4, but that is still proportional to the context length.

2. mHC: Sinkhorn projection and depth

NumPy Sinkhorn–Knopp, non-expansiveness, closure under products
import numpy as np
rng = np.random.default_rng(1)

def sinkhorn(logits, iters=20):
    M = np.exp(logits)
    for _ in range(iters):
        M = M / M.sum(0, keepdims=True)        # column normalisation T_c
        M = M / M.sum(1, keepdims=True)        # row normalisation T_r
    return M

n = 4
B = sinkhorn(rng.standard_normal((n, n)) * 2)
print("row sums:", np.round(B.sum(1), 6), " col sums:", np.round(B.sum(0), 6))
for it in [1, 2, 5, 20]:
    Bi = sinkhorn(rng.standard_normal((n, n)) * 2, it)
    print(f"  t={it:2d}: max|col sum-1| = {np.abs(Bi.sum(0) - 1).max():.1e}")

for iters in [2, 20, 100]:
    norms = [np.linalg.norm(sinkhorn(rng.standard_normal((n, n)) * 1.5, iters), 2) for _ in range(500)]
    print(f"Sinkhorn {iters:3d} steps, ‖B‖₂ over 500 random: max {max(norms):.6f}, min {min(norms):.6f}")
B1, B2 = sinkhorn(rng.standard_normal((n, n))), sinkhorn(rng.standard_normal((n, n)))
P = B1 @ B2
print("row/col sums of the product B1·B2:", np.round(P.sum(1), 6), np.round(P.sum(0), 6))

X = rng.standard_normal((n, 8))                 # residual stream n x d
print("1ᵀX preserved:", np.allclose((B1 @ X).sum(0), X.sum(0)))

# 61 layers deep: unconstrained HC vs mHC
L = 61
for eps in [0.1, 0.3, 0.5]:
    Ph, Pm = np.eye(n), np.eye(n)
    for _ in range(L):
        G = rng.standard_normal((n, n))
        Ph = (np.eye(n) + eps * G) @ Ph
        Pm = sinkhorn(3 * eps * G + 2 * np.eye(n)) @ Pm
    print(f"ε={eps}: ‖∏B‖₂  HC = {np.linalg.norm(Ph, 2):10.3e}   mHC = {np.linalg.norm(Pm, 2):.4f}")
 

Once Sinkhorn has converged, ∥B∥2\|B\|_2 is not merely at most 1 but exactly 1. Since B1=1B\mathbf 1=\mathbf 1 and B⊤1=1B^\top\mathbf 1=\mathbf 1, we have B⊤B1=1B^\top B\mathbf 1=\mathbf 1, i.e. 1/n\mathbf 1/\sqrt n is a singular vector with singular value 1. With only 2 iterations the matrix is not yet doubly stochastic, and matrices with norm above 1 come out (the first line). For the mHC product, the singular value along the 1\mathbf 1 direction stays at 1 and the rest are at most 1, so the norm stays at 1. Put the other way round, the deeper the stack, the more the residual path tends to mix the streams toward their average (products of doubly stochastic matrices tend to converge to the uniform averaging matrix). Placing the static bias SresS^{\text{res}} near the identity keeps each layer’s mixing small. The report does not give the initial value.

In PyTorch one block can be written like this (a transcription of the report’s Eqs. 1–8; the initial values are our choice).

PyTorch mHC block (PyTorch, for reference) 로컬에서 실행run locally (pip install torch)
import torch
import torch.nn as nn

def sinkhorn(logits: torch.Tensor, iters: int = 20) -> torch.Tensor:
    M = logits.exp()
    for _ in range(iters):
        M = M / M.sum(dim=-2, keepdim=True)    # column normalisation
        M = M / M.sum(dim=-1, keepdim=True)    # row normalisation
    return M

class MHCBlock(nn.Module):
    """X_{l+1} = B_l X_l + C_l F(A_l X_l); X has shape (..., n, d)."""

    def __init__(self, layer: nn.Module, d: int, n: int = 4, iters: int = 20):
        super().__init__()
        self.layer, self.n, self.iters = layer, n, iters
        self.norm = nn.RMSNorm(n * d)
        self.W_pre = nn.Linear(n * d, n, bias=False)
        self.W_res = nn.Linear(n * d, n * n, bias=False)
        self.W_post = nn.Linear(n * d, n, bias=False)
        self.S_pre = nn.Parameter(torch.zeros(n))
        self.S_res = nn.Parameter(4.0 * torch.eye(n))   # our choice: start near identity
        self.S_post = nn.Parameter(torch.zeros(n))
        self.alpha = nn.Parameter(torch.full((3,), 0.01))  # gates "initialised to small values"

    def forward(self, X: torch.Tensor) -> torch.Tensor:
        *lead, n, d = X.shape
        x = self.norm(X.reshape(*lead, n * d))
        A = torch.sigmoid(self.alpha[0] * self.W_pre(x) + self.S_pre)            # (..., n)
        B = sinkhorn(self.alpha[1] * self.W_res(x).view(*lead, n, n) + self.S_res, self.iters)
        C = 2 * torch.sigmoid(self.alpha[2] * self.W_post(x) + self.S_post)      # (..., n)
        h = torch.einsum('...n,...nd->...d', A, X)                                # layer input A_l X_l
        y = self.layer(h)                                                          # (..., d)
        return torch.einsum('...ij,...jd->...id', B, X) + C.unsqueeze(-1) * y.unsqueeze(-2)
 
확인 문제Check yourself

In mHC, if the residual matrix B is doubly stochastic, what does the residual path (X → BX), excluding the layer-function output, always preserve exactly across the n streams?

Because the column sums are 1, 1⊤B=1⊤\mathbf 1^\top B=\mathbf 1^\top, and therefore 1⊤(BX)=1⊤X\mathbf 1^\top(BX)=\mathbf 1^\top X. It only mixes the signal between streams and does not change the total. The norm of each stream is not preserved (mixing toward the average shrinks it). Since ∥B∥2≤1\|B\|_2\le1, the total energy does not grow.

3. OPD: full-vocabulary KL vs token-level estimate

Given a student distribution π\pi (logits zz) and a teacher distribution pp at one position, the logit gradient of the reverse KL can be computed exactly.

∇zDKL(π∥p)=π⊙(log⁡π−log⁡p−DKL)\nabla_z D_{\text{KL}}(\pi\|p)=\pi\odot\big(\log\pi-\log p-D_{\text{KL}}\big)

The token-level estimate draws a single y∼πy\sim\pi and uses g^=(log⁡πy−log⁡py) ∇zlog⁡πy=(log⁡πy−log⁡py)(ey−π)\hat g=(\log\pi_y-\log p_y)\,\nabla_z\log\pi_y=(\log\pi_y-\log p_y)(e_y-\pi). Since Ey[∇zlog⁡πy]=0\mathbb E_y[\nabla_z\log\pi_y]=0, this estimator is unbiased (its expectation equals the expression above). The problem is the variance.

NumPy Variance of the token-level KL estimator
import numpy as np
rng = np.random.default_rng(2)
V = 2000                                        # vocabulary size (128K in reality)

def logsoftmax(z): z = z - z.max(); return z - np.log(np.exp(z).sum())

zt = rng.standard_normal(V) * 3                 # teacher logits
zs = zt + rng.standard_normal(V) * 1.5          # student = teacher + difference
lp, lq = logsoftmax(zs), logsoftmax(zt)
pi = np.exp(lp)
kl = (pi * (lp - lq)).sum()
g_exact = pi * (lp - lq - kl)                   # full-vocabulary gradient (zero variance)
print(f"KL(π‖p) = {kl:.3f},  ‖exact gradient‖ = {np.linalg.norm(g_exact):.4f}")

def token_level(S):
    ys = rng.choice(V, size=S, p=pi).astype(np.intp)
    coef = lp[ys] - lq[ys]                      # sg[log π − log p] (flip the sign for OPD's "advantage")
    g = -coef.mean() * pi                       # the −π part of ∇_z log π_y = e_y − π
    np.add.at(g, ys, coef / S)                  # the e_y part
    return g

for S in [1, 4, 16, 64]:
    est = np.array([token_level(S) for _ in range(300)])
    bias = np.linalg.norm(est.mean(0) - g_exact) / np.linalg.norm(g_exact)
    rel_err = np.mean(np.linalg.norm(est - g_exact, axis=1)) / np.linalg.norm(g_exact)
    cos = np.mean([e @ g_exact / (np.linalg.norm(e) * np.linalg.norm(g_exact)) for e in est])
    print(f"{S:3d} samples/position: error of 300-run mean {bias:.3f} | relative error of one estimate {rel_err:6.2f} | cos(est, exact) {cos:.2f}")
 

The one-token estimate is right in expectation (the error of the 300-run mean goes to 0 as the number of samples grows), but a single estimate is nearly orthogonal to the exact gradient (cosine 0.08). At each position of a sequence there is exactly one sample (the token that was actually generated), so the only remedy is to average over more positions. The full-vocabulary method uses the teacher’s whole distribution at every position, so it has none of this noise. The price is the cost of producing the teacher logits, which V4 absorbed with hidden-state caching and sorting by teacher.

Experimental results

Base models (report Table 1)

update RMS를 0.180.18로 맞추는 max⁡(n,m)⋅γ\sqrt{\max(n,m)}\cdot\gamma 배율은 Liu et al.(2025)의 트릭이다. 직교 행렬의 원소 RMS는 크기에 따라 달라지는데, 그것을 AdamW update의 전형적인 RMS에 맞춰 AdamW용 learning rate와 weight decay를 그대로 재사용하게 한다.

NumPy 하이브리드 Newton–Schulz: 특이값이 어디로 가는가
import numpy as np

QU, ST = (3.4445, -4.7750, 2.0315), (2.0, -1.5, 0.5)

def newton_schulz(M, steps=10, n_quintic=8):
    X = M / np.linalg.norm(M)                  # Frobenius 정규화 → 특이값 ≤ 1
    tall = X.shape[0] > X.shape[1]
    if tall: X = X.T                           # (작은 차원) x (큰 차원)으로 두면 X Xᵀ가 작다
    out = {}
    for k in range(steps):
        a, b, c = QU if k < n_quintic else ST
        A = X @ X.T
        X = a * X + (b * A + c * A @ A) @ X
        out[k + 1] = X.T if tall else X
    return out

rng = np.random.default_rng(0)
U, _ = np.linalg.qr(rng.standard_normal((256, 64)))
V, _ = np.linalg.qr(rng.standard_normal((64, 64)))
s = np.logspace(0, -3, 64)                     # 조건수 1000짜리 모멘텀 행렬
M = (U * s) @ V.T
target = U @ V.T                               # 이상적인 직교화 결과

for name, nq in [("hybrid 8+2", 8), ("quintic만", 10)]:
    res = newton_schulz(M, 10, nq)
    for k in (5, 8, 10):
        sv = np.linalg.svd(res[k], compute_uv=False)
        err = np.linalg.norm(res[k] - target) / np.linalg.norm(target)
        print(f"{name:10s} k={k:2d}  σ ∈ [{sv.min():.4f}, {sv.max():.4f}]   ‖X−UVᵀ‖/‖UVᵀ‖ = {err:.3f}")
 

quintic만 쓰면 10회 뒤에도 특이값이 0.68–1.13 사이에 남아 UV⊤UV^\top과의 상대 오차가 약 0.21에 머문다. 하이브리드는 마지막 2회에 그 출렁임을 거의 없앤다. 다만 가장 작은 특이값(σ0=10−3\sigma_0=10^{-3})은 8회의 quintic 동안 겨우 0.68 근처에 도달하므로, 아주 작은 특이값까지 1로 보내는 것이 목표는 아니다. 실전 Muon에서도 정확한 직교화보다 “대부분의 방향을 비슷한 크기로” 만드는 것이 핵심이다.

학습 불안정성: 두 가지 처방

V3는 학습 내내 회복 불가능한 loss spike가 없었다고 보고했지만, 1.6T의 V4는 spike를 겪었다(§4.2.3). 보고서는 spike가 MoE 층의 이상치(outlier)와 연결되어 있고 routing이 그것을 키운다고 진단하고, 두 기법을 공개한다. 둘 다 왜 듣는지에 대한 이론은 없다고 스스로 밝힌다.

  • Anticipatory Routing. step tt에서 feature는 현재 파라미터 θt\theta_t로 계산하되, routing 인덱스는 과거 파라미터 θt−Δt\theta_{t-\Delta t}로 계산한다. “router가 바꾼 expert 배정 → 그 expert의 업데이트 → 다시 router 변화”의 순환을 끊는다는 해석이다. step tt의 데이터를 t−Δtt-\Delta t 시점에 미리 읽어 routing을 계산해 두고, 추가 비용은 약 20%로 묶었다. 상시 켜 두지 않고 spike가 감지되면 짧게 rollback한 뒤 한동안만 켠다.
  • SwiGLU clamping. SwiGLU의 선형 성분을 [−10,10][-10,10]으로, gate 성분의 상한을 10으로 자른다. 이상치를 직접 없앤다.

RL을 하는 입장에서는 첫 번째가 익숙하다. V3.2의 Keep Routing(rollout 때의 expert 배정을 학습 때 강제)과 같은 문제, 즉 routing이 파라미터와 함께 움직이며 생기는 불안정을 다른 방식으로 다룬 것이다.

사후학습: 전문가를 키운 뒤 on-policy distillation으로 합치기

V4의 사후학습은 V3.2와 거의 같지만 한 단계가 통째로 바뀌었다. V3.2는 전문가들이 만든 데이터로 SFT한 뒤 mixed RL 한 단계로 마무리했는데, V4는 그 자리에 On-Policy Distillation(OPD) 을 넣었다(§5.1).

1단계: 전문가. 수학, 코드, agent, instruction following 등 도메인마다 base에서 SFT → GRPO RL로 전문가를 만든다. GRPO 하이퍼파라미터는 이전 연구와 “밀접하게 맞췄다”고만 적었다. V3.2에서 정리한 형태를 이 사이트의 표기로 쓰면

J(θ)=E[1G∑i=1G1∣yi∣∑t=1∣yi∣(min⁡(ρi,tA^i, clip⁡(ρi,t,1−ε,1+ε)A^i)Mi,t−β D^KL(i,t))],A^i=ri−mean⁡(r1..G)J(\theta)=\mathbb E\left[\frac1G\sum_{i=1}^G\frac1{|y_i|}\sum_{t=1}^{|y_i|}\Big(\min\big(\rho_{i,t}\hat A_i,\ \operatorname{clip}(\rho_{i,t},1-\varepsilon,1+\varepsilon)\hat A_i\big)M_{i,t}-\beta\,\hat D^{(i,t)}_{\text{KL}}\Big)\right],\qquad \hat A_i=r_i-\operatorname{mean}(r_{1..G})

이고, D^KL\hat D_{\text{KL}}은 πold\pi_{\text{old}} 샘플에 대해 importance ratio를 곱해 바로잡은 k3 추정량, Mi,tM_{i,t}는 음의 advantage이면서 πold\pi_{\text{old}}와 크게 벌어진 시퀀스를 끄는 off-policy mask다(V3.2 레슨). 같은 GRPO로 추론 강도별로 다른 전문가를 만든다. 길이 벌점과 문맥 창을 달리 준 세 가지 모드다(Table 2–3).

모드형식RL 때의 차이평가 문맥
Non-think</think> 요약—8K
Think High<think> 생각 </think> 요약길이 벌점·문맥 창 중간128K
Think Max시스템 프롬프트 앞에 “최대 추론” 지시문 + 위 형식더 긴 문맥, 더 약한 길이 벌점384K

검증이 어려운 과제에는 스칼라 보상모델을 버리고 rubric 기반 GRM을 쓰는데, GRM이 따로 있지 않고 actor 자신이 judge다. 정책 모델이 채점 능력도 같이 RL로 학습한다는 것이다(§5.1.1). 사람 annotation을 적게 쓰고도 잘 된다고 주장하지만 수치 근거는 없다.

agent 쪽 형식 변화도 있다. tool call을 |DSML| special token과 XML 형식으로 쓰게 바꿨다(JSON 문자열 escaping 실패가 줄었다고 보고). 그리고 tool을 호출하는 대화에서는 사용자 메시지가 새로 와도 이전 reasoning을 지우지 않는다(interleaved thinking). V3.2는 tool 결과가 이어지는 동안에는 reasoning을 유지하되 새 사용자 메시지에서 지웠다. 1M 문맥이 생겼으니 장기 agent 과제에서 사고의 연속성을 유지하는 쪽을 택한 것이다. 일반 대화에서는 여전히 지운다. 검색 여부 판단, 대화 제목, 검색 query 생성 같은 보조 작업은 Quick Instruction special token(<|action|>, <|title|>, <|query|> 등)을 입력 끝에 붙여 이미 계산된 KV cache 위에서 처리한다. 별도의 작은 모델로 같은 프롬프트를 다시 prefill할 필요가 없어진다.

2단계: OPD로 통합. 전문가 NN개(N>10N>10)를 교사로 두고, 학생 πθ\pi_\theta가 자기가 생성한 궤적 위에서 교사들과의 reverse KL을 줄인다(식 29).

LOPD(θ)=∑i=1Nwi DKL(πθ ∥ πEi),DKL(πθ∥πE)=Ey∼πθ∑t∑v∈Vπθ(v∣x,y<t)log⁡πθ(v∣x,y<t)πE(v∣x,y<t)\mathcal L_{\text{OPD}}(\theta)=\sum_{i=1}^Nw_i\,D_{\text{KL}}\big(\pi_\theta\,\|\,\pi_{E_i}\big),\qquad D_{\text{KL}}(\pi_\theta\|\pi_E)=\mathbb E_{y\sim\pi_\theta}\sum_t\sum_{v\in V}\pi_\theta(v\mid x,y_{<t})\log\frac{\pi_\theta(v\mid x,y_{<t})}{\pi_E(v\mid x,y_{<t})}

reverse KL은 mode-seeking이다. 학생은 교사가 확률을 거의 주지 않는 곳에 확률을 두면 크게 벌을 받으므로, 과제에 맞는 교사의 행동 쪽으로 붙는다(증류 레슨). 기존 구현은 RL 프레임워크를 재사용해 샘플된 토큰 하나의 sg⁡[log⁡πE(yt)−log⁡πθ(yt)]\operatorname{sg}[\log\pi_E(y_t)-\log\pi_\theta(y_t)]를 advantage처럼 쓰는 토큰 수준 추정을 했는데, V4는 이것이 gradient 분산이 커서 불안정하다며 어휘 전체의 logit으로 KL을 정확히 계산한다. 어휘가 10만이 넘는 교사 열몇 개의 logit을 저장할 수는 없으니, 교사의 마지막 hidden state만 저장해 두고 학습 때 교사의 출력 head를 다시 적용해 logit을 복원하며, 샘플을 교사 순서로 정렬해 한 번에 한 교사의 head만 GPU에 올린다(§5.2.2). 두 추정량의 차이는 아래 “깊게 보기”에서 계산해 본다.

핵심 method 깊게 보기

1. CSA의 압축과 인과성

식 11–12를 그대로 옮겨 압축 항목을 만들고, 세 가지를 확인한다. (1) 항목 수가 n/mn/m이다. (2) 각 채널의 softmax 가중치가 2m2m개 위치에서 합 1이다. (3) 토큰 하나를 바꾸면 정확히 두 압축 항목(CaC^a로 쓰는 자기 블록, CbC^b로 쓰는 다음 블록)만 바뀌고, 그 토큰 위치의 query가 볼 수 있는 항목(s<⌊t/m⌋s<\lfloor t/m\rfloor)은 하나도 바뀌지 않는다.

NumPy CSA 압축(식 11–12), 인과성, indexer top-k
import numpy as np
rng = np.random.default_rng(0)
n, d, c, m = 64, 32, 16, 4                     # 토큰 수, hidden, KV head dim, 압축률

H = rng.standard_normal((n, d))
Wa, Wb, Wza, Wzb = [rng.standard_normal((d, c)) / np.sqrt(d) for _ in range(4)]
Ba, Bb = 0.1 * rng.standard_normal((m, c)), 0.1 * rng.standard_normal((m, c))

def csa_compress(H):
    Ca, Cb, Za, Zb = H @ Wa, H @ Wb, H @ Wza, H @ Wzb
    nb = len(H) // m
    out, S_all = np.zeros((nb, c)), []
    for i in range(nb):
        za, ca = Za[m*i:m*(i+1)] + Ba, Ca[m*i:m*(i+1)]
        if i == 0:                             # 앞 블록이 없으면 -inf / 0으로 padding
            zb, cb = np.full((m, c), -np.inf), np.zeros((m, c))
        else:
            zb, cb = Zb[m*(i-1):m*i] + Bb, Cb[m*(i-1):m*i]
        z, cc = np.vstack([za, zb]), np.vstack([ca, cb])
        S = np.exp(z - z.max(0)); S /= S.sum(0)   # 2m개 위치에 걸친 softmax, 채널마다
        out[i] = (S * cc).sum(0); S_all.append(S)
    return out, S_all

C, S_all = csa_compress(H)
print("압축 항목 shape:", C.shape, f"(= n/m = {n//m})")
print("채널별 가중치 합 (항목 5):", np.round(S_all[5].sum(0)[:6], 6), "...")

# 토큰 37을 바꾸면 어떤 압축 항목이 변하나?
H2 = H.copy(); H2[37] += 1.0
C2, _ = csa_compress(H2)
changed = np.where(np.abs(C2 - C).max(1) > 1e-12)[0]
print("토큰 37 변경 → 바뀐 항목:", changed.tolist(), f"(블록 {37//m}은 C^a로, 블록 {37//m+1}은 C^b로)")
t = 37
print(f"query t={t}가 볼 수 있는 항목: s < {t//m} → 0..{t//m-1}; 그중 바뀐 것:",
      [s for s in changed if s < t // m], "→ 인과성 유지")

# lightning indexer: I[t,s] = Σ_h w_h · ReLU(q_h · K_s)
nI, cI, k = 4, 8, 3
Wiq = rng.standard_normal((d, nI * cI)) / np.sqrt(d)
Wik = rng.standard_normal((c, cI)) / np.sqrt(c)   # (장난감) 압축 항목에서 indexer key를 만든다
Ww  = rng.standard_normal((d, nI)) / np.sqrt(d)
t = n - 1
q = (H[t] @ Wiq).reshape(nI, cI); w = H[t] @ Ww
K = C[: t // m] @ Wik
I = (w[:, None] * np.maximum(q @ K.T, 0)).sum(0)
top = np.sort(np.argsort(-I)[:k])
print(f"\nquery t={t}: 볼 수 있는 압축 항목 {t//m}개 중 top-{k} = {top.tolist()}")

# 실제 V4-Pro 설정에서 query 하나가 읽는 KV 항목 수
for N in [8_192, 131_072, 1_048_576]:
    print(f"N={N:>9,}: dense {N:>9,} | CSA {min(1024, N//4) + 128:>5,} | HCA {N//128 + 128:>5,} | CSA indexer 채점 {N//4:>7,}")
 

마지막 열이 CSA에 남은 선형 비용이다. 압축으로 indexer가 채점할 항목이 V3.2의 NN개에서 N/4N/4개로 줄었지만 여전히 문맥 길이에 비례한다.

2. mHC: Sinkhorn 투영과 깊이

NumPy Sinkhorn–Knopp, 비확장성, 곱에 대한 닫힘
import numpy as np
rng = np.random.default_rng(1)

def sinkhorn(logits, iters=20):
    M = np.exp(logits)
    for _ in range(iters):
        M = M / M.sum(0, keepdims=True)        # 열 정규화 T_c
        M = M / M.sum(1, keepdims=True)        # 행 정규화 T_r
    return M

n = 4
B = sinkhorn(rng.standard_normal((n, n)) * 2)
print("행 합:", np.round(B.sum(1), 6), " 열 합:", np.round(B.sum(0), 6))
for it in [1, 2, 5, 20]:
    Bi = sinkhorn(rng.standard_normal((n, n)) * 2, it)
    print(f"  t={it:2d}: max|열 합-1| = {np.abs(Bi.sum(0) - 1).max():.1e}")

for iters in [2, 20, 100]:
    norms = [np.linalg.norm(sinkhorn(rng.standard_normal((n, n)) * 1.5, iters), 2) for _ in range(500)]
    print(f"Sinkhorn {iters:3d}회, 무작위 500개의 ‖B‖₂: 최대 {max(norms):.6f}, 최소 {min(norms):.6f}")
B1, B2 = sinkhorn(rng.standard_normal((n, n))), sinkhorn(rng.standard_normal((n, n)))
P = B1 @ B2
print("곱 B1·B2의 행 합/열 합:", np.round(P.sum(1), 6), np.round(P.sum(0), 6))

X = rng.standard_normal((n, 8))                 # 잔차 스트림 n x d
print("1ᵀX 보존:", np.allclose((B1 @ X).sum(0), X.sum(0)))

# 61층 깊이: 제약 없는 HC vs mHC
L = 61
for eps in [0.1, 0.3, 0.5]:
    Ph, Pm = np.eye(n), np.eye(n)
    for _ in range(L):
        G = rng.standard_normal((n, n))
        Ph = (np.eye(n) + eps * G) @ Ph
        Pm = sinkhorn(3 * eps * G + 2 * np.eye(n)) @ Pm
    print(f"ε={eps}: ‖∏B‖₂  HC = {np.linalg.norm(Ph, 2):10.3e}   mHC = {np.linalg.norm(Pm, 2):.4f}")
 

Sinkhorn이 수렴하면 ∥B∥2\|B\|_2는 1 이하인 정도가 아니라 정확히 1이다. B1=1B\mathbf 1=\mathbf 1이고 B⊤1=1B^\top\mathbf 1=\mathbf 1이라 B⊤B1=1B^\top B\mathbf 1=\mathbf 1, 즉 1/n\mathbf 1/\sqrt n이 특이값 1의 특이벡터다. 반복이 2회뿐이면 아직 doubly stochastic이 아니어서 norm이 1을 넘는 행렬이 나온다(첫 줄). mHC의 곱은 1\mathbf 1 방향의 특이값이 1로 유지되고 나머지는 1 이하라 norm이 1에 머문다. 반대로 말하면 깊이 쌓을수록 잔차 경로가 스트림들을 평균 쪽으로 섞는 경향이 있다(doubly stochastic 행렬의 곱은 균일 평균 행렬로 수렴하기 쉽다). 정적 bias SresS^{\text{res}}를 항등 행렬 근처로 두면 각 층의 섞임이 작아진다. 보고서는 초기값을 밝히지 않는다.

PyTorch로는 한 블록을 이렇게 쓸 수 있다(보고서 식 1–8을 옮긴 것이고, 초기화 값은 우리 선택이다).

PyTorch mHC 블록 (PyTorch, 참고용) 로컬에서 실행run locally (pip install torch)
import torch
import torch.nn as nn

def sinkhorn(logits: torch.Tensor, iters: int = 20) -> torch.Tensor:
    M = logits.exp()
    for _ in range(iters):
        M = M / M.sum(dim=-2, keepdim=True)    # column normalisation
        M = M / M.sum(dim=-1, keepdim=True)    # row normalisation
    return M

class MHCBlock(nn.Module):
    """X_{l+1} = B_l X_l + C_l F(A_l X_l); X has shape (..., n, d)."""

    def __init__(self, layer: nn.Module, d: int, n: int = 4, iters: int = 20):
        super().__init__()
        self.layer, self.n, self.iters = layer, n, iters
        self.norm = nn.RMSNorm(n * d)
        self.W_pre = nn.Linear(n * d, n, bias=False)
        self.W_res = nn.Linear(n * d, n * n, bias=False)
        self.W_post = nn.Linear(n * d, n, bias=False)
        self.S_pre = nn.Parameter(torch.zeros(n))
        self.S_res = nn.Parameter(4.0 * torch.eye(n))   # our choice: start near identity
        self.S_post = nn.Parameter(torch.zeros(n))
        self.alpha = nn.Parameter(torch.full((3,), 0.01))  # gates "initialised to small values"

    def forward(self, X: torch.Tensor) -> torch.Tensor:
        *lead, n, d = X.shape
        x = self.norm(X.reshape(*lead, n * d))
        A = torch.sigmoid(self.alpha[0] * self.W_pre(x) + self.S_pre)            # (..., n)
        B = sinkhorn(self.alpha[1] * self.W_res(x).view(*lead, n, n) + self.S_res, self.iters)
        C = 2 * torch.sigmoid(self.alpha[2] * self.W_post(x) + self.S_post)      # (..., n)
        h = torch.einsum('...n,...nd->...d', A, X)                                # layer input A_l X_l
        y = self.layer(h)                                                          # (..., d)
        return torch.einsum('...ij,...jd->...id', B, X) + C.unsqueeze(-1) * y.unsqueeze(-2)
 
확인 문제Check yourself

mHC에서 잔차 행렬 B가 doubly stochastic이면, 층 함수 출력을 제외한 잔차 경로(X → BX)가 n개 스트림에 대해 항상 정확히 보존하는 것은?

열 합이 1이라 1⊤B=1⊤\mathbf 1^\top B=\mathbf 1^\top이고, 따라서 1⊤(BX)=1⊤X\mathbf 1^\top(BX)=\mathbf 1^\top X다. 스트림 사이에 신호를 섞을 뿐 총합은 바꾸지 않는다. 각 스트림의 노름은 보존되지 않는다(평균 쪽으로 섞이면 줄어든다). ∥B∥2≤1\|B\|_2\le1이므로 전체 에너지는 늘지 않는다.

3. OPD: full-vocabulary KL vs 토큰 수준 추정

한 위치에서 학생 분포 π\pi(logit zz)와 교사 분포 pp가 있을 때 reverse KL의 logit gradient는 정확히 계산된다.

∇zDKL(π∥p)=π⊙(log⁡π−log⁡p−DKL)\nabla_z D_{\text{KL}}(\pi\|p)=\pi\odot\big(\log\pi-\log p-D_{\text{KL}}\big)

토큰 수준 추정은 y∼πy\sim\pi 하나를 뽑아 g^=(log⁡πy−log⁡py) ∇zlog⁡πy=(log⁡πy−log⁡py)(ey−π)\hat g=(\log\pi_y-\log p_y)\,\nabla_z\log\pi_y=(\log\pi_y-\log p_y)(e_y-\pi)를 쓴다. Ey[∇zlog⁡πy]=0\mathbb E_y[\nabla_z\log\pi_y]=0이므로 이 추정량은 불편이다(위 식과 기대값이 같다). 문제는 분산이다.

NumPy 토큰 수준 KL 추정량의 분산
import numpy as np
rng = np.random.default_rng(2)
V = 2000                                        # 어휘 크기 (실제는 128K)

def logsoftmax(z): z = z - z.max(); return z - np.log(np.exp(z).sum())

zt = rng.standard_normal(V) * 3                 # 교사 logit
zs = zt + rng.standard_normal(V) * 1.5          # 학생 = 교사 + 차이
lp, lq = logsoftmax(zs), logsoftmax(zt)
pi = np.exp(lp)
kl = (pi * (lp - lq)).sum()
g_exact = pi * (lp - lq - kl)                   # full-vocabulary gradient (분산 0)
print(f"KL(π‖p) = {kl:.3f},  ‖정확한 gradient‖ = {np.linalg.norm(g_exact):.4f}")

def token_level(S):
    ys = rng.choice(V, size=S, p=pi).astype(np.intp)
    coef = lp[ys] - lq[ys]                      # sg[log π − log p] (부호를 바꾸면 OPD의 "advantage")
    g = -coef.mean() * pi                       # ∇_z log π_y = e_y − π 의 −π 부분
    np.add.at(g, ys, coef / S)                  # e_y 부분
    return g

for S in [1, 4, 16, 64]:
    est = np.array([token_level(S) for _ in range(300)])
    bias = np.linalg.norm(est.mean(0) - g_exact) / np.linalg.norm(g_exact)
    rel_err = np.mean(np.linalg.norm(est - g_exact, axis=1)) / np.linalg.norm(g_exact)
    cos = np.mean([e @ g_exact / (np.linalg.norm(e) * np.linalg.norm(g_exact)) for e in est])
    print(f"샘플 {S:3d}개/위치: 300회 평균의 오차 {bias:.3f} | 한 번 추정의 상대 오차 {rel_err:6.2f} | cos(추정, 정확) {cos:.2f}")
 

토큰 하나짜리 추정은 기대값은 맞지만(300회 평균의 오차는 샘플을 늘릴수록 0으로 간다) 한 번의 추정은 정확한 gradient와 거의 직교한다(코사인 0.08). 시퀀스의 각 위치에서 샘플은 정확히 하나(실제로 생성된 토큰)뿐이니 위치를 늘려 평균내는 수밖에 없다. full-vocabulary 방식은 위치마다 교사의 분포 전체를 쓰므로 이 잡음이 없다. 대가는 교사 logit을 만드는 비용이고, V4는 hidden state 캐싱과 교사 순서 정렬로 그 비용을 감당했다.

실험 결과

Base 모델 (보고서 Table 1)

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: V4 report Table 1 (all on DeepSeek's internal evaluation framework, same settings). 분야를 고르고, 범례의 모델 이름을 눌러 켜고 끌 수 있다. 막대 길이는 행마다 그 행의 최고점을 기준으로 맞춘 상대값이고(% 지표와 rating이 섞여 있기 때문), 막대 옆 숫자가 보고서에 적힌 원래 값이다. 빈칸은 보고서에 값이 없는 경우다. 출처: V4 보고서 Table 1 (모두 DeepSeek 내부 평가 프레임워크, 같은 설정).

V4-Flash-Base has a little over 1/3 of V3.2’s active parameters, yet it leads on the knowledge benchmarks and LongBench-V2. It trails, however, on BigCodeBench (56.8 vs 63.9), MATH (57.4 vs 60.5), BBH and HellaSwag. Pro’s biggest jump is on knowledge benchmarks (Simple-QA verified 28.3 → 55.2, FACTS Parametric 27.1 → 62.6) — the familiar picture in which total parameters determine memorisation capacity.

Post-trained models (report Table 6, Table 7)

V4-Flash-Base는 활성 파라미터가 V3.2의 1/3 남짓인데 지식 벤치마크와 LongBench-V2에서 앞선다. 다만 BigCodeBench(56.8 vs 63.9), MATH(57.4 vs 60.5), BBH, HellaSwag에서는 뒤진다. 지식 벤치마크(Simple-QA verified 28.3 → 55.2, FACTS Parametric 27.1 → 62.6)에서 Pro의 도약이 가장 크다. 총 파라미터가 기억 용량을 결정한다는 익숙한 그림이다.

사후학습 모델 (보고서 Table 6, Table 7)

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: V4 report Table 6. 분야를 고르고, 범례의 모델 이름을 눌러 켜고 끌 수 있다. 막대 길이는 행마다 그 행의 최고점을 기준으로 맞춘 상대값이고(% 지표와 rating이 섞여 있기 때문), 막대 옆 숫자가 보고서에 적힌 원래 값이다. 빈칸은 보고서에 값이 없는 경우다. 출처: V4 보고서 Table 6.

V4-Pro-Max is the top score in the table on LiveCodeBench (93.5) and the internal Codeforces (3206), and on knowledge (SimpleQA-Verified 57.9) it is the highest of the open models but far behind Gemini-3.1-Pro (75.6). On agent benchmarks it is mostly in the same band as the open models (K2.6, GLM-5.1), and closed models lead on many items. The report itself describes its trajectory as “3–6 months behind the frontier” (§1).

Table 7 is more interesting for the effect of reasoning mode and size.

V4-Pro-Max는 LiveCodeBench(93.5)와 내부 Codeforces(3206)에서 표의 최고점이고, 지식(SimpleQA-Verified 57.9)에서는 열린 모델 중 가장 높지만 Gemini-3.1-Pro(75.6)와 차이가 크다. agent 벤치마크는 대부분 열린 모델들(K2.6, GLM-5.1)과 비슷한 구간이고, 닫힌 모델이 앞서는 항목이 많다. 보고서 스스로 “최전선보다 3–6개월 뒤처진 궤적”이라고 적는다(§1).

추론 모드와 크기의 효과는 Table 7이 더 흥미롭다.

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: V4 report Table 7. 분야를 고르고, 범례의 모델 이름을 눌러 켜고 끌 수 있다. 막대 길이는 행마다 그 행의 최고점을 기준으로 맞춘 상대값이고(% 지표와 rating이 섞여 있기 때문), 막대 옆 숫자가 보고서에 적힌 원래 값이다. 빈칸은 보고서에 값이 없는 경우다. 출처: V4 보고서 Table 7.
  1. On reasoning benchmarks, mode matters more than size. On HMMT, Flash-Max (94.8) beats Pro-High (94.0), and on LiveCodeBench Flash-Max’s 91.6 beats Pro-High’s 89.8. The thinking budget makes up for a 4× difference in active parameters.
  2. Knowledge is size. On SimpleQA-Verified, Flash-Max’s 34.1 falls short even of Pro’s Non-Think (45.0). Thinking longer does not produce facts you do not know.
  3. Agent tasks sit in between. On Terminal Bench 2.0, Pro Non-Think (59.1) beats Flash-Max (56.9). This matches the report’s summary that the larger model leads on more complex agent tasks (§1).
  4. 1M context. On MRCR, Non-Think is low at 37.5/44.7 and rises to around 80 in thinking modes. According to the report’s Figure 9, retrieval performance is stable up to 128K and starts to fall beyond it.

Follow-up: DeepSeek-V4.1-Flash

The motivation for V4.1-Flash (September 2026) is already visible in V4’s KV calculation. Sparse attention has cut compute enough; the bottleneck is now storage and movement. Agent workloads have long inputs, repeat prefill at every tool call, and must keep KV in HBM and on SSD for a long time to reuse prefixes (V4.1 §1). The report re-reads V4 as “a local-processing backbone built on SWA, with compressed global context attached”, and concentrates on simplifying the global branch.

Causal Encoder-Decoder (CED). The 40 layers are split into a 20-layer encoder and a 20-layer decoder, and each decoder layer’s global KV is projected with per-layer weights not from its own hidden states but from the hidden states of the encoder’s last layer (starting from YOCO).

Cl=HL/2WlKV,Zl=HL/2WlZ,l>L/2C_l=H_{L/2}W^{KV}_l,\qquad Z_l=H_{L/2}W^{Z}_l,\qquad l>L/2

In prefill, running only the encoder yields the decoder’s global KV. That is why the active parameters differ: 8B for prefill and 16B for decode. The SWA KV is still built by each layer from its own hidden states, so building the decoder’s SWA exactly would require running the decoder over the last L2×nwin\frac L2\times n_{\text{win}} tokens. V4.1 instead uses an approximation that reruns only the last nwinn_{\text{win}} tokens (SWA Bounded Replay) and reports that the quality loss is negligible. Prefill complexity goes from O(NL)O(NL) to O(NL/2+nwinL/2)≈O(NL/2)O(NL/2+n_{\text{win}}L/2)\approx O(NL/2) (V4.1 §2.2).

CSA2: sharing across layers. Each CSA2 layer is fixed to one of three modes (V4.1 §2.3.1).

  • Full: computes its own main KV and indexer and picks a fresh top-k (the same role as one CSA layer in V4).
  • Reindex: borrows the main KV and indexer K of the most recent Full layer, rescores them with its own indexer query, and picks a fresh top-k.
  • Reuse: borrows both the main KV and the top-k indices and only does attention.

Every mode has its own query and its own SWA KV. The encoder, with compression ratio m=2m=2, has 3 groups of 6 layers (each group Full 1 + Reuse 5); the decoder, with no compression (m=1m=1), has 5 groups of 4 layers (only the first group starts with Full, the others are Reindex 1 + Reuse 3). HCA is removed, and CSA’s overlapping window and absolute-position bias are dropped for simplicity. In the decoder’s Hierarchical Sparse Indexer, a Full layer picks 2,048 blocks (16,384 candidates) by the maximum score over 8-token blocks, and the subsequent Reindex layers pick a top-512 only within those candidates. The per-query cost of the deep indexers becomes independent of context length.

FP4 main KV. QAT in post-training makes the main KV stored as E2M1 with one E4M3 scale per 16 channels (NVFP4 without its second-level global scale). The justification for dropping the global scale is neat. The largest RMSNorm weight is about 1, so the L2 norm of the 512-channel KV latent is at most about 512\sqrt{512}, and RoPE preserves norms, so no channel exceeds 512≈22.6\sqrt{512}\approx22.6. The largest value the format can represent is 448×6=2688448\times6=2688, which leaves plenty of headroom (V4.1 §2.4.4). The SWA KV is sensitive to quantisation and stays in FP8.

Put together, the report gives a global KV of 890 bytes per token. Recounting from the configuration reproduces it exactly.

3×288+682⏟3 encoder Full layers, m=2+1×(288+68)⏟1 decoder Full layer, m=1=534+356=890 B/token\underbrace{3\times\frac{288+68}{2}}_{\text{3 encoder Full layers},\ m=2}+\underbrace{1\times(288+68)}_{\text{1 decoder Full layer},\ m=1}=534+356=890\ \text{B/token}

Here 288 is 512 channels of FP4 (256 B) + 32 E4M3 scales (32 B), and 68 is the 128-dimensional MXFP4 indexer key (64 B + 1 B of scale per 32 elements). Reindex and Reuse layers store no KV, so only 4 of the 40 layers hold global KV. Compared with the V4-Flash estimate above (about 3.47 KB) this is 3.9×, matching the report’s “about 1/4”. The report’s Figure 1(b) comparison — a 437× reduction relative to DeepSeek-V1 — also comes out as 389,120/890≈437389{,}120/890\approx437 if computed with a 95-layer GQA8 BF16 model (95×4,096=389,12095\times4{,}096=389{,}120 B) rather than a 61-layer one (DeepSeek LLM 67B configuration: 95 layers, 8 KV heads, head dimension 8192/64=1288192/64=128; DeepSeek LLM report arXiv 2401.02954 Table 2. That the report means this model by “V1” is our interpretation). Click the V4.1-Flash bar in the KV calculator above to see its composition.

On the SSD side. In V4, SWA KV took up almost half of the persistent KV cache capacity. V4.1 does not store SWA KV on SSD at all, keeping it only in a host-memory pool with a TTL of a few minutes; on a miss, bounded replay recomputes only nwinn_{\text{win}} tokens. Persistent KV thus becomes about 1/8 of V4-Flash’s (about 1/2 from dropping SWA, about 1/4 from compressing the global KV; V4.1 §3.2.1).

Other changes. Single-Pass mHC uses the input-mixing coefficients one block later (Fl(Al−1Xl)\mathcal F_l(A_{l-1}X_l)), so the residual is read and written only once. Activation memory traffic halves from (4n+4)d(4n+4)d to the theoretical lower bound (2n+2)d(2n+2)d. A conditional memory module, Engram (196B parameters, 2-, 3- and 4-gram hash tables), is added, and instead of MTP a speculative-decoding module, DSpark, is trained separately after pre-training. Pre-training uses 45T multimodal tokens, sparse attention from the start (no dense warm-up), and a fixed batch of 100.6M tokens. The report states that post-training uses V4’s SFT → RL → OPD recipe with no algorithmic changes, and that only the scale of data synthesis and environment construction changed (V4.1 §1). The final full-vocabulary OPD used more than 40 teachers (V4.1 §5.2.4).

→ Go deeper: Both ends of the model — Engram and other n-gram embeddings, compared.

  1. 추론 벤치마크에서는 크기보다 모드가 크다. HMMT에서 Flash-Max(94.8)가 Pro-High(94.0)보다 높고, LiveCodeBench에서 Flash-Max 91.6은 Pro-High 89.8보다 높다. thinking 예산이 활성 파라미터 4배의 차이를 메운다.
  2. 지식은 크기다. SimpleQA-Verified에서 Flash-Max 34.1은 Pro의 Non-Think(45.0)에도 못 미친다. 생각을 오래 해도 모르는 사실은 나오지 않는다.
  3. Agent 과제는 그 사이. Terminal Bench 2.0은 Pro Non-Think(59.1)가 Flash-Max(56.9)보다 높다. 복잡한 agent 과제일수록 큰 모델이 앞선다는 보고서의 요약(§1)과 맞는다.
  4. 1M 문맥. MRCR에서 Non-Think는 37.5/44.7로 낮고 thinking 모드에서 80 안팎으로 오른다. 보고서 Figure 9에 따르면 128K까지는 검색 성능이 안정적이고 그 너머에서 떨어지기 시작한다.

후속: DeepSeek-V4.1-Flash

V4.1-Flash(2026년 9월)의 문제의식은 V4의 KV 계산 그림에 이미 있다. sparse attention으로 연산은 충분히 줄었으니, 이제 병목은 저장과 이동이다. agent 워크로드는 입력이 길고 tool 호출마다 prefill이 반복되며, prefix 재사용을 위해 KV를 HBM과 SSD에 오래 들고 있어야 한다(V4.1 §1). 보고서는 V4를 “SWA 기반의 지역 처리 backbone에 압축된 global 문맥을 붙인 것”으로 다시 보고, global 가지를 단순화하는 데 집중한다.

Causal Encoder-Decoder(CED). 40층을 인코더 20층과 디코더 20층으로 나누고, 디코더 층의 global KV를 자기 hidden state가 아니라 인코더 마지막 층의 hidden state에서 층별 가중치로 투영한다(YOCO에서 출발).

Cl=HL/2WlKV,Zl=HL/2WlZ,l>L/2C_l=H_{L/2}W^{KV}_l,\qquad Z_l=H_{L/2}W^{Z}_l,\qquad l>L/2

prefill에서는 인코더만 돌리면 디코더의 global KV가 나온다. 그래서 활성 파라미터가 prefill 8B, decode 16B로 다르다. SWA KV는 여전히 층마다 자기 hidden state로 만들기 때문에, 디코더의 SWA를 정확히 만들려면 마지막 L2×nwin\frac L2\times n_{\text{win}}개 토큰에 디코더를 돌려야 한다. V4.1은 대신 마지막 nwinn_{\text{win}}개만 다시 돌리는 근사(SWA Bounded Replay)를 쓰고, 품질 손실이 무시할 만하다고 보고한다. prefill 복잡도는 O(NL)O(NL)에서 O(NL/2+nwinL/2)≈O(NL/2)O(NL/2+n_{\text{win}}L/2)\approx O(NL/2)가 된다(V4.1 §2.2).

CSA2: 층 방향 공유. 각 CSA2 층은 세 모드 중 하나로 고정된다(V4.1 §2.3.1).

  • Full: 자기 main KV와 indexer를 계산하고 top-k를 새로 고른다(V4의 CSA 한 층과 같은 역할).
  • Reindex: 가장 최근 Full 층의 main KV와 indexer K를 빌려 쓰고, 자기 indexer query로 다시 채점해 top-k를 새로 고른다.
  • Reuse: main KV도 top-k 인덱스도 빌려 쓰고 attention만 한다.

모든 모드가 자기 query와 자기 SWA KV는 가진다. 인코더는 압축률 m=2m=2로 6층 그룹 3개(각 그룹 Full 1 + Reuse 5), 디코더는 압축 없이(m=1m=1) 4층 그룹 5개(첫 그룹만 Full, 나머지는 Reindex 1 + Reuse 3)다. HCA는 없앴고, CSA의 겹치는 창과 절대 위치 bias도 단순화를 위해 뺐다. 디코더의 Hierarchical Sparse Indexer는 Full 층이 8토큰 블록의 최대 점수로 2,048개 블록(16,384개 후보)을 골라 두면, 뒤의 Reindex 층들은 그 후보 안에서만 top-512를 고른다. 깊은 indexer의 query당 비용이 문맥 길이와 무관해진다.

FP4 main KV. main KV를 E2M1 + 16채널마다 E4M3 scale 하나(NVFP4에서 2단계 global scale을 뺀 형식)로 저장하도록 사후학습에서 QAT를 했다. global scale을 뺄 수 있는 근거가 깔끔하다. RMSNorm 가중치의 최대 크기가 약 1이므로 512채널 KV latent의 L2 norm이 약 512\sqrt{512} 이하이고, RoPE는 norm을 보존하므로 어떤 채널도 512≈22.6\sqrt{512}\approx22.6을 넘지 않는다. 형식이 표현할 수 있는 최대값은 448×6=2688448\times6=2688이라 여유가 충분하다(V4.1 §2.4.4). SWA KV는 양자화에 민감해 FP8로 남겼다.

이것들을 합치면 global KV가 토큰당 890바이트라고 보고한다. 설정으로 다시 세어 보면 정확히 맞는다.

3×288+682⏟인코더 Full 3층, m=2+1×(288+68)⏟디코더 Full 1층, m=1=534+356=890 B/토큰\underbrace{3\times\frac{288+68}{2}}_{\text{인코더 Full 3층},\ m=2}+\underbrace{1\times(288+68)}_{\text{디코더 Full 1층},\ m=1}=534+356=890\ \text{B/토큰}

여기서 288은 512채널 FP4(256 B) + E4M3 scale 32개(32 B), 68은 128차원 MXFP4 indexer key(64 B + 32원소마다 scale 1 B)다. Reindex와 Reuse 층은 KV를 저장하지 않으니 40층 중 4층만 global KV를 가진다. 위의 V4-Flash 추정치(약 3.47 KB)와 비교하면 3.9배로, 보고서의 “약 1/4”과 맞고, DeepSeek-V1 대비 437배 감소라는 보고서 Figure 1(b)의 비교도 61층이 아닌 95층 GQA8 BF16(95×4,096=389,12095\times4{,}096=389{,}120 B)으로 계산하면 389,120/890≈437389{,}120/890\approx437이 된다(DeepSeek LLM 67B 설정: 95층, KV head 8개, head 차원 8192/64=1288192/64=128; DeepSeek LLM 보고서 arXiv 2401.02954 Table 2. 보고서가 “V1”으로 이 모델을 가리킨다는 것은 우리의 해석이다). 위 KV 계산기에서 V4.1-Flash 막대를 눌러 구성을 볼 수 있다.

SSD 쪽. V4에서는 persistent KV cache 용량의 거의 절반을 SWA KV가 차지했다. V4.1은 SWA KV를 SSD에 저장하지 않고 몇 분짜리 TTL의 호스트 메모리 풀에만 두며, 놓치면 bounded replay로 nwinn_{\text{win}}개 토큰만 다시 계산한다. 그래서 persistent KV가 V4-Flash의 약 1/8이 된다(SWA 제거로 약 1/2, global KV 압축으로 약 1/4; V4.1 §3.2.1).

그 밖의 변화. Single-Pass mHC는 입력 혼합 계수를 한 블록 늦게 쓰게 해서(Fl(Al−1Xl)\mathcal F_l(A_{l-1}X_l)) 잔차를 한 번만 읽고 쓰게 만든다. activation 메모리 트래픽이 (4n+4)d(4n+4)d에서 이론적 하한 (2n+2)d(2n+2)d로 절반이 된다. 조건부 메모리 모듈 Engram(196B 파라미터, 2·3·4-gram hash 테이블)을 붙였고, MTP 대신 사전학습 후에 따로 학습하는 speculative decoding 모듈 DSpark를 쓴다. 사전학습은 45T 멀티모달 토큰, 처음부터 sparse attention(dense warm-up 없음), 배치 100.6M 토큰 고정이다. 사후학습은 SFT → RL → OPD라는 V4의 레시피를 알고리즘 변경 없이 쓰고, 바뀐 것은 데이터 합성과 환경 구축의 규모뿐이라고 명시한다(V4.1 §1). 마지막 full-vocabulary OPD에는 교사가 40개 넘게 쓰였다(V4.1 §5.2.4).

→ 더 깊이: 모델의 양 끝 — Engram을 다른 n-gram 임베딩과 비교한다.

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: V4.1-Flash report Table 3 (HLE omitted because for some models it is a text-only subset). 분야를 고르고, 범례의 모델 이름을 눌러 켜고 끌 수 있다. 막대 길이는 행마다 그 행의 최고점을 기준으로 맞춘 상대값이고(% 지표와 rating이 섞여 있기 때문), 막대 옆 숫자가 보고서에 적힌 원래 값이다. 빈칸은 보고서에 값이 없는 경우다. 출처: V4.1-Flash 보고서 Table 3 (HLE는 일부 모델이 text-only 부분집합이라 뺐다).

V4.1-Flash gains a lot over V4-Flash on agent benchmarks (DeepSWE v1.1 54.4 → 74.2), and with 1/3 of the active parameters it beats V4-Pro on most of them. On tasks that need expert knowledge, such as Terminal-Bench 3.0/4.0, a gap to the largest closed models remains. The report says that raising the reasoning effort from 25 to 100 increases output tokens by about 2.5× and lifts DeepSWE v1.1 from 66.0 to 74.2, and that the 60–80 range gets most of the peak performance with less than half the tokens (V4.1 §5.3.2).

확인 문제Check yourself

V4.1-Flash's decoder consists of 20 CSA2 layers with compression ratio m=1. How many of them actually store global KV?

Only the first layer of the decoder’s first group is in Full mode and builds its own global KV (projected from the encoder’s last hidden states). The first layers of the other groups are in Reindex mode: they borrow that KV and indexer K and only pick a fresh top-k, and the remaining layers are in Reuse mode. So the decoder’s global KV is one m=1m=1 layer’s worth, 288+68=356288+68=356 bytes per token, and together with the 534 bytes of the 3 encoder Full layers (m=2m=2) it comes to 890 bytes. Every layer still has its own query and SWA KV.

Reading critically

  • V4 has no architecture ablations. None of these is validated separately within the V4 report: CSA/HCA compared with MLA or V3.2’s DSA under the same conditions, with versus without mHC, Muon versus AdamW, hash routing, or the Sqrt(Softplus) affinity. The only evidence is the prior work it cites (mHC, Muon is Scalable) and the final model’s performance. This contrasts with the V3 report, which ablated MTP and aux-loss-free balancing on small models. So we cannot separate whether “V4-Flash-Base beats V3.2-Base” should be credited to the architecture or to the data (32T vs the V3 family’s 14.8T + extensions) and training.
  • The efficiency numbers are estimates. 27%/10% (V4-Pro) and 10%/7% (V4-Flash) are the “estimated” single-token FLOPs (FP8-equivalent) and cumulative KV size from Figure 1. The report itself states that FP4×FP8 compute has the same peak as FP8×FP8 on current hardware. There are no measurements of real serving throughput or latency. The byte counts we computed above also assume an alternation order, scale overhead and SWA entry size.
  • It is a “preview” version. The report’s title and abstract say preview explicitly, and numbers may change in later versions. Indeed, Table 3 of the V4.1 report lists DS-V4-Pro-Max’s Codeforces as 3348, different from the V4 report (3206) (apparently different evaluation runs). Even between reports from the same company, care is needed when carrying numbers over for comparison.
  • Evaluation settings vary. Codeforces is an internal benchmark built from 14 Div.1 contests from May–November 2025. Code agents were evaluated with an internal harness that has only bash and file-editing tools (up to 500 steps, 512K context), and Terminal-Bench 2.0 is reported on the original version while admitting known environment problems. Some competitor cells are empty because “the API was too busy”; for MRCR/CorpusQA the competitor models were re-evaluated in-house, and GPT-5.4 is missing because its API did not respond. Reported values and independently reproduced values must be kept apart.
  • Data and post-training scale are undisclosed. There is no breakdown of the 32T, no long-context data, no number of OPD teachers (“more than ten”) or weights wiw_i, no details of how the GRM doubles as the actor, and no scale for the rubric data. The claim that “having the actor double as the judge is robust” has no numerical support. A policy grading itself can develop a self-preference bias, and there is no analysis of that either.
  • Long-context quality. The report itself admits that MRCR performance drops beyond 128K. “Supporting” 1M is not the same as doing as well at 1M as at 128K.
  • V4.1’s approximations. The quality loss of SWA Bounded Replay and Single-Pass mHC is only described as “negligible”, and the body we read has no table of numbers. The sentence “able to complete over 95% of real tasks” also comes with no stated measurement method.

Summary

  • V4 shrinks the KV cache along the sequence. CSA compresses 4 tokens (an overlapping 8-token window) into one entry and reads only a top-k with the lightning indexer; HCA packs 128 tokens into one entry and reads them all. A 128-token SWA branch in every layer covers the recent stretch the compression cannot reach. Computed from the configuration, V4-Pro’s global KV is about 5 KB per token, about 2% of a BF16 GQA8 model of the same depth.
  • mHC makes the mixing matrix of the widened residual stream doubly stochastic with Sinkhorn, obtaining ∥B∥2≤1\|B\|_2\le1 and closure under products. The residual path does not blow up however deep the stack.
  • Muon’s Newton–Schulz applies the same scalar polynomial to every singular value. V4 runs 8 fast quintic steps and then 2 steps of a polynomial with f(1)=1, f′(1)=0f(1)=1,\ f'(1)=0 to pin the singular values at 1.
  • Post-training merges experts for each domain and reasoning effort (SFT + GRPO) with full-vocabulary multi-teacher OPD. The token-level KL estimate is unbiased but was dropped for its high variance. In tool conversations, reasoning is kept across user turns.
  • V4.1-Flash uses cross-layer sharing (CED, CSA2’s Full/Reindex/Reuse) and FP4 main KV to bring the global KV to 890 bytes per token (about 1/4 of V4-Flash’s), and takes SWA KV off SSD to cut persistent KV to about 1/8. The 890 is reproduced exactly from the configuration.
  • The results are strong, but the V4 report has no architecture ablations, its efficiency figures are estimates, and its evaluation leans heavily on internal harnesses and internal benchmarks.

V4.1-Flash는 V4-Flash 대비 agent 벤치마크에서 크게 오르고(DeepSWE v1.1 54.4 → 74.2), 활성 파라미터가 1/3인데 대부분 V4-Pro를 앞선다. Terminal-Bench 3.0/4.0처럼 전문 지식이 필요한 과제에서는 가장 큰 닫힌 모델과 격차가 남는다. 보고서는 추론 강도를 25에서 100으로 올리면 출력 토큰이 약 2.5배 늘면서 DeepSWE v1.1이 66.0에서 74.2로 오르고, 60–80 구간이 최대 성능의 대부분을 절반 이하 토큰으로 얻는다고 적는다(V4.1 §5.3.2).

확인 문제Check yourself

V4.1-Flash의 디코더는 압축률 m=1인 CSA2 층 20개로 되어 있는데, 이 중 global KV를 실제로 저장하는 층은 몇 개인가?

디코더 첫 그룹의 첫 층만 Full 모드로 자기 global KV(인코더 마지막 hidden state에서 투영)를 만든다. 나머지 그룹의 첫 층은 Reindex 모드라 그 KV와 indexer K를 빌려 쓰며 top-k만 새로 고르고, 다른 층은 Reuse 모드다. 그래서 디코더의 global KV는 m=1m=1 층 하나 분량인 토큰당 288+68=356288+68=356바이트이고, 인코더 Full 3층(m=2m=2)의 534바이트와 합쳐 890바이트가 된다. 모든 층이 자기 query와 SWA KV는 따로 가진다.

비판적으로 읽기

  • V4에는 아키텍처 ablation이 없다. CSA/HCA를 MLA나 V3.2의 DSA와 같은 조건에서 비교한 실험, mHC 유무, Muon 대 AdamW, Hash routing, Sqrt(Softplus) affinity 어느 것도 V4 보고서 안에서 따로 검증되지 않았다. 근거는 인용한 선행 연구(mHC, Muon is Scalable)와 최종 모델의 성능뿐이다. V3 보고서가 MTP와 aux-loss-free 균형을 작은 모델로 ablation한 것과 대조된다. 그래서 “V4-Flash-Base가 V3.2-Base를 이긴다”는 결과를 아키텍처 덕분으로 읽을지, 데이터(32T vs V3 계열의 14.8T + 연장)와 학습 덕분으로 읽을지 분리할 수 없다.
  • 효율 숫자는 추정치다. 27%/10%(V4-Pro), 10%/7%(V4-Flash)는 Figure 1의 “추정된” 단일 토큰 FLOPs(FP8 등가)와 누적 KV 크기다. FP4×FP8 연산이 현재 하드웨어에서 FP8×FP8과 같은 peak라는 것도 보고서가 직접 밝힌다. 실제 서빙 처리량이나 지연 측정은 없다. 우리가 위에서 계산한 바이트 수도 교대 순서, scale 오버헤드, SWA 항목 크기를 가정한 것이다.
  • “preview” 버전이다. 보고서 제목과 초록이 preview라고 명시한다. 이후 버전에서 숫자가 바뀔 수 있다. 실제로 V4.1 보고서의 Table 3에는 DS-V4-Pro-Max의 Codeforces가 3348로, V4 보고서(3206)와 다르게 적혀 있다(서로 다른 평가 실행으로 보인다). 같은 회사 보고서끼리도 숫자를 옮겨 비교할 때 조심해야 한다.
  • 평가 설정이 제각각이다. Codeforces는 2025년 5–11월 Div.1 14개 대회로 만든 내부 벤치마크다. 코드 agent는 bash와 파일 편집 도구만 있는 내부 harness(최대 500 step, 512K 문맥)로 평가했고, Terminal-Bench 2.0은 환경 문제가 알려져 있다고 인정하면서 원본으로 보고한다. 일부 경쟁 모델 칸은 “API가 너무 바빠서” 비어 있고, MRCR/CorpusQA는 경쟁 모델을 직접 다시 평가했으며 GPT-5.4는 API가 응답하지 않아 빠졌다. 보고된 값과 독립적으로 재현된 값을 구분해야 한다.
  • 데이터와 사후학습 규모가 비공개다. 32T의 구성비, 긴 문맥 데이터, OPD 교사의 수(“열 개 이상”)와 가중치 wiw_i, GRM을 actor로 겸하는 방식의 세부, rubric 데이터 규모가 없다. “actor가 judge를 겸하면 robust하다”는 주장에는 수치 근거가 없다. 정책이 자기 자신을 채점하면 self-preference 편향이 생길 수 있는데 이에 대한 분석도 없다.
  • 긴 문맥 품질. MRCR에서 128K를 넘으면 성능이 떨어진다고 보고서도 인정한다. 1M을 “지원한다”와 1M에서 128K만큼 잘한다는 다르다.
  • V4.1의 근사들. SWA Bounded Replay와 Single-Pass mHC의 품질 손실이 “무시할 만하다”고만 적었고 우리가 읽은 본문에는 수치 표가 없다. “실제 과제의 95% 이상을 완료할 수 있다”는 문장도 측정 방법이 제시되지 않았다.

정리

  • V4는 KV cache를 시퀀스 방향으로 줄였다. CSA는 4토큰(겹치는 8토큰 창)을 한 항목으로 압축한 뒤 lightning indexer로 top-k만 읽고, HCA는 128토큰을 한 항목으로 묶어 전부 읽는다. 모든 층의 128토큰 SWA 가지가 압축이 닿지 않는 최근 구간을 메운다. 설정으로 계산하면 V4-Pro의 global KV는 토큰당 약 5 KB로, 같은 깊이의 BF16 GQA8의 약 2%다.
  • mHC는 넓힌 잔차 스트림의 혼합 행렬을 Sinkhorn으로 doubly stochastic하게 만들어 ∥B∥2≤1\|B\|_2\le1과 곱에 대한 닫힘을 얻는다. 깊이 쌓아도 잔차 경로가 폭발하지 않는다.
  • Muon의 Newton–Schulz는 특이값마다 같은 스칼라 다항식을 적용한다. V4는 빠른 quintic 8회 뒤 f(1)=1, f′(1)=0f(1)=1,\ f'(1)=0인 다항식 2회로 특이값을 1에 고정한다.
  • 사후학습은 도메인·추론 강도별 전문가(SFT + GRPO)를 full-vocabulary 다중 교사 OPD로 합친다. 토큰 수준 KL 추정은 불편이지만 분산이 커서 버렸다. tool 대화에서는 reasoning을 사용자 턴을 넘어 유지한다.
  • V4.1-Flash는 층 방향 공유(CED, CSA2의 Full/Reindex/Reuse)와 FP4 main KV로 global KV를 토큰당 890바이트(V4-Flash의 약 1/4)로, SWA KV를 SSD에서 빼서 persistent KV를 약 1/8로 줄였다. 890은 설정으로 정확히 재현된다.
  • 결과는 강하지만 V4 보고서에는 아키텍처 ablation이 없고, 효율 수치는 추정치이며, 평가는 내부 harness·내부 벤치마크 비중이 크다.

더 읽을거리Further reading