Track VII · Architecture Deep Dives · 02/12

MoE 해부: routing, 세분화·shared expert, 부하 균형, dropless, LatentMoEAnatomy of MoE: routing, fine-grained and shared experts, load balancing, dropless, LatentMoE

MoE 층을 router 식부터 GPU 사이 all-to-all까지 해부한다. softmax·sigmoid·√softplus gate와 재정규화, 세분화 expert의 조합 수와 shared expert, 다섯 가지 부하 균형(aux loss micro/global, aux-free bias, Quantile Balancing)을 같은 토큰 흐름에서 비교하고, capacity·token dropping·multi-round dropless, expert parallel 통신량, LatentMoE와 sparsity scaling을 식과 시뮬레이션으로 정리한다.Take an MoE layer apart from the router equation to the all-to-all between GPUs. Softmax, sigmoid and √softplus gates and renormalisation; the combinatorics of fine-grained experts and the shared expert; five load-balancing schemes (aux loss on micro or global batch, aux-free bias, Quantile Balancing) run on the same token stream; capacity, token dropping and multi-round dropless; expert-parallel communication volume; LatentMoE and sparsity scaling — each with equations and a simulation.

55 분min MoE · routing · load balancing · expert parallelism · all-to-all · LatentMoE · DeepSeekMoE 먼저 볼 것:Before this: 설계 공간: 블록의 손잡이와 비용The design space: the knobs of a block and what they cost, Transformer 블록 해부Anatomy of a Transformer block, 추론 최적화Inference optimisation

In the design-space lesson MoE was one line: EE enters the total, kk the active count. Every frontier model of 2026 except the smallest is built on that line, and the line hides almost everything that is hard about MoE. A router must decide, per token, which kk of EE experts to use; it must do so without collapsing onto a few experts; the chosen experts live on different GPUs, so the decision turns into network traffic; and the busiest GPU sets the step time for everyone. This lesson follows a token through an MoE layer and stops at each of those places.

The individual reports already have deep dives on single pieces (aux-loss-free balancing in V3, global-batch LBL in Qwen3, Quantile Balancing in K3, multi-round dropless in MAI, LatentMoE in Nemotron 3). Here we put them side by side and ask what each one is reacting to.

The router: four gate functions

For a token representation u∈Rd\mathbf u\in\mathbb R^d, the router computes one logit per expert, zi=ei⊤uz_i = \mathbf e_i^\top \mathbf u, turns it into a score si=σ(zi)s_i = \sigma(z_i) for some function σ\sigma, picks the top-kk set T\mathcal T and mixes:

y=∑j=1nsFFNj(s)(u)  +  ∑i∈Tgi FFNi(u),gi=λ si∑j∈Tsj.\mathbf y = \sum_{j=1}^{n_s}\mathrm{FFN}^{(s)}_j(\mathbf u) \;+\; \sum_{i\in\mathcal T} g_i\,\mathrm{FFN}_i(\mathbf u),\qquad g_i = \lambda\,\frac{s_i}{\sum_{j\in\mathcal T}s_j}.

Released configs use four variants.

score sis_iselectionweightsscale λ\lambda
Qwen3, MAI-Base-1softmax over all EEtop-kk of ssrenormalised over T\mathcal T1
gpt-osslogitstop-kk of zzsoftmax over the kk logits1
DeepSeek-V3, Kimi K2/K3sigmoid σ(zi)\sigma(z_i)top-kk of s+bs+brenormalised over T\mathcal T2.5 / 2.827 / 1.0
DeepSeek-V4softplus(zi)\sqrt{\mathrm{softplus}(z_i)}top-kk of s+bs+brenormalised over T\mathcal T2.5 (Pro), 1.5 (Flash)
From config.json: scoring_func, norm_topk_prob, routed_scaling_factor; MAI from T1 §2.1.

The first two rows are the same function. With softmax probabilities pi=ezi/Zp_i = e^{z_i}/Z,

pi∑j∈Tpj=ezi/Z∑j∈Tezj/Z=ezi∑j∈Tezj,\frac{p_i}{\sum_{j\in\mathcal T}p_j} = \frac{e^{z_i}/Z}{\sum_{j\in\mathcal T}e^{z_j}/Z} = \frac{e^{z_i}}{\sum_{j\in\mathcal T}e^{z_j}},

and since softmax is monotone, the top-kk of pp and of zz coincide. What does differ is what the weights respond to. Softmax weights depend only on logit differences (add a constant to every zz and nothing changes); sigmoid and √softplus scores are absolute, so the renormalised weight si/∑sjs_i/\sum s_j changes when all logits move together. And the softmax gradient couples every expert, ∂pi/∂zj=pi(δij−pj)\partial p_i/\partial z_j = p_i(\delta_{ij}-p_j), while a sigmoid score has its own gradient σ′(zi)\sigma'(z_i) per expert. The aux-loss-free paper chose sigmoid because “the sigmoid baseline performs better than the softmax baseline”, and found softmax “more sensitive to load imbalance” (Wang et al., §3 and App. C). V4 swapped sigmoid for softplus\sqrt{\mathrm{softplus}} without an ablation in the report.

Two consequences of renormalisation matter in practice. The routed weights always sum to λ\lambda, so the router cannot say “this token needs less MoE”; it can only redistribute mass among its kk choices. And with a shared expert that always contributes with weight 1, λ\lambda sets the routed-to-shared ratio, which is one reading of why DeepSeek uses λ=2.5\lambda=2.5 (the reports do not explain the value).

Fine-grained experts and the shared expert

Split each expert of a top-2-of-16 MoE into four quarter-width experts and route top-8 of 64: parameters and FLOPs are identical, but the number of expert combinations a token can choose goes from (162)=120\binom{16}{2}=120 to (648)=4,426,165,368\binom{64}{8}=4{,}426{,}165{,}368 (DeepSeekMoE §3.1). Every 2025–26 frontier MoE is fine-grained: DeepSeek-V3 (2568)≈4×1014\binom{256}{8}\approx4\times10^{14}, Kimi K3 (89616)≈7×1033\binom{896}{16}\approx7\times10^{33}.

Finer experts are not free. Each expert’s GEMM gets smaller (worse hardware efficiency), the router and the per-expert bookkeeping grow with EE, and the dispatch fans out to more GPUs. MAI measured exactly this tension: putting MoE in every layer won in FLOPs but lost in wall-clock time until they rewrote the MoE kernels (MAI lesson).

A shared expert is an expert every token passes through. DeepSeekMoE’s rationale: “through compressing common knowledge into these shared experts, redundancy among other routed experts will be mitigated”. Not everyone agrees it is needed: Qwen3’s MoE has none, and gpt-oss has none. MAI’s ablation is the most informative statement: with MoE in every layer the model “relies much more heavily on shared experts”, whereas adding shared experts to the interleaved MoE/dense layout “has little or no benefit” (T1 §2.1). Read that way, the dense FFN of an interleaved layout already plays the shared expert’s role.

Load balancing: what each scheme pushes on

An unconstrained router collapses: experts that receive more tokens train faster, become better, and attract more tokens. Even short of collapse, imbalance costs twice: with expert parallelism the most loaded GPU sets the step time, and with finite capacity the overflow is dropped. Five schemes are in use, and they differ in where the pressure acts.

Aux loss (Switch / GShard). With fif_i the fraction of routed slots that went to expert ii (a count, not differentiable) and PiP_i the mean router probability (differentiable),

Lbal=α E∑i=1EfiPi,∂Lbal∂Pi=αEfi.\mathcal L_{\text{bal}} = \alpha\,E\sum_{i=1}^{E} f_i P_i, \qquad \frac{\partial\mathcal L_{\text{bal}}}{\partial P_i} = \alpha E f_i .

It equals α\alpha at perfect balance and the gradient lowers the probability of overloaded experts. The pressure acts on the router’s logits and, through them, on every layer below: it is a gradient that competes with the language-modelling loss. Switch used α=10−2\alpha=10^{-2}; DeepSeekMoE used 10−310^{-3}–10−210^{-2} at the expert level plus a device-level term.

Over which tokens? If fi,Pif_i, P_i are computed per micro-batch, and a micro-batch is a handful of packed sequences from one domain, the loss demands balance inside each sequence. Qiu et al. synchronise only the vector ff over the global batch, which turns the penalty into one on the global load, and report lower perplexity as the “balance batch size” grows (e.g. 5.778 → 5.603 for a 15A2.54B model, BSZ 16 → 512). MAI states it more strongly: “the aggregation strategy [matters] much more than the load balancing loss type” (T1 §2.1).

