Track VII · Architecture Deep Dives · 08/12

DeepSeek 계보: V2 → V3 → V3.2 → V4 → V4.1The DeepSeek lineage: V2 → V3 → V3.2 → V4 → V4.1

DeepSeek 다섯 세대가 블록의 어느 부분을 왜 바꿨는지를 토큰당 비용의 세 인수(항목 크기 × 저장 항목 수 × KV를 가진 층 수)와 활성 파라미터로 읽는다. 각 세대가 공격한 병목, 보고서의 근거, 그리고 공개 config로 다시 계산한 KV·FLOPs와 교차점.Why each of five DeepSeek generations changed which part of the block, read through the per-token cost — entry size × entries stored × layers holding KV, plus active parameters. The bottleneck each generation attacked, the evidence its report gives, and KV/FLOPs and crossovers recomputed from the public configs.

The Track VI reviews read each DeepSeek report on its own (V3, V3.2, V4 + V4.1-Flash). This lesson reads them as one sequence of decisions. Across two and a half years the skeleton barely moves — a pre-norm stack of “attention slot + DeepSeekMoE slot”, a shared expert, an untied head — while one part after another is replaced. The question to keep asking is: at that moment, what was the most expensive thing about producing one token, and which change attacked it?

The components themselves are derived elsewhere: MLA and its absorption trick in attention and KV, DSA and CSA in sparse attention, aux-loss-free balancing and hash routing in MoE, mHC in stability components, MTP in MTP and embeddings. Here we only need their cost signatures.

One token’s bill

Decoding one token at context length LL costs, to first order,

FLOPs(L)≈2Nact+2∑ℓ(nℓread(L) cℓattn+nℓscore(L) cℓidx),KV(L)=∑ℓbℓ nℓstore(L)\text{FLOPs}(L)\approx 2N_{\text{act}}+2\sum_{\ell}\Big(n^{\text{read}}_\ell(L)\,c^{\text{attn}}_\ell+n^{\text{score}}_\ell(L)\,c^{\text{idx}}_\ell\Big),\qquad \text{KV}(L)=\sum_\ell b_\ell\,n^{\text{store}}_\ell(L)

NactN_{\text{act}} is the active parameter count; for layer ℓ\ell, nstoren^{\text{store}} is how many cache entries it keeps, nreadn^{\text{read}} how many the core attention reads, nscoren^{\text{score}} how many an indexer scores, bb the bytes per entry and cc the multiply-accumulates per entry. The V4.1 report states the storage half of this as a product of three axes (V4.1 §2.3):

KV bytes per token=b⏟bytes per entry×nstore/L⏟entries per token×#{ℓ:nℓstore>0}⏟layers holding KV\text{KV bytes per token}=\underbrace{b}_{\text{bytes per entry}}\times\underbrace{n^{\text{store}}/L}_{\text{entries per token}}\times\underbrace{\#\{\ell: n^{\text{store}}_\ell>0\}}_{\text{layers holding KV}}

Each generation is one move on this board:

GenerationWhat it shrankHow
V2 (2024-05)bbMLA: one 576-number latent per token-layer instead of 2nhdh2n_hd_h
V3 (2024-12)NactN_{\text{act}} per unit of qualitybetter-balanced, finer MoE; MTP; FP8 training
V3.2 (2025-12)nreadn^{\text{read}}DSA: read only the top-2,048 entries (compute, not storage)
V4 (2026-04)nstoren^{\text{store}}CSA/HCA: compress 4 or 128 tokens into one entry
V4.1 (2026-09)layers holding KV, and bb againcross-layer sharing (4 of 40 layers store global KV), FP4 KV

For the concrete numbers in MLA mode: one key read by the absorbed (MQA-mode) MLA of V2/V3 costs nh(dc+dhR)+nhdc=128×(576+512)=139,264n_h(d_c+d^R_h)+n_hd_c=128\times(576+512)=139{,}264 MACs; one key scored by V3.2’s indexer costs HIdI=64×128=8,192H^Id^I=64\times128=8{,}192. V4’s core attention has head dimension 512 for both K and V, so an attended entry costs nh×1024n_h\times1024. Every figure below is built from these counts and the layer layouts in each config.json.

Track VI 리뷰는 DeepSeek 보고서를 하나씩 읽었다(V3, V3.2, V4 + V4.1-Flash). 이 레슨은 그것들을 하나의 결정 순서로 읽는다. 2년 반 동안 골격은 거의 움직이지 않는다. “attention 자리 + DeepSeekMoE 자리”의 pre-norm 스택, shared expert, untied head. 그 사이 부품이 하나씩 교체된다. 계속 물어야 할 질문은 이것이다. 그 시점에 토큰 하나를 만드는 데 가장 비싼 것이 무엇이었고, 어떤 변경이 그것을 공격했나?

부품 자체는 다른 레슨에서 유도한다. MLA와 흡수(absorption) 기법은 attention과 KV, DSA와 CSA는 sparse attention, aux-loss-free 균형과 해시 라우팅은 MoE, mHC는 안정화 부품, MTP는 MTP와 임베딩. 여기서는 그 부품들의 비용 서명만 있으면 된다.

토큰 하나의 청구서

문맥 길이 LL에서 토큰 하나를 디코드하는 비용은 1차 근사로

FLOPs(L)≈2Nact+2∑ℓ(nℓread(L) cℓattn+nℓscore(L) cℓidx),KV(L)=∑ℓbℓ nℓstore(L)\text{FLOPs}(L)\approx 2N_{\text{act}}+2\sum_{\ell}\Big(n^{\text{read}}_\ell(L)\,c^{\text{attn}}_\ell+n^{\text{score}}_\ell(L)\,c^{\text{idx}}_\ell\Big),\qquad \text{KV}(L)=\sum_\ell b_\ell\,n^{\text{store}}_\ell(L)

NactN_{\text{act}}는 활성 파라미터 수, 층 ℓ\ell에 대해 nstoren^{\text{store}}는 보관하는 캐시 항목 수, nreadn^{\text{read}}는 core attention이 읽는 항목 수, nscoren^{\text{score}}는 indexer가 점수를 매기는 항목 수, bb는 항목당 바이트, cc는 항목당 곱셈-누적(MAC) 수다. V4.1 보고서는 저장 쪽을 세 축의 곱으로 쓴다(V4.1 §2.3).

토큰당 KV 바이트=b⏟항목당 바이트×nstore/L⏟토큰당 항목 수×#{ℓ:nℓstore>0}⏟KV를 가진 층 수\text{토큰당 KV 바이트}=\underbrace{b}_{\text{항목당 바이트}}\times\underbrace{n^{\text{store}}/L}_{\text{토큰당 항목 수}}\times\underbrace{\#\{\ell: n^{\text{store}}_\ell>0\}}_{\text{KV를 가진 층 수}}

각 세대는 이 판 위의 한 수다.

세대줄인 것방법
V2 (2024-05)bbMLA: 토큰·층당 2nhdh2n_hd_h 대신 576개짜리 latent 하나
V3 (2024-12)품질당 NactN_{\text{act}}더 잘 균형 잡힌 세분화 MoE, MTP, FP8 학습
V3.2 (2025-12)nreadn^{\text{read}}DSA: 상위 2,048개 항목만 읽기(저장이 아니라 계산)
V4 (2026-04)nstoren^{\text{store}}CSA/HCA: 토큰 4개 또는 128개를 한 항목으로 압축
V4.1 (2026-09)KV를 가진 층 수, 다시 bb층 간 공유(40층 중 4층만 global KV 저장), FP4 KV

