Chapter 3 · Model Architecture 3.7
Mixture of Experts (MoE): Routing, Load Balancing and Sparse Activation
A mixture-of-experts layer swaps the feed-forward network for many experts and routes each token to only k of them, so total parameters grow while per-token compute stays small. This page computes total and active parameters for Mixtral and DeepSeek-V3 and lets you try load balancing.
After this page you will be able to
- Write down the computation of one MoE layer: how the router picks k experts per token and how only the selected tokens are computed.
- Work out total and active parameters from a model configuration, and explain why compute follows active parameters while memory follows total parameters.
- Explain why routing becomes imbalanced, and compare the three remedies: auxiliary loss, capacity limits and bias-based balancing.
- Name the memory, bandwidth and communication costs of expert parallelism, and the common misconceptions about expert specialization.
On this page
- Why replace the FFN with experts
- How one MoE layer is computed
- A minimal implementation: compute only the selected tokens
- The parameter bill: total versus active parameters
- Load balancing: why it becomes uneven and how to flatten it
- Why the load becomes uneven
- Three common remedies
- Try it: watch routing become uneven, then flatten it
- Are experts really “specialists”
- Memory, bandwidth and communication
- Compute follows active parameters, memory follows total parameters
- Expert parallelism and communication
- Common misconceptions
- Summary and exercises
- Quick check
- Further reading
- FAQ
A mixture-of-experts (MoE) model replaces the feed-forward network (FFN) in every Transformer layer with parallel “experts”, and a very small router picks of them for each token. Total parameters grow with the number of experts , while the compute for one token grows only with , which is how an MoE gets “many parameters, little compute”. It costs three things: the load tends to be uneven, the weights of all experts have to sit in GPU memory, and experts spread over several GPUs add communication.
Why replace the FFN with experts
In a dense model, parameters and compute are tied together: every token passes through all parameters, so holding more knowledge costs proportionally more compute. The FFN is also where most of the parameters live; the modern LLM architecture page computes that it makes up 70.2% of Llama 3 8B. MoE splits that part into many pieces and lets each token use only a small fraction, which decouples model capacity from per-token compute. The idea, conditional computation, is old; these are the milestones:
| Year | Work | Key points |
|---|---|---|
| 2017 | Shazeer et al., sparsely-gated MoE layer | Up to thousands of feed-forward sub-networks between LSTM layers; model capacity up by more than 1000×, and the largest model has 137 billion parameters |
| 2020 | GShard (Lepikhin et al.) | A translation Transformer with sparsely-gated MoE layers scaled beyond 600 billion parameters and trained for 4 days on 2048 TPU v3 cores |
| 2021 | Switch Transformers (Fedus et al.) | One expert per token; simplified routing and balancing loss, and a study of the capacity factor; up to 7× faster pre-training than the dense T5-Base and T5-Large baselines at equal compute, scaled to a trillion parameters |
| 2024 | Mixtral 8x7B | Open weights; 8 experts per layer, 2 per token; Mistral reports 46.7B total parameters and 12.9B used per token |
| 2024 | DeepSeek-V3 | 1 shared expert plus 256 routed experts in each MoE layer, 8 routed experts per token; load balanced with a bias instead of an auxiliary loss; 671B total and 37B activated per token |
The Mixtral abstract states that it outperforms or matches Llama 2 70B and GPT-3.5 across all evaluated benchmarks while using about 5× fewer parameters per token than Llama 2 70B. It was an important step in making MoE popular among open models.
How one MoE layer is computed
MoE replaces only the FFN sublayer of a Transformer block. The attention layers stay dense and shared by all tokens, and the MoE layer works on each token independently. The token’s hidden state first enters the router, a linear layer that gives each of the experts a score. The highest-scoring experts are selected, and their outputs are added up weighted by the gate weights :
Here is expert , with the same structure as the FFN of a dense model (modern models mostly use SwiGLU), and is the set of selected experts. How the gate weight is computed differs from model to model:
| Model | Scoring | Selection | Gate weight |
|---|---|---|---|
| Switch Transformers (2021) | Softmax over all experts gives probabilities | top-1 | The probability of the selected expert itself |
| Mixtral 8x7B | Logits of a linear layer | top-2 | Softmax over only the 2 selected logits |
| DeepSeek-V3 | Sigmoid affinity | The 8 routed experts, out of 256, with the highest | The selected normalized to sum to 1; the public implementation also multiplies everything by a scaling factor of 2.5 |
The last two rows differ in a way worth noticing. Mixtral’s softmax splits the weight between just 2 candidates, so the two weights sum to 1. DeepSeek-V3 first gives every expert an independent score between 0 and 1 (a sigmoid, so the scores do not compete with each other) and normalizes only after selecting. The bias takes part in deciding “who is chosen” but not in the weights; the section on load balancing below has the details. Besides the routed experts, DeepSeek-V3 has a shared expert that every token passes through and whose output is simply added.
The router itself is tiny. Mixtral’s router has only parameters per layer, about 1.05 million over 32 layers, or 0.002% of the total.
A minimal implementation: compute only the selected tokens
The code below implements this flow: it groups tokens by expert, computes only the tokens routed to each expert, and compares the result with the dense formulation (“every expert on every token, then multiply by the sparse weights”). The results agree, but the sparse version needs only of the compute.
import numpy as np
rng = np.random.default_rng(0)
T, d, f, E, k = 16, 8, 32, 4, 2 # tokens, model dimension, expert hidden width, experts, experts per token
x = rng.normal(size=(T, d))
W_r = rng.normal(size=(d, E)) # router: one linear layer
W1 = rng.normal(size=(E, d, f)) / np.sqrt(d)
W2 = rng.normal(size=(E, f, d)) / np.sqrt(f)
def expert(i, h): # expert i: a two-layer MLP (illustrative; real models use SwiGLU)
return np.maximum(h @ W1[i], 0) @ W2[i]
def route(x):
logits = x @ W_r
top = np.argsort(-logits, axis=1)[:, :k] # the k highest-scoring experts of every token
chosen = np.take_along_axis(logits, top, axis=1)
gate = np.exp(chosen - chosen.max(1, keepdims=True))
return top, gate / gate.sum(1, keepdims=True) # softmax over the k selected scores only (Mixtral's formulation)
def moe_sparse(x): # group by expert and compute only the tokens routed to it
top, gate = route(x)
y, pairs = np.zeros_like(x), 0
for i in range(E):
rows, slot = np.nonzero(top == i)
if rows.size:
y[rows] += gate[rows, slot, None] * expert(i, x[rows])
pairs += rows.size
return y, pairs
def moe_dense(x): # reference: every expert on every token, times the sparse gate matrix
top, gate = route(x)
G = np.zeros((len(x), E))
np.put_along_axis(G, top, gate, axis=1)
return sum(G[:, i:i + 1] * expert(i, x) for i in range(E))
y_sparse, pairs = moe_sparse(x)
print("max error", np.abs(y_sparse - moe_dense(x)).max())
print("token-expert pairs: sparse", pairs, "dense", T * E, "- compute ratio", pairs / (T * E))
# max error 4.440892098500626e-16
# token-expert pairs: sparse 32 dense 64 - compute ratio 0.5
Real implementations face a different problem: every expert receives a different number of tokens in a batch, while GPUs like regular matrix multiplications. The common answer is to give every expert a capacity limit and pad up to it, dropping what exceeds it (more on this below); MegaBlocks instead handles groups of different sizes directly with block-sparse kernels and drops no tokens.
The parameter bill: total versus active parameters
An MoE model has two parameter counts. Total parameters are all the weights and decide how much memory is needed; active parameters are the weights actually used to process one token and decide the compute per token. The code below computes both from public configurations, taken from Table 1 of the Mixtral paper and from the DeepSeek-V3 paper and its public config.json:
def model(name, fixed, embed, moe_layers, experts, k, expert):
"""fixed: parameters every token uses (attention, routers, dense FFNs, shared experts; no vocabulary matrices);
embed: size of one vocabulary matrix."""
total = fixed + 2 * embed + moe_layers * experts * expert
active = fixed + 2 * embed + moe_layers * k * expert
share = (active - embed) / total
print(f"{name}: total {total / 1e9:.2f}B, active {active / 1e9:.2f}B "
f"({(active - embed) / 1e9:.2f}B without the input embedding), {share:.1%} of the total")
# resident: the fixed part every decoding step must read (the input embedding is only a lookup, so it is not counted)
return dict(total=total, resident=fixed + embed, layers=moe_layers, experts=experts, k=k, expert=expert)
# Mixtral 8x7B: 32 layers, 8 experts per layer (FFN width 14336), 2 experts per token
h, L, f, V, heads, kv_heads, E, k = 4096, 32, 14336, 32000, 32, 8, 8, 2
hd = h // heads
attn = h * heads * hd + 2 * h * kv_heads * hd + heads * hd * h # the Q, K, V and O projections
expert = 3 * h * f # SwiGLU: gate, up and down matrices
mixtral = model("Mixtral 8x7B", L * (attn + h * E), V * h, L, E, k, expert)
# DeepSeek-V3 main model (no MTP module): 61 layers, the first 3 with dense FFNs, the other 58 with
# 1 shared expert and 256 routed experts, 8 routed experts per token
h, L, dense_layers, V = 7168, 61, 3, 129280
heads, q_rank, kv_rank, nope, rope, v_dim = 128, 1536, 512, 128, 64, 128
E, shared, k, f_expert, f_dense = 256, 1, 8, 2048, 18432
mla = (h * q_rank + q_rank * heads * (nope + rope) + h * (kv_rank + rope)
+ kv_rank * heads * (nope + v_dim) + heads * v_dim * h) # the MLA projections, see the efficient-attention page
expert = 3 * h * f_expert
moe_layers = L - dense_layers
fixed = L * mla + dense_layers * 3 * h * f_dense + moe_layers * (shared * expert + h * E)
deepseek = model("DeepSeek-V3", fixed, V * h, moe_layers, E, k, expert)
print(f"one routed expert: {expert / 1e6:.2f}M parameters; FFN width used per token (8+1)x2048 = {(k + shared) * f_expert}, dense layers: {f_dense}")
# Mixtral 8x7B: total 46.70B, active 12.88B (12.75B without the input embedding), 27.3% of the total
# DeepSeek-V3: total 671.03B, active 37.55B (36.62B without the input embedding), 5.5% of the total
# one routed expert: 44.04M parameters; FFN width used per token (8+1)x2048 = 18432, dense layers: 18432
Taking the total apart shows where the parameters go:
| Part | Mixtral 8x7B | DeepSeek-V3 |
|---|---|---|
| Routed experts, all together | 45.10B (96.6%) | 653.91B (97.4%) |
| Shared experts, all together | none | 2.55B |
| Attention | 1.34B | 11.41B (MLA) |
| Dense FFNs of the first 3 layers | none | 1.19B |
| Routers | 1.05M | 106M |
| Vocabulary matrices (input and output) | 0.26B | 1.85B |
| Total | 46.70B | 671.03B |
A few points to take from the two tables:
- Experts hold more than 96% of the parameters. The total therefore depends almost only on the number and width of the experts, and the fixed parts (attention, routers) are small.
- “8x7B” does not mean 8×7B. Each expert is just an FFN, while attention and the vocabulary are shared by all 8 experts: a shared part of 1.61B plus 8 experts of 5.64B each makes 46.70B, whereas eight complete 7.24B models would need 57.9B. Set to 1 and the number of experts to 1 and you get the dense model of the same configuration, about 7.24B.
- The active FFN width can equal that of a dense layer. Every DeepSeek-V3 MoE layer gives each token an FFN width of , exactly the FFN width 18432 of the first 3 dense layers, but with far more possible expert combinations (see below).
- The computed numbers are within 1B of the official ones. Mistral reports 46.7B and 12.9B, which matches the “with input embedding” convention above; the DeepSeek-V3 paper says 671B and 37B, which after rounding matches the 36.62B that excludes the input embedding. The difference is only whether the input embedding, which is just a lookup, counts as an active parameter, and the paper does not itemize it.
- Compute follows the active parameters. Training compute is about , where is the number of training tokens. DeepSeek-V3 pre-trained on 14.8T tokens; with 36.62B active parameters that is about FLOPs, whereas a dense 671B model on the same data would need about , 18 times as much. This is an order-of-magnitude estimate that ignores attention-score compute and communication.
Load balancing: why it becomes uneven and how to flatten it
Why the load becomes uneven
The router is learned together with the experts. Shazeer et al. already observed in 2017 that the gating network tends to converge to a state in which it always gives large weights to the same few experts, and that this imbalance is self-reinforcing: favored experts train faster and so are chosen more often. The extreme case is called routing collapse: a few experts absorb almost all tokens, the others get no training, and only a handful of experts are really at work while the rest of the parameters are wasted.
Even without collapse, imbalance has a price: when experts sit on different GPUs, the time of the layer is set by the busiest expert and the other GPUs wait.
Three common remedies
| Method | What it does | Costs and caveats |
|---|---|---|
| Auxiliary balancing loss | Adds a term to the training loss | Too small a coefficient does not balance enough, too large interferes with the main task; Switch uses |
| Capacity limit and dropping | Each expert takes at most assignments per batch; the rest are dropped | A dropped token only goes through the residual connection in this layer; a large capacity wastes compute and memory, a small one drops a lot |
| Bias (auxiliary-loss-free) | Adds a dynamic bias to the scores when selecting top-k: lowered when overloaded, raised when idle | Produces no extra gradient; needs a step size , and the bias affects selection but not the gate weights |
The auxiliary balancing loss. For a batch of tokens and experts, Switch Transformers defines
is the fraction of tokens assigned to expert , obtained with an argmax and therefore not differentiable; is the average probability the router gives expert , which is differentiable. The gradient of the loss with respect to is : the more tokens an expert receives, the harder its routing probability is pushed down. If and agree (popular experts are both selected often and given high probability), then , with equality only for the uniform distribution, where the loss is exactly . Switch swept over powers of 10 from to and found that balances the load quickly without disturbing the training loss.
Two remarks. First, how to define for top- is not standardized: this page and the widget below use expert ‘s share of all assignments, which is still 1 when uniform, while the Hugging Face Mixtral implementation adds up the of every top- rank, which gives when uniform and differs only by a constant factor. Second, when and disagree (for example when the bias method has flattened while stays skewed) this quantity can drop below 1, as the widget shows; when is exactly uniform it equals 1 whatever is.
The capacity limit. Switch sets the capacity of every expert to the number of tokens per batch divided by the number of experts, times a capacity factor. With top- a batch has assignments, so the generalization is
For example, with , and , each expert receives 64 assignments on average, and a capacity factor of 1.25 gives . A token over the capacity does not pass through the expert, and the residual connection hands its representation unchanged to the next layer. Switch reports that the dropped fraction is usually below 1%, provided the auxiliary loss coefficient is large enough. The mechanism has its own cost: the MegaBlocks paper points out that existing frameworks force users to choose between dropping tokens and wasting compute on padding.
The bias method. DeepSeek-V3’s approach (developed from the Loss-Free Balancing of Wang et al.) gives every expert a bias and compares when selecting top-, while the gate weights still use the original . After every training step, look at how many tokens each expert received in that step: the bias of an overloaded expert is lowered by and that of an idle expert is raised by . The load adjustment never goes through the loss function, so there is no “interference gradient” (Wang et al.’s term). V3’s concrete settings:
- is 0.001 for the first 14.3T tokens and 0 for the remaining 500B tokens;
- a very small sequence-level balancing loss () is added only to prevent extreme imbalance within a single sequence;
- node-limited routing: each token goes to at most 4 nodes, which bounds cross-node communication;
- no tokens are dropped, in training or in inference.
The ablation in the DeepSeek-V3 paper (Table 5) replaces pure auxiliary-loss balancing with auxiliary-loss-free balancing on baseline MoE models of 15.7B and 228.7B parameters. Most benchmarks improve, a few get worse: on the 228.7B model HumanEval rises from 40.2 to 46.3, GSM8K from 70.7 to 74.5 and MATH from 37.2 to 39.6, while MMLU falls from 68.3 to 67.2. This is DeepSeek’s own experiment and only represents their setting.
Try it: watch routing become uneven, then flatten it
The widget below simulates a batch of tokens with synthetic router scores: every expert has a fixed “popularity” (multiplied by the skew) and every token adds noise. First look at the load, the capacity overflow and the dropped assignments without any bias, then click “Run 100 balancing steps” to flatten the load with DeepSeek-V3’s rule. The data is synthetic: it demonstrates the mechanism, not the routing of a real model.
- Default settings (8 experts, 2 per token, a batch of 256 tokens, skew 0.40, capacity factor 1.25, no bias yet): of 512 assignments, the busiest expert, expert 5, receives 146, which is 2.28 times the mean of 64. The capacity of each expert is 80, so 90 assignments (17.6%) are dropped, and for 16 tokens both experts are full, so they only pass through the residual connection. The balance loss is 1.25.
- Drag the skew to 0: the router has no preference at all, yet the busiest expert is still 16% above the mean (1.16×), which is just sampling noise over 256 tokens. With 64 tokens it is 1.31×, with 1024 tokens 1.09×. This is why the capacity factor needs some headroom, and also why small batches become unbalanced more easily.
- Capacity factor: back at skew 0.40, drag the capacity factor from 1.0 to 2.0 and the dropped assignments are 25.4%, 17.6% (1.25), 11.3% (1.5) and 3.5% (2.0). The routing imbalance itself has not changed: the more capacity is left, the fewer assignments are dropped, but the more empty slots every expert has to reserve.
- One expert per token (, Switch’s choice): the busiest expert is 2.88 times the mean and 27.0% of the tokens are dropped. Every token has only one expert, so when that expert is full, the token gets no expert at all.
- Run 100 steps of bias balancing (): the busiest expert falls to 1.20×, dropping falls to 0.0% and the balance loss is 1.01. The bias ranges from −0.55 to +0.65, and the learned biases roughly mirror the “popularity” set in the code: expert 5 is the most popular and gets the lowest bias, expert 2 is the least popular and gets the highest.
- The effect of the step (click “Clear the bias” first each time): drag the skew to 1.5 and set to 0.01. After 100 steps the busiest expert is still 3.31 times the mean (the bias can move only 0.01 per step, while about ±2 is needed here); another 100 steps bring it to 1.50. In the other direction, at skew 0.40 a of 0.2 oscillates: after 100 steps the panel shows 1.48× and 2.9% dropped, against 1.20× and 0.0% for , and the line chart shows visibly larger swings.
- A DeepSeek-V3-like setting (64 experts, 8 per token, a batch of 1024 tokens): without bias the busiest expert is 2.43 times the mean and 16.5% of the assignments are dropped; after 100 steps of bias balancing it is 1.41× and 0.4%. With more experts, “the busiest one” is the maximum over 64 experts, and the extreme of the sampling noise is larger, so more residual imbalance remains after balancing than with 8 experts.
Are experts really “specialists”
The name suggests that each expert owns a domain. The Mixtral paper analyzed this directly: it counted which experts were selected in layers 0, 15 and 31 on different subsets of The Pile and found no obvious division by topic. The distributions for ArXiv, PubMed abstracts and philosophy papers are very similar, and only DM Mathematics differs somewhat, which the paper attributes to its synthetic nature. What routing does show is structure at the syntax level: Python’s self and the English word “Question” are often sent to the same expert, indentation tokens in code are always assigned to the same experts (especially in the first and last layers), and adjacent tokens often choose the same experts.
DeepSeekMoE starts precisely from making experts more specialized, with two proposals:
- Finer experts. Split the experts into smaller ones and activate of them, which makes the combinations of experts more flexible.
- Shared experts. Set aside experts that every token passes through to hold common knowledge, which reduces redundancy among the routed experts.
DeepSeek-V3 keeps both. Side by side, the two designs look like this:
| Mixtral 8x7B | DeepSeek-V3 | |
|---|---|---|
| Routed experts per layer | 8 | 256 |
| FFN width of one expert | 14336 | 2048 |
| Experts selected per token | 2 | 8, plus 1 shared expert |
| FFN width used per token | ||
| Possible expert combinations | ||
| Dense layers | none | the first 3 |
| Routing score | softmax (after top-2) | sigmoid |
More combinations do not by themselves mean better results; for the actual gains see the ablations of the DeepSeekMoE paper. It reports that DeepSeekMoE 2B performs on par with GShard 2.9B, which has 1.5 times the expert parameters and compute, and that the 16B version matches LLaMA 2 7B with only about 40% of the compute. The paper also treats the dense model with the same total parameters as an upper bound for MoE: at the same total parameters a dense model is usually stronger, and MoE wins because the same compute can use more parameters.
Memory, bandwidth and communication
Compute follows active parameters, memory follows total parameters
An MoE has to be accounted in two ledgers: compute follows the active parameters, while memory has to hold all experts. Decoding is subtler. The tokens in a batch each choose their own experts, so the larger the batch, the more distinct experts one step uses and the closer the weights that must be read from memory come to the total. Assuming every token independently and uniformly selects experts, the expected number of distinct experts used by tokens is
The code below continues the previous one (mixtral and deepseek come from it) and checks the formula with a Monte Carlo simulation:
import numpy as np
rng = np.random.default_rng(0)
def touched(E, k, B):
"""Expected number of distinct experts used when B tokens each pick k experts independently and uniformly."""
return E * (1 - (1 - k / E) ** B)
def read_fraction(m, B):
"""Share of all parameters read in one decoding step (m comes from the previous snippet)."""
used = touched(m["experts"], m["k"], B)
return (m["resident"] + m["layers"] * used * m["expert"]) / m["total"]
for name, m in [("Mixtral 8x7B", mixtral), ("DeepSeek-V3", deepseek)]:
for B in (1, 4, 16, 64):
simulated = np.mean([np.unique(np.concatenate([rng.choice(m["experts"], m["k"], replace=False) for _ in range(B)])).size
for _ in range(400)])
print(f"{name} batch {B:2d}: {touched(m['experts'], m['k'], B):6.2f} experts used per layer (simulated {simulated:6.2f}), "
f"reads {read_fraction(m, B):.1%} of all weights")
# Mixtral 8x7B batch 1: 2.00 experts used per layer (simulated 2.00), reads 27.3% of all weights
# Mixtral 8x7B batch 4: 5.47 experts used per layer (simulated 5.56), reads 69.2% of all weights
# Mixtral 8x7B batch 16: 7.92 experts used per layer (simulated 7.93), reads 98.8% of all weights
# Mixtral 8x7B batch 64: 8.00 experts used per layer (simulated 8.00), reads 99.7% of all weights
# DeepSeek-V3 batch 1: 8.00 experts used per layer (simulated 8.00), reads 5.5% of all weights
# DeepSeek-V3 batch 4: 30.53 experts used per layer (simulated 30.54), reads 14.0% of all weights
# DeepSeek-V3 batch 16: 101.96 experts used per layer (simulated 102.07), reads 41.2% of all weights
# DeepSeek-V3 batch 64: 222.44 experts used per layer (simulated 222.38), reads 87.1% of all weights
Mixtral, with few experts, reads almost all weights at a batch of 16, while DeepSeek-V3, with many experts, needs a batch of a few dozen to get close. This is an idealized estimate under uniform, independent routing: real routing is uneven (which only makes fewer experts get used) and adjacent tokens in one sequence often choose the same experts, so actual numbers will be lower; the trend holds, though: in batched decoding the weight-reading bandwidth that MoE saves shrinks as the batch grows, and its compute advantage mostly lies in compute-bound settings.
Expert parallelism and communication
When experts are spread over several GPUs (expert parallelism, EP), tokens must be dispatched after routing to the GPUs that hold their experts and combined back after the computation: two all-to-all communications (see Collective Communication for what that primitive does and what it costs). The Mixtral paper also notes that the difficulty of expert parallelism is load balancing: the work has to be spread evenly over the GPUs so that none is overloaded. DeepSeek-V3 is a concrete example:
- Training: 16-way pipeline parallelism, 64-way expert parallelism across 8 nodes and ZeRO-1 data parallelism; the routed experts of every layer are spread evenly over the 64 GPUs of those 8 nodes; node-limited routing guarantees that each token is sent to at most 4 nodes, and dedicated communication kernels were written for the cross-node all-to-all.
- Inference (prefill): the minimum deployment unit is 4 nodes with 32 GPUs, using 32-way expert parallelism for the MoE part; to even out the number of tokens each GPU handles, high-load experts are replicated as redundant experts, and the set of high-load experts is adjusted periodically from online statistics (the paper gives every 10 minutes as an example); prefill uses 32 redundant experts, so each GPU holds 1 more on top of its original 8.
Common misconceptions
- Treating active parameters as the memory requirement. 13B active parameters do not mean 13B of weights will do: Mixtral has to hold all 46.7B.
- Treating experts as domain experts. See “Are experts really specialists” above: Mixtral’s routing looks more like a division of labor at the syntax level.
- Treating MoE as an ensemble of several models. Experts are only the FFNs inside each layer, the attention layers are shared, and routing is done independently for every layer and every token.
- Believing MoE is better in every situation. At the same total parameters a dense model is usually stronger; the advantage of MoE is that the same compute can use more parameters. With small memory, small batches and low latency targets, do the arithmetic carefully.
- Ignoring the effect of dropped tokens. A capacity factor that is too small drops a lot of tokens in training, and in inference dropping makes the output depend on what else is in the batch. DeepSeek-V3’s answer is to balance well enough that nothing is dropped in training or inference.
- Not monitoring expert load. When training an MoE, record the load histogram of every expert, the fraction of dropped tokens and the routing entropy; both routing collapse and excessive dropping show up in these curves.
Summary and exercises
Key points:
- MoE replaces the FFN with experts and the router selects for each token: total parameters grow with , the compute per token with .
- Experts hold more than 96% of the parameters; Mixtral 8x7B has 46.70B total and about 12.9B active parameters, DeepSeek-V3 671.03B total and about 37B active.
- There are three kinds of load balancing: an auxiliary loss (Switch), a capacity limit with dropping, and a bias (DeepSeek-V3); they address routing collapse and the bucket effect under expert parallelism.
- Compute follows active parameters and memory follows total parameters; in batched decoding the weights read approach the total as the batch grows.
- Experts do not correspond to domains; DeepSeekMoE uses finer experts and shared experts to raise specialization.
Quick check
1. Mixtral 8x7B has 8 experts per layer and selects 2 per token. Which statement about processing one token is correct?
- All 8 experts take part in the computation, just with different weights
- Only the 2 selected experts do the feed-forward computation; the other 6 do not, but their weights still occupy memory
- The 8 experts handle different domains, and the router picks them by the topic of the document
- The attention layer is also split into 8 parts and each token picks 2 of them
MoE replaces only the FFN sublayer; the attention layer is dense and shared by all tokens. An expert that is not selected does no computation in this step, yet its weights are still in memory. The routing analysis of the Mixtral paper found no obvious division of labor by topic.
2. The capacity factor is 1.25, a batch has 512 tokens, every token picks 2 experts and there are 16 experts. What is the capacity of each expert?
- 64
- 80
- 128
- 1.25
Each expert receives assignments on average, so the capacity is .
3. In the Switch Transformers auxiliary loss , which term carries the gradient back to the router?
- , the fraction of tokens assigned to expert
- , the average probability the router gives expert
- Both terms are equally differentiable
- Neither is differentiable, so the loss has no gradient
comes from an argmax and is not differentiable; the gradient flows only through , and the gradient with respect to is : the more load an expert has, the harder its probability is pushed down.
4. Where is the bias used in DeepSeek-V3’s auxiliary-loss-free balancing?
- It is added to the gate weights and directly amplifies the output of idle experts
- It is added only to the scores used for selecting top-k; the gate weights still come from the original scores
- It is added to the loss function as a regularizer
- It is used only in inference, not in training
The bias only affects “who is chosen”; the gate weights are still computed from the original affinities. At every training step the bias is adjusted by the load of each expert: lowered by if overloaded, raised by if idle.
5. Which statements about MoE compute and memory are correct? (multiple choice)
- Training FLOPs are roughly proportional to the active parameters, not to the total
- In decoding, the larger the batch, the more experts one step uses and the closer the weights read come to the total
- As long as the active parameters are few, memory only has to hold the activated part of the weights
- The router itself has very few parameters: Mixtral’s routers total about 1.05 million
The weights of all experts must be in memory, because the next token may select any of them. The other three statements come from the estimate, the batched-decoding calculation on this page and Mixtral’s configuration.
Exercises:
- Use the code above to estimate the active parameters of Mixtral 8x7B if every token selected only 1 expert (). How does the result relate to the structure of Mistral 7B?
- With , , and a capacity factor of 1.25, what is the capacity of each expert? If one expert receives 285 assignments in a batch, how many are dropped?
- DeepSeek-V3 has 256 routed experts per layer and selects 8 per token. How large must the batch be for the average number of routed experts used per layer to exceed half of them (128)?
- When is exactly uniform, what is whatever is, and why?
- Why does the bias method not interfere with the gradient of the main task the way an auxiliary loss with a large coefficient does?
Reference answers
- The active parameters are (including the two vocabulary matrices). That is exactly the dense model of the same configuration: every layer has a single FFN, Mixtral’s “each expert” is Mistral 7B’s FFN, and the shared parts (attention, vocabulary) are the same as in Mistral 7B.
- The capacity is ; the expert that receives 285 assignments drops .
- Solve to get , so (for the value is ).
- It equals 1. With , , because is a probability distribution and sums to 1.
- The bias appears only in the step that compares “who ranks in the top ”, and selection itself is not differentiable; the gate weights are still computed from the original scores. Adjusting the bias does not go through the loss function either, so no balancing term is mixed into the gradient of the main task (Wang et al. call this no interference gradient).
Further reading
-
Related pages: Modern LLM architecture and Efficient attention.
-
Shazeer et al., Outrageously Large Neural Networks: The Sparsely-Gated Mixture-of-Experts Layer (2017): the sparsely-gated MoE layer and the observation that imbalance is self-reinforcing.
-
Lepikhin et al., GShard: Scaling Giant Models with Conditional Computation and Automatic Sharding (2020).
-
Fedus et al., Switch Transformers (2021): the routing formulas, the capacity factor and the balancing loss (Section 2); the explainer on this site recomputes the paper’s tables and simulates capacity overflow.
-
Gale et al., MegaBlocks: Efficient Sparse Training with Mixture-of-Experts (2022): block-sparse kernels that avoid dropping tokens.
-
Jiang et al., Mixtral of Experts (2024): the configuration (Table 1) and the routing analysis (Section 5); the Mistral AI announcement Mixtral of experts gives 46.7B and 12.9B.
-
Dai et al., DeepSeekMoE: Towards Ultimate Expert Specialization in Mixture-of-Experts Language Models (2024): fine-grained and shared experts.
-
Wang et al., Auxiliary-Loss-Free Load Balancing Strategy for Mixture-of-Experts (2024): the bias method.
-
DeepSeek-AI, DeepSeek-V3 Technical Report (2024): Section 2.1.2 (routing and auxiliary-loss-free balancing), Section 3 (parallelism for training and inference) and Table 5 (ablation); the configuration is in config.json.
-
The Mixtral and DeepSeek-V3 implementations in Hugging Face Transformers: reference code for the balancing loss and routing.
-
Paper explainers on this site: DeepSeek-V2 (device-limited routing and the three balance losses), DeepSeek-V3 (auxiliary-loss-free balancing) and Mixtral of Experts.
-
A structure that resembles an MoE but is not one: π0 attaches an “action expert” to PaliGemma with tokens hard-assigned by type, no router and no sparse selection; see the π0 breakdown.
-
Qwen Team, Qwen3 Technical Report (2025): 128 fine-grained experts with 8 active, no shared experts, a global-batch load-balancing loss; total and activated parameters can be recomputed exactly from
config.json, see the paper breakdown. -
Zheng et al., Group Sequence Policy Optimization (2025): in reinforcement learning of MoE models, about 10% of the experts activated for a response change after each update, so token-level importance ratios fluctuate wildly; the paper uses a response-level ratio instead and drops Routing Replay; see the paper breakdown.
-
Lepikhin et al., GShard (2021): the early work scaling MoE to hundreds of billions of parameters, and the engineering basis for expert parallelism and load-balancing losses.
-
Combinations of MoE with sparse attention (e.g. MoBA, 2025) appear under long context and efficient attention.
FAQ
- What are 'active parameters' in an MoE model, and why is the total so much larger?
- Active parameters are the weights that actually take part in processing one token; total parameters are all the weights in the model. An MoE layer swaps the feed-forward network for several experts and the router sends every token through only k of them, so the total grows with the number of experts while the per-token compute grows only with k. From the public configs, Mixtral 8x7B has 46.70B total and about 12.8B to 12.9B active parameters (depending on whether the input embedding, which is only a lookup, is counted); DeepSeek-V3 has 671.03B total and about 36.6B to 37.6B active.
- Why does MoE save compute but not necessarily memory?
- Compute is set by how many experts a token passes through, but memory has to hold the weights of all experts. Decoding is trickier still: the tokens of a batch pick different experts. Under uniform, independent routing, with a batch of 16 an average of 7.92 of Mixtral's 8 experts per layer are used and one step already reads 98.8% of all parameters; with a batch of 64, an average of 222 of DeepSeek-V3's 256 routed experts are used. So the compute advantage of MoE shows up mainly where compute is the limit, such as training and large-batch prefill, while in batched decoding the saved weight bandwidth shrinks as the batch grows.
- Why does MoE training become unbalanced, and how is it fixed?
- The router and the experts are trained together. An expert that happens to score a little higher receives more tokens, learns faster and is chosen even more often, a self-reinforcing loop that in the extreme becomes routing collapse. There are three common remedies: the auxiliary balancing loss of Switch Transformers, α·N·Σ f_i·P_i with α = 0.01; a capacity limit per expert, where tokens over the limit are dropped and only pass through the residual connection; and DeepSeek-V3's auxiliary-loss-free bias, which adds a dynamic bias to each expert's routing score, lowered when the expert is overloaded and raised when it is idle.
- Is each expert in an MoE a domain specialist, such as a math expert or a code expert?
- Usually not. The Mixtral paper counted which experts were selected on different subsets of The Pile and found that the distributions for ArXiv, PubMed abstracts and philosophy papers are very similar; only DM Mathematics looks somewhat different. Routing looks more like a division of labor at the syntax level: for example Python's self and indentation tokens often go to the same expert, and adjacent tokens often choose the same experts. One of the starting points of DeepSeekMoE is to make experts more specialized, by splitting them into finer experts and adding shared experts.
- How does routing differ between Mixtral and DeepSeek-V3?
- Mixtral takes the top 2 of its 8 expert scores and applies a softmax over only those 2 scores to get the gate weights. Each DeepSeek-V3 MoE layer has 1 shared expert and 256 routed experts; it computes an affinity for every expert with a sigmoid, picks the 8 highest (the selection adds the bias used for load balancing, while the gate weights still come from the original scores), normalizes the selected scores, and also limits every token to at most 4 nodes.