Aux-loss-free bias (DeepSeek-V3). Add a per-expert bias bib_i to the scores for selection only, T=TopK(s+b)\mathcal T=\mathrm{TopK}(s+b), keep gig_i from the unbiased ss, and nudge bi←bi+u sign(ℓˉ−ℓi)b_i \leftarrow b_i + u\,\mathrm{sign}(\bar\ell - \ell_i) after each step. No gradient touches the model. Wang et al. report at 1B: perplexity 9.56 → 9.50 and global MaxVio 0.72 → 0.04 against the loss-controlled baseline, with u=10−3u=10^{-3}. V3 and V4 keep a tiny sequence-wise loss (weight 10−410^{-4}) next to it.

Quantile Balancing (Kimi K3). The sign update is SignSGD on the dual of the balanced-assignment LP; K3 instead jumps to that coordinate’s exact minimiser: with token cutoffs αi\alpha_i (the (k+1)(k{+}1)-th biased score), bj=−quantile⁡1−k/E(s:,j−α)b_j = -\operatorname{quantile}_{1-k/E}(s_{:,j}-\alpha), recentred. No step size (K3 lesson derives it).

Expert choice (each expert picks its top tokens) balances perfectly by construction but uses future tokens of the batch to decide the routing of earlier ones, which “violates” causality for language modelling (Wang et al.); it is not used in the decoder LLMs here.

The figure runs all five on the same synthetic stream. It is a toy with one honest ingredient: an expert’s general usefulness grows with the share of tokens it receives, which is the rich-get-richer loop that makes collapse possible.

설계 공간 레슨에서 MoE는 한 줄이었다. EE는 총량에, kk는 활성량에 들어간다. 2026년의 프론티어 모델은 가장 작은 것을 빼면 모두 이 한 줄 위에 서 있고, 이 줄은 MoE의 어려운 부분을 거의 다 숨긴다. router는 토큰마다 EE개 중 어느 kk개를 쓸지 정해야 하고, 몇몇 expert로 쏠려 무너지지 않아야 한다. 고른 expert들은 서로 다른 GPU에 있으니 그 결정은 네트워크 트래픽이 되고, 가장 바쁜 GPU가 모두의 step 시간을 정한다. 이 레슨은 토큰 하나를 따라 MoE 층을 지나가며 그 지점마다 멈춘다.

개별 보고서 레슨에는 이미 한 조각씩 깊이 다룬 부분이 있다(V3의 aux-loss-free 균형, Qwen3의 global-batch LBL, K3의 Quantile Balancing, MAI의 multi-round dropless, Nemotron 3의 LatentMoE). 여기서는 그것들을 나란히 놓고 각각이 무엇에 대응하는지 묻는다.

Router: gate 함수 네 가지

토큰 표현 u∈Rd\mathbf u\in\mathbb R^d에 대해 router는 expert마다 logit zi=ei⊤uz_i = \mathbf e_i^\top \mathbf u를 계산하고, 어떤 함수 σ\sigma로 점수 si=σ(zi)s_i = \sigma(z_i)를 만들고, top-kk 집합 T\mathcal T를 골라 섞는다.

y=∑j=1nsFFNj(s)(u)  +  ∑i∈Tgi FFNi(u),gi=λ si∑j∈Tsj.\mathbf y = \sum_{j=1}^{n_s}\mathrm{FFN}^{(s)}_j(\mathbf u) \;+\; \sum_{i\in\mathcal T} g_i\,\mathrm{FFN}_i(\mathbf u),\qquad g_i = \lambda\,\frac{s_i}{\sum_{j\in\mathcal T}s_j}.

공개 config는 네 가지 변형을 쓴다.

점수 sis_i선택가중치배율 λ\lambda
Qwen3, MAI-Base-1전체 EE에 대한 softmaxss의 top-kkT\mathcal T에서 재정규화1
gpt-osslogitzz의 top-kkkk개 logit의 softmax1
DeepSeek-V3, Kimi K2/K3sigmoid σ(zi)\sigma(z_i)s+bs+b의 top-kkT\mathcal T에서 재정규화2.5 / 2.827 / 1.0
DeepSeek-V4softplus(zi)\sqrt{\mathrm{softplus}(z_i)}s+bs+b의 top-kkT\mathcal T에서 재정규화2.5 (Pro), 1.5 (Flash)
config.json의 scoring_func, norm_topk_prob, routed_scaling_factor. MAI는 T1 §2.1.

처음 두 줄은 같은 함수다. softmax 확률 pi=ezi/Zp_i = e^{z_i}/Z에 대해

pi∑j∈Tpj=ezi/Z∑j∈Tezj/Z=ezi∑j∈Tezj\frac{p_i}{\sum_{j\in\mathcal T}p_j} = \frac{e^{z_i}/Z}{\sum_{j\in\mathcal T}e^{z_j}/Z} = \frac{e^{z_i}}{\sum_{j\in\mathcal T}e^{z_j}}

이고, softmax는 단조이므로 pp의 top-kk와 zz의 top-kk는 같다. 다른 것은 가중치가 무엇에 반응하느냐다. softmax 가중치는 logit의 차이에만 의존한다(모든 zz에 상수를 더해도 그대로다). sigmoid와 √softplus 점수는 절대값이라 모든 logit이 함께 움직이면 재정규화된 가중치 si/∑sjs_i/\sum s_j가 바뀐다. 또 softmax의 기울기는 모든 expert를 엮지만(∂pi/∂zj=pi(δij−pj)\partial p_i/\partial z_j = p_i(\delta_{ij}-p_j)) sigmoid 점수는 expert마다 자기 기울기 σ′(zi)\sigma'(z_i)만 갖는다. aux-loss-free 논문은 “sigmoid 기준선이 softmax 기준선보다 낫다”며 sigmoid를 골랐고, softmax가 “부하 불균형에 더 민감하다”고 보고했다(Wang et al. §3, 부록 C). V4는 보고서에서 ablation 없이 sigmoid를 softplus\sqrt{\mathrm{softplus}}로 바꿨다.

재정규화의 결과 두 가지가 실제로 중요하다. routed 가중치의 합은 항상 λ\lambda라서 router는 “이 토큰은 MoE가 덜 필요하다”고 말할 수 없고, kk개 선택 사이에서 질량을 옮길 수만 있다. 그리고 가중치 1로 늘 더해지는 shared expert가 있으면 λ\lambda가 routed 대 shared 비율을 정한다. DeepSeek가 λ=2.5\lambda=2.5를 쓰는 이유를 이렇게 읽을 수 있다(보고서는 값의 이유를 설명하지 않는다).

세분화 expert와 shared expert

top-2/16 MoE의 expert 하나를 폭이 1/4인 expert 넷으로 쪼개고 64개 중 top-8을 고르면 파라미터와 FLOPs는 같지만, 토큰이 고를 수 있는 expert 조합 수가 (162)=120\binom{16}{2}=120에서 (648)=4,426,165,368\binom{64}{8}=4{,}426{,}165{,}368이 된다(DeepSeekMoE §3.1). 2025–26년의 프론티어 MoE는 모두 세분화돼 있다. DeepSeek-V3는 (2568)≈4×1014\binom{256}{8}\approx4\times10^{14}, Kimi K3는 (89616)≈7×1033\binom{896}{16}\approx7\times10^{33}이다.

세분화는 공짜가 아니다. expert마다 GEMM이 작아지고(하드웨어 효율 저하), router와 expert별 관리 비용이 EE와 함께 늘고, dispatch가 더 많은 GPU로 퍼진다. MAI가 바로 이 긴장을 쟀다. 모든 층에 MoE를 두는 쪽이 FLOPs로는 이겼지만 MoE 커널을 다시 쓰기 전까지는 실제 시간으로 졌다(MAI 레슨).

shared expert는 모든 토큰이 지나가는 expert다. DeepSeekMoE의 근거는 “공통 지식을 shared expert로 압축하면 다른 routed expert들 사이의 중복이 줄어든다”는 것이다. 모두가 필요하다고 보지는 않는다. Qwen3 MoE와 gpt-oss에는 없다. 가장 쓸모 있는 진술은 MAI의 ablation이다. 모든 층이 MoE이면 모델이 “shared expert에 훨씬 크게 의존”하지만, MoE와 dense를 번갈아 두는 구조에 shared expert를 더하면 “이득이 거의 없다”(T1 §2.1). 그렇게 읽으면 번갈이 구조의 dense FFN이 이미 shared expert 역할을 한다.