MLA 모드의 구체적 숫자: V2/V3의 흡수된(MQA 모드) MLA가 key 하나를 읽는 비용은 nh(dc+dhR)+nhdc=128×(576+512)=139,264n_h(d_c+d^R_h)+n_hd_c=128\times(576+512)=139{,}264 MAC, V3.2 indexer가 key 하나에 점수를 매기는 비용은 HIdI=64×128=8,192H^Id^I=64\times128=8{,}192다. V4의 core attention은 K·V 모두 head 차원이 512라서 읽는 항목 하나가 nh×1024n_h\times1024다. 아래 모든 그림은 이 수와 각 config.json의 층 배치로 만든다.

통계를 볼 문맥 길이context for the stats

2024-05 · 236B / 21B · 60층 · d 51202024-05 · 236B / 21B · 60 layers · d 5120

×1
입력input
Embedding 102,400 × 5,120Embedding 102,400 × 5,120
출력 head와 untieduntied from the LM head
residualresidual
Pre-norm residual (폭 1)Pre-norm residual (width 1)
RMSNorm → 서브층 → 더하기RMSNorm → sublayer → add
토큰 혼합 (attention)token mixer
MLA · 128 headsMLA · 128 heads
K·V를 latent c^KV(512)로 공동 압축 + 공유 RoPE key 64 → 층당 576개 캐시K and V jointly compressed into a latent c^KV (512) + shared RoPE key (64) → 576 numbers cached per layer
query latent 1,536, head dim 128(NoPE)+64(RoPE); decode는 흡수된 MQA 모드query latent 1,536; head dim 128 (NoPE) + 64 (RoPE); decode runs the absorbed MQA mode
채널 혼합 (FFN)channel mixer (FFN)
DeepSeekMoE · 2 shared + 160 routed, top-6DeepSeekMoE · 2 shared + 160 routed, top-6
expert dim 1,536; softmax gate; 첫 층만 밀집 FFNexpert dim 1,536; softmax gate; only the first layer dense
device 제한 라우팅(8개 중 ≤3); aux loss 3개(α 0.003 / 0.05 / 0.02); 학습 중 token droppingdevice-limited routing (≤3 of 8 devices); three aux losses (α 0.003 / 0.05 / 0.02); token dropping in training
출발점: 각 부품이 노린 병목 Starting point: the bottleneck each part targets
KV 메모리KV memory
MLA · 128 heads.MLA · 128 heads. V2 부록 D.2: 약 250B MoE에서 토큰당 KV 860.2K → 34.6K 원소(MHA→MLA)인데 BBH 46.6→50.7, MMLU 57.5→59.0. 67B 대비 KV 93.3% 감소(6비트 KV 양자화 포함), 최대 생성 처리량 5.76×.V2 App. D.2: in a ~250B MoE, KV per token 860.2K → 34.6K elements (MHA→MLA) while BBH 46.6→50.7 and MMLU 57.5→59.0. KV 93.3% smaller than DeepSeek 67B (with ~6-bit KV quantisation), 5.76× max generation throughput.
FLOP당 품질quality per FLOP 통신·메모리 이동communication
DeepSeekMoE · 2 shared + 160 routed, top-6.DeepSeekMoE · 2 shared + 160 routed, top-6. 세분화 expert + 공유 expert(DeepSeekMoE)로 조합 수를 늘리고 공통 지식을 분리. EP 통신은 device 제한과 통신 균형 loss로 묶었다. 67B 밀집 대비 학습비 42.5% 절감(1T 토큰당 172.8K vs 300.6K GPU 시간).Fine-grained + shared experts (DeepSeekMoE) multiply the expert combinations and isolate common knowledge; EP traffic is bounded by device-limited routing and a communication-balance loss. 42.5% cheaper training than the dense 67B (172.8K vs 300.6K GPU hours per 1T tokens).
Click a generation. The strip draws every layer from the model's config.json (top row: token mixer, bottom row: FFN); the block below highlights what changed against the previous generation, and the right column names the bottleneck each change attacked with the evidence its report gives. Stats are computed from the configs at the chosen context (decode of one token; FLOPs = 2 × (active params + attention MACs); KV in each model's shipped format). Watch two numbers move: KV per token and layers whose KV grows with context. 세대를 클릭하세요. 띠는 모델 config.json의 모든 층을 그린다(윗줄 token mixer, 아랫줄 FFN). 아래 블록은 직전 세대 대비 바뀐 부분을 강조하고, 오른쪽 열은 각 변경이 노린 병목과 보고서의 근거를 적는다. 통계는 고른 문맥에서 config로 계산한 값이다(토큰 하나 디코드, FLOPs = 2 × (활성 파라미터 + attention MAC), KV는 각 모델이 실제 쓰는 형식). 두 숫자가 어떻게 움직이는지 보라: 토큰당 KV와 문맥에 따라 KV가 자라는 층 수.

V2: the KV cache was the bill

DeepSeek 67B was a dense GQA model (95 layers, 8 KV heads of 128). At decode, each step reads every cached K and V, so the number of sequences a GPU can serve at once — and hence throughput — is set by bytes per token. V2’s answer, MLA, caches one shared latent ctKV∈R512\mathbf c^{KV}_t\in\mathbb R^{512} plus one shared RoPE key ktR∈R64\mathbf k^R_t\in\mathbb R^{64} per token per layer, and lets each head reconstruct its own keys through WiUKW^{UK}_i — or, at decode, absorbs WiUKW^{UK}_i into the query so that nothing is reconstructed at all (derivation). The KV formula in V2’s Table 1 is (dc+dhR) l≈92dhl(d_c+d^R_h)\,l\approx\tfrac92d_hl, the size of GQA with 2.25 groups.

Why is this not just “GQA with 2 groups”? Because the constraint is a rank constraint, not sharing: every head still sees a different key WiUKctW^{UK}_i\mathbf c_t. V2’s Appendix D shows the consequence. Among 7B dense models trained on 1.33T tokens, MQA and GQA-8 lose to MHA (MMLU 37.9 and 41.2 vs 45.2). In a ~250B MoE, MLA cuts KV from 860.2K to 34.6K elements per token (60×576=34,56060\times576=34{,}560) and beats MHA (BBH 46.6→50.7, MMLU 57.5→59.0). The headline “93.3% smaller KV than DeepSeek 67B” also includes deployment-side ~6-bit KV quantisation; the NumPy block below reproduces it exactly from the two configs.

The FFN slot got DeepSeekMoE: 2 shared + 160 routed experts of width 1,536, top-6, softmax gate. The price of 160 experts spread over devices is all-to-all traffic, so V2 constrained routing to at most 3 of 8 devices and added three auxiliary losses (expert, device, communication balance; α = 0.003, 0.05, 0.02) plus training-time token dropping. Those devices are exactly what V3 later removes. V2: 236B total, 21B active, 42.5% cheaper to train than the dense 67B.

V3: attention untouched, the MoE re-engineered

