Mixture of Experts: Routing and Sparse Scaling
Paying for capacity without paying for compute
The feed-forward block inside a transformer is where most parameters live, and it is also the block that runs for every token at every layer. Mixture of Experts attacks that cost with an old idea made practical: keep many feed-forward blocks, call each one an expert, and let a small learned router send each token to only the best two of them. The layer suddenly holds four times the parameters while performing arithmetic on roughly a quarter of them â capacity for the model to store knowledge, compute for the wall clock to actually execute.
The trade is what makes MoE interesting. Parameters are cheap per token of compute but expensive per byte of memory: an MoE model of four hundred billion parameters must hold all four hundred billion in memory even though any single token activates less than a fifth of them. Compute-bound workloads get dramatically faster; memory-bound workloads get dramatically worse. That single fact explains most deployment decisions about these models, and it is why the same architecture can look like a bargain in an API and a headache on a single device.
A working MoE layer
import torch
import torch.nn as nn
import torch.nn.functional as F
class MoELayer(nn.Module):
def __init__(self, d_model: int, num_experts: int = 8, top_k: int = 2,
expert_hidden: int = None):
super().__init__()
self.num_experts = num_experts
self.top_k = top_k
hidden = expert_hidden or d_model * 4
self.experts = nn.ModuleList([
nn.Sequential(
nn.Linear(d_model, hidden),
nn.GELU(),
nn.Linear(hidden, d_model),
)
for _ in range(num_experts)
])
self.gate = nn.Linear(d_model, num_experts, bias=False)
def forward(self, x: torch.Tensor) -> torch.Tensor:
shape = x.shape
flat = x.reshape(-1, shape[-1])
scores = F.softmax(self.gate(flat), dim=-1)
top_vals, top_idx = torch.topk(scores, self.top_k, dim=-1)
top_vals = top_vals / top_vals.sum(dim=-1, keepdim=True)
out = torch.zeros_like(flat)
for e, expert in enumerate(self.experts):
mask = top_idx == e # which rows chose expert e
if not mask.any():
continue
rows = mask.any(dim=-1)
y = expert(flat[rows]) # [M, d]
sel = mask[rows].float() # [M, k]
w = (sel * top_vals[rows]).sum(dim=-1, keepdim=True)
out[rows] += y * w
return out.view(shape)
Two details carry the semantics. Renormalising the top-k weights after selection keeps the output scale comparable to a dense layer, which matters for training stability across hundreds of layers. And skipping experts that received no tokens is not an optimisation you may drop: with many experts and small batches, unselected experts are common, and looping over them wastes most of the step.
Load balancing is the loss nobody expects
Routers are self-fulfilling. If a few experts start receiving slightly more tokens, they receive more gradient, improve faster, and attract more tokens â until one or two experts handle everything and the rest rot, collapsing the layer back to a dense model at full memory cost. The fix is an auxiliary loss that penalises imbalance: measure the fraction of tokens each expert received, compare it against a uniform target, and add that divergence to the training objective.
def load_balancing_loss(gate_probs: torch.Tensor, num_experts: int) -> torch.Tensor:
"""Fraction-of-tokens term: pushes routing toward a uniform split."""
frac = gate_probs.mean(dim=0) # [num_experts]
target = torch.full_like(frac, 1.0 / num_experts)
importance = (frac * target).sum() * num_experts # scale to O(1)
return F.kl_div(frac.log(), target, reduction="batchmean") + importance
Watch two signals during training rather than trusting the loss alone: the coefficient of variation of tokens per expert, and the fraction of tokens routed to the single most popular expert. Both should stay flat over training. A creeping top-expert share is the early warning; by the time loss has visibly degraded, capacity has already been lost.
Balancing also has a cost side: a perfectly uniform split means every device holding experts does the same amount of work every step, which is exactly what you want for predictable latency. Skew is therefore not only a training concern but a serving one, since an unbalanced router turns into uneven utilisation across your fleet â some accelerators saturated, others idle, and tail latency set by whichever one received the hot expert's tokens.
What actually changes at serving time
| Property | Dense model | MoE model |
|---|---|---|
| Parameters | All activated | All resident, few activated |
| FLOPs per token | Proportional to size | Roughly size times top-k ratio |
| Memory at inference | Size of weights | Full size of weights |
| Batch behaviour | Uniform work | Load-dependent work |
| Parallelism | Straightforward | Requires expert distribution |
That second and third row together are the entire story. FLOPs drop, memory does not, so MoE shines when you are compute-limited and serving many requests, and disappoints when you hoped to fit a "smaller" model onto one device. The fifth row is the operational catch: because tokens scatter to different experts, different requests exercise different hardware, and imbalance turns into uneven latency. Serving frameworks respond by grouping tokens per expert into batches, sharding experts across devices, and accepting a little padding to keep every device busy.
Sizing the pool: experts, top-k and capacity
Three numbers define the shape of an MoE layer, and they interact rather than acting as independent dials. Expert count sets total capacity: more experts store more knowledge but give the router a harder classification problem, and with a fixed training budget each expert sees fewer tokens. Top-k sets cost and sharpness: one expert per token is cheapest and most decisive, while a larger k smooths the mixture and behaves more like a dense layer at proportionally higher compute. The capacity factor â a multiplier on the average tokens an expert may receive per batch â decides how much overflow you tolerate before dropping tokens.
| Setting | Raise it when | Pay for it with |
|---|---|---|
| More experts | Knowledge-heavy domains, large data | Harder routing, more memory |
| Higher top-k | Stability during early training | Linear compute increase |
| Higher capacity factor | Bursty or skewed traffic | Padding and memory headroom |
| Fewer experts per layer | Deployment on limited memory | Reduced total capacity |
Rules of thumb survive contact with reality better than defaults. Keep the ratio of total to activated parameters in a band you can serve â many production models land near four to one â because ratios far beyond that buy memory pressure faster than quality. Increase top-k during training only if routing is unstable, then anneal back down, since the inference cost is permanent. And treat the capacity factor as a latency control rather than a quality one: it exists so that a hot expert does not force you to drop the tokens that need it most.
Routing failure modes
Router collapse, covered above, is the training failure. Three serving failures are worth naming. Expert hotspots: certain prompts â code, math, particular languages â route narrowly, so a mixed workload sees latency spikes that average throughput never shows. Route instability: identical prompts landing on different experts across calls produce small output differences that break caching and complicate evaluation. And off-by-construction distribution shift: a router trained on one data mix sends production traffic somewhere it has barely been trained, and quality drops without any error being raised.
Diagnostics are simple to build. Log the top-1 expert share and per-expert token counts per request, aggregate them by traffic class, and alert on skew. Fix the output determinism problem by either fixing seeds at sampling or accepting variability explicitly in evaluation. And when quality drops after a traffic shift, check the router histogram first â it is cheaper than retraining and usually explains it.
Common Mistakes
Choosing MoE expecting a smaller model to deploy
Fix: All expert weights stay resident; budget memory for the full parameter count, not the activated count.
Adding a balance loss and never monitoring routing afterwards
Fix: Track top-expert share and per-expert token counts continuously during training and in production.
Comparing MoE latency to dense models at batch size one
Fix: The advantage appears with many tokens per step; measure at your real serving batch size.
Ignoring which prompts land on which experts
Fix: Slice routing histograms by traffic class to catch hotspots before users report slow responses.
Best Practices
- Keep expert count and top-k fixed across a model line so behaviour stays comparable between versions.
- Renormalise router weights after top-k selection so layer outputs keep a stable scale.
- Report activated parameters and total parameters side by side in every model card.
- Pair MoE deployments with expert-aware load tests, since imbalance only appears under mixed traffic.
Key Takeaways
- MoE multiplies stored capacity while activating only the top-k experts per token, cutting FLOPs but not memory.
- An auxiliary balancing loss prevents router collapse, and routing histograms are how you verify it is working.
- The serving trade is asymmetric: compute-bound workloads win, memory-bound ones pay the full parameter cost.
- Expert hotspots and route instability are production failures with simple logging-based diagnostics.
- Evaluating MoE means evaluating activated capacity, total memory, and per-class latency together.