부하 균형: 각 방식이 미는 곳

제약 없는 router는 무너진다. 토큰을 많이 받은 expert가 더 빨리 학습하고, 더 좋아지고, 더 많은 토큰을 끌어온다. 무너지지 않더라도 불균형은 두 번 비용을 치른다. expert parallel에서는 가장 많이 받은 GPU가 step 시간을 정하고, capacity가 유한하면 넘친 몫은 버려진다. 쓰이는 방식은 다섯 가지이고, 압력이 어디에 작용하는지가 다르다.

aux loss (Switch / GShard). fif_i를 expert ii로 간 라우팅 슬롯 비율(개수라서 미분 불가), PiP_i를 router 확률의 평균(미분 가능)이라 하면

Lbal=α E∑i=1EfiPi,∂Lbal∂Pi=αEfi.\mathcal L_{\text{bal}} = \alpha\,E\sum_{i=1}^{E} f_i P_i, \qquad \frac{\partial\mathcal L_{\text{bal}}}{\partial P_i} = \alpha E f_i .

완전 균형에서 α\alpha가 되고, 기울기는 과부하 expert의 확률을 낮춘다. 압력은 router의 logit, 그리고 그것을 통해 아래의 모든 층에 작용한다. 언어 모델링 손실과 경쟁하는 기울기다. Switch는 α=10−2\alpha=10^{-2}, DeepSeekMoE는 expert 수준에서 10−310^{-3}–10−210^{-2}에 device 수준 항을 더했다.

어떤 토큰들 위에서? fi,Pif_i, P_i를 micro-batch마다 계산하고 micro-batch가 한 도메인에서 온 packed sequence 몇 개라면, 손실은 시퀀스 안에서의 균형을 요구한다. Qiu et al.은 벡터 ff만 global batch에서 동기화해 벌점을 전역 부하에 대한 것으로 바꾸고, “balance batch size”가 클수록 perplexity가 낮아진다고 보고한다(예: 15A2.54B 모델에서 BSZ 16 → 512일 때 5.778 → 5.603). MAI는 더 강하게 말한다. “집계 방식이 균형 손실의 종류보다 훨씬 중요하다”(T1 §2.1).

aux-loss-free bias (DeepSeek-V3). expert마다 bias bib_i를 점수에 선택용으로만 더해 T=TopK(s+b)\mathcal T=\mathrm{TopK}(s+b)로 고르고, gig_i는 bias 없는 ss로 계산하며, 매 step 뒤 bi←bi+u sign(ℓˉ−ℓi)b_i \leftarrow b_i + u\,\mathrm{sign}(\bar\ell - \ell_i)로 조금씩 민다. 모델에 닿는 기울기가 없다. Wang et al.은 1B에서 손실 제어 기준선 대비 perplexity 9.56 → 9.50, 전역 MaxVio 0.72 → 0.04를 u=10−3u=10^{-3}로 보고한다. V3와 V4는 그 옆에 아주 작은 sequence-wise 손실(가중치 10−410^{-4})을 둔다.

Quantile Balancing (Kimi K3). sign 업데이트는 균형 할당 LP의 쌍대에 대한 SignSGD다. K3는 그 좌표의 정확한 최솟값으로 바로 뛴다. 토큰별 cutoff αi\alpha_i((k+1)(k{+}1)번째 bias 포함 점수)를 두고 bj=−quantile⁡1−k/E(s:,j−α)b_j = -\operatorname{quantile}_{1-k/E}(s_{:,j}-\alpha), 그리고 평균을 뺀다. step size가 없다(K3 레슨에서 유도한다).

Expert choice(expert가 자기 top 토큰을 고른다)는 구조상 완전 균형이지만 배치 안의 미래 토큰을 써서 앞 토큰의 routing을 정하므로 언어 모델링의 인과성을 “위반”한다(Wang et al.). 여기의 decoder LLM들은 쓰지 않는다.

아래 그림은 다섯 가지를 같은 합성 토큰 흐름 위에서 돌린다. 장난감이지만 정직한 재료 하나가 들어 있다. expert의 일반적인 쓸모가 받은 토큰 몫과 함께 커진다. routing collapse를 가능하게 하는 부익부 고리다.

32 experts, 8 domains with skewed frequencies; each domain has 4 experts that serve it well, and an expert that receives more tokens gets better at everything (the rich-get-richer loop behind routing collapse). All five routers see the same tokens and the same noise. Left: global imbalance (MaxVio = max load / mean − 1) per step. Right: specialisation, the share of routed slots that land on the token's own domain experts. With one domain per micro-batch, the micro-batch aux loss balances by destroying specialisation, while the same loss with global statistics keeps it. Lower γ and the sign-update bias reacts slowly; Quantile Balancing has no step size at all. expert 32개, 빈도가 치우친 도메인 8개. 각 도메인을 잘 처리하는 expert가 4개씩 있고, 토큰을 많이 받은 expert는 모든 일에 조금씩 나아진다(routing collapse를 일으키는 부익부 고리). 다섯 router는 같은 토큰과 같은 잡음을 본다. 왼쪽: step별 전역 불균형(MaxVio = 최대 부하/평균 − 1). 오른쪽: 전문화, 라우팅 슬롯 중 토큰 자기 도메인의 expert에 떨어진 비율. micro-batch마다 도메인이 하나이면 micro-batch aux loss는 전문화를 부숴서 균형을 맞추고, 같은 손실을 전역 통계로 계산하면 전문화가 유지된다. γ를 낮추면 sign 업데이트 bias는 느리게 반응하고, Quantile Balancing에는 step size 자체가 없다.

What to look for.

  1. No balancing (grey) drifts to a global MaxVio around 1.5: a few experts carry 2.5× the mean load.
  2. With one domain per micro-batch (the default), the micro-batch aux loss (amber) reaches the best balance by flattening every domain over all experts: specialisation falls from about 0.65 to about 0.2. The same loss with global statistics (green) keeps specialisation where it was. Switch to mixed micro-batches and the two move much closer together (at default α), which is exactly Qiu et al.’s argument: the damage comes from computing the statistics over one-domain micro-batches.
  3. The sign-update bias (blue) depends on γ: at γ = 0.001 (the value Wang et al. and V3 use with real models, whose logits are on a different scale) it has barely moved after 150 steps; from about 0.01 up it balances, and larger steps buy little more. Quantile Balancing (red) has no γ and gets there in a few steps. The residual MaxVio of ~0.3 under mixed micro-batches is sampling noise: with only 512 tokens per step, even a perfectly fair router shows some spread.
  4. Raise α for the aux losses and they balance better while specialisation drops; that trade-off is the “tug of war” the aux-free method was designed to remove. The bias methods never change the weights gg, so they cannot distort what each expert sees.

The toy’s numbers are not claims about any real model; its job is to make the mechanisms visible. The V3 lesson has a complementary figure in which the domains have fixed affinities.

Capacity, dropping and dropless

Under expert parallelism, each expert (or each GPU) has buffers sized in advance. Switch sets

capacity=CF⋅tokens per batch⋅kE,\text{capacity} = \text{CF}\cdot\frac{\text{tokens per batch}\cdot k}{E},

and tokens beyond it are dropped: “computation is skipped and the token representation is passed directly to the next layer through the residual connection”. A capacity factor above 1 trades memory for fewer drops. The alternative is dropless: process every routed token. That either requires buffers sized for the worst case (memory proportional to the maximum, not the mean, load), variable-size all-to-all and grouped GEMMs, or — MAI-Base-2’s choice — a fixed capacity with extra rounds for the overflow. DeepSeek-V3 drops no tokens in training or inference, relying on good balance; MAI found that even “carefully designed” token dropping with a generous capacity changed which balancing method looked best, and “converged to a fully dropless MoE” (T1 §2.1).

Expert parallelism and the all-to-all

With EE experts spread over RR GPUs (expert parallelism, EP), each MoE layer does two all-to-alls: dispatch sends each token’s vector to the GPUs hosting its experts, combine brings the kk weighted outputs back. Per token and layer, with hidden size dd and bb bytes per element:

bytes≈2⋅c⋅d⋅b,c=number of distinct destinations.\text{bytes} \approx 2\cdot c\cdot d\cdot b, \qquad c = \text{number of distinct destinations}.

If kk experts are picked uniformly at random among EE experts spread evenly over RR GPUs, the expected number of distinct GPUs is

E[cGPU]=R(1−(E−E/Rk)/(Ek))  ≤  min⁡(k,R),\mathbb E[c_{\text{GPU}}] = R\Big(1-\binom{E-E/R}{k}\Big/\binom{E}{k}\Big) \;\le\; \min(k, R),

so deduplicating per GPU saves little when R≫kR \gg k (7.68 copies instead of 8 for V3’s top-8 over 64 GPUs). What matters more is which links the copies cross: NVLink inside a node is several times faster than the inter-node network. DeepSeek-V3’s node-limited routing first picks at most M=4M=4 nodes per token (by the sum of the top k/Mk/M affinities on each node) and only then the top-kk experts inside them, capping the slow inter-node copies at 4 regardless of kk. V4 dropped that constraint.

볼 것.

  1. 균형 장치 없음(회색)은 전역 MaxVio 1.5 근처로 흘러간다. 몇몇 expert가 평균의 2.5배를 진다.
  2. micro-batch마다 도메인이 하나인 기본 설정에서 micro-batch aux loss(황색)는 모든 도메인을 모든 expert에 평평하게 펴서 가장 좋은 균형에 도달한다. 전문화가 약 0.65에서 약 0.2로 떨어진다. 같은 손실을 전역 통계로 계산하면(초록) 전문화가 그대로다. micro-batch를 섞으면 (기본 α에서) 둘이 훨씬 가까워진다. Qiu et al.의 논증이 정확히 이것이다. 피해는 한 도메인짜리 micro-batch 위에서 통계를 내는 데서 온다.
  3. sign 업데이트 bias(파랑)는 γ에 달려 있다. γ = 0.001(Wang et al.과 V3가 logit 척도가 다른 실제 모델에 쓰는 값)이면 150 step 뒤에도 거의 움직이지 않았고, 약 0.01부터 균형을 맞추며, 그보다 큰 step은 별 이득이 없다. Quantile Balancing(빨강)은 γ가 없고 몇 step 만에 도달한다. 섞인 micro-batch에서 남는 MaxVio ~0.3은 표본 잡음이다. step당 토큰이 512개뿐이라 완벽히 공정한 router도 어느 정도 퍼진다.
  4. aux loss의 α를 올리면 균형은 나아지고 전문화는 떨어진다. aux-free 방식이 없애려던 “줄다리기”가 이것이다. bias 방식은 가중치 gg를 바꾸지 않으므로 각 expert가 보는 것을 왜곡할 수 없다.

장난감의 숫자는 실제 모델에 대한 주장이 아니다. 메커니즘을 보이게 하는 것이 목적이다. V3 레슨에는 도메인 affinity가 고정된, 보완적인 그림이 있다.

Capacity, dropping, dropless

expert parallel에서는 expert(또는 GPU)마다 버퍼 크기를 미리 정한다. Switch는

capacity=CF⋅배치 토큰 수⋅kE\text{capacity} = \text{CF}\cdot\frac{\text{배치 토큰 수}\cdot k}{E}

로 두고, 넘친 토큰은 버린다(drop). “계산을 건너뛰고 토큰 표현을 residual 연결로 다음 층에 그대로 넘긴다.” capacity factor를 1보다 크게 하면 메모리를 내고 drop을 줄인다. 대안은 dropless, 라우팅된 토큰을 전부 처리하는 것이다. 최악의 경우에 맞춘 버퍼(평균이 아니라 최대 부하에 비례하는 메모리)와 가변 크기 all-to-all, grouped GEMM이 필요하거나, MAI-Base-2처럼 capacity를 고정하고 넘친 몫을 추가 라운드로 처리한다. DeepSeek-V3는 좋은 균형에 기대어 학습과 추론 모두에서 토큰을 버리지 않는다. MAI는 넉넉한 capacity로 “신중하게 설계한” token dropping조차 어떤 균형 방식이 좋아 보이는지를 바꾼다는 것을 발견하고 “완전 dropless MoE로 수렴했다”(T1 §2.1).

Expert parallel과 all-to-all

EE개 expert를 GPU RR장에 나누면(expert parallelism, EP) MoE 층마다 all-to-all이 두 번 일어난다. dispatch는 토큰 벡터를 그 expert가 있는 GPU로 보내고, combine은 가중된 출력 kk개를 되가져온다. hidden 크기 dd, 원소당 bb바이트이면 토큰·층당

바이트≈2⋅c⋅d⋅b,c=서로 다른 목적지 수.\text{바이트} \approx 2\cdot c\cdot d\cdot b, \qquad c = \text{서로 다른 목적지 수}.

EE개 expert가 GPU RR장에 고르게 있고 kk개를 무작위로 고르면 서로 다른 GPU 수의 기댓값은

E[cGPU]=R(1−(E−E/Rk)/(Ek))  ≤  min⁡(k,R)\mathbb E[c_{\text{GPU}}] = R\Big(1-\binom{E-E/R}{k}\Big/\binom{E}{k}\Big) \;\le\; \min(k, R)

이므로, R≫kR \gg k이면 GPU별 중복 제거의 이득은 작다(V3의 top-8을 64 GPU에 펼치면 8 대신 7.68). 더 중요한 것은 사본이 어떤 링크를 건너느냐다. 노드 안의 NVLink는 노드 사이 네트워크보다 몇 배 빠르다. DeepSeek-V3의 node-limited routing은 토큰마다 먼저 노드를 최대 M=4M=4개 고르고(각 노드 expert의 상위 k/Mk/M개 affinity 합으로), 그 안에서 top-kk expert를 고른다. 그러면 느린 노드 간 사본은 kk와 무관하게 4개로 묶인다. V4는 이 제약을 없앴다.

token drop 시 버려지는 슬롯slots dropped (token dropping) – dropless 라운드dropless rounds – 최악 버퍼 / 고정worst-case buffer / fixed –
토큰당 사본: expert별copies per token: per expert – GPU별(중복 제거)per GPU (dedup) – 노드 간across nodes – all-to-all 바이트/토큰/층all-to-all bytes/token/layer –
4,096 tokens routed by top-k over E experts whose popularity follows a Zipf law (skew), experts split evenly over the GPUs, 8 GPUs per node, d = 7168. Bars are per-GPU loads relative to the mean; the dashed line is the capacity. Red is what token dropping throws away, or what a multi-round dropless MoE processes in extra rounds. Raise k: the per-expert copies grow linearly, but copies per GPU and per node grow more slowly because experts on the same GPU share one transfer. Set the node limit M (DeepSeek-V3 uses 4) and the expensive inter-node copies are capped. d/ℓ is a LatentMoE compression of the dispatched vector. Bytes count dispatch + combine in BF16. 토큰 4,096개를 E개 expert에 top-k로 보낸다. expert 인기는 Zipf 분포(편중)를 따르고, expert는 GPU에 고르게 나뉘며, 노드당 GPU 8장, d = 7168이다. 막대는 GPU별 부하/평균이고 점선이 capacity다. 빨강은 token dropping이 버리는 몫, 또는 multi-round dropless MoE가 추가 라운드로 처리하는 몫이다. k를 올리면 expert별 사본은 선형으로 늘지만, 같은 GPU의 expert들은 전송 한 번을 나눠 쓰므로 GPU별·노드별 사본은 더 천천히 는다. 노드 제한 M을 켜면(DeepSeek-V3는 4) 비싼 노드 간 사본이 상한에 묶인다. d/ℓ은 보내는 벡터를 LatentMoE로 압축하는 비율이다. 바이트는 dispatch + combine을 BF16으로 센다.

Try: skew 0.6, capacity factor 1.25: token dropping loses a sizeable share of slots, while a multi-round dropless MoE needs 2–3 rounds and a worst-case buffer of about twice the fixed one. k from 2 to 16 at 64 GPUs: per-expert copies grow 8×, distinct GPUs a bit less, distinct nodes saturate at 8. Node limit M = 4: inter-node copies drop to ≤ 4 at the same k. d/ℓ = 2 or 4: the bytes halve or quarter — the LatentMoE trade.

LatentMoE: spend the saved bandwidth on experts