Open the V3 tab: the attention box is grey. V3 keeps MLA with identical dimensions (dc=512d_c=512, dhR=64d^R_h=64, 128 heads) because at 128K the KV bill was already acceptable; what limited quality per FLOP was the MoE. Three changes, each with an ablation in the report:

  • Balance without fighting the loss. V2’s auxiliary losses push router probabilities toward uniform, and that gradient competes with the LM gradient. V3 adds a per-expert bias bib_i used only for top-K selection, nudged up or down by observed load; gating weights still come from the raw sigmoid affinity. Large-MoE ablation (Table 5): BBH 66.7→67.9, GSM8K 70.7→74.5, HumanEval 40.2→46.3. The report’s own control (§4.5.3) shows the gain comes from balancing over the batch rather than per sequence — a batch-wise aux loss matches it (validation loss 2.253 vs 2.253 at 1B). That frees routing to specialise by domain.
  • Finer and sparser. 256 routed experts of width 2,048, top-8, 1 shared; sigmoid affinity normalised over the selected experts; node-limited routing (≤4 nodes) instead of device-limited; no token dropping at all.
  • MTP and FP8. One sequential MTP module (Table 4: HumanEval 44.5→53.7 at equal inference cost) that doubles as a speculative draft (85–90% acceptance, 1.8× TPS), and FP8 training with fine-grained tile scales.

The NumPy block recounts 671.0B total / 37.6B active from the config, matching the reported 671B / 37B. Note in the figure what the stats do not change from V2: KV per token grows only by one layer (60 → 61 layers × 1,152 B in BF16).

V3.2: the context becomes the bill

By late 2025 the workload had changed: reasoning traces and agent trajectories routinely filled 128K, and RL post-training generates those trajectories by the million. V3.2’s report names “vanilla attention is too expensive on long sequences” as the first bottleneck and makes exactly one architectural change, DSA. A lightning indexer (HI=64H^I=64 heads × dI=128d^I=128, ReLU, FP8, key shared across heads) scores every past token, and MLA — in its MQA mode, so that the 2,048 selected latents are shared by all 128 heads — attends only to the top k=2048k=2048.

DSA changes nreadn^{\text{read}} and adds nscore=Ln^{\text{score}}=L:

cV3.2(L)=8,192 L+139,264 min⁡(L,k),cV3(L)=139,264 Lc_{\text{V3.2}}(L)=8{,}192\,L+139{,}264\,\min(L,k),\qquad c_{\text{V3}}(L)=139{,}264\,L

So V3.2 is more expensive than V3 until 8,192L+139,264k=139,264L8{,}192L+139{,}264k=139{,}264L, i.e. L⋆=k⋅139,264131,072≈1.06k≈2,176L^\star=k\cdot\frac{139{,}264}{131{,}072}\approx1.06k\approx2{,}176 tokens. Above that, the indexer dominates: at 128K the remaining per-token attention cost is 0.059+0.016≈0.0740.059+0.016\approx0.074 of dense, and 80% of it is the indexer — still O(L2)O(L^2) over a sequence. That residue is the next generation’s target.

Notice also what DSA does not do: it stores every token’s KV in every layer. Only the KV format changed (FP8 656 B + a 132 B indexer key, from the released kernels). In the figure below, the V3 → V3.2 step is large in FLOPs and small in memory.

V4: compress the sequence itself

