Different inputs can call for different kinds of prediction. Instead of sending every example through the same complete network, a mixture of experts lets a routing mechanism choose among smaller specialist networks. For LLMs, sparse routing means a token uses only part of the model's available parameters. Mixtral-8x7B uses 13 of its 47 billion parameters per token. DeepSeek-V3 activates 37 of 671 billion.
We build a small router to see how specialists divide the inputs. Its structure follows the mixtures described by Jacobs, Jordan, Nowlan and Hinton in 1991. Our four experts specialise on different regions, but removing the load-balancing loss leaves most idle.
This post picks up where the Combining Models tutorial left off. We implement a tiny sparse-MoE in PyTorch and trace routing from Switch Transformer's top-1 selection through Mixtral's top-2 to DeepSeek-V3's auxiliary-loss-free approach.
A working example: a tiny sparse MoE in 30 lines of PyTorch
import torch
import torch.nn as nn
import torch.nn.functional as F
class Expert(nn.Module):
def __init__(self, d_in, d_hidden, d_out):
super().__init__()
self.fc1 = nn.Linear(d_in, d_hidden)
self.fc2 = nn.Linear(d_hidden, d_out)
def forward(self, x):
return self.fc2(F.relu(self.fc1(x)))
class SparseMoE(nn.Module):
def __init__(self, d_in, d_hidden, d_out, n_experts=4, top_k=2):
super().__init__()
self.n_experts, self.top_k = n_experts, top_k
self.gate = nn.Linear(d_in, n_experts)
self.experts = nn.ModuleList(
[Expert(d_in, d_hidden, d_out) for _ in range(n_experts)])
def forward(self, x):
gate_probs = F.softmax(self.gate(x), dim=-1) # (N, E)
topk_vals, topk_idx = torch.topk(gate_probs, self.top_k, dim=-1)
topk_w = topk_vals / topk_vals.sum(-1, keepdim=True)
out = torch.zeros(x.size(0), self.experts[0].fc2.out_features)
for k in range(self.top_k):
for e in range(self.n_experts):
m = (topk_idx[:, k] == e)
if m.any():
out[m] = out[m] + topk_w[m, k:k+1] * self.experts[e](x[m])
# Switch aux loss: encourage uniform expert utilisation
f_i = torch.bincount(topk_idx[:, 0], minlength=self.n_experts).float()
f_i = f_i / f_i.sum()
P_i = gate_probs.mean(0)
aux = self.n_experts * (f_i * P_i).sum()
return out, aux
That's it. A single linear layer (gate) that picks the top experts, plus a list of small expert networks. The auxiliary loss at the end is the load-balancing term Switch Transformer added to make sparse training stable, derived below. Trained on a 4-blob dataset with 4 experts and top-2 routing for 80 epochs, this hits 99.8% test accuracy:

The right panel is the punchline. Each expert claims one of the four regions of input space without anyone telling it to. The blue cluster is handled by Expert 0, the red by Expert 1, the orange by Expert 2, the green by Expert 3. The 4-class classification task gets partitioned across the experts, not shared.
The leap from soft to sparse routing
The classical mixture of experts uses soft gating: the model output is with produced by a softmax. Every expert contributes to every prediction, weighted by the gate. The maths is clean and the gradients are well-defined.
The problem at LLM scale is FLOPs. If you have 64 experts and every one runs on every token, you're paying for 64 expert forward passes per token. The whole point of having 64 experts was to not run them all.
Shazeer et al. (2017), in "Outrageously Large Neural Networks", made the leap: pick only the top experts per token, set the rest to zero. The forward pass becomes with the gate weights re-normalised over the chosen subset. With out of 64 experts, you've cut compute by 32x and held capacity constant.
Sparse routing is hard to train. The argmax inside is non-differentiable, so the gating network can only learn through the gradient flowing through the weights of the experts that happened to be picked. Experts that never get picked never get a gradient and never get better. This is the "rich get richer" problem and it's the central engineering challenge of sparse MoE.
Watching four experts crystallise
The most striking thing about training a sparse MoE is how fast specialisation emerges. Initialise the gating network at random, train for 80 epochs on the 4-blob data above, and snapshot the top-1 expert assignment at increasing epochs:

At epoch 0, the gating is essentially random. Three experts dominate by accident and one is barely active. By epoch 4 the territories are recognisable but messy: each expert is starting to favour one or two of the data clusters, and the boundaries are wobbly. By epoch 30 every expert owns one cluster, with sharp clean boundaries between them. By epoch 80 nothing visibly changes, just minor refinement at the boundaries.
The pattern is not coincidence. Once an expert gets even a small advantage on a particular subset of inputs, the gate routes more of those inputs to it, and the gradient signal makes that expert better on that subset, and the cycle compounds. The fundamental loop of MoE training is: gate routes → expert improves on routed inputs → gate routes more strongly. Specialisation is a fixed point of this dynamics, and it's reached fast.
When the loop breaks: load balancing and expert collapse
That same compounding loop has a failure mode. If one expert gets a big random head start, all the tokens flow to it, and the other experts never get to learn anything. The system collapses to a single dense network with extra dead weight.
To see this, train the same 4-expert model with top-1 routing and no auxiliary loss:

In the left panel, expert 1 gets 0% of tokens. Expert 0 gets 4.5%. Two experts (orange and green) split everything else. The model still hits 96.8% training accuracy, but you've wasted the parameter budget on two experts that never learned anything.
Fedus et al. (2022), "Switch Transformer", fixed this with a single elegant addition. They define two quantities per expert : is the fraction of tokens routed to expert , and is the average gate probability assigned to expert . The load-balancing loss is:
where is the number of experts. This loss is minimised when both and are uniform at , giving . Imbalanced routing makes and line up on the same experts, increasing the dot product. Adding (with typically 0.01 to 0.1) to the cross-entropy training loss is enough to keep all experts in the game. The right panel shows the result: every expert gets 24-25% of tokens, training accuracy lifts from 96.8% to 98.8%, and no parameters are wasted.
This is the shape of every sparse-MoE training loss in production today. Cross-entropy on the task plus a small auxiliary term that pushes routing toward uniformity.
The headline trade-off: top-1 vs top-2
Switch Transformer made an aggressive choice: route each token to exactly one expert. That's the simplest and cheapest option. Mixtral 8x7B (Jiang et al. 2024) walked this back to top-2: each token activates 2 of the 8 experts, with the gating network producing two weights that sum to 1. The trade-off:

On this toy task top-2 lifts accuracy by 1 percentage point, paying for it with roughly 2x the active parameters per token (132 vs 72). At LLM scale Mixtral chose this trade because the quality gap was larger than the toy data shows: top-1 routing makes individual training tokens depend on a single expert's gradient, which slows learning per parameter. Top-2 lets each token contribute to two experts, smoothing the optimisation landscape considerably.
The math is and . You scale capacity (total parameters) by adding more experts. You scale compute (FLOPs per token) by raising . These are independent levers, and that's the whole pitch of sparse MoE: decoupling the parameter budget from the compute budget.
Why MoE scales LLMs
Take a fixed compute budget, say 13B active parameters per forward pass. A dense model gets exactly 13B parameters. A sparse-MoE model with top-2 routing and 8 experts gets total parameters but activates only per token. If each expert is roughly the size of the dense FFN block, the MoE has 4x the parameter count at the same compute.