The dispatched vector is the dd-dimensional token representation. LatentMoE (Elango et al.; used by Nemotron 3, MAI-Base-1/2 and Kimi K3) projects it once to a latent ℓ<d\ell<d, runs the routed experts in Rℓ\mathbb R^\ell and projects the mixed output back:

y=∑jFFNj(s)(u)+W↑ Norm(∑i∈Tgi FFNi(W↓u)),g=router(u).\mathbf y = \sum_j \mathrm{FFN}^{(s)}_j(\mathbf u) + W^{\uparrow}\,\mathrm{Norm}\Big(\sum_{i\in\mathcal T} g_i\,\mathrm{FFN}_i(W^{\downarrow}\mathbf u)\Big), \qquad g = \text{router}(\mathbf u).

The router and the shared expert still see the full u\mathbf u (the routing decision is made on the uncompressed representation). Dispatch bytes and every routed expert’s weights shrink by d/ℓd/\ell, and the designs spend that factor on more and more-active experts. Kimi K3 makes the bookkeeping exact: 16×3584=57,344=8×716816\times3584 = 57{,}344 = 8\times7168, so K3 moves the same bytes per token as K2 while routing to twice as many experts out of 896 (K3 lesson). Nemotron 3 Ultra uses d/ℓ=8192/2048=4d/\ell = 8192/2048 = 4 and routes top-22 of 512. The price is two d×ℓd\times\ell matrices per layer and a rank bottleneck; K3 adds an RMSNorm before W↑W^\uparrow because the chain W↓→W^\downarrow\to expert →W↑\to W^\uparrow blew up activations at 2.8T scale.

Sparsity scaling

With kk fixed, more experts lowers loss at constant FLOPs: Kimi K2 measured that sparsity 48 needs 1.69× / 1.39× / 1.15× fewer FLOPs than sparsity 8 / 16 / 32 to reach the same validation loss (K2 Figure 5), and stopped at 48 because of infrastructure complexity. The 2026 configs sit in a narrow band:

Modelrouted EE / active kksharedsparsity E/kE/klatent d→ℓd\to\ellbalancing (as reported)
Qwen3-235B-A22B128 / 8016–global-batch LBL
gpt-oss-120b128 / 4032–not stated
DeepSeek-V3256 / 8132–aux-free bias (u=10−3u=10^{-3}) + seq-wise 10−410^{-4}, node-limited M=4M=4
Kimi K2384 / 8148–bias-based selection (noaux_tc)
Qwen3.8-Flash-Next512 / 10151–not stated in the report body
Kimi K3896 / 162567168 → 3584Quantile Balancing
DeepSeek-V4-Pro384 / 6164–aux-free bias (10−310^{-3}) + balance loss 10−410^{-4}
MAI-Base-1512 / 80646656 → 3072GShard loss, global aggregation, dropless
MAI-Base-2512 / 71738704 → 4096multi-round dropless
Nemotron 3 Ultra512 / 221238192 → 2048not covered here
Configs and reports as cited above; V4 from the V4 lesson (§4.2.2).

The trend from 2025 to 2026 is up and to the right — more experts, more active experts per token, latents to pay for it — with the per-expert width shrinking (Qwen3.8: 640). Sparsity is not the whole story either: Nemotron’s 22-of-512 in a 4× latent is, in bytes and FLOPs, about the same as 5.5-of-128 at full width (Nemotron lesson), but with (51222)\binom{512}{22} instead of (1285)\binom{128}{5} combinations.

Building it

The NumPy block checks the claims above: the two softmax gates are identical; sigmoid weights are not shift-invariant; the aux-loss gradient (with ff held constant) matches finite differences and pushes down only the overloaded expert; the combinatorics; capacity drops versus dropless rounds; and the expected fan-out of the all-to-all.

NumPy Router lab: gates, aux-loss gradient, combinatorics, capacity, all-to-all fan-out
import numpy as np
from math import comb
rng = np.random.default_rng(0)

# ---- 1. four gate functions used by released configs ---------------------------
def topk(scores, k):
    return np.argsort(-scores, axis=-1)[..., :k]

def gate_softmax_then_topk(z, k):           # Qwen3 / MAI: softmax over all, keep top-k, renormalise
    p = np.exp(z - z.max(-1, keepdims=True)); p /= p.sum(-1, keepdims=True)
    idx = topk(p, k); w = np.take_along_axis(p, idx, -1)
    return idx, w / w.sum(-1, keepdims=True)

def gate_topk_then_softmax(z, k):           # gpt-oss: top-k on logits, softmax over the k
    idx = topk(z, k); zz = np.take_along_axis(z, idx, -1)
    w = np.exp(zz - zz.max(-1, keepdims=True))
    return idx, w / w.sum(-1, keepdims=True)

def gate_score_renorm(z, k, f, scale=1.0):  # DeepSeek-V3/K2/K3 (sigmoid), V4 (sqrt softplus)
    s = f(z); idx = topk(s, k); w = np.take_along_axis(s, idx, -1)
    return idx, scale * w / w.sum(-1, keepdims=True)

sigmoid = lambda z: 1 / (1 + np.exp(-z))
sqrt_softplus = lambda z: np.sqrt(np.log1p(np.exp(z)))

z = rng.normal(size=(4, 16))
i1, w1 = gate_softmax_then_topk(z, 4)
i2, w2 = gate_topk_then_softmax(z, 4)
print("softmax->top-k->renorm == top-k->softmax:", np.array_equal(i1, i2) and np.allclose(w1, w2))
i3, w3 = gate_score_renorm(z, 4, sigmoid)
i4, w4 = gate_score_renorm(z, 4, sqrt_softplus)
print("sigmoid and sqrt-softplus pick the same experts (both monotone):", np.array_equal(i3, i4))
print("but give different weights:", np.round(w3[0], 3), "vs", np.round(w4[0], 3), "vs softmax", np.round(w1[0], 3))
_, ws = gate_topk_then_softmax(z + 3.0, 4); _, wg = gate_score_renorm(z + 3.0, 4, sigmoid)
print("shift all logits by +3: softmax weights unchanged:", np.allclose(ws, w2),
      "| sigmoid weights unchanged:", np.allclose(wg, w3))

# ---- 2. the Switch/GShard aux loss and its gradient ---------------------------
def lbl(zb, k):
    """E * sum_i f_i P_i over a batch; f from top-k counts (constant), P from softmax (differentiable)."""
    E = zb.shape[1]
    p = np.exp(zb - zb.max(1, keepdims=True)); p /= p.sum(1, keepdims=True)
    f = np.bincount(topk(zb, k).ravel(), minlength=E) / (zb.shape[0] * k)
    return E * (f * p.mean(0)).sum(), f, p

zb = rng.normal(size=(256, 8)); zb[:, 0] += 1.5          # expert 0 is popular
L0, f, p = lbl(zb, 2)
E, N = 8, zb.shape[0]
analytic = (E / N) * p * (f - (f * p).sum(1, keepdims=True))       # dLBL/dz_tj with f held fixed
eps, t, j = 1e-6, 3, 0
zp = zb.copy(); zp[t, j] += eps
p2 = np.exp(zp - zp.max(1, keepdims=True)); p2 /= p2.sum(1, keepdims=True)
numeric = (E * (f * p2.mean(0)).sum() - L0) / eps
print(f"\nLBL = {L0:.3f} (1.0 = perfectly balanced); load of expert 0 = {f[0]*E:.2f}x mean")
print(f"dLBL/dz[3,0]: analytic {analytic[t, j]:.6f}  numeric {numeric:.6f}")
print("sign of the mean gradient per expert (+ = pushed down):", np.sign(analytic.mean(0)).astype(int))

# ---- 3. combinatorial flexibility --------------------------------------------
print("\nexpert combinations per token, C(E, k):")
for name, E_, k_ in [("16 experts top-2 (DeepSeekMoE baseline)", 16, 2), ("64 experts top-8 (same FLOPs, 4x finer)", 64, 8),
                     ("gpt-oss-120b 128/4", 128, 4), ("DeepSeek-V3 256/8", 256, 8), ("Kimi K2 384/8", 384, 8),
                     ("Kimi K3 896/16", 896, 16), ("Nemotron 3 Ultra 512/22", 512, 22)]:
    print(f"  {name:40s} {comb(E_, k_):.3e}")

