Track VII · Architecture Deep Dives · 01/12

설계 공간: 블록의 손잡이와 비용The design space: the knobs of a block and what they cost

프론티어 모델의 블록을 손잡이 몇 개(d, 층, head, KV 폭, expert 총·활성·shared, expert 폭, latent, 어휘, 전역 층 비율, 문맥)로 적고, 각 손잡이가 메모리·FLOPs·KV라는 세 청구서에 어떻게 찍히는지 식으로 유도한다. 공개된 config로 DeepSeek-V3/V3.2/V4, Kimi K2/K3, Qwen3/Qwen3.8, gpt-oss, MAI-Base, Nemotron 3 Ultra의 보고된 파라미터 수를 재현하고, 같은 모델로 문맥 길이에 따른 비용 순위를 비교한다.Write a frontier block down as a handful of knobs (d, layers, heads, KV width, experts total/active/shared, expert width, latent, vocabulary, full-attention share, context) and derive how each knob lands on three bills — memory, FLOPs and KV. With released configs we reproduce the reported parameter counts of DeepSeek-V3/V3.2/V4, Kimi K2/K3, Qwen3/Qwen3.8, gpt-oss, MAI-Base and Nemotron 3 Ultra, then compare how their costs re-order as the context grows.

45 분min architecture · MoE · KV cache · FLOPs · parameter count · design space 먼저 볼 것:Before this: Transformer 블록 해부Anatomy of a Transformer block, 추론 최적화Inference optimisation, 사전학습과 스케일링 법칙Pretraining and scaling laws

Strip the names off a 2026 frontier model and what is left is a short list of numbers. DeepSeek-V3 is d=7168, L=61, MLA(128 heads, d_c=512), 256 experts top-8 + 1 shared, f=2048. Kimi K2 is the same list with two numbers changed. Kimi K3, Nemotron 3 Ultra and Qwen3.8-Flash-Next change which kind of layer some entries are. This track asks, for every entry on that list, why it has the value it has. Before we can answer “why”, we need to know exactly what each knob costs.

This lesson does that accounting once, carefully, and checks it against released configs. Every later lesson in Track VII (MoE, attention and KV, sparse attention, linear attention and SSMs) moves one or two of these knobs and argues from the same three bills.

Three bills

A model costs us in three currencies, and different knobs land on different bills.

  1. Memory for weights: the total parameter count NtotN_{\text{tot}}. It decides how many GPUs the model needs before it can run at all.
  2. FLOPs per token: the active parameter count NactN_{\text{act}} plus the attention core. It decides training cost and the compute-bound part of serving.
  3. Cache per sequence: the KV cache plus any recurrent state. It decides how many sequences fit next to the weights, i.e. batch size and long-context feasibility.

A fourth bill, communication, appears once the model is spread over many GPUs; the MoE lesson prices it.

Parameters, knob by knob

Count only matrices (norms and biases are noise at this scale). With hidden size dd, vocabulary VV:

  • Embedding and LM head: VdVd each, so 2Vd2Vd untied and VdVd tied. At V≈1.3×105V\approx 1.3\times10^5–2.5×1052.5\times10^5 and d≈4d\approx 4K–9K this is 1–2B, a rounding error in the total but up to ~11% of the active count of a small-active model (gpt-oss-120b, Qwen3.8-Flash-Next).
  • Token mixer, per layer. GQA with nhn_h query heads, nkvn_{kv} KV heads and head size dhd_h:
PGQA=d nhdh⏟WQ+2 d nkvdh⏟WK,WV+nhdh d⏟WO.P_{\text{GQA}} = \underbrace{d\,n_h d_h}_{W_Q} + \underbrace{2\,d\,n_{kv} d_h}_{W_K,W_V} + \underbrace{n_h d_h\,d}_{W_O}.

MLA (DeepSeek-V2/V3, Kimi K2/K3) replaces WK,WVW_K,W_V by a down-projection to a latent of width dcd_c plus a decoupled RoPE key of width drd_r, and up-projections back to the heads; the query is also low-rank with rank qrq_r:

PMLA=d qr+qrnh(dn+dr)  +  d (dc+dr)+dc nh(dn+dv)  +  nhdv d.P_{\text{MLA}} = d\,q_r + q_r n_h (d_n+d_r) \;+\; d\,(d_c+d_r) + d_c\,n_h (d_n + d_v) \;+\; n_h d_v\, d.

Linear-attention and SSM layers (KDA, Gated DeltaNet, Mamba-2) are a handful of d×(heads⋅dh)d\times(\text{heads}\cdot d_h) projections; their cost shows up in the cache bill as a constant state instead of a growing KV.

  • FFN. A SwiGLU FFN of intermediate width ff is 3df3df (two matrices for a relu² FFN, as in Nemotron). An MoE layer with EE routed experts of width ff, nsn_s shared experts, a router and, for LatentMoE, a down/up projection to a latent of width ℓ\ell:
PMoE=E⋅3ℓf  +  ns⋅3dfs  +  dE  +  2dℓ,PMoEact=k⋅3ℓf  +  ns⋅3dfs  +  dE  +  2dℓP_{\text{MoE}} = E\cdot 3\ell f \;+\; n_s\cdot 3 d f_s \;+\; dE \;+\; 2d\ell, \qquad P^{\text{act}}_{\text{MoE}} = k\cdot 3\ell f \;+\; n_s\cdot 3 d f_s \;+\; dE \;+\; 2d\ell

(with ℓ=d\ell=d and no projection for an ordinary MoE). This is the whole trick of MoE in one line: EE appears only in the total, kk only in the active count.

FLOPs per token

A matrix–vector product costs 2 FLOPs per weight, so the linear layers cost 2Nact2N_{\text{act}} per token in the forward pass (the embedding lookup is free; the LM head is not). The attention core has no weights. For one new token at context TT, a full-attention layer computes nhn_h dot products of length dhd_h against every cached key and the same again for the values:

Fattn(T)=4 nhdh T(GQA),Fattn(T)=2 nh (2dc+dr) T(MLA, absorbed decode).F_{\text{attn}}(T) = 4\,n_h d_h\,T \quad\text{(GQA)},\qquad F_{\text{attn}}(T) = 2\,n_h\,(2d_c + d_r)\,T \quad\text{(MLA, absorbed decode)} .

The MLA form is larger per key because, in decode, MLA runs as multi-query attention over the 576-wide latent (derived in the attention lesson). A sliding-window layer replaces TT by min⁡(T,W)\min(T,W); a linear-attention layer replaces the whole term by a constant. Training costs about three forward passes, and averages the causal context to T/2T/2:

Ftrain≈6Nact+3 Fattn(T/2),Fdecode(T)≈2Nact+Fattn(T).F_{\text{train}} \approx 6N_{\text{act}} + 3\,F_{\text{attn}}(T/2), \qquad F_{\text{decode}}(T) \approx 2N_{\text{act}} + F_{\text{attn}}(T).

Cache per sequence

Mcache(T)=(∑full layersbentry)⏟KV bytes/token⋅T  +  ∑window layersbentrymin⁡(T,W)+∑recurrent layersbstate⏟fixedM_{\text{cache}}(T) = \underbrace{\Big(\sum_{\text{full layers}} b_{\text{entry}}\Big)}_{\text{KV bytes/token}}\cdot T \;+\; \underbrace{\sum_{\text{window layers}} b_{\text{entry}}\min(T,W) + \sum_{\text{recurrent layers}} b_{\text{state}}}_{\text{fixed}}

with bentry=2nkvdh⋅2b_{\text{entry}} = 2n_{kv}d_h\cdot 2 bytes for BF16 GQA and (dc+dr)⋅2(d_c+d_r)\cdot 2 for MLA. Only the first term grows with TT, and only the full-attention layers contribute to it. Every long-context architecture of 2025–26 is a way of shrinking that one sum: fewer bytes per entry (GQA, MLA), fewer full layers (sliding window, hybrids), or fewer entries per token (sequence compression in DeepSeek-V4).

Configure a frontier model

The calculator below implements exactly these formulas. Pick a preset: it loads the model’s released config.json (or the report’s table for MAI), and the grey tick shows the reported count.

2026년의 프론티어 모델에서 이름을 떼어 내면 짧은 숫자 목록이 남는다. DeepSeek-V3는 d=7168, L=61, MLA(head 128, d_c=512), expert 256개 중 top-8 + shared 1, f=2048이다. Kimi K2는 같은 목록에서 숫자 두 개를 바꾼 것이다. Kimi K3, Nemotron 3 Ultra, Qwen3.8-Flash-Next는 일부 항목의 종류를 바꾼다. 이 트랙은 목록의 항목마다 그 값이 왜 그 값인지 묻는다. “왜”에 답하려면 먼저 각 손잡이의 비용을 정확히 알아야 한다.

이 레슨은 그 회계를 한 번 꼼꼼하게 하고, 공개된 config로 검증한다. Track VII의 이후 레슨(MoE, attention과 KV, sparse attention, linear attention과 SSM)은 이 손잡이 한두 개를 움직이고, 같은 세 장의 청구서로 논증한다.

청구서 세 장

모델은 세 가지 통화로 비용을 청구하고, 손잡이마다 찍히는 청구서가 다르다.

  1. 가중치 메모리: 총(total) 파라미터 NtotN_{\text{tot}}. 모델을 아예 돌리려면 GPU가 몇 장 필요한지를 정한다.
  2. 토큰당 FLOPs: 활성(active) 파라미터 NactN_{\text{act}}와 attention core. 학습 비용과 서빙의 compute-bound 부분을 정한다.
  3. 시퀀스당 cache: KV cache와 순환 state. 가중치 옆에 시퀀스가 몇 개 들어가는지, 즉 batch 크기와 긴 문맥의 가능 여부를 정한다.

네 번째 청구서인 통신은 모델을 여러 GPU에 펼치는 순간 나타난다. 값은 MoE 레슨에서 매긴다.

파라미터, 손잡이별로

행렬만 센다(이 규모에서 norm과 bias는 잡음이다). hidden 크기 dd, 어휘 VV일 때:

  • 임베딩과 LM head: 각각 VdVd, 묶지 않으면(untied) 2Vd2Vd, 묶으면 VdVd. V≈1.3×105V\approx 1.3\times10^5–2.5×1052.5\times10^5, d≈4d\approx 4K–9K이면 1–2B로 총량에서는 반올림 오차지만, 활성 파라미터가 작은 모델(gpt-oss-120b, Qwen3.8-Flash-Next)에서는 활성의 ~11%까지 된다.
  • 토큰 믹서, 층마다. query head nhn_h, KV head nkvn_{kv}, head 크기 dhd_h인 GQA는
PGQA=d nhdh⏟WQ+2 d nkvdh⏟WK,WV+nhdh d⏟WO.P_{\text{GQA}} = \underbrace{d\,n_h d_h}_{W_Q} + \underbrace{2\,d\,n_{kv} d_h}_{W_K,W_V} + \underbrace{n_h d_h\,d}_{W_O}.

MLA(DeepSeek-V2/V3, Kimi K2/K3)는 WK,WVW_K,W_V를 폭 dcd_c인 latent로의 down-projection, 폭 drd_r인 분리된 RoPE key, 그리고 head로 되돌리는 up-projection으로 바꾼다. query도 rank qrq_r로 저차원화한다.

PMLA=d qr+qrnh(dn+dr)  +  d (dc+dr)+dc nh(dn+dv)  +  nhdv d.P_{\text{MLA}} = d\,q_r + q_r n_h (d_n+d_r) \;+\; d\,(d_c+d_r) + d_c\,n_h (d_n + d_v) \;+\; n_h d_v\, d.

linear attention·SSM 층(KDA, Gated DeltaNet, Mamba-2)은 d×(head 수⋅dh)d\times(\text{head 수}\cdot d_h) projection 몇 개이고, 비용은 cache 청구서에 커지는 KV 대신 고정 state로 나타난다.

  • FFN. 중간 폭 ff인 SwiGLU FFN은 3df3df(Nemotron처럼 relu² FFN이면 행렬 2개). routed expert EE개(폭 ff), shared expert nsn_s개, router, 그리고 LatentMoE라면 폭 ℓ\ell인 latent로의 down/up projection을 가진 MoE 층은