V4 (preview, April 2026) moved to 1M-token contexts, where V3.2’s ~50 GB of KV per sequence makes the KV, not the arithmetic, the constraint on concurrency and on prefix caching. The attention slot is rebuilt around compressing along the sequence:

  • CSA (m=4m=4): a learned, per-channel softmax-weighted sum over an overlapping 2m2m-token window produces one entry per 4 tokens; a lightning indexer (still 64 × 128) scores the L/4L/4 entries and the core attends to the top-1,024 (Pro) or 512 (Flash).
  • HCA (m′=128m'=128): one entry per 128 tokens, all read densely — at 1M that is ~8K entries.
  • Every layer also keeps a 128-token sliding window of uncompressed KV (covering the not-yet-full block and local detail), a per-head sink logit, RMSNorm on queries and KV entries, and partial RoPE on the last 64 of 512 dims with a counter-rotation on the output. The core is MQA with head dimension 512, the same width as the old MLA latent.

The compress_ratios array in the config gives the layout you see in the strip: V4-Pro starts with two HCA layers then alternates CSA/HCA (30 CSA + 31 HCA); V4-Flash starts with two SWA-only layers (21 CSA + 20 HCA). Why two kinds? CSA buys resolution (4 tokens) at the cost of a selection step; HCA buys reach (everything) at 128-token resolution with no selection. Alternating them gives every query both a precise and a complete view within two layers.

The report estimates V4-Pro at 27% of V3.2’s single-token FLOPs and 10% of its KV at 1M (V4-Flash: 10% and 7%). Recounted from the configs with the formula above (NumPy block): 26.2% and 10.5% for Pro, 12.1% and 7.3% for Flash. These are estimates on both sides; the report contains no same-condition ablation of CSA/HCA against MLA or DSA, nor of mHC, Muon or hash routing, so data and recipe (32–33T tokens) are not separated from architecture.

The other slots changed too, each against a different bottleneck. The residual became mHC, a 4-wide stream whose mixing matrix is projected to the doubly stochastic set by 20 Sinkhorn steps — non-expansive at any depth, which is what lets the widened residual train stably at 61 layers (derivation). The MoE switched to softplus\sqrt{\text{softplus}} affinity, dropped the node limit, made the first 3 layers hash-routed (num_hash_layers: 3), and added SwiGLU clamping (swiglu_limit: 10). The 1.6T run did hit loss spikes, unlike V3; the report links them to MoE outliers amplified by routing and adds Anticipatory Routing on demand. Optimiser: Muon.

V4.1-Flash: share across layers, then shrink the bytes

Five months later the bottleneck had moved again, from compute to storage and movement: agents re-prefill at every tool call and keep prefixes in HBM and on SSD. V4.1-Flash attacks the third axis — how many layers hold KV:

  • Causal Encoder–Decoder. Of 40 layers, the 20 decoder layers project their global KV from the encoder’s last layer, so prefill only runs the encoder (8B active vs 16B for decode).
  • CSA2. Each layer is Full (own KV + indexer), Reindex (borrows KV, re-scores) or Reuse (borrows KV and top-k). The config’s kv_source_layer_ids: [2, 8, 14, 20] means only 4 of 40 layers store global KV; the decoder indexer first picks 2,048 blocks of 8 then the Reindex layers pick top-512 inside those candidates, so deep layers’ indexing no longer scales with LL.
  • FP4 global KV (288 B per entry: 512 e2m1 values + 32 E4M3 scales; FlashMLA), SWA stays FP8 (528 B).

Recount: 3×288+682+1×(288+68)=8903\times\frac{288+68}{2}+1\times(288+68)=890 B per token, exactly the reported value, about 1/4 of V4-Flash. The residual became Single-Pass mHC (activation traffic (4n+4)d→(2n+2)d(4n+4)d\to(2n+2)d), MTP was replaced by a separately trained DSpark draft, and a 196B-parameter Engram n-gram memory was added at layers 1 and 14 — parameters with almost no per-token FLOPs, the same idea Qwen3.8 uses (see the Qwen lineage).

V2: 청구서는 KV 캐시였다

DeepSeek 67B는 밀집 GQA 모델이었다(95층, 128차원 KV head 8개). 디코드는 매 스텝 캐시된 K·V를 전부 읽으므로, GPU 하나가 동시에 서비스할 수 있는 시퀀스 수 — 곧 처리량 — 가 토큰당 바이트로 정해진다. V2의 답 MLA는 토큰·층마다 공유 latent ctKV∈R512\mathbf c^{KV}_t\in\mathbb R^{512} 하나와 공유 RoPE key ktR∈R64\mathbf k^R_t\in\mathbb R^{64} 하나만 캐시하고, 각 head가 WiUKW^{UK}_i로 자기 key를 복원하게 한다. 디코드에서는 WiUKW^{UK}_i를 query 쪽에 흡수해 아무것도 복원하지 않는다(유도). V2 표 1의 KV 식은 (dc+dhR) l≈92dhl(d_c+d^R_h)\,l\approx\tfrac92d_hl, 그룹 2.25개짜리 GQA의 크기다.

왜 그냥 “그룹 2개짜리 GQA”가 아닌가? 제약이 공유가 아니라 rank 제약이기 때문이다. 모든 head는 여전히 서로 다른 key WiUKctW^{UK}_i\mathbf c_t를 본다. V2 부록 D가 그 결과를 보여 준다. 1.33T 토큰으로 학습한 7B 밀집 모델에서 MQA와 GQA-8은 MHA에 진다(MMLU 37.9, 41.2 vs 45.2). 약 250B MoE에서 MLA는 토큰당 KV를 860.2K에서 34.6K 원소로 줄이면서(60×576=34,56060\times576=34{,}560) MHA를 이긴다(BBH 46.6→50.7, MMLU 57.5→59.0). “DeepSeek 67B 대비 KV 93.3% 감소”라는 헤드라인은 배포 시 약 6비트 KV 양자화도 포함한 값이다. 아래 NumPy 블록이 두 config로 정확히 재현한다.

FFN 자리에는 DeepSeekMoE가 들어갔다. 폭 1,536인 shared 2개 + routed 160개, top-6, softmax gate. expert 160개를 장치에 흩어 놓은 대가는 all-to-all 통신이므로, V2는 라우팅을 8개 장치 중 최대 3개로 제한하고 보조 loss 세 개(expert·device·통신 균형, α = 0.003, 0.05, 0.02)와 학습 중 token dropping을 더했다. 이 장치들이 바로 V3가 걷어 내는 것이다. V2: 총 236B, 활성 21B, 밀집 67B보다 학습비 42.5% 저렴.

V3: attention은 그대로, MoE를 다시 설계

V3 탭을 열면 attention 상자가 회색이다. V3는 MLA를 같은 크기(dc=512d_c=512, dhR=64d^R_h=64, 128 heads)로 유지한다. 128K에서 KV 청구서는 이미 감당할 만했고, 품질당 FLOPs를 막은 것은 MoE였기 때문이다. 바뀐 셋은 모두 보고서에 ablation이 있다.

  • loss와 싸우지 않는 균형. V2의 보조 loss는 router 확률을 균등 쪽으로 미는데, 그 gradient가 LM gradient와 경쟁한다. V3는 expert마다 bias bib_i를 두고 top-K 선택에만 쓰며, 관측된 부하에 따라 올리고 내린다. gating 가중치는 여전히 원래 sigmoid affinity에서 나온다. 큰 MoE ablation(표 5): BBH 66.7→67.9, GSM8K 70.7→74.5, HumanEval 40.2→46.3. 보고서의 대조 실험(§4.5.3)은 이득이 시퀀스가 아니라 batch 단위 균형에서 온다는 것을 보여 준다. batch 단위 aux loss도 같은 값을 낸다(1B에서 val loss 2.253 vs 2.253). 그 덕에 라우팅이 도메인별로 전문화될 수 있다.
  • 더 잘게, 더 성기게. 폭 2,048인 routed 256개, top-8, shared 1개. 선택된 expert 안에서만 정규화하는 sigmoid affinity. device 제한 대신 node 제한(≤4 노드). token dropping은 아예 없다.
  • MTP와 FP8. 순차 MTP 모듈 하나(표 4: 같은 추론 비용에서 HumanEval 44.5→53.7)는 추측 디코딩 draft도 겸한다(수락률 85–90%, 1.8× TPS). 학습은 세분화 tile scale의 FP8.

NumPy 블록은 config에서 총 671.0B / 활성 37.6B를 다시 세며, 보고값 671B / 37B와 맞는다. 그림에서 V2 대비 통계가 바뀌지 않는 것도 보라. 토큰당 KV는 층이 하나 늘어난 만큼만 커진다(60 → 61층 × BF16 1,152 B).

V3.2: 문맥이 청구서가 된다

2025년 말에는 워크로드가 바뀌어 있었다. 추론 trace와 에이전트 궤적이 128K를 흔히 채웠고, RL 사후학습은 그런 궤적을 수백만 개 생성한다. V3.2 보고서는 “vanilla attention은 긴 시퀀스에서 너무 비싸다”를 첫 병목으로 꼽고, 구조 변경을 딱 하나 한다. DSA. lightning indexer(HI=64H^I=64 heads × dI=128d^I=128, ReLU, FP8, head 공유 key)가 지난 모든 토큰에 점수를 매기고, MLA는 — 선택된 2,048개 latent를 128 head가 공유하도록 MQA 모드로 — 상위 k=2048k=2048개에만 attend한다.

DSA는 nreadn^{\text{read}}를 바꾸고 nscore=Ln^{\text{score}}=L을 더한다.

cV3.2(L)=8,192 L+139,264 min⁡(L,k),cV3(L)=139,264 Lc_{\text{V3.2}}(L)=8{,}192\,L+139{,}264\,\min(L,k),\qquad c_{\text{V3}}(L)=139{,}264\,L

따라서 V3.2는 8,192L+139,264k=139,264L8{,}192L+139{,}264k=139{,}264L, 즉 L⋆=k⋅139,264131,072≈1.06k≈2,176L^\star=k\cdot\frac{139{,}264}{131{,}072}\approx1.06k\approx2{,}176 토큰까지는 V3보다 더 비싸다. 그 위에서는 indexer가 지배한다. 128K에서 남은 토큰당 attention 비용은 밀집의 0.059+0.016≈0.0740.059+0.016\approx0.074이고, 그중 80%가 indexer다. 시퀀스 전체로는 여전히 O(L2)O(L^2). 이 잔여가 다음 세대의 표적이다.

DSA가 하지 않는 것도 보라. 모든 층에 모든 토큰의 KV를 저장한다. 바뀐 것은 KV 형식뿐이다(공개 kernel 기준 FP8 656 B + indexer key 132 B). 아래 그림에서 V3 → V3.2 한 걸음은 FLOPs로는 크고 메모리로는 작다.

V4: 시퀀스 자체를 압축

V4(2026년 4월, preview)는 1M 토큰 문맥으로 갔다. 거기서는 V3.2의 시퀀스당 약 50 GB KV가 산술이 아니라 동시 처리량과 prefix caching의 제약이 된다. attention 자리는 시퀀스 방향 압축을 중심으로 다시 지어졌다.

  • CSA(m=4m=4): 겹치는 2m2m 토큰 창 위에서 채널별 softmax 가중합으로 토큰 4개당 항목 하나를 만든다. lightning indexer(여전히 64 × 128)가 L/4L/4개 항목에 점수를 매기고, core는 top-1,024(Pro) 또는 512(Flash)에 attend한다.
  • HCA(m′=128m'=128): 토큰 128개당 항목 하나, 전부 밀집으로 읽는다. 1M에서 약 8K 항목.
  • 모든 층은 압축하지 않은 KV 128토큰의 sliding window(아직 차지 않은 블록과 국소 세부를 담당), head별 sink logit, query와 KV 항목의 RMSNorm, 512차원 중 마지막 64차원의 partial RoPE와 출력의 역회전을 가진다. core는 head 차원 512의 MQA로, 옛 MLA latent와 같은 폭이다.

config의 compress_ratios 배열이 띠에 보이는 배치를 준다. V4-Pro는 HCA 2층으로 시작해 CSA/HCA를 교대한다(CSA 30 + HCA 31). V4-Flash는 SWA 전용 2층으로 시작한다(CSA 21 + HCA 20). 왜 두 종류인가? CSA는 선택 단계를 대가로 해상도(4토큰)를 산다. HCA는 선택 없이 128토큰 해상도로 도달 범위(전부)를 산다. 교대하면 모든 query가 두 층 안에 정밀한 시야와 완전한 시야를 모두 얻는다.

보고서는 1M에서 V4-Pro가 V3.2의 토큰당 FLOPs 27%, KV 10%라고 추정한다(V4-Flash: 10%, 7%). 위 식과 config로 다시 세면(NumPy 블록) Pro 26.2%·10.5%, Flash 12.1%·7.3%. 양쪽 모두 추정치다. 보고서에는 CSA/HCA를 MLA나 DSA와 같은 조건으로 비교한 ablation도, mHC·Muon·해시 라우팅의 ablation도 없다. 데이터와 레시피(32–33T 토큰)가 구조와 분리되지 않는다.

다른 자리도 각자 다른 병목을 상대로 바뀌었다. residual은 mHC가 됐다. 4배 폭 stream이고, 혼합 행렬을 Sinkhorn 20회로 이중확률행렬 집합에 투영한다. 깊이와 무관하게 비확장적이라 넓힌 residual이 61층에서 안정적으로 학습된다(유도). MoE는 softplus\sqrt{\text{softplus}} affinity로 바꾸고 node 제한을 없앴으며, 처음 3층을 해시 라우팅으로 만들고(num_hash_layers: 3), SwiGLU clamp(swiglu_limit: 10)를 더했다. 1.6T 학습은 V3와 달리 loss spike를 겪었다. 보고서는 이를 라우팅으로 증폭된 MoE 이상치와 연결하고, 필요할 때 Anticipatory Routing을 켠다. 옵티마이저는 Muon.

V4.1-Flash: 층 사이에서 공유하고, 바이트를 다시 줄인다

다섯 달 뒤 병목은 다시 옮겨 갔다. 계산에서 저장과 이동으로. 에이전트는 도구 호출마다 다시 prefill하고 prefix를 HBM과 SSD에 오래 보관한다. V4.1-Flash는 세 번째 축 — KV를 가진 층 수 — 를 공격한다.

  • Causal Encoder–Decoder. 40층 중 decoder 20층은 global KV를 encoder 마지막 층에서 투영한다. prefill은 encoder만 돌린다(활성 8B, 디코드는 16B).
  • CSA2. 각 층은 Full(자기 KV + indexer), Reindex(KV를 빌리고 다시 점수), Reuse(KV와 top-k를 빌림) 중 하나다. config의 kv_source_layer_ids: [2, 8, 14, 20]은 40층 중 4층만 global KV를 저장한다는 뜻이다. decoder indexer는 먼저 8토큰 블록 2,048개를 고르고 Reindex 층들은 그 후보 안에서 top-512를 고르므로, 깊은 층의 indexing이 더는 LL에 비례하지 않는다.
  • FP4 global KV(항목당 288 B: e2m1 값 512개 + E4M3 scale 32개, FlashMLA). SWA는 FP8(528 B)로 남는다.

다시 세면 3×288+682+1×(288+68)=8903\times\frac{288+68}{2}+1\times(288+68)=890 B/토큰, 보고값과 정확히 같고 V4-Flash의 약 1/4이다. residual은 Single-Pass mHC가 됐고(활성 트래픽 (4n+4)d→(2n+2)d(4n+4)d\to(2n+2)d), MTP는 따로 학습하는 DSpark draft로 바뀌었으며, 196B 파라미터의 Engram n-gram 메모리가 층 1과 14에 붙었다. 토큰당 FLOPs가 거의 없는 파라미터로, Qwen3.8이 쓰는 것과 같은 생각이다(Qwen 계보 참고).

Drag the context length and watch which generation is cheapest; hollow circles mark crossovers. V3.2 only beats V3 in FLOPs above ~2.2K tokens (below that the indexer is pure overhead) and its stored KV barely moves; V4 cuts the stored KV by compressing the sequence; V4.1-Flash shares KV across layers. Lower top-k to move V3.2's crossover. In HBM bytes, lower the batch: weights dominate and small active parameter counts win; raise it and long-context KV reads take over. 문맥 길이를 끌며 어느 세대가 가장 싼지 보라. 빈 원이 교차점이다. V3.2는 약 2.2K 토큰 위에서만 FLOPs로 V3를 이기고(그 아래에선 indexer가 순수 오버헤드), 저장 KV는 거의 그대로다. V4는 시퀀스를 압축해 저장 KV를 줄이고, V4.1-Flash는 층 사이에서 KV를 공유한다. top-k를 낮추면 V3.2의 교차점이 움직인다. HBM 바이트에서 batch를 낮추면 가중치가 지배해 활성 파라미터가 작은 모델이 이기고, 높이면 긴 문맥 KV 읽기가 지배한다.

Reading the crossover figure

Things to try in the figure above:

  1. KV + state per sequence, context at 1M: V3 ≈ 74 GB, V3.2 ≈ 50 GB (FP8 only), V4-Pro ≈ 5.3 GB, V4-Flash ≈ 3.7 GB, V4.1-Flash below 1 GB plus its fixed SWA windows. The three big drops are the three axes of the table at the top.
  2. FLOPs per token: the V3.2 line sits above V3 at the far left and crosses at ~2.2K tokens. Drag top-k up to 16K and the crossover moves to ~17K; down to 512 and it leaves the plot on the left (~540 tokens) — L⋆≈1.06kL^\star\approx1.06k. Every sparse-attention design has this “fixed selection overhead vs linear savings” crossover.
  3. FLOPs per token at 1M: even V4-Pro (49B active) is cheaper than V3.2 (37B active), because V3.2’s indexer scores a million keys in 61 layers while V4’s scores a quarter of them in 30.
  4. HBM bytes per token, batch 1 at 8K: weights dominate and the ranking is just the active-parameter ranking (V4-Flash, then V4.1-Flash and V2). Raise the batch to 1,024 and move to 128K or beyond: weights amortise (nearly all experts are touched anyway) and the KV read decides — this is the regime that justifies V4 and V4.1.

The bytes metric is a first-order model (our assumption: 1 byte per weight for every model, uniform routing, KV in each model’s shipped format, decode only). It is good for orderings and crossovers, not for absolute tokens per second.

NumPy Recompute the lineage's per-token costs from the configs
import numpy as np

# ---- 1. parameters from config.json (V2, V3) ----
def deepseek_params(c):
    d, H = c['hidden_size'], c['num_attention_heads']
    nope, rope, vd = c['qk_nope_head_dim'], c['qk_rope_head_dim'], c['v_head_dim']
    attn = (d * c['q_lora_rank'] + c['q_lora_rank'] * H * (nope + rope)          # q down / up
            + d * (c['kv_lora_rank'] + rope) + c['kv_lora_rank'] * H * (nope + vd)  # kv down / up
            + H * vd * d)                                                         # output
    expert = 3 * d * c['moe_intermediate_size']
    nd, L = c['first_k_dense_replace'], c['num_hidden_layers']
    dense_ffn = 3 * d * c['intermediate_size']
    moe_total = (c['n_routed_experts'] + c['n_shared_experts']) * expert + c['n_routed_experts'] * d
    moe_active = (c['num_experts_per_tok'] + c['n_shared_experts']) * expert + c['n_routed_experts'] * d
    emb = 2 * c['vocab_size'] * d
    total = L * attn + nd * dense_ffn + (L - nd) * moe_total + emb
    active = L * attn + nd * dense_ffn + (L - nd) * moe_active + emb
    return total / 1e9, active / 1e9

V2 = dict(hidden_size=5120, num_attention_heads=128, qk_nope_head_dim=128, qk_rope_head_dim=64, v_head_dim=128,
          q_lora_rank=1536, kv_lora_rank=512, moe_intermediate_size=1536, intermediate_size=12288,
          first_k_dense_replace=1, num_hidden_layers=60, n_routed_experts=160, n_shared_experts=2,
          num_experts_per_tok=6, vocab_size=102400)
V3 = dict(V2, hidden_size=7168, moe_intermediate_size=2048, intermediate_size=18432, first_k_dense_replace=3,
          num_hidden_layers=61, n_routed_experts=256, n_shared_experts=1, num_experts_per_tok=8, vocab_size=129280)
for name, c, rep in [('V2', V2, (236, 21)), ('V3', V3, (671, 37))]:
    t, a = deepseek_params(c)
    print(f"{name}: total {t:6.1f}B (report {rep[0]}B)   active {a:5.1f}B (report {rep[1]}B)")

# V2's "93.3% smaller KV than DeepSeek 67B": 67B = 95 layers, GQA 8 x 128, BF16; V2 KV ~6 bits/element
kv67 = 95 * 2 * 8 * 128 * 2
kvV2 = 60 * 576 * 6 / 8
print(f"V2 vs 67B KV per token: {kvV2:.0f} B vs {kv67} B -> {1 - kvV2 / kv67:.1%} smaller (report 93.3%)")

# ---- 2. per-token decode cost at context L: (stored bytes, read bytes, attention MACs) per layer ----
def mla_dense(L):        return L * 1152, L * 1152, L * 128 * 1088            # V3: BF16 576 numbers
def dsa(L, k=2048):      # V3.2: FP8 KV 656 B + indexer key 132 B; indexer 64x128; MQA-mode MLA
    s = min(L, k)
    return L * (656 + 132), L * 132 + s * 656, L * 64 * 128 + s * 128 * 1088
def comp(L, m, k, H, scored=True, e=584, idx=68, win=128):   # V4 CSA (m=4) / HCA (m=128) + SWA window
    n, w = L // m, min(L, win)
    att = min(n, k) if k else n
    return (n * (e + idx * scored) + w * e, n * idx * scored + att * e + w * e,
            n * 64 * 128 * scored + (att + w) * H * 1024)
def swa(L, H, e=584):
    w = min(L, 128); return w * e, w * e, w * H * 1024

ratios = lambda first, n: first + [4 if i % 2 == 0 else 128 for i in range(n)]   # config compress_ratios
V4 = {'V4-Pro': (ratios([128, 128], 59), 128, 1024, 49), 'V4-Flash': (ratios([0, 0], 41), 64, 512, 13)}

def cost(model, L, k=2048):
    if model == 'V3':     parts, act = [mla_dense(L)] * 61, 37
    elif model == 'V3.2': parts, act = [dsa(L, k)] * 61, 37
    else:
        rs, H, kk, act = V4[model]
        parts = [swa(L, H) if r == 0 else comp(L, 4, kk, H) if r == 4 else comp(L, 128, 0, H, False) for r in rs]
    stored, read, macs = map(sum, zip(*parts))
    return stored, read, 2 * (act * 1e9 + macs)          # FLOPs = 2 (active params + attention MACs)

L = 1 << 20
s32, _, f32 = cost('V3.2', L)
for m, rep in [('V4-Pro', (27, 10)), ('V4-Flash', (10, 7))]:
    s, _, f = cost(m, L)
    print(f"{m} / V3.2 at 1M: FLOPs {f / f32:.1%} (report ~{rep[0]}%), KV {s / s32:.1%} (report ~{rep[1]}%)")

# ---- 3. where does V3.2 start to beat V3? ----
Ls = np.unique(np.logspace(9, 16, 600, base=2).astype(np.int64)).tolist()   # python ints (Pyodide is 32-bit)
for k in (512, 2048, 8192):
    x = Ls[np.argmax([cost('V3.2', l, k)[2] < cost('V3', l)[2] for l in Ls])]
    print(f"top-k {k:5d}: V3.2 cheaper than V3 above L ~ {x:6d}   (analytic 1.0625 k = {1.0625 * k:.0f})")
for l in (8192, 131072, 1 << 20):
    print(f"KV per sequence at L={l:>7}: " + "  ".join(f"{m} {cost(m, l)[0] / 1e9:5.2f} GB" for m in ['V3', 'V3.2', 'V4-Pro', 'V4-Flash']))
print("V4.1-Flash global KV per token:", 3 * (288 + 68) / 2 + (288 + 68), "B (report 890)")
 

What to check in the output: the parameter recount lands within 1% of the reported sizes; 93.3% comes out exactly; the V4/V3.2 ratios land on the report’s 27%/10% for Pro (Flash’s FLOPs ratio is 2 points higher than reported — the report does not publish its accounting); the V3.2 crossover is ≈1.06k\approx1.06k for every top-k.

What never changed, and why that matters

Across five generations DeepSeek never gave up four things: the shared expert, fine-grained routed experts with an MoE in almost every layer, a 512-wide KV latent per entry (MLA’s dcd_c became V4’s head dimension), and one MTP-style module. What it changed, every time, was co-designed with a kernel and a storage format — FlashMLA’s dense BF16 MLA, the 656-byte FP8 sparse format for V3.2, 584 bytes for V4, 528/288 bytes for V4.1. Reading the lineage as “attention variants” misses that half of each step is a byte format.

The second pattern is the order of attack. Each generation went after the cost that dominated at the context length its users had just reached: bytes per entry at 4K–128K (V2), quality per active parameter (V3), reads at 128K (V3.2), storage at 1M (V4), storage across layers and persistent prefixes for agents (V4.1). The crossover figure is the quantitative version of that story: each new design loses at short context and wins past a crossover that sits below its users’ typical context.

확인 문제Check yourself

V3.2 cut 128K-context attention FLOPs per token to about 7% of V3's. By roughly how much did it cut the KV cache stored per sequence at 128K, and why?

DSA reduces what is read (nread=min⁡(L,2048)n^{\text{read}}=\min(L,2048)), not what is stored: every layer still keeps every token’s latent, plus a 132-byte indexer key. The only reduction comes from the format: 656+132=788656+132=788 bytes per token-layer instead of BF16’s 1,152, i.e. 788/1152≈68%788/1152\approx68\%. Cutting storage needed V4’s sequence compression (nstore=L/4n^{\text{store}}=L/4 or L/128L/128).

확인 문제Check yourself

In the bytes-per-token view at batch 1 and 8K context, which quantity mostly decides the ranking of the generations?

At batch 1 every active weight is read once per token and nothing amortises it; at 8K the KV read is at most about 0.6 GB (V2/V3), against 13–49 GB of weights. So the ranking follows NactN_{\text{act}} (13B V4-Flash first). Raise the batch and the weight term shrinks as ≈Nact/B\approx N_{\text{act}}/B until all experts are touched, while each sequence’s KV read does not shrink — that is when the attention designs separate.

Summary

  • Per-token cost = active parameters + (entries read × cost per entry) + (entries scored × indexer cost); storage = bytes per entry × entries per token × layers holding KV. Each DeepSeek generation shrank one factor.
  • V2: MLA shrank bytes per entry (rank constraint, not sharing; 34.6K vs 860.2K elements and better scores than MHA). V3 left attention alone and fixed the MoE: bias-only balancing, 256 finer experts, MTP, FP8.
  • V3.2’s DSA cut reads, not storage, and only wins above L⋆≈1.06k≈2.2L^\star\approx1.06k\approx2.2K tokens; at 128K the remaining cost is 80% indexer.
  • V4 compressed the sequence (CSA m=4 with top-k, HCA m′=128 dense, SWA 128 everywhere) plus mHC, hash-routed first layers and Muon: ≈26% FLOPs and ≈10% KV of V3.2 at 1M by our recount (report 27%/10%), with no in-report ablation.
  • V4.1-Flash shared KV across layers (4 of 40 store it), stored it in FP4 and prefilled with the encoder only: 890 B/token, reproduced exactly.
  • Every new design loses at short context and wins past a crossover; the lineage moved that crossover below the context its users had just reached.

교차점 그림 읽기

위 그림에서 해 볼 것들.

  1. 시퀀스당 KV+상태, 문맥 1M: V3 약 74 GB, V3.2 약 50 GB(FP8만), V4-Pro 약 5.3 GB, V4-Flash 약 3.7 GB, V4.1-Flash는 1 GB 미만 + 고정 SWA 창. 세 번의 큰 하락이 맨 위 표의 세 축이다.
  2. 토큰당 FLOPs: 맨 왼쪽에서 V3.2 선은 V3보다 위에 있고 약 2.2K 토큰에서 교차한다. top-k를 16K로 올리면 교차점이 약 17K로 움직이고, 512로 내리면 그림 왼쪽 밖(약 540 토큰)으로 나간다. L⋆≈1.06kL^\star\approx1.06k. 모든 sparse attention 설계에 이런 “고정 선택 오버헤드 vs 선형 절약” 교차점이 있다.
  3. 1M에서 토큰당 FLOPs: V4-Pro(활성 49B)조차 V3.2(활성 37B)보다 싸다. V3.2의 indexer는 61층에서 백만 개 key에 점수를 매기지만 V4는 30층에서 그 1/4에 매긴다.
  4. 토큰당 HBM 바이트, batch 1·8K: 가중치가 지배하고 순위는 활성 파라미터 순위 그대로다(V4-Flash, 다음 V4.1-Flash와 V2). batch를 1,024로 올리고 128K 이상으로 가면 가중치는 상각되고(어차피 거의 모든 expert를 건드린다) KV 읽기가 결정한다. 이것이 V4와 V4.1을 정당화하는 영역이다.

바이트 지표는 1차 모델이다(우리 가정: 모든 모델 가중치 1바이트, 균등 라우팅, KV는 각 모델의 실제 형식, 디코드만). 순서와 교차점에는 쓸 만하지만 초당 토큰 절대값은 아니다.

NumPy 계보의 토큰당 비용을 config로 다시 계산하기
import numpy as np

# ---- 1. config.json으로 파라미터 세기 (V2, V3) ----
def deepseek_params(c):
    d, H = c['hidden_size'], c['num_attention_heads']
    nope, rope, vd = c['qk_nope_head_dim'], c['qk_rope_head_dim'], c['v_head_dim']
    attn = (d * c['q_lora_rank'] + c['q_lora_rank'] * H * (nope + rope)          # q down / up
            + d * (c['kv_lora_rank'] + rope) + c['kv_lora_rank'] * H * (nope + vd)  # kv down / up
            + H * vd * d)                                                         # 출력
    expert = 3 * d * c['moe_intermediate_size']
    nd, L = c['first_k_dense_replace'], c['num_hidden_layers']
    dense_ffn = 3 * d * c['intermediate_size']
    moe_total = (c['n_routed_experts'] + c['n_shared_experts']) * expert + c['n_routed_experts'] * d
    moe_active = (c['num_experts_per_tok'] + c['n_shared_experts']) * expert + c['n_routed_experts'] * d
    emb = 2 * c['vocab_size'] * d
    total = L * attn + nd * dense_ffn + (L - nd) * moe_total + emb
    active = L * attn + nd * dense_ffn + (L - nd) * moe_active + emb
    return total / 1e9, active / 1e9

V2 = dict(hidden_size=5120, num_attention_heads=128, qk_nope_head_dim=128, qk_rope_head_dim=64, v_head_dim=128,
          q_lora_rank=1536, kv_lora_rank=512, moe_intermediate_size=1536, intermediate_size=12288,
          first_k_dense_replace=1, num_hidden_layers=60, n_routed_experts=160, n_shared_experts=2,
          num_experts_per_tok=6, vocab_size=102400)
V3 = dict(V2, hidden_size=7168, moe_intermediate_size=2048, intermediate_size=18432, first_k_dense_replace=3,
          num_hidden_layers=61, n_routed_experts=256, n_shared_experts=1, num_experts_per_tok=8, vocab_size=129280)
for name, c, rep in [('V2', V2, (236, 21)), ('V3', V3, (671, 37))]:
    t, a = deepseek_params(c)
    print(f"{name}: 총 {t:6.1f}B (보고 {rep[0]}B)   활성 {a:5.1f}B (보고 {rep[1]}B)")

# V2의 "67B 대비 KV 93.3% 감소": 67B = 95층, GQA 8 x 128, BF16; V2 KV는 원소당 ~6비트
kv67 = 95 * 2 * 8 * 128 * 2
kvV2 = 60 * 576 * 6 / 8
print(f"토큰당 KV, V2 vs 67B: {kvV2:.0f} B vs {kv67} B -> {1 - kvV2 / kv67:.1%} 감소 (보고 93.3%)")

# ---- 2. 문맥 L에서 토큰 하나 디코드: 층별 (저장 바이트, 읽는 바이트, attention MAC) ----
def mla_dense(L):        return L * 1152, L * 1152, L * 128 * 1088            # V3: BF16 576개
def dsa(L, k=2048):      # V3.2: FP8 KV 656 B + indexer key 132 B; indexer 64x128; MQA 모드 MLA
    s = min(L, k)
    return L * (656 + 132), L * 132 + s * 656, L * 64 * 128 + s * 128 * 1088
def comp(L, m, k, H, scored=True, e=584, idx=68, win=128):   # V4 CSA (m=4) / HCA (m=128) + SWA 창
    n, w = L // m, min(L, win)
    att = min(n, k) if k else n
    return (n * (e + idx * scored) + w * e, n * idx * scored + att * e + w * e,
            n * 64 * 128 * scored + (att + w) * H * 1024)
def swa(L, H, e=584):
    w = min(L, 128); return w * e, w * e, w * H * 1024

ratios = lambda first, n: first + [4 if i % 2 == 0 else 128 for i in range(n)]   # config compress_ratios
V4 = {'V4-Pro': (ratios([128, 128], 59), 128, 1024, 49), 'V4-Flash': (ratios([0, 0], 41), 64, 512, 13)}

def cost(model, L, k=2048):
    if model == 'V3':     parts, act = [mla_dense(L)] * 61, 37
    elif model == 'V3.2': parts, act = [dsa(L, k)] * 61, 37
    else:
        rs, H, kk, act = V4[model]
        parts = [swa(L, H) if r == 0 else comp(L, 4, kk, H) if r == 4 else comp(L, 128, 0, H, False) for r in rs]
    stored, read, macs = map(sum, zip(*parts))
    return stored, read, 2 * (act * 1e9 + macs)          # FLOPs = 2 (활성 파라미터 + attention MAC)

L = 1 << 20
s32, _, f32 = cost('V3.2', L)
for m, rep in [('V4-Pro', (27, 10)), ('V4-Flash', (10, 7))]:
    s, _, f = cost(m, L)
    print(f"1M에서 {m} / V3.2: FLOPs {f / f32:.1%} (보고 ~{rep[0]}%), KV {s / s32:.1%} (보고 ~{rep[1]}%)")

# ---- 3. V3.2는 어디서부터 V3를 이기나? ----
Ls = np.unique(np.logspace(9, 16, 600, base=2).astype(np.int64)).tolist()   # python ints (Pyodide is 32-bit)
for k in (512, 2048, 8192):
    x = Ls[np.argmax([cost('V3.2', l, k)[2] < cost('V3', l)[2] for l in Ls])]
    print(f"top-k {k:5d}: L ~ {x:6d} 이상에서 V3.2가 V3보다 쌈   (해석해 1.0625 k = {1.0625 * k:.0f})")
for l in (8192, 131072, 1 << 20):
    print(f"L={l:>7}에서 시퀀스당 KV: " + "  ".join(f"{m} {cost(m, l)[0] / 1e9:5.2f} GB" for m in ['V3', 'V3.2', 'V4-Pro', 'V4-Flash']))
print("V4.1-Flash 토큰당 global KV:", 3 * (288 + 68) / 2 + (288 + 68), "B (보고 890)")
 

출력에서 확인할 것: 파라미터 재계산이 보고 크기와 1% 안에서 맞는다. 93.3%가 정확히 나온다. V4/V3.2 비율은 Pro에서 보고서의 27%/10%에 맞는다(Flash의 FLOPs 비율은 보고값보다 2%p 높다. 보고서는 계산 방식을 공개하지 않는다). V3.2 교차점은 모든 top-k에서 ≈1.06k\approx1.06k다.

바뀌지 않은 것, 그리고 그것이 중요한 이유

다섯 세대 동안 DeepSeek은 네 가지를 버리지 않았다. shared expert, 거의 모든 층의 세분화 routed expert MoE, 항목당 512폭의 KV latent(MLA의 dcd_c가 V4의 head 차원이 됐다), 그리고 MTP 계열 모듈 하나. 매번 바꾼 것은 kernel과 저장 형식을 함께 설계한 것이다. FlashMLA의 밀집 BF16 MLA, V3.2의 656바이트 FP8 sparse 형식, V4의 584바이트, V4.1의 528/288바이트. 이 계보를 “attention 변형들”로만 읽으면 각 단계의 절반이 바이트 형식이라는 점을 놓친다.

두 번째 패턴은 공격 순서다. 각 세대는 사용자가 막 도달한 문맥 길이에서 지배적인 비용을 쫓았다. 4K–128K에서 항목당 바이트(V2), 활성 파라미터당 품질(V3), 128K에서 읽기(V3.2), 1M에서 저장(V4), 층에 걸친 저장과 에이전트의 영속 prefix(V4.1). 교차점 그림은 이 이야기의 정량판이다. 새 설계는 짧은 문맥에서 지고, 사용자의 전형적 문맥보다 아래에 놓인 교차점을 지나면 이긴다.

확인 문제Check yourself

V3.2는 128K 문맥에서 토큰당 attention FLOPs를 V3의 약 7%로 줄였다. 128K에서 시퀀스당 저장 KV는 대략 얼마로 줄었고, 왜인가?

DSA는 읽는 양(nread=min⁡(L,2048)n^{\text{read}}=\min(L,2048))을 줄이지 저장하는 양을 줄이지 않는다. 모든 층이 모든 토큰의 latent와 132바이트 indexer key를 보관한다. 줄어든 것은 형식뿐이다. 토큰·층당 BF16 1,152 대신 656+132=788656+132=788바이트, 즉 788/1152≈68%788/1152\approx68\%. 저장을 줄이려면 V4의 시퀀스 압축(nstore=L/4n^{\text{store}}=L/4 또는 L/128L/128)이 필요했다.

확인 문제Check yourself

batch 1, 문맥 8K의 토큰당 바이트 관점에서 세대 순위를 주로 결정하는 양은?

batch 1에서는 모든 활성 가중치를 토큰마다 한 번씩 읽고 상각해 줄 것이 없다. 8K에서 KV 읽기는 많아야 약 0.6 GB(V2/V3)로, 가중치 13–49 GB에 비하면 작다. 그래서 순위는 NactN_{\text{act}}를 따른다(13B인 V4-Flash가 1등). batch를 올리면 가중치 항은 모든 expert를 건드릴 때까지 ≈Nact/B\approx N_{\text{act}}/B로 줄지만 시퀀스마다의 KV 읽기는 줄지 않는다. 그때 attention 설계들이 갈라진다.

정리

  • 토큰당 비용 = 활성 파라미터 + (읽는 항목 × 항목당 비용) + (점수 매기는 항목 × indexer 비용), 저장 = 항목당 바이트 × 토큰당 항목 수 × KV를 가진 층 수. DeepSeek의 각 세대는 인수 하나를 줄였다.
  • V2: MLA가 항목당 바이트를 줄였다(공유가 아니라 rank 제약; 34.6K vs 860.2K 원소로 MHA보다 좋은 점수). V3는 attention을 두고 MoE를 고쳤다. 선택 전용 bias 균형, 더 잘게 나눈 256 expert, MTP, FP8.
  • V3.2의 DSA는 저장이 아니라 읽기를 줄였고 L⋆≈1.06k≈2.2L^\star\approx1.06k\approx2.2K 토큰 위에서만 이긴다. 128K에서 남은 비용의 80%가 indexer다.
  • V4는 시퀀스를 압축했다(top-k를 쓰는 CSA m=4, 밀집 HCA m′=128, 모든 층에 SWA 128)와 mHC, 해시 라우팅 첫 층, Muon. 우리 재계산으로 1M에서 V3.2의 FLOPs ≈26%, KV ≈10%(보고 27%/10%), 보고서 안 ablation은 없다.
  • V4.1-Flash는 층 사이에서 KV를 공유하고(40층 중 4층만 저장) FP4로 저장하며 encoder만으로 prefill한다. 890 B/토큰을 정확히 재현.
  • 새 설계는 늘 짧은 문맥에서 지고 교차점 뒤에서 이긴다. 이 계보는 그 교차점을 사용자가 막 도달한 문맥보다 아래로 옮겨 왔다.

더 읽을거리Further reading