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-Flash | DeepSeek-V4-Pro | DeepSeek-V4.1-Flash | |
|---|---|---|---|
| Release | 2026-04 (preview) | 2026-04 (preview) | 2026-09 |
| Parameters (total / active) | 284B / 13B | 1.6T / 49B | 552B backbone + 196B Engram / prefill 8B, decode 16B |
| Layers / hidden | 43 / 4096 | 61 / 7168 | 40 (encoder 20 + decoder 20) / 5120 |
| Attention | 2 SWA layers + alternating CSA·HCA | 2 HCA layers + alternating CSA·HCA | 2 SWA layers + CSA2 (Full/Reindex/Reuse) |
| MoE | 1 shared + 6 of 256 routed | 1 shared + 6 of 384 routed | 1 shared + 6 of 384 routed |
| Context | 1M | 1M | 1M |
| Pre-training tokens | 32T | 33T | 45T (multimodal) |
| Optimizer | Muon + AdamW | Muon + AdamW | Muon (head-wise) + AdamW + Sinkhorn-balanced |
| Openness | weights released (Hugging Face) | weights released | weights released |
| Link | arXiv 2606.19348 | same | arXiv 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 to ; 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.
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 , CSA builds two sets of KV candidates and two sets of compression weights (report Eqs. 9–10).
The -th compressed entry is a weighted sum over tokens: of its own block and of the immediately preceding block (Eqs. 11–12).
The softmax normalises over the positions separately for each channel (which is why is a Hadamard product), and are learned biases for each position inside the block. The window is , but it overlaps half of each neighbouring entry, so the number of entries is . 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 , and the query side is made low-rank (Eqs. 13–16).
Only the compressed entries with the highest scores are kept (Eq. 17). The causality condition is : 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 is shared with the indexer query. Because the output — the number of heads times the head dimension — is large ( in V4-Pro), the output projection is also split in two. The heads are grouped into groups, each group is reduced to dimensions, and the dimensions are then mapped to (grouped output projection). Counting with V4-Pro’s setting (), the projection parameters drop from million for a single projection to million (our calculation).
HCA: compress heavily and read everything
HCA applies the same compression without overlap and at a much larger ratio (Eqs. 20–23).
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 carries the rotation of the absolute position . So RoPE for position is applied once more to the last 64 dimensions of the output.
Because rotation matrices satisfy , only the relative distance remains in the output.
- Sliding-window branch. Alongside the compressed entries, each query also sees the uncompressed KV of the most recent 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 , 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.
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-Flash | DeepSeek-V4-Pro | DeepSeek-V4.1-Flash | |
|---|---|---|---|
| 발표 | 2026-04 (preview) | 2026-04 (preview) | 2026-09 |
| 파라미터 (총 / 활성) | 284B / 13B | 1.6T / 49B | 552B backbone + 196B Engram / prefill 8B, decode 16B |
| 층 / hidden | 43 / 4096 | 61 / 7168 | 40 (인코더 20 + 디코더 20) / 5120 |
| Attention | SWA 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 |
| 문맥 | 1M | 1M | 1M |
| 사전학습 토큰 | 32T | 33T | 45T (멀티모달) |
| Optimizer | Muon + AdamW | Muon + AdamW | Muon(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 함수가 에서 로 바뀌었고, 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의 크기는 세 축의 곱이다.
V4.1 보고서가 이 틀을 명시적으로 쓴다(V4.1 §2.3). GQA와 MLA는 첫째 축을, V4의 CSA/HCA는 둘째 축을, V4.1의 CSA2는 셋째 축을 줄인다. V3.2의 DSA는 어느 축도 줄이지 않는다. 읽는 양(연산)만 top-k로 줄이고 저장은 그대로다.
CSA: 압축한 뒤 sparse하게 읽기
입력 hidden state 에서 CSA는 KV 후보 두 벌과 압축 가중치 두 벌을 만든다(보고서 식 9–10).
번째 압축 항목은 자기 블록 의 와 바로 앞 블록 의 , 합쳐 개 토큰의 가중합이다(식 11–12).
softmax는 개 위치에 걸쳐 채널마다 따로 정규화되고(가 Hadamard 곱인 이유), 는 블록 안 위치별 학습 bias다. 창이 이지만 이웃 항목과 절반씩 겹치므로 항목 수는 이다. 겹치게 만든 이유는 블록 경계에 걸친 정보가 한쪽 항목에서 잘리지 않게 하기 위해서로 보인다.
다음은 V3.2의 lightning indexer를 압축 항목 위에서 돌리는 것이다. indexer key도 같은 방식으로 압축해 를 만들고, query 쪽은 저랭크로 만든다(식 13–16).
점수가 높은 개 압축 항목만 남긴다(식 17). 인과성 조건은 다. 블록이 다 차지 않은 항목은 미래 토큰을 포함할 수 있으니 볼 수 없다.
core attention은 MQA다. 압축 항목 하나가 key이자 value이고(head가 하나), 모든 query head가 그것을 공유한다(식 18–19). query 저랭크 latent 는 indexer query와 같이 쓴다. head 수 와 head 차원 를 곱한 출력 가 크므로(V4-Pro에서 ), 출력 투영도 둘로 나눈다. 개 head를 개 그룹으로 묶어 그룹마다 차원으로 줄인 뒤, 차원을 로 보낸다(grouped output projection). V4-Pro 설정()으로 세어 보면 투영 파라미터가 한 번에 보낼 때의 억 개에서 억 개로 줄어든다(우리 계산).
HCA: 크게 압축하고 전부 읽기
HCA는 같은 압축을 겹침 없이, 훨씬 큰 비율 로 한다(식 20–23).
그리고 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로도 쓰이므로 출력 가 절대 위치 의 회전을 품게 된다. 그래서 출력의 마지막 64차원에 위치 의 RoPE를 한 번 더 건다.
회전행렬이 를 만족하므로 출력에는 상대 거리 만 남는다.
- Sliding window 가지. 각 query는 압축 항목과 함께 최근 개 토큰의 압축하지 않은 KV도 본다. 자기 블록이 덜 찬 구간(인과성 때문에 압축 항목으로 못 보는 부분)과 가까운 문맥의 세밀한 의존성을 메운다.
- Attention sink. head마다 학습되는 sink logit 를 분모에 더한다(식 27). 한 head가 “볼 것이 없다”는 판단을 할 수 있게, 즉 attention 합이 1보다 작아질 수 있게 한다.
아래 그림은 이 구성 요소들이 한 query에서 어떻게 맞물리는지를 축소된 장난감으로 보여 준다.
- 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.
- 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.
- 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 bytes. The CSA indexer key () is stored in MXFP4 after post-training QAT (§5.2.1), so we count it as bytes + 1 byte of scale per 32 elements, i.e. bytes. With these, V4-Pro’s global KV per token is
(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 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.
- t를 움직이면 CSA 줄의 회색(아직 볼 수 없는) 영역이 query 바로 앞까지 오지 않는다. 그 빈틈은 항상 연두색 SWA 창이 덮는다.
- top-k를 1로 줄이면 관련 토큰 중 일부를 놓친다. 실제 CSA는 indexer가 학습되어 있고 V4-Pro에서 k=1024라, 장난감보다 훨씬 넉넉하다.
- m을 키우면 CSA 항목 하나가 더 많은 토큰을 덮는다. 같은 k로 더 넓게 보지만 항목 하나에 섞이는 토큰이 많아져 해상도가 떨어진다. HCA는 그 극단이다.
얼마나 줄었나: KV cache 계산
보고서의 저장 형식(§2.3.4)은 KV 항목의 RoPE 64차원은 BF16, 나머지 448차원은 FP8이다. 그러면 항목 하나가 바이트다. CSA indexer key()는 사후학습의 QAT 이후 MXFP4로 저장되니(§5.2.1) 바이트 + 32원소마다 1바이트 scale로 바이트로 잡는다. 이것으로 V4-Pro의 토큰당 global KV를 세면
이다(앞 2층 HCA 뒤 59층이 CSA부터 교대한다고 가정한 우리 추정. 보고서는 교대 순서와 FP8 scale 오버헤드를 적지 않는다). BF16 GQA8(head dim 128)을 같은 61층으로 쌓으면 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 토큰 서빙에서 무엇을 뜻하는지 다룬다.
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 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 to . The layer function (attention or MoE) still takes and returns dimensions, and three small matrices connect the stream and the layer (Eq. 1).
With this is the ordinary residual . Since is much smaller than (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 layers is , and if the spectral norm of 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 to the set of doubly stochastic matrices (the Birkhoff polytope) (Eq. 2).
The properties this constraint gives are proved in three lines.
- Row and column sums are 1 and the entries are non-negative, so . Since , it is non-expansive. The signal grows neither in the forward pass nor in the backward pass, where the transpose is applied.
- If , then , , and the entries are non-negative, so . It is closed under multiplication, so however many layers are stacked, the whole residual path is still non-expansive.
- . The residual path exactly preserves the sum of the streams and only mixes mass between them.
and are made non-negative and bounded with a sigmoid (; Eqs. 6–7), to keep signals from cancelling each other. All three matrices depend on the input. From , the flattened and RMS-normalised , a linear map produces a dynamic component, which is multiplied by a gate initialised to a small value and added to a static bias (Eqs. 3–5).
After makes the entries positive, the Sinkhorn–Knopp iteration , alternating column and row normalisation, is run for 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, 저장하지 않고 토큰 재계산)를 둔다(§3.5.2). 이 문제는 V4.1에서 다시 등장한다.
mHC: 잔차 스트림을 넓히되 폭발하지 않게
Hyper-Connections(HC)는 잔차 스트림을 에서 로 넓힌다. 층 함수 (attention이나 MoE)은 여전히 차원을 받고 내보내며, 세 개의 작은 행렬이 스트림과 층을 잇는다(식 1).
이면 보통의 residual 이다. 는 보다 훨씬 작으니(V4는 4) 연산은 거의 늘지 않으면서 잔차 폭이라는 새 스케일링 축이 생긴다. 문제는 깊이다. 층 함수 기여를 빼면 층 뒤의 잔차 경로는 이고, 의 spectral norm이 1보다 조금만 커도 곱은 지수적으로 커진다. 보고서는 HC를 여러 층 쌓으면 학습이 자주 수치적으로 불안정해졌다고 적는다(§2.2).
mHC는 을 doubly stochastic 행렬의 집합(Birkhoff polytope)으로 제한한다(식 2).
이 제약이 주는 성질은 세 줄로 증명된다.
- 행 합과 열 합이 1이고 원소가 음수가 아니므로 이다. 이므로 비확장(non-expansive) 이다. 순전파에서도, 전치가 곱해지는 역전파에서도 신호가 커지지 않는다.
- 이면 , , 원소도 음수가 아니므로 이다. 곱에 대해 닫혀 있으니 몇 층을 쌓아도 잔차 경로 전체가 여전히 비확장이다.
- 이다. 잔차 경로는 스트림들의 합을 정확히 보존하고, 스트림 사이에 질량을 섞기만 한다.
과 은 sigmoid로 음이 아니고 유계가 되게 한다(; 식 6–7). 신호가 서로 상쇄되는 것을 막기 위해서다. 세 행렬은 입력에 따라 달라진다. 을 펼쳐 RMSNorm한 에서 선형 사상으로 동적 성분을 만들고, 작은 값으로 초기화한 게이트 를 곱해 정적 bias 에 더한다(식 3–5).
로 양수를 만든 뒤 열 정규화와 행 정규화를 번갈아 하는 Sinkhorn–Knopp 반복 을 회 돌린다(식 8). 양수 행렬에서 이 반복은 doubly stochastic 행렬로 수렴한다.
→ 더 깊이: 안정화 부품 — mHC를 다른 residual 변형, norm 위치와 함께 본다.
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 matrix — and memory traffic for residual activations that are 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
| V3 | V4 | V4.1-Flash | |
|---|---|---|---|
| Pre-training tokens | 14.8T | 32T (Flash) / 33T (Pro), corpus over 32T | 45T, text + images |
| Tokenizer | byte-level BPE 128K | V3 tokenizer + special tokens for context construction, still 128K | not described separately in the body |
| Document packing | packing, no cross-sample masking | packing + sample-level attention masking | sample-level masking |
| Notes | larger share of math and code, FIM 0.1 | auto-generated and templated web documents removed (to prevent model collapse), long documents (papers, technical reports) prioritised, more languages, agentic data in mid-training | multimodal 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-Flash | V4-Pro | |
|---|---|---|
| Optimizer | Muon (most matrices) + AdamW (embedding, output head, RMSNorm weights, mHC static biases and gates) | same |
| AdamW | , , weight decay 0.1 | same |
| Muon | momentum 0.95, weight decay 0.1, update RMS rescaled to 0.18 | same |
| Tokens / max batch | 32T / 75.5M tokens | 33T / 94.4M tokens |
| LR | 2000-step warmup → hold at → cosine to at the end | peak , final |
| Context | 4K → 16K → 64K → 1M | same |
| Sparse attention | dense for the first 1T tokens, sparse after indexer warm-up at 64K | longer dense phase, same method |
| Load balancing | bias update speed 0.001, balance loss weight 0.0001 | same |
| MTP loss weight | 0.3 → 0.1 from the start of LR decay | same |
(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:
For the ideal result is , the matrix with every singular value set to 1. SVD is expensive, so we start from (so that the singular values are at most 1) and iterate an odd polynomial (Eq. 28).
Substituting gives , so the iteration applies the scalar polynomial to each singular value independently. A one-dimensional graph therefore tells the whole story. V4 uses for the first 8 steps to lift small singular values quickly, then switches to for the last 2 steps to pin them exactly at 1 (§2.4). The second polynomial has , so it converges quadratically near 1.
→ Go deeper: the derivations behind Muon and Newton–Schulz iterations are in Muon and orthogonalised optimisers.
Sinkhorn 반복이 미분 가능한 연산이라 역전파가 그대로 통과한다. 대가는 층마다 행렬에 20번의 정규화를 하는 작은 연산과, 배로 늘어난 잔차 activation의 메모리 트래픽이다. V4는 재계산과 fused kernel로 이것을 감당하고(§3.4.2), V4.1은 이 트래픽을 다시 절반으로 줄인다(아래 V4.1 절).
데이터
| V3 | V4 | V4.1-Flash | |
|---|---|---|---|
| 사전학습 토큰 | 14.8T | 32T(Flash) / 33T(Pro), 코퍼스 32T 이상 | 45T, 텍스트+이미지 |
| 토크나이저 | byte-level BPE 128K | V3 토크나이저 + 문맥 구성용 special token, 128K 유지 | 본문에 별도 서술 없음 |
| 문서 packing | packing, cross-sample masking 없음 | packing + sample-level attention masking | sample-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-Flash | V4-Pro | |
|---|---|---|
| Optimizer | Muon(대부분의 행렬) + AdamW(embedding, 출력 head, RMSNorm 가중치, mHC의 정적 bias·게이트) | 같음 |
| AdamW | , , weight decay 0.1 | 같음 |
| Muon | momentum 0.95, weight decay 0.1, update RMS를 0.18로 재조정 | 같음 |
| 토큰 / 최대 배치 | 32T / 75.5M 토큰 | 33T / 94.4M 토큰 |
| LR | 2000 step warmup → 유지 → 끝에서 cosine으로 | 피크 , 끝 |
| 문맥 | 4K → 16K → 64K → 1M | 같음 |
| Sparse attention | 처음 1T 토큰은 dense, 64K에서 indexer warm-up 후 sparse | dense 구간이 더 김, 방법은 같음 |
| 부하 균형 | 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은 다음과 같다.
일 때 이상적인 결과는 , 즉 모든 특이값을 1로 만든 행렬이다. SVD는 비싸므로 (특이값이 1 이하가 되게)에서 시작해 홀수 다항식을 반복한다(식 28).
을 대입하면 이므로, 이 반복은 특이값마다 독립적으로 스칼라 다항식 를 적용한다. 그래서 1차원 그래프로 전부 이해할 수 있다. V4는 처음 8회에 로 작은 특이값을 빠르게 끌어올리고, 마지막 2회를 로 바꿔 1에 정확히 고정한다(§2.4). 두 번째 다항식 는 이라 1 근처에서 이차 수렴한다.
→ 더 깊이: Muon과 Newton–Schulz 반복의 유도는 Muon과 직교화 옵티마이저에 있다.
The factor that sets the update RMS to 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.
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 stays at about 0.21. The hybrid all but removes that wobble in its last 2 steps. The smallest singular value (), 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 , features are computed with the current parameters , but the routing indices are computed with past parameters . The interpretation is that this breaks the loop “router changes expert assignment → that expert is updated → router changes again”. The data for step is read ahead at time 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 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:
Here is the k3 estimator corrected with an importance ratio for samples from , and is the off-policy mask that switches off sequences with negative advantage that have drifted far from (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).
| Mode | Format | Difference during RL | Eval context |
|---|---|---|---|
| Non-think | </think> summary | — | 8K |
| Think High | <think> thinking </think> summary | medium length penalty and context window | 128K |
| Think Max | a “maximum reasoning” instruction before the system prompt + the format above | longer context, weaker length penalty | 384K |
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 experts () as teachers, the student minimises the reverse KL to the teachers on trajectories it generated itself (Eq. 29).
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 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 entries. (2) Each channel’s softmax weights sum to 1 over the positions. (3) Changing one token changes exactly two compressed entries (its own block, used as , and the next block, used as ), and none of the entries visible to the query at that token’s position () changes.
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 to , but that is still proportional to the context length.
2. mHC: Sinkhorn projection and depth
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, is not merely at most 1 but exactly 1. Since and , we have , i.e. 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 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 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).
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)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, , and therefore . 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 , the total energy does not grow.
3. OPD: full-vocabulary KL vs token-level estimate
Given a student distribution (logits ) and a teacher distribution at one position, the logit gradient of the reverse KL can be computed exactly.
The token-level estimate draws a single and uses . Since , this estimator is unbiased (its expectation equals the expression above). The problem is the variance.
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를 로 맞추는 배율은 Liu et al.(2025)의 트릭이다. 직교 행렬의 원소 RMS는 크기에 따라 달라지는데, 그것을 AdamW update의 전형적인 RMS에 맞춰 AdamW용 learning rate와 weight decay를 그대로 재사용하게 한다.
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 사이에 남아 과의 상대 오차가 약 0.21에 머문다. 하이브리드는 마지막 2회에 그 출렁임을 거의 없앤다. 다만 가장 작은 특이값()은 8회의 quintic 동안 겨우 0.68 근처에 도달하므로, 아주 작은 특이값까지 1로 보내는 것이 목표는 아니다. 실전 Muon에서도 정확한 직교화보다 “대부분의 방향을 비슷한 크기로” 만드는 것이 핵심이다.
학습 불안정성: 두 가지 처방
V3는 학습 내내 회복 불가능한 loss spike가 없었다고 보고했지만, 1.6T의 V4는 spike를 겪었다(§4.2.3). 보고서는 spike가 MoE 층의 이상치(outlier)와 연결되어 있고 routing이 그것을 키운다고 진단하고, 두 기법을 공개한다. 둘 다 왜 듣는지에 대한 이론은 없다고 스스로 밝힌다.
- Anticipatory Routing. step 에서 feature는 현재 파라미터 로 계산하되, routing 인덱스는 과거 파라미터 로 계산한다. “router가 바꾼 expert 배정 → 그 expert의 업데이트 → 다시 router 변화”의 순환을 끊는다는 해석이다. step 의 데이터를 시점에 미리 읽어 routing을 계산해 두고, 추가 비용은 약 20%로 묶었다. 상시 켜 두지 않고 spike가 감지되면 짧게 rollback한 뒤 한동안만 켠다.
- SwiGLU clamping. SwiGLU의 선형 성분을 으로, 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에서 정리한 형태를 이 사이트의 표기로 쓰면
이고, 은 샘플에 대해 importance ratio를 곱해 바로잡은 k3 추정량, 는 음의 advantage이면서 와 크게 벌어진 시퀀스를 끄는 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로 통합. 전문가 개()를 교사로 두고, 학생 가 자기가 생성한 궤적 위에서 교사들과의 reverse KL을 줄인다(식 29).
reverse KL은 mode-seeking이다. 학생은 교사가 확률을 거의 주지 않는 곳에 확률을 두면 크게 벌을 받으므로, 과제에 맞는 교사의 행동 쪽으로 붙는다(증류 레슨). 기존 구현은 RL 프레임워크를 재사용해 샘플된 토큰 하나의 를 advantage처럼 쓰는 토큰 수준 추정을 했는데, V4는 이것이 gradient 분산이 커서 불안정하다며 어휘 전체의 logit으로 KL을 정확히 계산한다. 어휘가 10만이 넘는 교사 열몇 개의 logit을 저장할 수는 없으니, 교사의 마지막 hidden state만 저장해 두고 학습 때 교사의 출력 head를 다시 적용해 logit을 복원하며, 샘플을 교사 순서로 정렬해 한 번에 한 교사의 head만 GPU에 올린다(§5.2.2). 두 추정량의 차이는 아래 “깊게 보기”에서 계산해 본다.
핵심 method 깊게 보기
1. CSA의 압축과 인과성
식 11–12를 그대로 옮겨 압축 항목을 만들고, 세 가지를 확인한다. (1) 항목 수가 이다. (2) 각 채널의 softmax 가중치가 개 위치에서 합 1이다. (3) 토큰 하나를 바꾸면 정확히 두 압축 항목(로 쓰는 자기 블록, 로 쓰는 다음 블록)만 바뀌고, 그 토큰 위치의 query가 볼 수 있는 항목()은 하나도 바뀌지 않는다.
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의 개에서 개로 줄었지만 여전히 문맥 길이에 비례한다.
2. mHC: Sinkhorn 투영과 깊이
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이 수렴하면 는 1 이하인 정도가 아니라 정확히 1이다. 이고 이라 , 즉 이 특이값 1의 특이벡터다. 반복이 2회뿐이면 아직 doubly stochastic이 아니어서 norm이 1을 넘는 행렬이 나온다(첫 줄). mHC의 곱은 방향의 특이값이 1로 유지되고 나머지는 1 이하라 norm이 1에 머문다. 반대로 말하면 깊이 쌓을수록 잔차 경로가 스트림들을 평균 쪽으로 섞는 경향이 있다(doubly stochastic 행렬의 곱은 균일 평균 행렬로 수렴하기 쉽다). 정적 bias 를 항등 행렬 근처로 두면 각 층의 섞임이 작아진다. 보고서는 초기값을 밝히지 않는다.
PyTorch로는 한 블록을 이렇게 쓸 수 있다(보고서 식 1–8을 옮긴 것이고, 초기화 값은 우리 선택이다).
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)mHC에서 잔차 행렬 B가 doubly stochastic이면, 층 함수 출력을 제외한 잔차 경로(X → BX)가 n개 스트림에 대해 항상 정확히 보존하는 것은?
열 합이 1이라 이고, 따라서 다. 스트림 사이에 신호를 섞을 뿐 총합은 바꾸지 않는다. 각 스트림의 노름은 보존되지 않는다(평균 쪽으로 섞이면 줄어든다). 이므로 전체 에너지는 늘지 않는다.
3. OPD: full-vocabulary KL vs 토큰 수준 추정
한 위치에서 학생 분포 (logit )와 교사 분포 가 있을 때 reverse KL의 logit gradient는 정확히 계산된다.
토큰 수준 추정은 하나를 뽑아 를 쓴다. 이므로 이 추정량은 불편이다(위 식과 기대값이 같다). 문제는 분산이다.
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)
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)
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이 더 흥미롭다.
- 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.
- 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.
- 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).
- 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).
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 tokens. V4.1 instead uses an approximation that reruns only the last tokens (SWA Bounded Replay) and reports that the quality loss is negligible. Prefill complexity goes from to (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 , has 3 groups of 6 layers (each group Full 1 + Reuse 5); the decoder, with no compression (), 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 , and RoPE preserves norms, so no channel exceeds . The largest value the format can represent is , 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.
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 if computed with a 95-layer GQA8 BF16 model ( B) rather than a 61-layer one (DeepSeek LLM 67B configuration: 95 layers, 8 KV heads, head dimension ; 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 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 (), so the residual is read and written only once. Activation memory traffic halves from to the theoretical lower bound . 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.
- 추론 벤치마크에서는 크기보다 모드가 크다. HMMT에서 Flash-Max(94.8)가 Pro-High(94.0)보다 높고, LiveCodeBench에서 Flash-Max 91.6은 Pro-High 89.8보다 높다. thinking 예산이 활성 파라미터 4배의 차이를 메운다.
- 지식은 크기다. SimpleQA-Verified에서 Flash-Max 34.1은 Pro의 Non-Think(45.0)에도 못 미친다. 생각을 오래 해도 모르는 사실은 나오지 않는다.
- Agent 과제는 그 사이. Terminal Bench 2.0은 Pro Non-Think(59.1)가 Flash-Max(56.9)보다 높다. 복잡한 agent 과제일수록 큰 모델이 앞선다는 보고서의 요약(§1)과 맞는다.
- 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에서 출발).
prefill에서는 인코더만 돌리면 디코더의 global KV가 나온다. 그래서 활성 파라미터가 prefill 8B, decode 16B로 다르다. SWA KV는 여전히 층마다 자기 hidden state로 만들기 때문에, 디코더의 SWA를 정확히 만들려면 마지막 개 토큰에 디코더를 돌려야 한다. V4.1은 대신 마지막 개만 다시 돌리는 근사(SWA Bounded Replay)를 쓰고, 품질 손실이 무시할 만하다고 보고한다. prefill 복잡도는 에서 가 된다(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는 가진다. 인코더는 압축률 로 6층 그룹 3개(각 그룹 Full 1 + Reuse 5), 디코더는 압축 없이() 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이 약 이하이고, RoPE는 norm을 보존하므로 어떤 채널도 을 넘지 않는다. 형식이 표현할 수 있는 최대값은 이라 여유가 충분하다(V4.1 §2.4.4). SWA KV는 양자화에 민감해 FP8로 남겼다.
이것들을 합치면 global KV가 토큰당 890바이트라고 보고한다. 설정으로 다시 세어 보면 정확히 맞는다.
여기서 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( B)으로 계산하면 이 된다(DeepSeek LLM 67B 설정: 95층, KV head 8개, head 차원 ; 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로 개 토큰만 다시 계산한다. 그래서 persistent KV가 V4-Flash의 약 1/8이 된다(SWA 제거로 약 1/2, global KV 압축으로 약 1/4; V4.1 §3.2.1).
그 밖의 변화. Single-Pass mHC는 입력 혼합 계수를 한 블록 늦게 쓰게 해서() 잔차를 한 번만 읽고 쓰게 만든다. activation 메모리 트래픽이 에서 이론적 하한 로 절반이 된다. 조건부 메모리 모듈 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 임베딩과 비교한다.
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).
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 layer’s worth, bytes per token, and together with the 534 bytes of the 3 encoder Full layers () 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 , 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 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 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).
V4.1-Flash의 디코더는 압축률 m=1인 CSA2 층 20개로 되어 있는데, 이 중 global KV를 실제로 저장하는 층은 몇 개인가?
디코더 첫 그룹의 첫 층만 Full 모드로 자기 global KV(인코더 마지막 hidden state에서 투영)를 만든다. 나머지 그룹의 첫 층은 Reindex 모드라 그 KV와 indexer K를 빌려 쓰며 top-k만 새로 고르고, 다른 층은 Reuse 모드다. 그래서 디코더의 global KV는 층 하나 분량인 토큰당 바이트이고, 인코더 Full 3층()의 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 교사의 수(“열 개 이상”)와 가중치 , 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하게 만들어 과 곱에 대한 닫힘을 얻는다. 깊이 쌓아도 잔차 경로가 폭발하지 않는다.
- Muon의 Newton–Schulz는 특이값마다 같은 스칼라 다항식을 적용한다. V4는 빠른 quintic 8회 뒤 인 다항식 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
- DeepSeek-AI, DeepSeek-V4: Towards Highly Efficient Million-Token Context Intelligence (2026) — 이 레슨이 리뷰하는 보고서. CSA/HCA, mHC, Muon, OPD, 인프라(TileLang, 결정적 커널, KV 저장)까지.The report this lesson reviews. CSA/HCA, mHC, Muon, OPD, and the infrastructure (TileLang, deterministic kernels, KV storage).
- DeepSeek-AI, DeepSeek-V4.1-Flash: Pushing the Limits of KV Cache Compression (2026) — 후속작. Causal Encoder-Decoder, CSA2의 층 간 KV·인덱스 재사용, FP4 main KV, SWA Bounded Replay.The follow-up. Causal Encoder-Decoder, CSA2's cross-layer KV and index reuse, FP4 main KV, SWA Bounded Replay.
- DeepSeek-AI, DeepSeek-V3.2: Pushing the Frontier of Open Large Language Models (2025) — CSA의 sparse 선택 부분인 DeepSeek Sparse Attention(lightning indexer)과 GRPO 안정화 기법의 출처.Source of DeepSeek Sparse Attention (the lightning indexer), the sparse-selection part of CSA, and of the GRPO stabilisation techniques.
- Xie et al., mHC: Manifold-Constrained Hyper-Connections (2025) — 잔차 행렬을 Birkhoff polytope에 투영하는 아이디어의 원 논문. V4 보고서에는 ablation이 없으니 근거는 여기서 본다.The original paper behind projecting the residual matrix onto the Birkhoff polytope. The V4 report has no ablation, so this is where to look for evidence.
- Liu et al., Muon is Scalable for LLM Training (2025) — weight decay와 update RMS 맞추기로 Muon을 대규모 LLM에 적용한 레시피. V4가 그대로 따르고 Newton–Schulz만 바꿨다.The recipe that applied Muon to large-scale LLMs by matching weight decay and update RMS. V4 follows it as is and changes only the Newton–Schulz iteration.
- Yuan et al., Native Sparse Attention: Hardware-Aligned and Natively Trainable Sparse Attention (2025) — 압축 토큰 + 선택 + sliding window를 섞는 학습 가능한 sparse attention. CSA/HCA와 비교해 읽기 좋다.Trainable sparse attention mixing compressed tokens + selection + a sliding window. Good to read alongside CSA/HCA.
- Sun et al., You Only Cache Once: Decoder-Decoder Architectures for Language Models (2024) — 위쪽 층이 아래쪽 층의 KV를 공유하는 YOCO. V4.1-Flash의 CED가 이것을 확장했다.YOCO, where upper layers share the KV of lower layers. V4.1-Flash's CED extends it.
- Gu et al., MiniLLM: On-Policy Distillation of Large Language Models (2023) — 학생 샘플 위에서 reverse KL을 줄이는 on-policy distillation. V4 사후학습의 통합 단계가 이 목적함수다.On-policy distillation that minimises reverse KL on student samples. The merge stage of V4's post-training uses this objective.