PMoE=E⋅3ℓf  +  ns⋅3dfs  +  dE  +  2dℓ,PMoEact=k⋅3ℓf  +  ns⋅3dfs  +  dE  +  2dℓP_{\text{MoE}} = E\cdot 3\ell f \;+\; n_s\cdot 3 d f_s \;+\; dE \;+\; 2d\ell, \qquad P^{\text{act}}_{\text{MoE}} = k\cdot 3\ell f \;+\; n_s\cdot 3 d f_s \;+\; dE \;+\; 2d\ell

이다(보통 MoE는 ℓ=d\ell=d이고 projection이 없다). MoE의 요령 전체가 이 한 줄에 있다. EE는 총량에만, kk는 활성량에만 나온다.

토큰당 FLOPs

행렬–벡터 곱은 가중치 하나당 2 FLOPs이므로 선형층은 forward에서 토큰당 2Nact2N_{\text{act}}다(임베딩 조회는 공짜, LM head는 아니다). attention core에는 가중치가 없다. 문맥 TT에서 새 토큰 하나에 대해 full attention 층은 캐시된 모든 key와 길이 dhd_h인 내적을 nhn_h번, value에 대해 같은 양을 더 한다.

Fattn(T)=4 nhdh T(GQA),Fattn(T)=2 nh (2dc+dr) T(MLA, 흡수된 decode).F_{\text{attn}}(T) = 4\,n_h d_h\,T \quad\text{(GQA)},\qquad F_{\text{attn}}(T) = 2\,n_h\,(2d_c + d_r)\,T \quad\text{(MLA, 흡수된 decode)} .

MLA가 key당 더 큰 이유는 decode에서 MLA가 폭 576인 latent 위의 multi-query attention으로 돌기 때문이다(attention 레슨에서 유도한다). sliding window 층은 TT를 min⁡(T,W)\min(T,W)로, linear attention 층은 항 전체를 상수로 바꾼다. 학습은 forward 약 세 번이고 causal 문맥을 평균 T/2T/2로 본다.

Ftrain≈6Nact+3 Fattn(T/2),Fdecode(T)≈2Nact+Fattn(T).F_{\text{train}} \approx 6N_{\text{act}} + 3\,F_{\text{attn}}(T/2), \qquad F_{\text{decode}}(T) \approx 2N_{\text{act}} + F_{\text{attn}}(T).

시퀀스당 cache

Mcache(T)=(∑full 층bentry)⏟토큰당 KV 바이트⋅T  +  ∑window 층bentrymin⁡(T,W)+∑순환 층bstate⏟고정M_{\text{cache}}(T) = \underbrace{\Big(\sum_{\text{full 층}} b_{\text{entry}}\Big)}_{\text{토큰당 KV 바이트}}\cdot T \;+\; \underbrace{\sum_{\text{window 층}} b_{\text{entry}}\min(T,W) + \sum_{\text{순환 층}} b_{\text{state}}}_{\text{고정}}

BF16 GQA면 bentry=2nkvdh⋅2b_{\text{entry}} = 2n_{kv}d_h\cdot 2바이트, MLA면 (dc+dr)⋅2(d_c+d_r)\cdot 2바이트다. TT에 따라 커지는 것은 첫 항뿐이고, 거기에 기여하는 것은 full attention 층뿐이다. 2025–26년의 모든 긴 문맥 아키텍처는 이 합 하나를 줄이는 방법이다. 항목당 바이트를 줄이거나(GQA, MLA), full 층을 줄이거나(sliding window, 하이브리드), 토큰당 항목 수를 줄인다(DeepSeek-V4의 시퀀스 압축).

프론티어 모델 설정해 보기

아래 계산기는 정확히 이 식들을 구현한다. 기준 모델을 고르면 공개된 config.json(MAI는 보고서 표)을 불러오고, 회색 눈금이 보고된 값이다.