The toy chart on the left is honest. At small scale, a dense MLP and a sparse MoE with matched active compute give essentially identical accuracy (98.4% vs 98.3%). The right chart shows the difference that matters at scale: dense has 420 total parameters; MoE has 884 total but uses only 460 per token. Doubling the parameter count for free changes nothing on a 4-blob toy task, but on a 1.4-trillion-token pretraining run it gives the model 2x the capacity to memorise patterns at the same training cost.
This is why every frontier open-weight model from 2024 onward is sparse-MoE: Mixtral 8x7B (47B total / 13B active), Mixtral 8x22B (141B / 39B), DBRX (132B / 36B), DeepSeek-V2 (236B / 21B), DeepSeek-V3 (671B / 37B), Qwen3 30B-A3B (30B / 3B). The ratios vary but the architecture is the same. Sparse MoE is now load-bearing infrastructure for LLMs, not a research curiosity.
DeepSeek-V3: the auxiliary-loss-free upgrade
The Switch aux loss has a cost: it nudges the model away from the routing the optimiser would have chosen on its own. For most of training that's fine because keeping experts alive is more valuable than perfect routing. But late in training, the aux loss starts dragging on quality.
DeepSeek-MoE / DeepSeek-V3 (2024) shipped two architectural refinements that have become widely copied:
Shared experts. Of the total experts, fix some small number (say 1-2) to always be active for every token. The shared experts learn the common-knowledge patterns; the routed experts handle the long tail of specialisation. In DeepSeek-V3 there's 1 shared expert plus 256 routed experts, with 8 routed experts active per token plus the shared one. This solves a subtle problem with pure sparse MoE: every expert is forced to relearn things that every token needs, wasting capacity.
Auxiliary-loss-free balancing. Instead of adding a loss term that fights the optimiser, DeepSeek introduced a per-expert bias on the routing logits that gets nudged up or down based on observed expert utilisation. Underutilised experts get their bias raised; overutilised ones get it lowered. The bias is updated as a running statistic, not as part of backpropagation, so it doesn't perturb the optimisation. Empirically, this gives Switch-equivalent load balancing with a measurable quality improvement.
A toy implementation of the auxiliary-loss-free trick fits in three lines:
# Maintain a per-expert routing bias, updated each step
bias = torch.zeros(n_experts)
target_load = 1.0 / n_experts
# In the forward pass:
gate_logits = self.gate(x) + bias # Add bias before softmax
# After the step:
load = (topk_idx[:, 0].bincount(minlength=n_experts).float()
/ topk_idx.size(0))
bias = bias + lr_bias * (target_load - load) # Underloaded -> bias up
The bias gets added to the gate logits (so it shifts routing) but is updated by a separate rule (so it doesn't see gradients). This is the same trick that ProGAN's exponential moving averages, batch normalisation's running statistics, and target networks in Deep Q-Networks all use: a parameter that the optimiser doesn't see, updated by a separate moving rule.
When sparse MoE makes sense, and when it doesn't
A short decision tree:
| Situation | Reach for |
|---|---|
| You're scaling LLM total parameters and inference cost is the bottleneck | Sparse MoE (top-2 routing, shared experts, aux-loss-free balancing) |
| You're training a small model where parameter count isn't the constraint | Dense MLP / Transformer; MoE adds engineering complexity for no win |
| You have natural input regimes that need different sub-models | Soft (dense) MoE (gradients are clean, no balancing tricks needed) |
| You're combining several different trained models | Stacking (see Combining Models) |
| You want one model on tabular data | Gradient boosting (XGBoost, LightGBM); MoE is overkill |
The dominant story for LLMs in 2026 is sparse MoE. The dominant story for tabular ML, image classification, and most non-LLM tasks is still dense models with the right inductive bias, possibly ensembled in the bagging/boosting/stacking sense. MoE is a scaling technique, and scaling matters most where the parameter budget runs to the hundreds of billions.
Foundations: the chain of papers
The architecture has a clear lineage. Each step solves a specific problem the previous step ran into.
Jacobs, Jordan, Nowlan, Hinton (1991), "Adaptive Mixtures of Local Experts", Neural Computation. The original mixture-of-experts paper from Hinton's group. Soft gating, jointly trained gate and experts, EM-style derivation. Every modern sparse-MoE design is a descendant of this idea.
Shazeer et al. (2017), "Outrageously Large Neural Networks", ICLR. The first sparse-MoE-in-a-Transformer paper. Introduced top-k gating and a "load balancing loss". 137-billion-parameter MoE language model in 2017, when GPT-2 (2019) had 1.5B. The paper's approach to the gradient problem of sparse routing is cited by every successor.
Fedus, Zoph, Shazeer (2022), "Switch Transformer", JMLR. Cleaned up the Shazeer et al. machinery into a simpler top-1 architecture, defined the auxiliary loss above, and demonstrated 1.6T-parameter scaling on T5. Most production MoE LLMs follow this paper's training recipe.
Lepikhin et al. (2021), "GShard", ICLR. Google's parallel work on scaling MoE Transformers across thousands of TPUs. Where Switch focused on the algorithm, GShard focused on the systems engineering: the SPMD compiler, expert parallelism, capacity factor enforcement.
Jiang et al. (2024), "Mixtral of Experts". The first widely-deployed open-weight sparse-MoE LLM. 8 experts, top-2 routing, 47B total / 13B active. Crystallised the production recipe and gave the open-source community a reference implementation.
Dai et al. (2024), "DeepSeekMoE". Introduced shared experts and fine-grained expert segmentation. The follow-up DeepSeek-V3 technical report (2024) added the auxiliary-loss-free balancing trick. Together these gave DeepSeek a state-of-the-art-quality open-weight model at a fraction of the training cost of comparable dense models.
Interactive Tools
- LLM Cost Calculator: Estimate the cost difference between dense and MoE models per million tokens. The active-vs-total-parameter distinction is exactly what determines inference cost.
- Distribution Explorer: The softmax over the gating network produces a Categorical distribution. Visualise how its entropy changes with the gate temperature.
- Attention Visualizer: The other softmax in the block, with its own temperature slider. Attention routes over positions where the gate routes over experts, and both sharpen the same way.
- Convolution Visualiser: Some MoE variants (Conv-MoE) replace the FFN with convolutional experts; useful intuition for the per-expert operation.
Related Posts
- Stacking and Ensemble Methods in Python: The classical soft-gated mixture of experts that this post extends, alongside bagging, boosting, and stacking.
- KV Cache Memory: Sizing LLM Inference: KV-cache memory is the other major LLM-inference bottleneck. MoE attacks the FLOPs side; KV-cache compression attacks the memory side.
- GraphRAG in Python: Knowledge Graphs for Document QA: Another modern LLM architectural idea covered on the site, with the same "scale by structure, not by brute force" philosophy.
- Bayesian Model Comparison: The Evidence Framework: How a Bayesian would think about choosing between expert sub-models versus combining them.
- Deep Q-Networks: Experience Replay and Target Networks: Target networks use the same "parameter the optimiser doesn't see, updated by a separate rule" trick that DeepSeek's auxiliary-loss-free balancing uses.
- Parallel LLM Decoding: Speculative and Diffusion: An orthogonal way to speed up generation; MoE cuts FLOPs per token while parallel decoding cuts the number of sequential decoding steps.
- The AI Jobpocalypse, Your Kids, and Chicken Impossible: The broader implications of ever-cheaper LLM inference that architectures like sparse MoE keep driving down.
- On-Policy Distillation: When Self-Generated Data Wins: Shrinking inference cost from the architecture side (sparse routing) versus the training side (distillation).
- Shrinking the KV Cache: MQA, GQA, and Multi-Head Latent Attention: Both push LLM efficiency: sparse FFN routing here, a leaner KV cache there.
- AI Experts Are Dead. Long Live the AI Experts.: The bigger-picture take on where ever-more-capable LLMs leave human experts.
- TurboQuant: How a Random Rotation Makes LLM Quantization Near-Optimal: Sparse routing cuts active parameters; quantisation shrinks the bits each one costs, the complementary lever on the same memory and bandwidth budget.
- LLM Serving: Continuous Batching and PagedAttention: Sparse routing cuts the FLOPs per token; the serving layer then decides how those tokens are batched and their KV cache paged across concurrent requests.
- Beyond Attention: Linear Attention and Mamba SSMs: Two routes to cheaper LLMs (sparse FFN routing here, sub-quadratic sequence mixing there).













