Mixture of experts: routers, load balancing, fine-grained and shared experts, expert parallelism

How a mixture-of-experts layer picks experts for each token, keeps them evenly used, splits them finely and shares some, spreads them over GPUs, and what it costs to serve, on the running example of Topic: llm-architecture: the tiny GPT trained dense and as six MoE variants at the same active FFN size, one trained MoE layer run expert-parallel over four processes, and the router fields of 23 real configs. Training measured on Apple M1 Pro (MPS), analysis on its CPU; transformers 5.20.1 quoted by file and line. Reading: 35 min, plus 21 in closed details. Data as of October 2026.

A mixture-of-experts (MoE) layer stores E feed-forward networks, the experts, but sends each token through only the k that a small router picks, so the model has many parameters but each token pays for k experts. The page is the price of that one discrete choice: the router learns only through what it picked, traffic must be kept balanced, buffers overflow, and the experts must live on many GPUs.

Fig. 1, step by step: one token, one layer, 8 experts stored, 2 computed

  1. Eight experts, all in memory. One MoE layer of the trained moe8top2 tiny GPT holds 8 experts, each an FFN of 262,144 weights. Token 1 of the running sequence, "Once", arrives as its 256-number hidden state h.
  2. The router scores every expert. A 256 × 8 matrix Wr turns h into 8 logits and a softmax turns them into scores that sum to 1. Recorded for "Once" in layer 1: E6 gets 0.61, E0 0.13, the other six 0.02 to 0.07.
  3. Keep the best 2. Only E6 and E0 will run for this token; the other 6 are skipped. Their two scores renormalised to sum to 1 are the gate weights, 0.82 and 0.18.
  4. Dispatch and combine. h travels to the two experts and their outputs come back weighted by the gates (the denser stream is E6's): y = h + 0.82 · E6(h) + 0.18 · E0(h).
  5. Memory pays for 8, compute for 2. All 2,097,152 expert weights must be stored, because the next token may pick any of them; this token computed with 524,288, what the dense FFN costs. Total parameters (what must sit in memory) and active parameters (what one token computes with) come apart. Under expert parallelism the experts sit on different GPUs, and the token travels to them and back (section 7).

Recorded, not drawn by hand: the router logits of the trained moe8top2 for token 1 of the running sequence in layer 1 (src/analysis/analyse.py), softmax and renormalisation computed on the page.

You need: the feed-forward block each expert copies, and SwiGLU (The transformer from zero); the running example, the root's tiny GPT on TinyStories (Topic: llm-architecture). What an all-to-all is and how expert parallelism composes with the other parallelisms in training are on Distributed Training.

Expert
one of E ordinary FFNs in an MoE layer, narrower than the dense FFN it replaces.
Router (gate)
a d × E linear layer that scores every expert for each token; the k best are used.
Gate weight
the weight gi a chosen expert's output gets, usually its score renormalised over the k chosen.
Shared expert
an expert every token uses, outside the router.
Fine-grained experts
many narrow experts and a larger k instead of few wide ones, at the same compute.
Collapse, MaxVio
traffic piling onto a few experts; MaxVio = (busiest load − mean load) / mean load, 0 when balanced.
Capacity factor
a fixed buffer per expert as a multiple of its average load; assignments past it are dropped.
Expert parallelism (EP)
experts split over GPUs; tokens move to them and back by two all-to-alls per MoE layer.
The design choices in one table, with what 2025 to 2026 configs chose (reference)
ChoiceOptionsWhat it buysWhat it costsWhat 2025 to 2026 configs chose
Router scoresoftmax over all experts; sigmoid per expert; softmax over the top k onlysigmoid: scores that do not shrink as experts are addednothing in selection (same top k from the same logits); the gate weights differsigmoid in DeepSeek-V3, Kimi K2 and K3, GLM, MiniMax, Nemotron 3 Super; softmax in Qwen3 and Qwen3.5; sqrt(softplus) in DeepSeek-V4-Pro (section 9)
Experts per token k1 (Switch, Llama 4), 2 (Mixtral), 4 to 22 (fine-grained)more k: a smoother layer, more ways to combine expertsexpert FLOPs and all-to-all bytes grow with kk = 4 to 22 out of E = 128 to 896 in most (Kimi K3: 16 of 896); k = 1 of 128 in Llama 4 Maverick; expert widths 512 to 3,072 (Llama 4: 8,192)
Expert sizefew large (8 of the dense FFN size) or many small (fine-grained)many small: C(E, k) combinations explode at equal computeskinnier matrix multiplies, more dispatch fan-outfine-grained almost everywhere since DeepSeekMoE (January 2024)
Shared experts0, 1 or 2 always-on experts beside the routed onescommon knowledge in one place; routed experts specialisetheir FLOPs every token1 in most; 2 in Kimi K3 (and DeepSeek-V2); none in Qwen3, gpt-oss and MiniMax-M2
Balancingauxiliary loss (Switch); per-expert bias, no loss (DeepSeek-V3); batch or global scopeprevents collapse onto a few expertsa loss fights the language-model loss; a bias needs an update in the training loopa selection bias in the DeepSeek, Kimi, GLM and MiniMax lines (noaux_tc, use_routing_bias); Qwen3 adopted a global-batch auxiliary loss
Capacityfixed buffer per expert (capacity factor) or droplessstatic shapes, predictable memorydropped tokens skip the FFN silentlydropless (grouped GEMM kernels); DeepSeek-V3 drops no tokens
Where the experts goevery layer; first k layers dense; every other layer; hash-routed first layersthe first layer balances worst: DeepSeekMoE 16B kept it dense “since we observe that the load balance status converges especially slower for the first layer” (Dai et al. 2024, DeepSeekMoE, section 5.1.2)a little computefirst 1 to 3 dense (DeepSeek, Kimi, GLM); every other layer (Llama 4 Maverick); first 3 hash-routed (DeepSeek-V4-Pro)
Parallelismexpert parallel (EP) over GPUs, with TP and DPexperts' memory spread outtwo all-to-alls per MoE layer each way; the busiest GPU sets the pacenode-limited routing (DeepSeek-V3: at most 4 nodes per token); wide EP at serving time
Measured on the running example (Apple M1 Pro, MPS, 1,500 steps, 12.3M tokens, seed 0)

Held-out loss (20 fixed validation batches): dense 2.278; 8 experts top 2 2.256; 16 + 1 shared top 3 2.210, at the same active FFN size and 2.6 to 2.8 times the parameters. Balancing by bias 2.230 against aux loss 2.256; no balancing 2.296 with MaxVio 1.88 against 0.12.

The Switch Transformers, Mixtral and DeepSeek-V3 paper pages own those papers' details (a live Switch layer, Mixtral's routing analysis and decode roofline, V3's ablation tables); the network side of expert parallelism is Interconnects and scaling's, EP at serve time Distributed and disaggregated serving's. This page owns the MoE layer end to end.

1. Total and active: more weights, the same compute per token

In a dense transformer every token multiplies through every weight, about 2 FLOPs per parameter per token, and the FFN holds most of them: one tiny-GPT block has 262,144 attention weights (four 256 × 256 projections) and 524,288 FFN weights (256 × 1,024 up, 1,024 × 256 down), two thirds of the block. MoE splits that FFN into experts. The root's tiny GPT (d = 256, 6 blocks, GELU) has MoE presets that keep the active FFN exactly the dense size, so comparisons on this page are at equal compute (presets in the root's src/data/configs.py). Fig. 2 draws them to scale:

Fig. 2, step by step: compute stays at the dense size while storage grows fourfold

  1. Dense: every weight runs. The tiny GPT's dense FFN (256 → 1,024 → 256) is 524,288 weights per layer, and every token uses all of them: stored equals per token. A block's footprint is proportional to its weights.
  2. moe8top2: 8 experts, 2 per token. Each expert is half as wide (512), 262,144 weights; a token uses the 2 the router picks (lit: E6 and E0, the trained model's choice for "Once" in layer 1). Stored 2,099,200 with the 2,048-weight router, per token 526,336: four times the storage at the dense cost.
  3. moe16top3_shared: finer, plus one always on. 16 routed experts of 256 plus 1 shared, 131,072 weights each; a token uses 3 routed (E13, E15 and E3 for "Once") and the shared one. Stored 2,232,320, per token 528,384.
  4. Whole models. Attention, embeddings and norms are not copied, so the model totals grow less than the FFN: 5.84M dense, 15.29M and 16.08M for the two MoE presets, while active stays at 5.84M, 5.85M and 5.86M.
  5. A real layer, at another scale. One DeepSeek-V3 MoE layer: 257 experts of 3 × 7,168 × 2,048 = 44,040,192 weights each (11.32 billion with the router); a token uses 9, 396 million (3.5%). Which 8 routed experts light is illustrative. The router itself (256 × 7,168) would be 1/24 of one block.
presetexperts per layerexpert hiddenactive per tokenFFN weights per layer, storedused per tokenmodel totalmodel active
baseline (dense)11,024the FFN524,288524,2885,836,0325,836,032
moe8top28 routed5122 routed2,099,200526,33615,285,5045,848,320
moe16top3_shared16 routed + 1 shared2563 routed + 1 shared2,232,320528,38416,084,2245,860,608

Per layer, moe8top2 stores 8 × (2 × 256 × 512) = 2,097,152 expert weights plus a 256 × 8 = 2,048-weight router; each expert is half the dense FFN, so a token's 2 experts (524,288) cost what the dense FFN costs. moe16top3_shared: 17 experts of 2 × 256 × 256 = 131,072 plus a 4,096-weight router; a token uses 4 of them. Totals from the tiny GPT's own param_groups() (the root's src/data/README.md, recorded 2026-10-18); active counts differ from dense only by the routers (6 × 2,048 = 12,288 and 6 × 4,096 = 24,576) derived.

Adding experts moves memory, not compute, until the batch grows

The same move on a real model, step by step: build the dense twin (one FFN as wide as the k routed experts plus the shared ones a token uses), then add the other experts and watch which of the five numbers move. Predict before stepping: which grows, FLOPs per token or weight memory, and what happens to the bytes a decode step reads when 64 sequences share the step?

Step by step: adding experts moves memory, not compute, until the batch grows

  1. The dense twin.
  2. Add the other experts.
  3. FLOPs barely move.
  4. The bill is memory.
  5. Batch 8: more experts read.
  6. Batch 64: nearly all of them.

Parameters from the root's Config calculator code (window.CC, unchanged; validated to residual 0 on 44 Hugging Face checkpoints), weights in BF16, decode reads with the input embedding counted as a full read and uniform independent routing (illustrative: real routing is skewed and touches fewer experts) derived. For a dense model the MoE version splits each FFN into 8 experts with 2 active (the Mixtral pattern). Moved here from the root's Config calculator on 2026-10-23.

y = h + ∑i ∈ TopK(s(h)) gi(h) · Ei(h) + ∑j Sj(h)
h
the token's hidden state entering the FFN sub-layer (after the norm), d numbers; the leading h is the residual connection
s(h)
router scores, one per expert, from logits Wr h (Wr is E × d)
TopK
the k experts with the highest scores (section 3 adds a bias to this choice, section 2 a group limit)
gi(h)
gate weight of chosen expert i, usually its score renormalised over the k chosen
Ei, Sj
routed expert i and shared expert j: ordinary FFNs, narrower than the dense one

What it costs, and when it pays. Compute per token stays at the active count plus the router, 2 × d × E FLOPs (4,096 per token per layer for moe8top2 against 1,048,576 for its two experts, 0.4%). Memory is priced on the total, because any token may pick any expert. MoE pays when parameters are cheap to store but compute per token is the bottleneck: pretraining at a fixed FLOP budget, and serving at large batch. It pays least on one memory-bound GPU at small batch (section 8).

How to check it. Count both numbers from a config with the Dense vs MoE calculator; on a live PyTorch model, sum p.numel() over one layer's experts and multiply by k/E. Mixtral 8x7B is 46.7B total and 12.9B active, not 56B, because only the FFNs are copied eight times (Mistral, 2023-12-11, vendor); DeepSeek-V3 is 671B and 37B (report, vendor); both are rebuilt from their configs in section 9.

2. The router: score, select, dispatch, combine

The router runs on every token in every MoE layer, so it must be cheap, and it must learn although "send to expert 3" is a discrete decision with no gradient. In DeepSeek-V3 its matrix Wr is 256 × 7,168 = 1,835,008 weights against 11.32 billion in the whole MoE layer, 0.016% (derived from its config). Fig. 3 steps the tiny GPT's router through the first 8 tokens of the running sequence ("Once upon a time, in a big forest, there lived a rhinoceros named Roxy...", never seen in training):

Fig. 3: eight real tokens through one router: 16 assignments, and the busiest expert sets the pace

  1. 8 tokens reach the FFN sub-layer. Each is the 256-number hidden state of one token after attention and the norm. The router is a 256 × 8 matrix: one logit per expert per token.
  2. The router scores every expert. Each column of bars is one token's 8 scores, coloured by expert: a softmax over the 8 for the softmax models, independent sigmoids for the sigmoid model. This costs 2 × 256 × 8 = 4,096 FLOPs per token.
  3. Each token keeps its top 2. The two chosen bars stay; only those experts run for this token, and the other 6 are skipped.
  4. Dispatch: each assignment goes to its expert. 16 assignments for 8 tokens travel along their expert's row; each cube in a stack is one token copy sent to that expert.
  5. The load each expert gets. The glass sheet is the mean, 2 per expert. The busiest expert sets the step time when experts sit on different GPUs, and an idle one holds weights that did no work.
  6. Combine: a weighted sum of the two experts. Each token adds g1 Ea(h) + g2 Eb(h) to its residual stream; the numbers under the tokens are the two gate weights.

Recorded router outputs of the four 8-expert models, trained identically except for how they balance (section 3), one forward pass each (src/analysis/analyse.py, measured on Apple M1 Pro (CPU)). Switching model or layer replays the steps; section 4 puts buffers of fixed size behind these stacks.

Normalise, then select. A softmax over all E experts (Switch, Mixtral, Qwen3) turns logits into probabilities that sum to 1; a sigmoid per expert (DeepSeek-V3 and the models that copied it) gives each expert an independent affinity in (0, 1). Both are increasing functions of the logit, so from the same logits they pick the same top k and differ only in the gate weights, until a bias or a group limit is added to the selection. Combine renormalises the k chosen scores to sum to 1 (most models), optionally multiplies by a constant routed_scaling_factor (2.5 in DeepSeek-V3, 5.0 in Nemotron 3 Super), and adds the weighted expert outputs to the residual stream. Predict: add experts that score a logit of 0; what happens to the best expert's softmax probability, and to its sigmoid?

A softmax probability is a share of one distribution: it averages 1/E and shrinks as experts are added, and after renormalisation a logit gap of 1 is a weight ratio of e ≈ 2.72. A sigmoid depends on its own logit only, which is why the many-expert models moved to it.

Softmax scores dilute as experts are added; sigmoid scores do not

The router logits of one token of the running sequence in one layer of the trained moe8top2 model (recorded, not illustrative). Pick the token and layer, then add experts with logit 0.

The evidence for sigmoid (depth)

DeepSeek-V3's report switches to sigmoid without arguing it (section 2.1.2, "slightly different from DeepSeek-V2"), but the same group's auxiliary-loss-free paper says "we find that the sigmoid baseline performs better than the softmax baseline", with softmax gates at higher perplexity for similar balance on 1B models in its appendix C (Wang et al. 2024, vendor: the authors are DeepSeek's).

The router learns only through the experts it picked. Top-k selection has no gradient; the language-model loss reaches the router only through the gate weights gi of the chosen experts. An expert that stops being chosen stops producing any evidence that it would have been good, which is why routing can collapse (section 3). Measured on the trained moe8top2, layer 4, tokens 1 to 8: with the language-model loss alone the gradient on the 6 unchosen logits of each token is at most 9.9 × 10-8 of the largest chosen one (rounding: analytically zero, since the renormalised gates are a softmax over the chosen logits only); with the Switch auxiliary loss added it is up to 0.079 of it, on all eight (measured on Apple M1 Pro (CPU), src/code/grad_check.py).

Group-limited routing. Experts are split into groups (one per node); each token first picks its best groups, then its experts inside them. DeepSeek-V3: 8 groups of 32, a group scored by the sum of its two best experts, 4 groups per token (modeling_deepseek_v3.py:140 to modeling_deepseek_v3.py:151): its "at most 4 nodes" (section 7). Kimi K2 and K3 and GLM set one group, so no limit.

Predict: the trained moe8top2 model is run with k = 1, 3 or 4 experts per token instead of the 2 it was trained with. Which hurts held-out loss most?
The router in code, and three ways of writing the same top-k softmax (depth)
# topic_llm_architecture/src/data/tiny_gpt.py, lines 391 to 424
391      def forward(self, x):
392          cfg, (B, T, D) = self.cfg, x.shape
393          xf = x.reshape(-1, D)
394          n, E, k = xf.shape[0], cfg.n_experts, cfg.top_k
395          logits = self.router(xf).float()
396          scores = logits.sigmoid() if cfg.router == "sigmoid" else logits.softmax(-1)
397          sel = scores + self.e_bias if cfg.balance == "bias" else scores     # the bias steers selection only
398          top_i = sel.topk(k, -1).indices                                     # (n,k)
399          top_w = scores.gather(-1, top_i)
400          if cfg.router == "sigmoid" or k > 1:
401              top_w = top_w / top_w.sum(-1, keepdim=True)                     # renormalise over the chosen experts
402          out = torch.zeros_like(xf)
403          load = torch.bincount(top_i.flatten(), minlength=E)                 # assignments per expert, before drops
404          cap = math.ceil(cfg.capacity_factor * n * k / E) if cfg.capacity_factor else None
405          dropped = 0
406          for e in range(E):
407              tok, slot = (top_i == e).nonzero(as_tuple=True)
408              if cap is not None and tok.numel() > cap:                        # first come first served, the rest dropped
409                  dropped += tok.numel() - cap
410                  tok, slot = tok[:cap], slot[:cap]
411              if tok.numel():
412                  out.index_add_(0, tok, self.experts[e](xf[tok]) * top_w[tok, slot, None].to(x.dtype))
413          for s in self.shared:
414              out = out + s(xf)
415          aux = xf.new_zeros(())
416          if cfg.balance == "aux" and self.training:                          # Switch: E * sum_i f_i * P_i
417              f = load.float() / (n * k)
418              aux = E * (f * scores.mean(0)).sum()
419          if cfg.balance == "bias" and self.training:                         # DeepSeek-V3: nudge under-loaded experts up
420              with torch.no_grad():
421                  self.e_bias += cfg.bias_rate * torch.sign(load.float().mean() - load.float())
422          self.last = {"top_i": top_i.view(B, T, k), "top_w": top_w.view(B, T, k), "load": load,
423                       "dropped_frac": dropped / max(1, n * k)}
424          return out.view(B, T, D), aux

The tiny GPT's router, tiny_gpt.py:379 onward (root src/data/tiny_gpt.py), which defines the arithmetic of every run on this page (tiny_gpt.py:396 onward; training ran it through an equivalent batched forward, section 6). The loop gathers each expert's tokens, runs the expert on that slice and scatter-adds the weighted result; transformers' Qwen3-MoE does the same in modeling_qwen3_moe.py:233 to modeling_qwen3_moe.py:243, and production stacks replace the loop by one grouped matrix multiply over ragged token groups (section 4).

Softmax over all experts, then top k, then renormalise (Qwen3-MoE in transformers, modeling_qwen3_moe.py:260 to modeling_qwen3_moe.py:263); top k of the logits, then softmax over those k (gpt-oss, modeling_gpt_oss.py:127 to modeling_gpt_oss.py:128); and Mixtral's paper formula Softmax(TopK(x · Wg)) with the other logits set to minus infinity (Mixtral, section 2.1). All three give the same gate weights: renormalising k softmax probabilities cancels the shared denominator and leaves a softmax over the k chosen logits. The trap is the renormalisation flag: Qwen3MoeConfig defaults to norm_topk_prob=False (configuration_qwen3_moe.py:106; Qwen3MoeConfig() gives norm_topk_prob = False, measured) while the released Qwen3-30B-A3B and 235B-A22B configs set it to true, so a model built from the default config weights its experts by raw probabilities that sum to less than one. Check: diff your config against the released one, field by field. Llama 4 applies a sigmoid only to the one logit it keeps (modeling_llama4.py:148 to modeling_llama4.py:150); DeepSeek-V4-Pro's config sets scoring_func to sqrtsoftplus, the square root of softplus, used by the same code path (modeling_deepseek_v4.py:1072).

Asking for more experts per token than exist fails loudly: the tiny GPT with 4 experts and top_k = 6 raises RuntimeError: selected index k out of range from torch.topk inside the router; the same message appears when a converted checkpoint's num_experts_per_tok does not match its expert count.

Other routing styles: noisy top-k, top-2, top-1, expert choice, hash routing (depth)

The layer was introduced between LSTM layers by Shazeer et al. in 2017 (Outrageously Large Neural Networks), put in a transformer by GShard in 2020 (GShard), and cut to one expert per token by Switch Transformers; the routing rules they and their successors tried:

Noisy top-k (2017)

Gaussian noise scaled by a learned softplus is added to the logits before the top k, so near-ties share traffic (Shazeer et al.: H(x) = x Wg + StandardNormal() · Softplus(x Wnoise)). Its descendant in transformers is Mixtral's multiplicative router_jitter_noise, 0 in the released configs (modeling_mixtral.py:123).

Top-2 (GShard, Mixtral)

GShard dispatched the second expert at random in proportion to its weight, to save capacity (GShard, "Random routing"); Mixtral keeps both always. Two gate weights give the router a comparison, not a single scalar.

Top-1 (Switch, 2021)

Shazeer et al. had "conjectured that routing to k>1 experts was necessary in order to have non-trivial gradients to the routing functions"; Switch showed k = 1 "preserves model quality" at less compute (Switch, section 2.1). ST-MoE later found top-2 better by +0.004 at 8 times the scale (ST-MoE, Table 8). Llama 4 Maverick is top-1 plus a shared expert.

Expert choice (2022)

Experts pick their top tokens instead of tokens picking experts: perfect balance by construction, "over 2× faster training convergence" than GShard top-2 at 8B/64E (Zhou et al., vendor, Google). It "might not immediately apply to auto-regressive text generation" because a token's experts depend on future tokens in the batch: no decoder LLM in section 9 uses it.

Hash routing

A fixed table maps each token id to its experts: no router to train, no collapse (Roller et al. 2021). DeepSeekMoE's Table 1 has it at a Pile loss of 1.932 against GShard's 1.867 at 2B (DeepSeekMoE). DeepSeek-V4-Pro uses it for its first 3 MoE layers (num_hash_layers 3; a frozen tid2eid table, modeling_deepseek_v4.py:1111), presumably because hidden states there are still close to the raw token embedding, so a learned router has little more than the token id to go on (our reading; the code and config give no reason).

What the router learned on the running sequence: routing tracks the token, not the topic (depth, measured)

Mixtral's own analysis: "Surprisingly, we do not observe obvious patterns in the assignment of experts based on the topic" (Mixtral, section 5); assignments track syntax and token identity more than subject, and domain specialisation appears mostly with global-batch balancing (section 3). Measured on the tiny GPT (moe8top2, 40,960 held-out tokens): given only the token id, its most common first-choice expert is right 77% to 98% of the time depending on the layer, against 12.5% for an id-blind router: routing is largely a function of the token itself (the expert-to-token table is below). Below, each piece of the 256-token running sequence is coloured by its first-choice expert in the chosen layer (Mixtral's Figure 8 does the same for its real model); tap a piece for both experts and their weights in every layer.

A different measure gives a different picture. Goodfire's audit of Qwen3.6-35B-A3B asked what each expert's neurons respond to rather than which tokens reach it: judged by agents reading summaries of those neurons, its 10,240 experts are narrowly themed and narrow with depth (one is devoted to bosses in RPG board games), and the essay argues a router, one small linear layer, could not route ten thousand unrelated things to one packed expert. Token-predictable routing and topic-specific experts can both hold; the theming is agent-judged, one team's reading, with no rubric published (Neural Networks Are Already Clean).

The tokens each expert most often receives as first choice over 5 held-out batches (40,960 tokens), with the share of that token's occurrences that went there. Determinism is the fraction of tokens whose first-choice expert is the one most common for their token id: 1 would mean routing is a lookup on the token id alone, 1/8 that it ignores it.

3. Collapse, and the two ways to balance

An expert chosen slightly more often gets more gradient, improves, and is chosen more often still; the others starve and, getting no gradient (section 2), never show they were worth reviving. This is routing collapse. It costs quality (the model shrinks to the experts that survived) and time (with experts on different GPUs the busiest one sets the step, and with fixed buffers its overflow is dropped). The tiny GPT's training log records every 10 steps how many of the batch's 16,384 assignments (8,192 tokens × 2) went to each expert; Fig. 4 replays it. Predict first: with no balancing at all, how much of a layer's traffic does the busiest expert end up with?

Right plate:

Fig. 4: without balancing the router collapses within 100 steps; the aux loss keeps all eight near 1/8, the bias gets there by step 800

  1. Step 0: even by chance. At initialisation the router's random weights spread traffic roughly evenly: both plates sit near the glass sheet at 1/8 (MaxVio 0.67 on one batch of 8,192 tokens, batch noise).
  2. Steps 0 to 100: the collapse. Without balancing, layers 3 to 6 pile onto one or two experts almost at once (MaxVio 2.20 at step 10 and 1.59 at step 100; the ceiling is 3); with the auxiliary loss the same stretch peaks at 1.19 at step 10 and is down to 0.35 by step 100.
  3. Steps 100 to 300. The aux-loss run is near even (0.23 at step 300); the bias runs come down more slowly (0.51 for the sigmoid router with the bias), because each bias moves only 0.001 a step.
  4. Steps 300 to 800: the bias catches up. 0.11 by step 800 for the sigmoid router with the bias, against 0.17 with the aux loss.
  5. Steps 800 to 1,500: nothing revives. The starved experts of the unbalanced run never come back (1.87 at the end): with no traffic they get no gradient that would show they were useful.
  6. After training, on held-out text. On 20 held-out batches: MaxVio 1.88 without balancing, 0.12 with the aux loss, 0.04 with the sigmoid router and the bias.

Each plate: one run's 6 layers (rows) by 8 experts (columns, 16 for the fine-grained run), height the expert's share of that logged batch's 16,384 assignments; the glass sheet is perfect balance. Same data, seed and schedule for every run; measured on Apple M1 Pro (MPS), the root's train.py through the batched MoE forward of src/runs/fast_moe.py. The 151 logged frames play as five stretches.

Measured, no balancing. The run with balancing switched off (balance=none, everything else equal) ends with MaxVio 1.88 averaged over its 6 layers, against 0.12 with the auxiliary loss; in its worst layer (3) one expert takes 48% of all assignments, and 14 of its 48 experts get under 1% of the traffic. Its held-out loss is 2.296 against 2.256: higher. MaxVio is the metric of Wang et al. 2024: 0 is perfect; with top 2 the ceiling is 3 (one expert in every token's pair).

Fix 1: an auxiliary load-balancing loss (Switch, 2021)

Worked example first: E = 4 collapsed onto expert 1, so the dispatch fractions are f = (1, 0, 0, 0) and the mean router probabilities P = (0.7, 0.1, 0.1, 0.1). The loss below is 4 × 0.7 = 2.8 times its coefficient, against 1 times when routing is uniform.

ℒaux = α · E · ∑i=1E fi Pi
fi
fraction of the batch's tokens dispatched to expert i (a count: no gradient)
Pi
mean router probability given to expert i over the batch (differentiable)
α
coefficient: Switch used 10−2 after a sweep from 10−1 to 10−5 "found 10−2 balanced load quickly without interfering with training loss" (Switch, eq. 4 to 6)
E
the number of experts: under uniform routing ∑ fiPi = 1/E, so the factor keeps the loss at α whatever E is

Because f has no gradient, the loss does not move tokens; it lowers the router probability of experts that are both popular and confident, and the top-k follows. Its cost is that it is a second objective: wherever a token genuinely belongs with one expert, the balancing gradient pushes the other way. The tiny GPT uses it with α = 0.01, f counted over the n · k assignments (tiny_gpt.py:418, added to the loss at train.py:123).

Fix 2: a per-expert bias and no loss (DeepSeek, 2024)

Add a bias bi to expert i's score for the top-k choice only; the gate weight uses the score without it. After each step, lower the bias of overloaded experts and raise it for underloaded ones:

select by si + bi;   weight by si;   bi ← bi + γ · sign(c̄ − ci)
ci
tokens expert i received in the step; c̄ their mean over experts
γ
"bias update speed": 0.001 for DeepSeek-V3's first 14.3T tokens and 0 for the last 500B (DeepSeek-V3, sections 2.1.2 and 4.2)

The bias never enters the output, so it never enters the gradient: balancing moves the decision boundary instead of adding a competing objective. V3 still kept a sequence-wise loss of the Switch form with α = 0.0001, "just to avoid extreme imbalance within any single sequence", and "does not drop any tokens during training". The tiny GPT's version is tiny_gpt.py:397 and tiny_gpt.py:421 (γ = 0.001, every training step).

Measured: aux loss against bias. Held-out loss and MaxVio after 1,500 steps: softmax router with the auxiliary loss 2.256 and 0.12; softmax router with the bias instead 2.265 and 0.06; sigmoid router with the bias (DeepSeek-V3's recipe) 2.230 and 0.04. The softmax pair differs only in the balancing switch; the seed-1 rerun of the aux-loss model (2.254) sets the noise to read these gaps against.

Predict: the bias scheme nudges every expert's bias by ±0.001 per step. After 1,500 steps of training the tiny GPT, how large is the largest bias in magnitude?

Over which tokens is balance measured? A loss computed per micro-batch is close to a per-sequence constraint: even a pure code sequence is pushed to spread over every expert. Qwen's global-batch loss synchronises fi across data-parallel ranks, so balance is demanded only over the whole, diverse batch; Qwen3 adopted it (Qwen3 report). DeepSeek's bias balances per batch too. The cost of batch-level balance is imbalance inside one sequence or a small batch, which comes back at serving time (section 8).

The router z-loss balances nothing. Often listed with balancing, it bounds router logits that grow until bfloat16 roundoff in the exponential causes loss spikes: ℒz = (1/B) ∑tokens (log ∑j exj)2, coefficient cz = 0.001 (ST-MoE, section 3.3). The same concern is why Switch computed the router in float32 inside a bfloat16 model ("selective precision"), and transformers' DeepSeek-V3 router still does (modeling_deepseek_v3.py:135).

Checked: fine-tuning with transformers balances nothing by default

Qwen3-MoE, Mixtral, gpt-oss and Llama 4 compute their auxiliary loss only when output_router_logits=True, and their configs ship with it off. DeepSeek-V3, GLM-4.5, Nemotron-H and DeepSeek-V4 load the bias but never update it. A plain fine-tune therefore runs with no balancing at all; log per-expert counts, set the flag, or implement the bias update (details below).

Load in detail: held-out loads, a heat map per layer, MaxVio, aux loss and drops over training (depth, measured)

Expert load after training on held-out text, per balancing scheme

Share of the 2 × 163,840 expert assignments on 20 fixed held-out batches (the same windows as the training script's held-out loss), per layer, after 1,500 steps. Dashed line: perfect balance (1/8). measured on Apple M1 Pro (MPS training, CPU analysis).

Heat map: rows are experts, columns are logged steps (every 10), colour is the expert's share of that step's assignments (white-ish 0, darkest half the batch or more). Balanced routing shows as eight bands of the same even intensity.

The evidence for the bias and for global-batch balance, device-level losses, and what transformers actually computes (depth, checked)

Bias against loss, published. DeepSeek's own evidence (vendor): on 1B and 3B MoE models, validation perplexity 9.56 to 9.50 and 7.97 to 7.92 with MaxVio 0.72 to 0.04 and 0.52 to 0.04 (Wang et al. 2024, Table 2); in V3's Table 5 better scores "on most" benchmarks, though the large model's MMLU went the other way (68.3 to 67.2).

Global-batch balance, published. Qwen reports "approximately 0.1 in pre-training PPL and 2 in benchmark scores" better, and domain specialisation that "only clearly emerges when trained with the global-batch LBL" (up to 42.8B parameters and 400B tokens; Qiu et al. 2025, vendor, Alibaba), at under 3% extra latency, because the synchronised statistic is one number per expert; Alibaba: Qwen has a toy in which the same routing costs four times the minimum per micro-batch and nothing over the global batch. DeepSeek reached the same conclusion from the other side: a batch-wise auxiliary loss matched its bias (validation loss 2.258 sequence-wise, 2.253 bias, 2.253 batch-wise at 1B; 2.085, 2.080, 2.080 at 3B; V3 report section 4.5.3), with two named risks: imbalance "within certain sequences or small batches" and "domain-shift-induced load imbalance during inference".

Balance devices, not experts. DeepSeekMoE kept a small expert-level loss "to mitigate the risk of routing collapse" and added a larger device-level one, the same f · P product over groups of experts that share a device, because "it becomes unnecessary to enforce strict balance constraints at the expert level ... our primary objective is to ensure balanced computation across the devices" (DeepSeekMoE, eq. 15 to 17). DeepSeek-V2 used three such losses, expert-level, device-level and communication balance, with coefficients 0.003, 0.05 and 0.02 (DeepSeek-V2, sections 2.2.3 and 3.1.2); V3 replaced them with the bias.

transformers' version is not the per-layer Switch loss. load_balancing_loss_func (Qwen3-MoE, Mixtral and the models that copy them, modeling_qwen3_moe.py:503) adds the counts and probabilities of all layers together before multiplying (modeling_qwen3_moe.py:552 to modeling_qwen3_moe.py:569), and divides counts by tokens, not by tokens × k. Measured on hand-made logits (8 experts, top 2, src/code/hf_aux_check.py): perfectly balanced routing returns 2.00, not 1; one layer collapsed onto two experts returns 7.91; two layers each collapsed but onto different experts return 3.97, half as bad, because pooled over layers the traffic looks spread. The per-layer Switch loss gives 3.96 for every collapsed layer. A dashboard alarm set at "aux loss above 1" fires on a perfectly balanced model with k = 2. And the loss only exists if asked for: output_router_logits defaults to False (configuration_qwen3_moe.py:107) and the released Qwen3, Mixtral, gpt-oss and Llama 4 configs keep it off, so a plain fine-tune with Trainer adds no balancing loss (modeling_qwen3_moe.py:650): a tiny Qwen3-MoE returns aux_loss = None by default and 2.03 with the flag (about k = 2, perfect balance under this formula).

In transformers the bias is only loaded, never updated. DeepSeek-V3's router in transformers 5.20.1 stores e_score_correction_bias as a buffer (modeling_deepseek_v3.py:131), adds it at selection (modeling_deepseek_v3.py:137) and keeps it in float32 (modeling_deepseek_v3.py:551), but no line of modeling_deepseek_v3.py updates it and the file computes no auxiliary loss; three AdamW steps on a tiny DeepSeek-V3 left a non-zero e_score_correction_bias bit for bit unchanged (it is a buffer, not a parameter). The same holds for GLM-4.5 (modeling_glm4_moe.py:284), Nemotron-H (modeling_nemotron_h.py:772) and DeepSeek-V4 (modeling_deepseek_v4.py:1080). The training loop has to implement the update itself, as the tiny GPT does. (transformers 5.20.1, torch 2.14.1, CPU; src/code/hf_checks.py, hf_aux_check.py.)

z-loss evidence. cz = 0.001 was chosen "based on the best model quality after pre-training with a hyperparameter sweep". In ST-MoE's Table 4 the baseline was stable in 4 of 6 runs, update clipping in 3 of 3 at a large quality cost (−4.206 against −1.755), and the z-loss in 3 of 3 with a slight gain (−1.741).

4. Capacity factors and dropped tokens

Accelerators like static shapes: a compiled step wants each expert's batch size before routing has happened. The classic answer is a fixed buffer per expert. Worked example: n = 4,096 tokens, E = 64, k = 2, capacity factor 1.25: the average load is 128 and the buffer holds 160; an expert attracting 200 drops 40, one attracting 60 computes 100 padded slots for nothing.

C = ⌈ CF · n · k / E ⌉
C
token slots in each expert's buffer (the tiny GPT: tiny_gpt.py:404)
CF
capacity factor: 1.0 provisions exactly the average load
n, k, E
tokens in the batch, experts per token, experts

Assignments beyond C are dropped: that token gets no output from that expert in that layer and passes on through the residual connection. Nothing fails; the loss just gets worse. Predict: the model trained dropless is evaluated at CF 1.25 and 1.0; how much of the traffic is dropped, and does the loss move?

Fig. 5, step by step: one buffer size after another on the same 64 assignments

  1. One batch, no buffer. Tokens 1 to 32 of the running sequence in layer 1 of moe8top2: 64 assignments, a mean of 8 per expert, but the experts get 3 to 14.
  2. CF 2.0: 16 slots each. Each buffer is a rack of slots up to its orange line. Nothing is dropped, but 64 of the 128 slots are padding: every expert computes its full buffer.
  3. CF 1.25: 10 slots. E1, E3 and E6 overflow; their dropped assignments spill above the orange line, faded, with the count: 8 of 64 assignments dropped, 24 slots padded.
  4. CF 1.0: 8 slots, exactly the mean. 16 dropped (25%), and still 16 padded: an expert that is short cannot lend its room to one that overflows.
  5. CF 0.5: 4 slots. 34 of 64 dropped: more than half the batch skips this layer's experts.
  6. Dropless. A grouped GEMM runs each expert on exactly the tokens it got: no padding, no drops, and no static shape.

The 64 assignments are the trained model's recorded choices; one 32-token sequence is a far smaller and more correlated batch than training uses, so it drops far more than the held-out batches below. On the 8 tokens of Fig. 3, 1.25 × 8 × 2 / 8 = 2.5 slots per expert, rounded up to 3 by the tiny GPT's math.ceil (tiny_gpt.py:404; implementations that round down allow 2).

Measured. The moe8top2 model (trained dropless) evaluated on 10 held-out batches: dropless 2.244; capacity factor 2.0 2.244 (0.0% of assignments dropped); 1.25 2.252 (0.0%); 1.0 2.514 (3.1%); 0.5 6.051 (50.0%, and 47.1% of tokens lost both experts). The model trained with capacity factor 1.0 (and so with drops in every training step) is 2.310 on its own training rule against 2.256 for the dropless model, and evaluated dropless it reaches 2.276.

Capacity is per batch, so small batches drop more. The same model and the same 2 × 32 held-out sequences at capacity factor 1.25, cut into batches of 32, 4 and 1 sequences: 0.0%, 0.2% and 1.8% of assignments dropped, held-out loss 2.179, 2.195 and 2.242 (measured). With 256 tokens per batch the average expert gets 64 assignments and a capacity of 80; random fluctuation over that small a sample overflows far more often than over 8,192 tokens. This is the training against serving trap: a model trained with large batches at CF 1.25 sees a different drop rate at serving batch sizes, one reason serving stacks run MoE layers dropless.

Below a capacity factor of about 1.25 drops climb and the loss follows

Each point: the trained model evaluated on 10 fixed held-out batches of 32 × 256 tokens (81,920 tokens) with the capacity factor imposed at inference; buffers fill first come, first served in batch order (tiny_gpt.py:408). measured on Apple M1 Pro (CPU). Losses are from a 6-layer toy and transfer only in direction: drops hurt, and they hurt a model trained without them more.

Dropless. The drop exists only because of static buffers. MegaBlocks computes the experts as block-sparse matrix multiplication over ragged per-expert groups, so nothing is padded and it "never drops tokens" (MegaBlocks, 2022); Mixtral's release added MegaBlocks kernels to vLLM. Modern stacks call this a grouped GEMM: one kernel launch that multiplies each expert's weights by its own variable-length slice of tokens. DeepSeek-V3 "does not drop any tokens during training" and serves without drops. The capacity factor survives in older recipes, some TPU stacks and as an admission limit at serving time.

How to check it. Log, per MoE layer and step, the dropped fraction and the max-over-mean load; the tiny GPT's training log records both every 10 steps (dropped, moe_load in log.json). A dropped fraction above a few percent, or rising during training, means the balancing is losing.

What the papers said about capacity, and which tokens to drop (depth)

"If the tokens are unevenly dispatched then certain experts will overflow ... resulting in these tokens not being processed by this layer. A larger capacity factor alleviates this overflow issue, but also increases computation and communication costs" (Switch, Figure 3). ST-MoE recommends "top-2 routing with 1.25 capacity factor", states "The train capacity factor is 1.25 and the eval capacity factor is 2.0" for its models, and finds that "increasing both the train and eval capacity factors (CF) improves quality" (ST-MoE, Table 8); Switch tried re-routing overflow to the second choice ("No-Token-Left-Behind") and "found no empirical benefits". Which tokens are dropped is a design choice too: the tiny GPT drops in batch order, while DeepSeek-V2 dropped per device at a budget "equivalent to 1.0", the "tokens with the lowest affinity scores" first, and kept about 10% of training sequences never dropped so inference could run either way (DeepSeek-V2, section 2.2.4).

5. Fine-grained and shared experts

With 8 or 16 large experts each expert must hold many unrelated kinds of knowledge ("knowledge hybridity"), and every expert relearns what all tokens need, such as syntax and frequent words ("knowledge redundancy") (DeepSeekMoE, introduction). DeepSeekMoE (January 2024) made two moves, both drawn in Fig. 6 at the same compute:

Fig. 6, step by step: same compute, finer experts: 28 possible expert sets become 1,820

  1. Few wide experts. moe8top2: 8 experts 512 wide, top 2 (lit: E6 and E0, the trained model's choice for "Once" in layer 1). A token computes 1,024 hidden units, the dense FFN's width; C(8, 2) = 28 possible expert sets. Block width is the expert's hidden size.
  2. Fine-grained segmentation. Split each expert m = 2 ways (hidden size divided by m) and route to m · k = 4 of the m · E = 16: parameters and FLOPs stay the same, the combinations explode, C(16, 4) = 1,820 against C(8, 2) = 28. The four lit here are illustrative.
  3. A shared expert. One expert runs on every token outside the router, to absorb common knowledge so the routed experts can specialise. The tiny GPT's moe16top3_shared: 3 routed (E13, E15 and E3 for "Once") plus the shared one, C(16, 3) = 560 routed sets.
  4. DeepSeek-V3, at another scale. 256 routed experts 2,048 wide plus 1 shared, top 8: C(256, 8) ≈ 4.1 × 1014 sets, against the 18,432-wide FFN of its dense layers. Which 8 light is illustrative.

The published evidence (vendor, DeepSeek; 2B total, 100B tokens, Pile loss): dense 0.2B 2.060, Hash Layer 1.932, Switch 1.881, GShard 1.867, DeepSeekMoE 1.808, with GShard and DeepSeekMoE at the same 0.3B active (Table 1). Disabling the shared expert and routing one more expert at the same compute raised the Pile loss "from 1.808 to 2.414"; 1, 2 or 4 shared experts gave 1.808, 1.806 and 1.811 (sections 4.4 and 4.5). DeepSeekMoE was also more sensitive than GShard to masking its top routed experts, which the paper reads as "lower redundancy among routed experts".

Measured on the tiny GPT. 16 experts of width 256 plus one shared, top 3 (the same active FFN and 5% more total parameters than moe8top2): held-out 2.210 against 2.256 for 8 experts top 2 and 2.278 dense. DeepSeekMoE's shared-expert ablation, repeated on the trained model at inference: switching the shared expert off raises the loss to 3.863, and routing one more expert in its place to 3.850 (from 2.210; the model was not retrained, unlike DeepSeekMoE's 1.808 to 2.414, so this measures how much the trained model leans on it). Masking each token's best routed expert (DeepSeekMoE's redundancy test) raises the loss by 1.685 for the fine-grained model and 2.811 for moe8top2: the opposite direction to DeepSeekMoE's Figure 4 (does not reproduce), though here the masked expert is one of 3 routed choices against one of 2, so the two numbers are not a matched comparison.

What it costs. Narrower experts are skinnier matrix multiplies (256 wide in the tiny GPT, 2,048 in DeepSeek-V3, against its dense 18,432), so utilisation falls; a token visits more experts, so the all-to-all fans out wider (section 7); and smaller experts make imbalance more likely. Not everyone keeps a shared expert: Qwen3's MoE "excludes shared experts" while keeping 128 fine-grained experts with 8 active (Qwen3 report), and gpt-oss and MiniMax-M2 have none. The calculator splits any real config m ways.

Latent experts (2026): routing in a smaller dimension (depth)

Nemotron 3 Super and Kimi K3 project tokens down before the routed experts and back up after them, "into a smaller latent dimension for expert routing and computation, improving accuracy per byte" (Nemotron 3 Super card, vendor; moe_latent_size 1,024 against d = 4,096); Kimi K3's config sets routed_expert_hidden_size 3,584 against d = 7,168 and its card names "Stable LatentMoE", 16 of 896 experts active. If the down-projection runs before dispatch, a token sends 1,024 or 3,584 numbers per expert through the all-to-all instead of d (section 7): our reading of the configs; neither card describes the communication.

6. Dense against MoE at equal active compute, measured

Nine runs of the root's tiny GPT, 1,500 steps of 32 × 256 tokens (12.3M TinyStories tokens) on the same seeded batches, every MoE run at the dense model's active FFN size; held-out loss on the same 20 validation batches throughout.

Held-out loss: dense 2.278, 8 experts top 2 2.256, 16 + 1 shared top 3 2.210. Seed spread: moe8top2 seed 0 and 1: 2.256 and 2.254; dense seed 0 and 1: 2.278 and 2.264. So the 8-expert model's gain over dense (0.022) is about the size of the dense seed-to-seed spread (0.014) and should not be read as more than a lean; the fine-grained model's gain (0.068) is several times that spread. Both store 2.6 to 2.8 times the dense parameters for the same active FFN. Rough speed on this laptop: dense 40,091 tokens/s, moe8top2 15,045 with the batched forward; the tiny GPT's original per-expert loop is slower still (5,165 tokens/s against 16,300 for the batched forward, median over a 40-step probe each; the loop calls nonzero() once per expert per layer, and every call waits for the GPU).

What transfers. The direction (more stored parameters at equal active compute lower the loss), that balancing costs little at this scale, and the mechanics (collapse without balancing, drops at small batch, the shared expert's role) transfer. The size of the gap does not: published comparisons at billion scale put an MoE's benefit at roughly the quality of a dense model a few times its active size (DeepSeekMoE 16B "comparable" to LLaMA2 7B "with only about 40% of computations", vendor), and the tiny GPT trains on 12M tokens, where the dense model is far from saturated. Wall-clock speed does not transfer at all.

More stored parameters at the same compute lower the loss; only the fine-grained layout clears the seed noise

measured on Apple M1 Pro (MPS), fp32, torch 2.14.1, shared machine at low priority. Tokens per second are rough (other jobs ran beside these) and say nothing about a GPU.

Protocol: optimiser, the batched forward, and why (depth)

AdamW at lr 3e-3 with cosine decay, fp32 on MPS. The dense reference is the root's ref_baseline_s1500 run. MoE runs go through src/runs/fast_moe.py, the root's train.py with the tiny GPT's per-expert loop replaced by one batched einsum over the experts that received tokens: the same choices, drops, bias updates and gradients (checked on CPU: logits within 2e-6, gradients within 1.2e-6, the same parameters left without gradient), because the loop forces a GPU sync per expert per layer and ran far too slowly on MPS. One seed each except where marked; the root's README notes that MPS reruns differ in the third decimal, and the seed-1 pair gives the spread to read gaps against. Held-out loss is recomputed on CPU from the final checkpoint (20 fixed validation batches, 163,840 tokens); the training log's own final value agrees to the third decimal. The tiny GPT's MoE loops over experts in Python, which a real kernel does not.

7. Expert parallelism and the all-to-all

DeepSeek-V3's experts are 656.6B of its 671B parameters (98%, derived from its config: 58 layers × 257 experts × 44.04M). No GPU holds them, so expert parallelism (EP) gives each of W ranks E/W experts of every MoE layer, and every token travels to the ranks that hold its experts and back. This page ran it: layer 4 of the trained moe8top2, the 256-token running sequence split into four 64-token shards, two experts per rank, over four real processes. Predict: every rank sends the same number of token copies; does every rank receive the same number?

Fig. 9: sends are equal by construction; receives are not, and the busiest rank sets the pace

  1. Four ranks, 64 tokens each. The 256-token running sequence is split into four shards. Each rank holds 2 of the layer's 8 experts and a copy of the router; attention ran before this on each rank's own tokens.
  2. Route locally. Each rank runs its router on its own tokens: 64 × top 2 = 128 assignments, stacked by the rank that owns the chosen expert (colours are ranks).
  3. Exchange counts. A small all-to-all of 4 integers per rank tells every rank how many rows it will receive from each other rank: the 4 × 4 matrix in front.
  4. Dispatch: the all-to-all. Each assignment sends the token's hidden state (256 numbers) to the expert's rank, the streams proportional to the counts; 26% of the copies stay home.
  5. Compute: receives are uneven. Ranks receive 114 to 141 rows against a mean of 128: the busiest does 1.10 times the mean expert work, and everyone waits for it.
  6. Combine: the reverse all-to-all. Outputs go home and are weighted by the gates there. The distributed layer equals the one-process layer bit for bit (maximum difference 0.0).

Counts recorded from torch.distributed.all_to_all_single on the gloo backend (CPU, one process per rank; src/ep/ep_alltoall.py), measured on Apple M1 Pro (CPU). Gloo over shared memory says nothing about NCCL timings, so only counts, bytes and equality are reported.

Each rank sends 64 tokens × 2 = 128 rows of 256 numbers (65,536 bytes in BF16), but receives between 114 and 141: the busiest rank does 1.10 times the mean expert work. 26% of the copies stay on their own rank. The distributed output equals the one-process layer bit for bit (maximum difference 0.0).

What it costs. Per token per MoE layer, k · d numbers go out and k · d come back (fewer if the expert is local). DeepSeek-V3 at k = 8, d = 7,168 in BF16: 8 × 7,168 × 2 B = 112 KiB each way per token per layer, 58 layers, forward; the backward pass repeats both. Every rank talks to every rank, the combine cannot finish before the slowest rank, and load imbalance becomes idle GPUs. How the bytes meet NVLink and InfiniBand is owned by Interconnects and scaling (All-to-all and MoE, Collective simulator); how EP composes with data, tensor, pipeline and context parallelism in one training step by Distributed Training (Expert section and Layout calculator); the PyTorch mesh and process-group APIs by Distributed PyTorch.

What the MoE design does about it. The router is the lever. DeepSeek-V3 limits each token to experts on at most 4 nodes (the group-limited top-k of section 2) because "NVLink offers a bandwidth of 160 GB/s, roughly 3.2 times that of IB (50 GB/s)", and notes it "can scale up this number to a maximum of 13 experts (4 nodes × 3.2 experts/node) while preserving the same communication cost" (V3 report, section 3.2.2). Its training used 64-way EP over 8 nodes, its DualPipe schedule overlaps the all-to-alls of one micro-batch with the compute of another, and its kernels are open as DeepEP (dispatch and combine over NVLink and RDMA, with a low-latency mode for decoding). Latent experts (section 5) shrink what is sent, and so do fewer bits: the two directions can be quantised differently because they carry different risks. Thinking Machines' 4-bit training of Inkling 2 Small sends dispatch in NVFP4 (4.5 bits a value), which costs nothing extra since the expert's matmul quantises its input to NVFP4 anyway; combine feeds the residual stream, where plain MXFP8 hurt, so the outputs go through a 32-point random Hadamard rotation that spreads outliers, then an 8-bit fixed-point format (S2F6) with one scale per 32 values, 8.25 bits a value against BF16's 16 (vendor-reported "no measurable accuracy degradation"; End-to-End 4-Bit Training).

The code each rank ran, and its output (depth)
# mixture_of_experts/src/ep/ep_alltoall.py, lines 45 to 80
45          # 2. sort the T*k assignments by destination rank
46          flat_e = top_i.flatten()                             # (T*k,)
47          flat_t = torch.arange(T).repeat_interleave(k)
48          dest = flat_e // per
49          order = torch.argsort(dest, stable=True)
50          send_cnt = torch.bincount(dest, minlength=world)     # how many token copies go to each rank
51          # 3. exchange counts so every rank knows how much it will receive (a tiny all-to-all of W integers)
52          recv_cnt = torch.empty_like(send_cnt)
53          dist.all_to_all_single(recv_cnt, send_cnt)
54          t1 = time.perf_counter()
55          # 4. dispatch all-to-all: hidden states (and their expert ids) travel to the expert's rank
56          send_x = h[flat_t[order]]                            # (T*k, D)
57          recv_x = torch.empty(int(recv_cnt.sum()), D)
58          dist.all_to_all_single(recv_x, send_x, recv_cnt.tolist(), send_cnt.tolist())
59          send_e = flat_e[order].to(torch.float32)[:, None]
60          recv_e = torch.empty(int(recv_cnt.sum()), 1)
61          dist.all_to_all_single(recv_e, send_e, recv_cnt.tolist(), send_cnt.tolist())
62          t2 = time.perf_counter()
63          # 5. local experts compute on what they received
64          y = torch.zeros_like(recv_x)
65          re = recv_e[:, 0].long()
66          for e in range(rank * per, rank * per + per):
67              m = re == e
68              if m.any():
69                  y[m] = moe.experts[e](recv_x[m])
70          t3 = time.perf_counter()
71          # 6. combine all-to-all: outputs go home, in the order they were sent
72          back = torch.empty_like(send_x)
73          dist.all_to_all_single(back, y, send_cnt.tolist(), recv_cnt.tolist())
74          t4 = time.perf_counter()
75          # 7. weight and sum at home; shared experts run locally with no communication
76          out = torch.zeros(T, D)
77          w = top_w.flatten()[order]
78          out.index_add_(0, flat_t[order], back * w[:, None])
79          for s in moe.shared:
80              out = out + s(h)

Output (counts of token copies each rank sent to each rank; one row per sending rank):

          to rank    0     1     2     3
rank 0 sends    34    31    25    38   (total 128)
rank 1 sends    39    35    33    21   (total 128)
rank 2 sends    36    34    34    24   (total 128)
rank 3 sends    32    21    44    31   (total 128)
received      141   121   136   114
max |difference| against the same layer in one process: 0.0

Each rank: route locally with its copy of the router, (T, d) → indices (T, k); exchange counts with a small all-to-all of W integers; dispatch each token's hidden state (d numbers) to the rank of each chosen expert, T · k rows per rank; compute with a grouped GEMM on GPUs; combine with the reverse all-to-all, weighting by the gates at home. Shared experts run at home with no communication.

8. What an MoE costs to serve

Memory is priced on the total, compute on the active. DeepSeek-V3's 671B parameters are 1,342 GB in BF16, 671 GB in FP8 and about 336 GB at 4 bits (derived), while each token computes like a 37B dense model. Experts are where the bytes are, so experts are what gets quantised: gpt-oss was "post-trained with MXFP4 quantization of the MoE weights, making gpt-oss-120b run on a single 80GB GPU" (model card, vendor), and DeepSeek-V4-Pro's config sets expert_dtype to fp4.

Decode reads the experts that were hit. Decoding is limited by weight bytes read per step. A dense model reads all its weights once per step whatever the batch; an MoE reads only the experts its batch touched. Predict for DeepSeek-V3 (E = 256, k = 8): how many of a layer's 256 experts does a batch of 32 sequences touch?

At batch 1 an MoE decodes like its active size; by batch 256 it reads nearly every expert

Expected distinct experts per layer E · (1 − (1 − k/E)B), assuming uniform independent routing (real routing is skewed, which touches fewer) derived: 8 at B = 1, about 163 at B = 32 and about 256 at B = 256. The lit squares are one seeded random draw of the same rule (illustrative). Each touched expert serves only about B · k / E tokens (8 at B = 256), so its matrix multiplies are skinny and bandwidth-bound unless the batch is very large. The Dense vs MoE calculator turns this into bytes per step for any config; the Mixtral paper page animates one decode step of Mixtral against Llama 2 70B and 13B on a roofline.

Fewer experts per token, at inference. Lowering k after training cuts compute per token, and the plain version is the baseline to beat: on Gemma4-26B-A4B, Qwen3-30B-A3B and Qwen3-VL, dynamic expert skipping (choosing per token how many experts to run) rarely beat simply running a smaller fixed k at matched compute, and the effective k a skipping method was calibrated to drifted at test time (Don't Skip the Baseline (arXiv 2610.28369)).

Imbalance comes back at request time. Real traffic is skewed (one language, one code base, one prompt template), so some experts run hot and their GPUs set the tail latency. DeepSeek-V3's deployment adds redundant copies of hot experts, chosen from live statistics "periodically (e.g., every 10 minutes)": 32 redundant experts in a prefill unit of 4 nodes and 32 GPUs; in decoding, a unit of 40 nodes and 320 GPUs where "each GPU hosts only one expert, and 64 GPUs are responsible for hosting redundant experts and shared experts" (V3 report, section 3.4, vendor). The placement algorithm is open as EPLB; serving MoE at that width (expert parallelism at serve time, the all-to-all, EPLB's hot-expert replicas) is section 5 of Distributed and disaggregated serving.

Attention is untouched. MoE shrinks FFN compute only; the KV cache and attention FLOPs are those of the attention design, which is why the models that pushed sparsity furthest also changed attention (MLA in DeepSeek, Kimi and Mistral Large 3; sparse or linear attention in DeepSeek-V3.2 and V4, GLM-5, MiniMax M3, Qwen3-Next and Kimi K3): see Attention variants and Long context.

How to check it. In a serving engine, log the router's top-k indices per layer over a window of real traffic and compare the busiest expert's count with the mean; measure decode step time against batch size: an MoE's curve rises faster than a dense model's of the same active size until every expert is hit, then flattens.

9. What real configs choose

The trends, read from the router fields of 23 MoE configs from Mixtral (December 2023) to Kimi K3 (July 2026). Experts per layer went from 8 to 16 (Mixtral, Jamba, early 2024) to 128 to 896 (14 of the 15 models from July 2025 on have 128 or more); expert width fell from 3.5 times d (Mixtral) to 0.25 to 0.5 times d; routers moved to sigmoid scores with a selection bias in the DeepSeek line and the many models built on its code (Kimi, GLM, MiniMax, Nemotron), while Qwen kept softmax with a global-batch loss; most keep one shared expert and the first 1 to 3 layers dense; and the 2026 models add tricks around the experts rather than inside them: hash-routed first layers (DeepSeek-V4-Pro), latent projections (Nemotron 3 Super, Kimi K3), FP4 experts (DeepSeek-V4-Pro's expert_dtype).

The 23 configs, field by field (reference)

Read verbatim from the config.json files the root's Architecture map saved (fetched 2026-10-18; release dates and published totals from its curated sources). "−" means the config has no such field; the router function for models whose config does not name it is read from the transformers code that runs them.

23 MoE models, December 2023 to July 2026

E: routed experts per MoE layer; k: routed experts per token; shared: always-on experts; width: one routed expert's hidden size (d: model width); MoE layers: of all layers; balancing: the config's topk_method (noaux_tc = DeepSeek's bias) or use_routing_bias; groups: n_group/topk_group; scale: routed_scaling_factor; C(E, k) = number of possible expert sets per token. Config fields can disagree with what training used: router_aux_loss_coef (0.001 in Qwen3, 0.02 in Mixtral, 0.9 in gpt-oss-120b) is the value transformers would use to fine-tune, not a stated pretraining value.

Totals rebuilt from two configs: DeepSeek-V3 and Mixtral 8x7B (depth)

DeepSeek-V3 (d = 7,168, 61 layers, first 3 dense with FFN 18,432, 256 routed experts of width 2,048 plus 1 shared, top 8, vocabulary 129,280 with an untied head, MLA). One expert: 3 × 7,168 × 2,048 = 44,040,192. One MoE layer: 257 experts + a 7,168 × 256 router = 11.32B. 58 MoE layers: 656.6B. Everything else (attention in all 61 layers, 3 dense FFNs, embedding and head, norms): 14.46B. Total 671.03B. Active: 58 × (9 × 44.04M + router) plus the same dense part: 37.55B with the input embedding, 36.63B without it, which is the accounting that rounds to the report's 37B (the root's Config calculator; Hub count 684.5B = this 671.0B + 13.46B multi-token-prediction module + FP8 scales). Experts are 98% of the total and 61% of the active count, so attention and embeddings, invisible in the total, are a large share of what a token costs.

Mixtral 8x7B (d = 4,096, 32 layers, 8 experts of width 14,336, top 2, GQA 32/8, vocabulary 32,000). One expert: 3 × 4,096 × 14,336 = 176.2M; 32 × 8 experts = 45.1B; attention 1.34B; embeddings 0.26B: total 46.70B, active 12.88B (both match Mistral's 46.7B and 12.9B; "8x7B" is not 56B because only the FFN is copied).

Design questions

You have 64 H100s (8 nodes of 8, NVLink inside, 400 Gb/s InfiniBand between) and a compute budget for a 7B-active model. Design the FFN and its parallelism.

Fine-grained MoE: for example 128 routed experts of width about d/4 with top 8 plus 1 shared, first 1 to 3 layers dense, sigmoid scores with bias balancing and a tiny sequence-wise loss, dropless kernels, router in float32 (and a z-loss if logits grow). Expert parallel 8-way inside each node (NVLink), data parallel (FSDP/ZeRO) across nodes for attention and dense parts, so the all-to-all stays on NVLink; if experts must span nodes, group-limit each token to 2 to 4 nodes. Measure per-expert load and dropped fraction from step 1, and check memory: total parameters, not active, set the shard sizes.

Serve a 1T-total, 32B-active MoE at low latency for batch 1 and cheaply at batch 512. What changes between the two?

Batch 1: few experts touched, decode reads about the active weights, latency is set by memory bandwidth and the all-to-all latency; use fewer, larger nodes and quantised experts (4 to 8 bits) so the model fits in as few GPUs as possible. Batch 512: nearly all experts touched every step; spread experts wide (EP over many GPUs) so each GPU's few experts get a useful slice of tokens, replicate hot experts (EPLB), disaggregate prefill from decode, and use grouped GEMM (Distributed and disaggregated serving, sections 5 to 7). The KV cache, not the experts, then limits the batch: that is an attention-design question.

"Sigmoid routing picks different experts from softmax": true or false?

From the same logits both pick the same top k (both are increasing); they differ in gate weights. Once a selection bias or a group limit is added, softmax-plus-bias and sigmoid-plus-bias can pick differently, because the bias is added on different scales.