총total – 활성active – E/k – 학습 FLOPs/토큰train FLOPs/token – decode FLOPs/토큰decode FLOPs/token – KV/토큰token – 시퀀스당 KV+stateKV+state per sequence –
Every preset is a released configuration (config.json or the report's table); the grey tick on the first two bars is the reported parameter count, so you can see the cost model reproduce it. Then turn one knob at a time: E moves only the total (memory), k and f move the active count (FLOPs), the latent ℓ shrinks every routed expert, the full-KV layer share moves the KV bar, and T shows when attention starts to dominate a decoded token. Bars: total / active parameters by component, FLOPs of one decoded token at context T (linear layers vs attention core), and the KV + recurrent state one sequence holds at T (BF16 KV, FP32 state). 모든 기준 모델은 공개된 설정(config.json 또는 보고서 표)이다. 위 두 막대의 회색 눈금이 보고된 파라미터 수라서 비용 모델이 그것을 재현하는지 볼 수 있다. 그다음 손잡이를 하나씩 돌려 보자. E는 총량(메모리)만, k와 f는 활성량(FLOPs)을 움직이고, latent ℓ은 모든 routed expert를 줄이며, 전역 층 비율은 KV 막대를, T는 attention이 decode 토큰 하나의 비용을 지배하기 시작하는 지점을 보여 준다. 막대: 구성요소별 총·활성 파라미터, 문맥 T에서 토큰 하나를 decode하는 FLOPs(선형층 대 attention core), 시퀀스 하나가 T에서 들고 있는 KV + 순환 state(KV는 BF16, state는 FP32).

Things to try.

  1. DeepSeek-V3, untouched. The calculator gives 671B / 36.6B against the reported 671B / 37B. The routed experts are 97% of the total and 56% of the active count; attention is 11.4B. Move T from 4K to 128K: the share of decode FLOPs spent in the attention core goes from about half to 97%. That single number is the motivation for DeepSeek-V3.2’s DSA — switch the preset to V3.2 and at 128K it falls to 69%.
  2. Kimi K2. Drag E from 384 down to 256 and back: the total moves by about 340B, the active count by nothing. Then compare the decode FLOPs at 128K with V3: K2 has half the heads (64), and its attention FLOPs halve.
  3. Kimi K3. The latent is on (ℓ = 3584 = d/2). Turn it off (drag ℓ to the right end) and the routed experts double in size: the total goes from 2.78T to about 5.5T for the same E and k. Now set the full-KV share to 100%: the KV per token goes from 27 KiB to 104 KiB.
  4. Nemotron 3 Ultra, MAI-Base-2, gpt-oss. Three different cheap mixers (Mamba-2 state, a 512-token window, a 128-token window). In all three the KV per token is set only by the few full layers, and the fixed part is visible at short context.
  5. Any preset: push T to 1M. Wherever attention is dense, the “attention core” segment swallows the FLOPs bar. Wherever the full layers are few or sparse, it does not.

Where the calculator is off, it is off for a reason we can name: Kimi K2’s reported 1.04T includes its MTP layer, which the config’s num_hidden_layers does not, and the MAI-Base-2 row needs three dimensions the report does not state (head size, window and where the shared expert sits); we assume Base-1’s values and still land within 2% of 2.8T / 80B.

Why each knob has the value it has

The bills explain most choices directly. A few worth deriving:

Sparsity E/kE/k. At fixed kk and ff, raising EE buys parameters (capacity) without FLOPs. Kimi K2 fitted this as a “sparsity scaling law” with 8 active experts fixed: reaching the same validation loss took 1.69×, 1.39× and 1.15× fewer FLOPs at sparsity 48 than at 8, 16 and 32 (K2 report, Figure 5). The price is the memory bill and the communication bill, which is why K2 stopped at 48 and why K3’s sparsity 56 needed a latent projection to keep communication flat (see MoE).

Number of heads. In MLA the head count multiplies the attention-core FLOPs and not the cache (the latent is shared by all heads). K2 halved the heads from 128 to 64 because at 128K, 128 heads cost +83% inference FLOPs for a 0.5–1.2% validation-loss gain (K2 report, Figure 6). The code below recomputes that +83% from the config; depending on whether you count decode with absorbed MLA, decode in MHA mode, or a prefill average, you get +96%, +86% or +77%, which brackets the report’s number.

KV width and full-layer share. These only enter the cache bill and the attention term. That is why they are the knobs every long-context design moves (MLA for width, hybrids and windows for the share, V4’s CSA/HCA for entries per token).

Vocabulary. VdVd is negligible in the total, but it is in the active count of every token, and the softmax over VV is a non-trivial part of small-active models. Qwen3.8-Flash-Next’s 248K vocabulary costs 10.6% of its 6B active parameters by our count — and the model adds a 51B n-gram table in host memory instead of a bigger vocabulary (MTP and embeddings).

NumPy Reproduce the reported parameter counts from the released configs
import numpy as np

def mixer_params(d, a):
    t = a['type']
    if t == 'gqa':
        return d*a['nh']*a['dh'] + 2*d*a['nkv']*a['dh'] + a['nh']*a['dh']*d
    if t == 'mla':
        nh, qr, dc, dn, dr, dv = a['nh'], a['qr'], a['dc'], a['dn'], a['dr'], a['dv']
        p = d*qr + qr*nh*(dn+dr) + d*(dc+dr) + dc*nh*(dn+dv) + nh*dv*d
        return p + (d*nh*dv if a.get('gate') else 0)          # K3: full-rank output gate
    if t == 'kda':                                            # q, k, v, output gate, output
        return 5*d*a['nh']*a['dh']
    if t == 'mamba':                                          # in_proj (x,z,B,C,dt) + out_proj
        di = a['H']*a['P']
        return d*(2*di + 2*a['G']*a['N'] + a['H']) + di*d

def count(m):
    d, nmat = m['d'], (3 if m.get('gated', True) else 2)      # SwiGLU: 3 matrices, relu^2: 2
    emb = m['V']*d*(1 if m.get('tied') else 2)
    mix = sum(n*mixer_params(d, a) for n, a in m['mixers'])
    dense = m.get('n_dense', 0)*nmat*d*m.get('f_dense', 0)
    lat = m.get('latent', 0)
    e1 = nmat*(lat or d)*m['f']                               # one routed expert
    shared = m.get('n_shared', 0)*nmat*d*m.get('f_shared', m['f'])
    extra = d*m['E'] + (2*d*lat if lat else 0)                # router + latent down/up
    L = m['n_moe']
    total = emb + mix + dense + L*(m['E']*e1 + shared + extra)
    active = m['V']*d + mix + dense + L*(m['k']*e1 + shared + extra)   # LM head yes, lookup no
    return total/1e9, active/1e9

MLA = lambda nh: dict(type='mla', nh=nh, qr=1536, dc=512, dn=128, dr=64, dv=128)
MODELS = {   # config.json values (MAI: report Table 1). reported (total, active) in B
 'DeepSeek-V3':     (dict(d=7168, V=129280, mixers=[(61, MLA(128))], n_dense=3, f_dense=18432,
                          n_moe=58, E=256, k=8, f=2048, n_shared=1), (671, 37)),
 'Kimi K2':         (dict(d=7168, V=163840, mixers=[(61, MLA(64))], n_dense=1, f_dense=18432,
                          n_moe=60, E=384, k=8, f=2048, n_shared=1), (1040, 32.6)),
 'Qwen3-235B-A22B': (dict(d=4096, V=151936, mixers=[(94, dict(type='gqa', nh=64, nkv=4, dh=128))],
                          n_moe=94, E=128, k=8, f=1536), (235, 22)),
 'gpt-oss-120b':    (dict(d=2880, V=201088, mixers=[(36, dict(type='gqa', nh=64, nkv=8, dh=64))],
                          n_moe=36, E=128, k=4, f=2880), (116.83, 5.13)),
 'Kimi K3':         (dict(d=7168, V=163840, mixers=[(69, dict(type='kda', nh=96, dh=128)),
                                                    (24, dict(MLA(96), gate=True))],
                          n_dense=1, f_dense=33792, n_moe=92, E=896, k=16, f=3072, latent=3584,
                          n_shared=2, f_shared=3072), (2780, 104.2)),
 'Nemotron 3 Ultra':(dict(d=8192, V=131072, gated=False,
                          mixers=[(48, dict(type='mamba', H=256, P=64, G=8, N=128)),
                                  (12, dict(type='gqa', nh=64, nkv=2, dh=128))],
                          n_moe=48, E=512, k=22, f=5120, latent=2048, n_shared=1, f_shared=10240), (550, 55)),
 'MAI-Base-1':      (dict(d=6656, V=200019, tied=True, mixers=[(78, dict(type='gqa', nh=80, nkv=8, dh=128))],
                          n_dense=39, f_dense=6656, n_moe=39, E=512, k=8, f=5120, latent=3072), (962, 34.7)),
}
print(f"{'model':17s} {'total':>8s} {'reported':>9s} {'active':>8s} {'reported':>9s}")
for name, (m, (rt, ra)) in MODELS.items():
    T, A = count(m)
    print(f"{name:17s} {T:7.1f}B {rt:8.1f}B {A:7.1f}B {ra:8.1f}B   ({100*(T/rt-1):+.1f}%, {100*(A/ra-1):+.1f}%)")

# Kimi K2: 64 vs 128 heads at a 128K context (report: +83% inference FLOPs)
d, L, T = 7168, 61, 131072
lin = lambda nh: 2*count(dict(MODELS['Kimi K2'][0], mixers=[(61, MLA(nh))]))[1]*1e9
for mode, per_key, ctx in [('decode, absorbed MLA', lambda nh: 2*nh*(2*512+64), T),
                           ('decode, MHA mode',     lambda nh: 2*nh*(192+128), T),
                           ('prefill average',      lambda nh: 2*nh*(192+128), T/2)]:
    f = {nh: lin(nh) + L*per_key(nh)*ctx for nh in (64, 128)}
    print(f"{mode:22s} 64 heads {f[64]/1e9:7.0f} GFLOP/token, 128 heads {f[128]/1e9:7.0f}  -> +{100*(f[128]/f[64]-1):.0f}%")
 

Every total lands within 0.1% except Kimi K2, and the active counts are within 3% of the reported values (which are rounded: “37B”, “22B”). Kimi K2 is 1.3% short of the reported 1.04T, which is about one layer of 384 experts — the MTP layer, which num_hidden_layers = 61 does not include. Nothing here is fitted: the same four formulas, fed with config values, reproduce models built by five labs.

If you have PyTorch and transformers, you can get the exact count without allocating a byte by building the model on the meta device:

PyTorch PyTorch: exact parameter count on the meta device 로컬에서 실행run locally (pip install torch)
import torch
from transformers import AutoConfig, AutoModelForCausalLM

for repo in ["Qwen/Qwen3-235B-A22B", "openai/gpt-oss-120b"]:
    cfg = AutoConfig.from_pretrained(repo)
    with torch.device("meta"):                      # shapes only, no memory
        model = AutoModelForCausalLM.from_config(cfg)
    total = sum(p.numel() for p in model.parameters())
    experts = sum(p.numel() for n, p in model.named_parameters() if ".experts." in n)
    print(f"{repo}: total {total/1e9:.2f}B, of which routed experts {experts/1e9:.2f}B")
 

The frontier on one chart

The same cost model, fed each released config unchanged, gives the chart below. It answers a question the parameter counts hide: which model is cheapest depends on the context length.

해 볼 것.

  1. DeepSeek-V3 그대로. 계산기는 보고값 671B / 37B에 대해 671B / 36.6B를 준다. routed expert가 총량의 97%, 활성의 56%이고 attention은 11.4B다. T를 4K에서 128K로 옮기면 decode FLOPs 중 attention core 비중이 절반쯤에서 97%로 간다. 이 숫자 하나가 DeepSeek-V3.2의 DSA의 동기다. 기준 모델을 V3.2로 바꾸면 128K에서 69%로 떨어진다.
  2. Kimi K2. E를 384에서 256으로 내렸다 올려 보자. 총량은 약 340B 움직이고 활성량은 그대로다. 그다음 128K의 decode FLOPs를 V3와 비교하자. K2는 head가 절반(64)이라 attention FLOPs가 절반이다.
  3. Kimi K3. latent가 켜져 있다(ℓ = 3584 = d/2). 끄면(ℓ을 오른쪽 끝까지) routed expert 크기가 두 배가 되어 같은 E, k로 총량이 2.78T에서 약 5.5T가 된다. 이제 전역 층 비율을 100%로 하면 토큰당 KV가 27 KiB에서 104 KiB가 된다.
  4. Nemotron 3 Ultra, MAI-Base-2, gpt-oss. 싼 믹서가 셋 다 다르다(Mamba-2 state, 512 토큰 window, 128 토큰 window). 셋 모두 토큰당 KV는 몇 안 되는 full 층만이 정하고, 짧은 문맥에서는 고정 부분이 보인다.
  5. 아무 모델이나 T를 1M으로. attention이 dense한 곳에서는 “attention core” 구간이 FLOPs 막대를 삼킨다. full 층이 적거나 sparse한 곳에서는 그렇지 않다.

계산기가 틀리는 곳은 이유를 댈 수 있는 곳이다. Kimi K2의 보고값 1.04T에는 MTP 층이 들어 있는데 config의 num_hidden_layers에는 없다. MAI-Base-2는 보고서에 없는 차원 세 개(head 크기, window, shared expert의 위치)가 필요해서 Base-1 값을 가정했고, 그래도 2.8T / 80B의 2% 안에 든다.

손잡이마다 그 값인 이유

청구서로 대부분의 선택이 바로 설명된다. 유도해 볼 만한 것 몇 개.

Sparsity E/kE/k. kk와 ff를 고정하고 EE를 키우면 FLOPs 없이 파라미터(용량)를 산다. Kimi K2는 활성 expert 8개를 고정하고 이것을 “sparsity scaling law”로 적합했다. 같은 검증 손실에 도달하는 데 sparsity 48이 8, 16, 32보다 각각 1.69배, 1.39배, 1.15배 적은 FLOPs가 들었다(K2 보고서 Figure 5). 대가는 메모리와 통신 청구서이고, 그래서 K2는 48에서 멈췄으며 K3의 sparsity 56은 통신을 그대로 두려고 latent projection이 필요했다(MoE 참고).

head 수. MLA에서 head 수는 attention core FLOPs에 곱해지고 cache에는 곱해지지 않는다(latent는 모든 head가 공유한다). K2는 head를 128에서 64로 줄였다. 128K에서 128 head는 추론 FLOPs를 83% 늘리는데 검증 손실은 0.5–1.2%만 좋아지기 때문이다(K2 보고서 Figure 6). 아래 코드가 그 +83%를 config로 다시 계산한다. decode를 흡수된 MLA로 세는지, MHA 모드로 세는지, prefill 평균으로 세는지에 따라 +96%, +86%, +77%가 나오고, 보고값은 그 사이에 있다.

KV 폭과 full 층 비율. 이 둘은 cache 청구서와 attention 항에만 들어간다. 그래서 모든 긴 문맥 설계가 이 손잡이를 움직인다(폭은 MLA, 비율은 하이브리드와 window, 토큰당 항목 수는 V4의 CSA/HCA).

어휘. VdVd는 총량에서는 무시할 만하지만 모든 토큰의 활성량에 들어가고, VV에 대한 softmax는 활성이 작은 모델에서 무시할 수 없다. Qwen3.8-Flash-Next의 248K 어휘는 우리 계산으로 활성 6B의 10.6%다. 그리고 이 모델은 어휘를 더 키우는 대신 host 메모리에 51B짜리 n-gram 표를 붙였다(MTP와 임베딩).

NumPy 공개 config로 보고된 파라미터 수 재현하기
import numpy as np

def mixer_params(d, a):
    t = a['type']
    if t == 'gqa':
        return d*a['nh']*a['dh'] + 2*d*a['nkv']*a['dh'] + a['nh']*a['dh']*d
    if t == 'mla':
        nh, qr, dc, dn, dr, dv = a['nh'], a['qr'], a['dc'], a['dn'], a['dr'], a['dv']
        p = d*qr + qr*nh*(dn+dr) + d*(dc+dr) + dc*nh*(dn+dv) + nh*dv*d
        return p + (d*nh*dv if a.get('gate') else 0)          # K3: full-rank 출력 gate
    if t == 'kda':                                            # q, k, v, 출력 gate, 출력
        return 5*d*a['nh']*a['dh']
    if t == 'mamba':                                          # in_proj (x,z,B,C,dt) + out_proj
        di = a['H']*a['P']
        return d*(2*di + 2*a['G']*a['N'] + a['H']) + di*d

def count(m):
    d, nmat = m['d'], (3 if m.get('gated', True) else 2)      # SwiGLU: 행렬 3개, relu^2: 2개
    emb = m['V']*d*(1 if m.get('tied') else 2)
    mix = sum(n*mixer_params(d, a) for n, a in m['mixers'])
    dense = m.get('n_dense', 0)*nmat*d*m.get('f_dense', 0)
    lat = m.get('latent', 0)
    e1 = nmat*(lat or d)*m['f']                               # routed expert 하나
    shared = m.get('n_shared', 0)*nmat*d*m.get('f_shared', m['f'])
    extra = d*m['E'] + (2*d*lat if lat else 0)                # router + latent down/up
    L = m['n_moe']
    total = emb + mix + dense + L*(m['E']*e1 + shared + extra)
    active = m['V']*d + mix + dense + L*(m['k']*e1 + shared + extra)   # LM head는 포함, 조회는 제외
    return total/1e9, active/1e9

MLA = lambda nh: dict(type='mla', nh=nh, qr=1536, dc=512, dn=128, dr=64, dv=128)
MODELS = {   # config.json 값 (MAI는 보고서 Table 1). 보고된 (총, 활성), 단위 B
 'DeepSeek-V3':     (dict(d=7168, V=129280, mixers=[(61, MLA(128))], n_dense=3, f_dense=18432,
                          n_moe=58, E=256, k=8, f=2048, n_shared=1), (671, 37)),
 'Kimi K2':         (dict(d=7168, V=163840, mixers=[(61, MLA(64))], n_dense=1, f_dense=18432,
                          n_moe=60, E=384, k=8, f=2048, n_shared=1), (1040, 32.6)),
 'Qwen3-235B-A22B': (dict(d=4096, V=151936, mixers=[(94, dict(type='gqa', nh=64, nkv=4, dh=128))],
                          n_moe=94, E=128, k=8, f=1536), (235, 22)),
 'gpt-oss-120b':    (dict(d=2880, V=201088, mixers=[(36, dict(type='gqa', nh=64, nkv=8, dh=64))],
                          n_moe=36, E=128, k=4, f=2880), (116.83, 5.13)),
 'Kimi K3':         (dict(d=7168, V=163840, mixers=[(69, dict(type='kda', nh=96, dh=128)),
                                                    (24, dict(MLA(96), gate=True))],
                          n_dense=1, f_dense=33792, n_moe=92, E=896, k=16, f=3072, latent=3584,
                          n_shared=2, f_shared=3072), (2780, 104.2)),
 'Nemotron 3 Ultra':(dict(d=8192, V=131072, gated=False,
                          mixers=[(48, dict(type='mamba', H=256, P=64, G=8, N=128)),
                                  (12, dict(type='gqa', nh=64, nkv=2, dh=128))],
                          n_moe=48, E=512, k=22, f=5120, latent=2048, n_shared=1, f_shared=10240), (550, 55)),
 'MAI-Base-1':      (dict(d=6656, V=200019, tied=True, mixers=[(78, dict(type='gqa', nh=80, nkv=8, dh=128))],
                          n_dense=39, f_dense=6656, n_moe=39, E=512, k=8, f=5120, latent=3072), (962, 34.7)),
}
print(f"{'model':17s} {'total':>8s} {'reported':>9s} {'active':>8s} {'reported':>9s}")
for name, (m, (rt, ra)) in MODELS.items():
    T, A = count(m)
    print(f"{name:17s} {T:7.1f}B {rt:8.1f}B {A:7.1f}B {ra:8.1f}B   ({100*(T/rt-1):+.1f}%, {100*(A/ra-1):+.1f}%)")

# Kimi K2: 128K 문맥에서 head 64 대 128 (보고서: 추론 FLOPs +83%)
d, L, T = 7168, 61, 131072
lin = lambda nh: 2*count(dict(MODELS['Kimi K2'][0], mixers=[(61, MLA(nh))]))[1]*1e9
for mode, per_key, ctx in [('decode, absorbed MLA', lambda nh: 2*nh*(2*512+64), T),
                           ('decode, MHA mode',     lambda nh: 2*nh*(192+128), T),
                           ('prefill average',      lambda nh: 2*nh*(192+128), T/2)]:
    f = {nh: lin(nh) + L*per_key(nh)*ctx for nh in (64, 128)}
    print(f"{mode:22s} 64 heads {f[64]/1e9:7.0f} GFLOP/token, 128 heads {f[128]/1e9:7.0f}  -> +{100*(f[128]/f[64]-1):.0f}%")
 

총량은 Kimi K2를 빼면 모두 0.1% 안에 들고, 활성량은 보고값(반올림된 “37B”, “22B”)의 3% 안이다. Kimi K2는 보고된 1.04T보다 1.3% 모자라는데, 이는 expert 384개짜리 층 하나 정도로 num_hidden_layers = 61에 들어 있지 않은 MTP 층이다. 여기에 적합(fit)한 것은 없다. 같은 식 네 개에 config 값을 넣었을 뿐인데 다섯 연구소의 모델이 재현된다.

PyTorch와 transformers가 있다면 meta device에서 모델을 만들어 메모리를 한 바이트도 쓰지 않고 정확한 수를 얻을 수 있다.

PyTorch PyTorch: meta device에서 정확한 파라미터 수 로컬에서 실행run locally (pip install torch)
import torch
from transformers import AutoConfig, AutoModelForCausalLM

for repo in ["Qwen/Qwen3-235B-A22B", "openai/gpt-oss-120b"]:
    cfg = AutoConfig.from_pretrained(repo)
    with torch.device("meta"):                      # 모양만, 메모리 없음
        model = AutoModelForCausalLM.from_config(cfg)
    total = sum(p.numel() for p in model.parameters())
    experts = sum(p.numel() for n, p in model.named_parameters() if ".experts." in n)
    print(f"{repo}: total {total/1e9:.2f}B, of which routed experts {experts/1e9:.2f}B")
 

한 장의 그림으로 본 프론티어

같은 비용 모델에 공개 config를 그대로 넣으면 아래 그림이 된다. 파라미터 수가 숨기는 질문에 답한다. 어느 모델이 가장 싼지는 문맥 길이에 달려 있다.

The same cost model as above, applied to each released config without changes. Drag T and watch the ranking below re-order: at 4K the fixed parts (recurrent state, window caches) decide it and the hybrids are the most expensive; at 1M only the full-length KV layers matter and the order flips. The flat start of the hybrid curves is the fixed recurrent state (FP32) or sliding-window cache; the slope is set by the full-KV layers alone. Pick "attention share" to see where the attention core overtakes the linear layers for each design. 위와 같은 비용 모델을 공개 설정 그대로 적용했다. T를 끌면 아래 순위가 바뀐다. 4K에서는 고정 부분(순환 state, window cache)이 순위를 정해 하이브리드가 가장 비싸고, 1M에서는 전체 길이 KV를 가진 층만 중요해져 순서가 뒤집힌다. 하이브리드 곡선이 평평하게 시작하는 부분은 고정 크기 순환 state(FP32)나 sliding window cache이고, 기울기는 full-KV 층만이 정한다. "attention 비중"을 고르면 설계마다 attention core가 선형층을 추월하는 지점이 보인다.

What the chart says, in numbers from the same model (BF16 KV, FP32 recurrent state, per sequence):

Modelfull-KV layersKV per tokencache at 128Kcache at 1Mattention share of decode FLOPs at 128K
Qwen3-235B-A22B94 of 94 (GQA 64/4)188 KiB24 GiB188 GiB90%
DeepSeek-V361 of 61 (MLA)68.6 KiB8.6 GiB69 GiB97%
DeepSeek-V3.261 (MLA + DSA top-2048)76 KiB9.5 GiB76 GiB69%
gpt-oss-120b18 of 36 (other 18: window 128)36 KiB4.5 GiB36 GiB79%
MAI-Base-217 of 102 (other 85: window 512)17 KiB2.5 GiB17 GiB42%
Kimi K324 of 93 (other 69: KDA)27 KiB3.8 GiB27 GiB76%
Nemotron 3 Ultra12 of 60 (other 48: Mamba-2)12 KiB1.9 GiB12 GiB32%
DeepSeek-V4-Pro61, compressed 4× / 128×4.9 KiB0.6 GiB4.9 GiB26%

Three remarks.

  • The cache column is set by full-KV layers alone. V3 and V3.2 have the same cache (DSA reads less, it does not store less), while MAI-Base-2 is 4× smaller than V3 per token even though its full layers are plain GQA: there are only 17 of them and they have 2 KV heads. V4 is the only design that shrinks the number of entries.
  • FLOPs are not time. In decode the GQA attention core is memory-bound (each KV byte is used for only a few FLOPs) while absorbed MLA is close to compute-bound; the attention lesson computes the arithmetic intensity, and Track VIII turns it into milliseconds.
  • Our numbers for KDA and V4 carry assumptions (FP32 KDA state; V4’s 576-byte entries with a 68-byte FP4 indexer key per CSA entry, as in the V4 lesson). The V4-Pro figure of 4.97 KB/token matches that lesson’s derivation and the report’s “about 2% of a BF16 GQA8 baseline”.
확인 문제Check yourself

Starting from DeepSeek-V3, you double the number of routed experts (256 → 512) and keep top-8. Which bills change?

EE appears only in E⋅3ℓfE\cdot 3\ell f (the total) and in the router dEdE; the active count has k⋅3ℓfk\cdot 3\ell f. So the total roughly doubles its routed part (+650B) while active parameters grow only by the router (58 × 7168 × 256 ≈ 0.1B). FLOPs per token barely move; memory and the all-to-all fan-out over more GPUs are what you pay. KV is untouched.

Summary

  • A block is a short list of knobs; each lands on specific bills: EE on memory only, kk and ff on FLOPs, head count on attention FLOPs, KV width and full-layer share on the cache.
  • Parameters: 2Vd+∑Pmixer+L (E⋅3ℓf+ns3dfs+dE+2dℓ)2Vd + \sum P_{\text{mixer}} + L\,(E\cdot 3\ell f + n_s 3df_s + dE + 2d\ell); active replaces EE by kk. Fed with configs, this reproduces reported counts within ~1–2%.
  • FLOPs per token: 2Nact2N_{\text{act}} plus an attention core that grows with TT only in full layers; at 128K, dense attention is 90–97% of the decode FLOPs of V3 or Qwen3.
  • Cache per sequence grows only through full-KV layers. The long-context designs of 2025–26 attack bytes per entry (MLA), number of full layers (windows, hybrids) or entries per token (V4).
  • Which model is cheapest depends on TT: active parameters rule short contexts, full-KV layers rule long ones.

그림이 말하는 것을 같은 모델의 숫자로 적으면 이렇다(BF16 KV, FP32 순환 state, 시퀀스 하나 기준).

모델full-KV 층토큰당 KV128K cache1M cache128K decode FLOPs 중 attention
Qwen3-235B-A22B94층 중 94 (GQA 64/4)188 KiB24 GiB188 GiB90%
DeepSeek-V361층 중 61 (MLA)68.6 KiB8.6 GiB69 GiB97%
DeepSeek-V3.261 (MLA + DSA top-2048)76 KiB9.5 GiB76 GiB69%
gpt-oss-120b36층 중 18 (나머지 18: window 128)36 KiB4.5 GiB36 GiB79%
MAI-Base-2102층 중 17 (나머지 85: window 512)17 KiB2.5 GiB17 GiB42%
Kimi K393층 중 24 (나머지 69: KDA)27 KiB3.8 GiB27 GiB76%
Nemotron 3 Ultra60층 중 12 (나머지 48: Mamba-2)12 KiB1.9 GiB12 GiB32%
DeepSeek-V4-Pro61, 4배 / 128배 압축4.9 KiB0.6 GiB4.9 GiB26%

세 가지를 짚어 두자.

  • cache 열은 full-KV 층만이 정한다. V3와 V3.2는 cache가 같다(DSA는 덜 읽을 뿐 덜 저장하지 않는다). MAI-Base-2는 full 층이 평범한 GQA인데도 토큰당 V3보다 4배 작다. full 층이 17개뿐이고 KV head가 2개이기 때문이다. 항목 수를 줄이는 설계는 V4뿐이다.
  • FLOPs는 시간이 아니다. decode에서 GQA의 attention core는 memory-bound(KV 바이트 하나당 FLOPs가 몇 개뿐)이고, 흡수된 MLA는 compute-bound에 가깝다. attention 레슨에서 산술 강도를 계산하고, Track VIII에서 밀리초로 바꾼다.
  • KDA와 V4의 숫자에는 가정이 들어 있다(KDA state는 FP32, V4는 V4 레슨처럼 576바이트 항목 + CSA 항목마다 68바이트 FP4 indexer key). V4-Pro의 4.97 KB/토큰은 그 레슨의 유도, 그리고 보고서의 “BF16 GQA8 기준선의 약 2%“와 맞는다.
확인 문제Check yourself

DeepSeek-V3에서 routed expert 수를 두 배(256 → 512)로 하고 top-8은 유지한다. 어느 청구서가 바뀌는가?

EE는 E⋅3ℓfE\cdot 3\ell f(총량)와 router dEdE에만 나오고, 활성량에는 k⋅3ℓfk\cdot 3\ell f가 들어간다. 그래서 총량은 routed 부분이 거의 두 배(+650B)가 되고, 활성 파라미터는 router만큼(58 × 7168 × 256 ≈ 0.1B)만 는다. 토큰당 FLOPs는 거의 그대로이고, 대가는 메모리와 더 많은 GPU로 퍼지는 all-to-all이다. KV는 그대로다.

정리

  • 블록은 짧은 손잡이 목록이고 손잡이마다 찍히는 청구서가 다르다. EE는 메모리에만, kk와 ff는 FLOPs에, head 수는 attention FLOPs에, KV 폭과 full 층 비율은 cache에.
  • 파라미터: 2Vd+∑Pmixer+L (E⋅3ℓf+ns3dfs+dE+2dℓ)2Vd + \sum P_{\text{mixer}} + L\,(E\cdot 3\ell f + n_s 3df_s + dE + 2d\ell), 활성은 EE 대신 kk. config를 넣으면 보고값을 ~1–2% 안으로 재현한다.
  • 토큰당 FLOPs는 2Nact2N_{\text{act}}에 full 층에서만 TT와 함께 커지는 attention core를 더한 것이다. 128K에서 dense attention은 V3·Qwen3 decode FLOPs의 90–97%다.
  • 시퀀스당 cache는 full-KV 층을 통해서만 커진다. 2025–26년의 긴 문맥 설계는 항목당 바이트(MLA), full 층 수(window, 하이브리드), 토큰당 항목 수(V4)를 공략한다.
  • 어느 모델이 가장 싼지는 TT에 달려 있다. 짧은 문맥은 활성 파라미터가, 긴 문맥은 full-KV 층이 지배한다.

더 읽을거리Further reading