# ---- 4. capacity: token dropping vs dropless rounds ---------------------------
def route_counts(n_tok, E_, k_, skew):
    w = rng.permutation((np.arange(E_) + 1.0) ** -skew)
    g = np.log(w)[None, :] + rng.gumbel(size=(n_tok, E_))   # Gumbel top-k = sampling without replacement
    return np.bincount(np.argpartition(-g, k_, axis=1)[:, :k_].ravel().astype(np.intp), minlength=E_)

print("\nskew  CF    dropped  dropless rounds")
for skew in (0.0, 0.5):
    loads = route_counts(8192, 64, 8, skew)
    for cf in (1.0, 1.25, 2.0):
        cap = cf * loads.sum() / 64                            # Switch: capacity = CF * tokens*k / E
        print(f"{skew:4.1f}  {cf:4.2f}  {100*np.maximum(loads-cap, 0).sum()/loads.sum():6.1f}%  {int(np.ceil(loads.max()/cap))}")

# ---- 5. all-to-all fan-out: copies per token ---------------------------------
R, k_, E_ = 64, 8, 256                                         # 64 GPUs (8 nodes x 8), V3-like 256 experts
idx = np.argsort(rng.random((20000, E_)), 1)[:, :k_]            # uniform routing
gpus = idx // (E_ // R); nodes = gpus // 8
d_gpu = np.mean([len(set(r)) for r in gpus]); d_node = np.mean([len(set(r)) for r in nodes])
expect = lambda groups: groups * (1 - comb(E_ - E_ // groups, k_) / comb(E_, k_))   # P(group hit) = 1 - C(E-e,k)/C(E,k)
print(f"\nuniform top-{k_} over {R} GPUs: distinct GPUs per token {d_gpu:.2f} (exact {expect(R):.2f}),"
      f" distinct nodes {d_node:.2f} (exact {expect(8):.2f}); node-limited routing caps it at M = 4")
print(f"dispatch+combine bytes/token/layer, BF16, d=7168: per expert {2*k_*7168*2/1024:.0f} KiB,"
      f" deduplicated per GPU {2*d_gpu*7168*2/1024:.0f} KiB, latent d/2 {d_gpu*7168*2/1024:.0f} KiB")
 

Note in part 2 that the aux-loss gradient is positive only for expert 0: the loss pushes every token’s logit for the popular expert down, regardless of whether that token was well served by it. That is the interference the bias methods avoid. In part 4, a skew of 0.5 already drops 13% of slots at CF = 1.25, which is why the large models went dropless.

A PyTorch MoE layer with a sigmoid router, a selection-only bias updated by sign, a shared expert and dropless dispatch by sorting token slots by expert:

PyTorch PyTorch: DeepSeek-style MoE layer (sigmoid gate, aux-free bias, shared expert, dropless) 로컬에서 실행run locally (pip install torch)
import torch
import torch.nn as nn
import torch.nn.functional as F

class SwiGLU(nn.Module):
    def __init__(self, d, f):
        super().__init__()
        self.w1, self.w3, self.w2 = nn.Linear(d, f, bias=False), nn.Linear(d, f, bias=False), nn.Linear(f, d, bias=False)
    def forward(self, x):
        return self.w2(F.silu(self.w1(x)) * self.w3(x))

class MoE(nn.Module):
    def __init__(self, d, f, n_experts, k, n_shared=1, scale=2.5, bias_lr=1e-3):
        super().__init__()
        self.router = nn.Linear(d, n_experts, bias=False)
        self.experts = nn.ModuleList(SwiGLU(d, f) for _ in range(n_experts))
        self.shared = nn.ModuleList(SwiGLU(d, f) for _ in range(n_shared))
        self.register_buffer("bias", torch.zeros(n_experts))       # aux-loss-free: used for selection only
        self.k, self.scale, self.bias_lr = k, scale, bias_lr

    def forward(self, x):                                          # x: [T, d] (flattened tokens)
        scores = torch.sigmoid(self.router(x).float())             # [T, E], router in fp32
        idx = torch.topk(scores + self.bias, self.k, dim=-1).indices
        w = scores.gather(-1, idx)
        w = (self.scale * w / w.sum(-1, keepdim=True)).to(x.dtype)  # weights from unbiased scores
        # dropless dispatch: sort the T*k slots by expert id, run each expert on its contiguous slice
        flat = idx.flatten()
        order = flat.argsort()
        counts = torch.bincount(flat, minlength=len(self.experts)).tolist()
        tok = order // self.k                                      # which token each sorted slot belongs to
        wts = w.flatten()[order].unsqueeze(-1)
        y = torch.zeros_like(x)
        start = 0
        for e, n in enumerate(counts):
            if n:
                t = tok[start:start + n]
                y.index_add_(0, t, self.experts[e](x[t]) * wts[start:start + n])
                start += n
        if self.training:                                          # sign update of the bias, once per step
            with torch.no_grad():                                  # (all-reduce `load` across ranks in DP/EP)
                load = torch.tensor(counts, device=x.device, dtype=torch.float32)
                self.bias += self.bias_lr * torch.sign(load.mean() - load)
        return y + sum(s(x) for s in self.shared)

moe = MoE(d=64, f=32, n_experts=16, k=4)
print(moe(torch.randn(10, 64)).shape)                              # torch.Size([10, 64])
 
확인 문제Check yourself

A team trains with a GShard-style aux loss computed per micro-batch, and each micro-batch packs a few long documents of one domain. The experts end up nearly uniform across domains. Which single change most directly addresses this?

Computed per micro-batch, ∑ifiPi\sum_i f_iP_i penalises imbalance within a one-domain micro-batch, i.e. it asks each domain to use every expert equally, which forbids specialisation. Synchronising ff over the global batch (a single EE-vector all-reduce) turns it into a penalty on the global load only (Qiu et al.; Qwen3, MAI). Raising α makes it worse; the gate function and capacity do not change what is being balanced.

확인 문제Check yourself

Kimi K3 routes 16 of 896 experts with a 3584-wide latent (d = 7168). Compared with Kimi K2 (8 of 384, no latent), the dispatch bytes per token are…

Dispatch carries one vector per routed expert (before deduplication): K2 sends 8×7168=57,3448\times7168 = 57{,}344 numbers, K3 sends 16×3584=57,34416\times3584 = 57{,}344. LatentMoE halves the vector and the design spends the saving on doubling kk (and the expert count), so communication stays flat while the combinatorial capacity explodes.

Summary

  • The gate: softmax-then-top-k with renormalisation equals top-k-then-softmax; sigmoid and √softplus scores are absolute rather than relative; renormalised weights always sum to the scale λ.
  • Fine-grained experts buy combinatorial flexibility ((2568)≈4×1014\binom{256}{8}\approx4\times10^{14}) at constant FLOPs; shared experts matter most when every layer is MoE.
  • Balancing schemes differ in where they push: aux loss on the router gradient (and its scope, micro or global batch, decides whether it kills specialisation), bias methods on selection only, Quantile Balancing with an exact one-step bias.
  • Capacity turns imbalance into dropped tokens or extra rounds; frontier models are dropless.
  • All-to-all bytes ≈ 2 · copies · d · b; node-limited routing caps the expensive copies, LatentMoE shrinks d and spends the saving on more experts and a larger k.

해 볼 것. skew 0.6, capacity factor 1.25: token dropping은 슬롯의 상당 부분을 잃고, multi-round dropless MoE는 2–3 라운드와 고정 버퍼의 약 두 배인 최악 버퍼가 필요하다. GPU 64장에서 k를 2에서 16으로: expert별 사본은 8배가 되고, 서로 다른 GPU 수는 그보다 조금 덜, 노드 수는 8에서 포화한다. 노드 제한 M = 4: 같은 k에서 노드 간 사본이 4 이하로 떨어진다. d/ℓ = 2 또는 4: 바이트가 절반, 1/4이 된다. 이것이 LatentMoE의 거래다.

LatentMoE: 아낀 대역폭을 expert에 쓴다

dispatch되는 벡터는 dd차원 토큰 표현이다. LatentMoE(Elango et al.; Nemotron 3, MAI-Base-1/2, Kimi K3가 사용)는 그것을 latent ℓ<d\ell<d로 한 번 투영하고, routed expert를 Rℓ\mathbb R^\ell에서 돌리고, 섞은 출력을 다시 올린다.

y=∑jFFNj(s)(u)+W↑ Norm(∑i∈Tgi FFNi(W↓u)),g=router(u).\mathbf y = \sum_j \mathrm{FFN}^{(s)}_j(\mathbf u) + W^{\uparrow}\,\mathrm{Norm}\Big(\sum_{i\in\mathcal T} g_i\,\mathrm{FFN}_i(W^{\downarrow}\mathbf u)\Big), \qquad g = \text{router}(\mathbf u).

router와 shared expert는 여전히 온전한 u\mathbf u를 본다(routing 결정은 압축 전 표현에서 내린다). dispatch 바이트와 모든 routed expert의 가중치가 d/ℓd/\ell배 줄고, 설계들은 그 배수를 expert 수와 활성 expert 수에 쓴다. Kimi K3의 회계가 정확하다. 16×3584=57,344=8×716816\times3584 = 57{,}344 = 8\times7168이라 K3는 토큰당 K2와 같은 바이트를 옮기면서 896개 중 두 배 많은 expert로 보낸다(K3 레슨). Nemotron 3 Ultra는 d/ℓ=8192/2048=4d/\ell = 8192/2048 = 4이고 512개 중 top-22다. 대가는 층마다 d×ℓd\times\ell 행렬 두 개와 rank 병목이다. K3는 W↓→W^\downarrow\to expert →W↑\to W^\uparrow 사슬이 2.8T 규모에서 activation을 폭발시켰기 때문에 W↑W^\uparrow 앞에 RMSNorm을 넣었다.

Sparsity scaling

kk를 고정하고 expert를 늘리면 FLOPs가 같은 채로 손실이 내려간다. Kimi K2는 같은 검증 손실에 도달하는 데 sparsity 48이 sparsity 8 / 16 / 32보다 1.69배 / 1.39배 / 1.15배 적은 FLOPs가 든다고 측정했고(K2 Figure 5), 인프라 복잡도 때문에 48에서 멈췄다. 2026년의 config는 좁은 띠 안에 있다.

모델routed EE / 활성 kksharedsparsity E/kE/klatent d→ℓd\to\ell균형 방식(보고된 대로)
Qwen3-235B-A22B128 / 8016–global-batch LBL
gpt-oss-120b128 / 4032–밝히지 않음
DeepSeek-V3256 / 8132–aux-free bias (u=10−3u=10^{-3}) + seq-wise 10−410^{-4}, node-limited M=4M=4
Kimi K2384 / 8148–bias 기반 선택(noaux_tc)
Qwen3.8-Flash-Next512 / 10151–보고서 본문에 없음
Kimi K3896 / 162567168 → 3584Quantile Balancing
DeepSeek-V4-Pro384 / 6164–aux-free bias (10−310^{-3}) + 균형 손실 10−410^{-4}
MAI-Base-1512 / 80646656 → 3072GShard 손실, 전역 집계, dropless
MAI-Base-2512 / 71738704 → 4096multi-round dropless
Nemotron 3 Ultra512 / 221238192 → 2048여기서는 다루지 않음
config와 보고서는 위에 인용한 대로. V4는 V4 레슨(§4.2.2).

2025년에서 2026년으로의 흐름은 오른쪽 위다. expert를 늘리고, 토큰당 활성 expert를 늘리고, 그 비용을 latent로 치른다. expert 하나의 폭은 줄어든다(Qwen3.8: 640). sparsity가 전부도 아니다. Nemotron의 512개 중 22개를 4배 latent에서 고르는 것은 바이트와 FLOPs로는 온전한 폭에서 128개 중 5.5개를 고르는 것과 비슷하지만(Nemotron 레슨), 조합 수는 (1285)\binom{128}{5} 대신 (51222)\binom{512}{22}다.

직접 만들기

NumPy 블록이 위의 주장들을 확인한다. 두 softmax gate는 같고, sigmoid 가중치는 이동 불변이 아니며, (ff를 상수로 둔) aux loss 기울기는 유한차분과 맞고 과부하 expert만 내리누른다. 조합 수, capacity drop 대 dropless 라운드, all-to-all의 기대 사본 수도 계산한다.

NumPy Router 실험실: gate, aux loss 기울기, 조합 수, capacity, all-to-all 사본
import numpy as np
from math import comb
rng = np.random.default_rng(0)

# ---- 1. 공개 config가 쓰는 gate 함수 네 가지 ---------------------------------
def topk(scores, k):
    return np.argsort(-scores, axis=-1)[..., :k]

def gate_softmax_then_topk(z, k):           # Qwen3 / MAI: 전체 softmax, top-k, 재정규화
    p = np.exp(z - z.max(-1, keepdims=True)); p /= p.sum(-1, keepdims=True)
    idx = topk(p, k); w = np.take_along_axis(p, idx, -1)
    return idx, w / w.sum(-1, keepdims=True)

def gate_topk_then_softmax(z, k):           # gpt-oss: logit의 top-k, k개에 대한 softmax
    idx = topk(z, k); zz = np.take_along_axis(z, idx, -1)
    w = np.exp(zz - zz.max(-1, keepdims=True))
    return idx, w / w.sum(-1, keepdims=True)

def gate_score_renorm(z, k, f, scale=1.0):  # DeepSeek-V3/K2/K3 (sigmoid), V4 (sqrt softplus)
    s = f(z); idx = topk(s, k); w = np.take_along_axis(s, idx, -1)
    return idx, scale * w / w.sum(-1, keepdims=True)

sigmoid = lambda z: 1 / (1 + np.exp(-z))
sqrt_softplus = lambda z: np.sqrt(np.log1p(np.exp(z)))

z = rng.normal(size=(4, 16))
i1, w1 = gate_softmax_then_topk(z, 4)
i2, w2 = gate_topk_then_softmax(z, 4)
print("softmax->top-k->renorm == top-k->softmax:", np.array_equal(i1, i2) and np.allclose(w1, w2))
i3, w3 = gate_score_renorm(z, 4, sigmoid)
i4, w4 = gate_score_renorm(z, 4, sqrt_softplus)
print("sigmoid and sqrt-softplus pick the same experts (both monotone):", np.array_equal(i3, i4))
print("but give different weights:", np.round(w3[0], 3), "vs", np.round(w4[0], 3), "vs softmax", np.round(w1[0], 3))
_, ws = gate_topk_then_softmax(z + 3.0, 4); _, wg = gate_score_renorm(z + 3.0, 4, sigmoid)
print("shift all logits by +3: softmax weights unchanged:", np.allclose(ws, w2),
      "| sigmoid weights unchanged:", np.allclose(wg, w3))

# ---- 2. Switch/GShard aux loss와 그 기울기 -----------------------------------
def lbl(zb, k):
    """배치 위의 E * sum_i f_i P_i. f는 top-k 개수(상수), P는 softmax(미분 가능)."""
    E = zb.shape[1]
    p = np.exp(zb - zb.max(1, keepdims=True)); p /= p.sum(1, keepdims=True)
    f = np.bincount(topk(zb, k).ravel(), minlength=E) / (zb.shape[0] * k)
    return E * (f * p.mean(0)).sum(), f, p

zb = rng.normal(size=(256, 8)); zb[:, 0] += 1.5          # expert 0이 인기
L0, f, p = lbl(zb, 2)
E, N = 8, zb.shape[0]
analytic = (E / N) * p * (f - (f * p).sum(1, keepdims=True))       # f를 고정한 dLBL/dz_tj
eps, t, j = 1e-6, 3, 0
zp = zb.copy(); zp[t, j] += eps
p2 = np.exp(zp - zp.max(1, keepdims=True)); p2 /= p2.sum(1, keepdims=True)
numeric = (E * (f * p2.mean(0)).sum() - L0) / eps
print(f"\nLBL = {L0:.3f} (1.0 = perfectly balanced); load of expert 0 = {f[0]*E:.2f}x mean")
print(f"dLBL/dz[3,0]: analytic {analytic[t, j]:.6f}  numeric {numeric:.6f}")
print("sign of the mean gradient per expert (+ = pushed down):", np.sign(analytic.mean(0)).astype(int))

# ---- 3. 조합의 유연성 ----------------------------------------------------------
print("\nexpert combinations per token, C(E, k):")
for name, E_, k_ in [("16 experts top-2 (DeepSeekMoE baseline)", 16, 2), ("64 experts top-8 (same FLOPs, 4x finer)", 64, 8),
                     ("gpt-oss-120b 128/4", 128, 4), ("DeepSeek-V3 256/8", 256, 8), ("Kimi K2 384/8", 384, 8),
                     ("Kimi K3 896/16", 896, 16), ("Nemotron 3 Ultra 512/22", 512, 22)]:
    print(f"  {name:40s} {comb(E_, k_):.3e}")

# ---- 4. capacity: token dropping 대 dropless 라운드 ---------------------------
def route_counts(n_tok, E_, k_, skew):
    w = rng.permutation((np.arange(E_) + 1.0) ** -skew)
    g = np.log(w)[None, :] + rng.gumbel(size=(n_tok, E_))   # Gumbel top-k = 비복원 추출
    return np.bincount(np.argpartition(-g, k_, axis=1)[:, :k_].ravel().astype(np.intp), minlength=E_)

print("\nskew  CF    dropped  dropless rounds")
for skew in (0.0, 0.5):
    loads = route_counts(8192, 64, 8, skew)
    for cf in (1.0, 1.25, 2.0):
        cap = cf * loads.sum() / 64                            # Switch: capacity = CF * tokens*k / E
        print(f"{skew:4.1f}  {cf:4.2f}  {100*np.maximum(loads-cap, 0).sum()/loads.sum():6.1f}%  {int(np.ceil(loads.max()/cap))}")

# ---- 5. all-to-all 사본 수 ------------------------------------------------------
R, k_, E_ = 64, 8, 256                                         # GPU 64장(8노드 x 8), V3 같은 expert 256개
idx = np.argsort(rng.random((20000, E_)), 1)[:, :k_]            # 균등 routing
gpus = idx // (E_ // R); nodes = gpus // 8
d_gpu = np.mean([len(set(r)) for r in gpus]); d_node = np.mean([len(set(r)) for r in nodes])
expect = lambda groups: groups * (1 - comb(E_ - E_ // groups, k_) / comb(E_, k_))   # P(그룹 적중) = 1 - C(E-e,k)/C(E,k)
print(f"\nuniform top-{k_} over {R} GPUs: distinct GPUs per token {d_gpu:.2f} (exact {expect(R):.2f}),"
      f" distinct nodes {d_node:.2f} (exact {expect(8):.2f}); node-limited routing caps it at M = 4")
print(f"dispatch+combine bytes/token/layer, BF16, d=7168: per expert {2*k_*7168*2/1024:.0f} KiB,"
      f" deduplicated per GPU {2*d_gpu*7168*2/1024:.0f} KiB, latent d/2 {d_gpu*7168*2/1024:.0f} KiB")
 

2번에서 aux loss 기울기는 expert 0에서만 양수다. 그 토큰이 인기 expert에게 잘 처리되었는지와 상관없이 모든 토큰의 인기 expert logit을 내리누른다. bias 방식이 피하는 간섭이 이것이다. 4번에서 skew 0.5만으로도 CF = 1.25에서 슬롯의 13%가 버려진다. 큰 모델들이 dropless로 간 이유다.

sigmoid router, sign으로 갱신되는 선택용 bias, shared expert, 토큰 슬롯을 expert별로 정렬하는 dropless dispatch를 갖춘 PyTorch MoE 층:

PyTorch PyTorch: DeepSeek식 MoE 층 (sigmoid gate, aux-free bias, shared expert, dropless) 로컬에서 실행run locally (pip install torch)
import torch
import torch.nn as nn
import torch.nn.functional as F

class SwiGLU(nn.Module):
    def __init__(self, d, f):
        super().__init__()
        self.w1, self.w3, self.w2 = nn.Linear(d, f, bias=False), nn.Linear(d, f, bias=False), nn.Linear(f, d, bias=False)
    def forward(self, x):
        return self.w2(F.silu(self.w1(x)) * self.w3(x))

class MoE(nn.Module):
    def __init__(self, d, f, n_experts, k, n_shared=1, scale=2.5, bias_lr=1e-3):
        super().__init__()
        self.router = nn.Linear(d, n_experts, bias=False)
        self.experts = nn.ModuleList(SwiGLU(d, f) for _ in range(n_experts))
        self.shared = nn.ModuleList(SwiGLU(d, f) for _ in range(n_shared))
        self.register_buffer("bias", torch.zeros(n_experts))       # aux-loss-free: 선택에만 쓴다
        self.k, self.scale, self.bias_lr = k, scale, bias_lr

    def forward(self, x):                                          # x: [T, d] (펼친 토큰)
        scores = torch.sigmoid(self.router(x).float())             # [T, E], router는 fp32
        idx = torch.topk(scores + self.bias, self.k, dim=-1).indices
        w = scores.gather(-1, idx)
        w = (self.scale * w / w.sum(-1, keepdim=True)).to(x.dtype)  # 가중치는 bias 없는 점수로
        # dropless dispatch: T*k 슬롯을 expert id로 정렬하고 expert마다 연속 구간을 돌린다
        flat = idx.flatten()
        order = flat.argsort()
        counts = torch.bincount(flat, minlength=len(self.experts)).tolist()
        tok = order // self.k                                      # 정렬된 슬롯이 속한 토큰
        wts = w.flatten()[order].unsqueeze(-1)
        y = torch.zeros_like(x)
        start = 0
        for e, n in enumerate(counts):
            if n:
                t = tok[start:start + n]
                y.index_add_(0, t, self.experts[e](x[t]) * wts[start:start + n])
                start += n
        if self.training:                                          # bias의 sign 업데이트, step마다 한 번
            with torch.no_grad():                                  # (DP/EP에서는 rank 간에 load를 all-reduce)
                load = torch.tensor(counts, device=x.device, dtype=torch.float32)
                self.bias += self.bias_lr * torch.sign(load.mean() - load)
        return y + sum(s(x) for s in self.shared)

moe = MoE(d=64, f=32, n_experts=16, k=4)
print(moe(torch.randn(10, 64)).shape)                              # torch.Size([10, 64])
 
확인 문제Check yourself

한 팀이 GShard식 aux loss를 micro-batch마다 계산해 학습하고, micro-batch마다 한 도메인의 긴 문서 몇 개를 packing한다. expert들이 도메인과 무관하게 거의 균일해졌다. 이것을 가장 직접 고치는 변화 하나는?

micro-batch마다 계산한 ∑ifiPi\sum_i f_iP_i는 한 도메인짜리 micro-batch 안의 불균형을 벌한다. 즉 도메인마다 모든 expert를 똑같이 쓰라고 요구하니 전문화가 금지된다. ff를 global batch에서 동기화하면(EE차원 벡터 all-reduce 한 번) 전역 부하에 대한 벌점이 된다(Qiu et al.; Qwen3, MAI). α를 올리면 더 나빠지고, gate 함수나 capacity는 무엇을 균형 맞추는지를 바꾸지 않는다.

확인 문제Check yourself

Kimi K3는 896개 중 16개 expert로, 폭 3584인 latent(d = 7168)에서 라우팅한다. Kimi K2(384개 중 8개, latent 없음)와 비교하면 토큰당 dispatch 바이트는?

dispatch는 (중복 제거 전) routed expert마다 벡터 하나를 나른다. K2는 8×7168=57,3448\times7168 = 57{,}344개, K3는 16×3584=57,34416\times3584 = 57{,}344개다. LatentMoE가 벡터를 절반으로 줄이고, 설계는 그 절약으로 kk(그리고 expert 수)를 두 배로 했다. 통신은 그대로인데 조합 용량은 폭발한다.

정리

  • gate: softmax→top-k→재정규화는 top-k→softmax와 같다. sigmoid와 √softplus 점수는 상대값이 아니라 절대값이다. 재정규화된 가중치의 합은 항상 배율 λ다.
  • 세분화 expert는 FLOPs를 그대로 두고 조합의 유연성((2568)≈4×1014\binom{256}{8}\approx4\times10^{14})을 산다. shared expert는 모든 층이 MoE일 때 가장 중요하다.
  • 균형 방식은 미는 곳이 다르다. aux loss는 router 기울기를(그리고 집계 범위, micro냐 global이냐가 전문화를 죽이는지를 정한다), bias 방식은 선택만을, Quantile Balancing은 한 step짜리 정확한 bias로 민다.
  • capacity는 불균형을 버려지는 토큰이나 추가 라운드로 바꾼다. 프론티어 모델은 dropless다.
  • all-to-all 바이트 ≈ 2 · 사본 수 · d · b. node-limited routing은 비싼 사본을 묶고, LatentMoE는 d를 줄여 그 절약을 expert 수와 k에 쓴다.

더 읽을거리Further reading