Mixture of Experts
After this lesson, you will be able to:
- Explain the core MoE trick — replace a dense FFN with a bank of E specialist experts plus a router that picks the top-k for each token — so total parameters can grow far faster than active compute per token
- Walk through the routing math (softmax over expert logits, top-k selection, weighted combination) and code a simple MoE block from scratch in PyTorch
- Diagnose the load-balancing failure mode (one expert hogs every token) and apply the auxiliary load-balancing loss that fixes it
- Pick MoE vs dense based on your real constraint (training FLOPs budget, GPU memory, inference batch size) and recognize when MoE's communication overhead actually loses you money
Before you start
Don't worry if "mixture of experts" sounds exotic — once you see the routing as a simple softmax-pick-top-k, the rest is plumbing. The hard parts are infrastructure (load balancing, communication) not math.
#The Core Idea
Every machine learning architecture before MoE assumed a fixed compute budget per token, and the only way to spend more was to make the dense matrix bigger. MoE breaks that link. Total parameters and per-token compute become two separate dials.
#How Routing Works
#The Load-Balancing Problem
#Try It Yourself
The numpy version below runs on this page. Edit it and run it.
Tests: Check that the output has the same shape as the input, that each expert has 33,088 parameters, and that top-k routing picks exactly k experts per token.
The same idea with real PyTorch needs a library that does not run on this page. Copy the code below to Google Colab.
# Copy to Colab: needs torch, so it cannot run on this page.
# A minimal 4-expert MoE block in PyTorch
import torch
import torch.nn as nn
import torch.nn.functional as F
class Expert(nn.Module):
"""A single expert: a 2-layer MLP."""
def __init__(self, d_model, d_ff):
super().__init__()
self.fc1 = nn.Linear(d_model, d_ff)
self.fc2 = nn.Linear(d_ff, d_model)
def forward(self, x):
return self.fc2(F.gelu(self.fc1(x)))
class MoEBlock(nn.Module):
def __init__(self, d_model=64, d_ff=256, num_experts=4, top_k=1):
super().__init__()
self.num_experts = num_experts
self.top_k = top_k
self.router = nn.Linear(d_model, num_experts, bias=False)
self.experts = nn.ModuleList([
Expert(d_model, d_ff) for _ in range(num_experts)
])
def forward(self, x):
# x: (B, T, d_model)
B, T, D = x.shape
x_flat = x.view(-1, D) # (B*T, D)
# Router probabilities
logits = self.router(x_flat) # (B*T, E)
probs = F.softmax(logits, dim=-1) # (B*T, E)
# Top-k selection
top_p, top_i = probs.topk(self.top_k, dim=-1)
top_p = top_p / top_p.sum(-1, keepdim=True)
# Run experts. For clarity we loop; in production use scatter ops.
out = torch.zeros_like(x_flat)
for e_idx in range(self.num_experts):
mask = (top_i == e_idx) # (B*T, k)
if not mask.any(): continue
token_idx, slot = mask.nonzero(as_tuple=True)
if len(token_idx) == 0: continue
expert_in = x_flat[token_idx]
expert_out = self.experts[e_idx](expert_in)
weight = top_p[token_idx, slot].unsqueeze(-1)
out.index_add_(0, token_idx, expert_out * weight)
return out.view(B, T, D), probs
# === DEMO ===
torch.manual_seed(0)
moe = MoEBlock(d_model=64, d_ff=256, num_experts=4, top_k=1)
x = torch.randn(2, 8, 64) # batch=2, seq=8, d=64
y, probs = moe(x)
# Inspect routing decisions
print("Output shape:", y.shape)
print("\nRouter probabilities per token (first sequence):")
print(probs.view(2, 8, 4)[0].detach().numpy().round(2))
# Count expert utilization
top_experts = probs.argmax(-1)
counts = torch.bincount(top_experts, minlength=4)
print("\nExpert utilization (top-1):", counts.tolist())
# Compare param counts
total_ffn = sum(sum(p.numel() for p in e.parameters()) for e in moe.experts)
active_ffn = total_ffn // moe.num_experts * moe.top_k
print(f"\nTotal FFN params: {total_ffn:,}")
print(f"Active FFN params per token (top-{moe.top_k}): {active_ffn:,}")
print(f"Ratio: {total_ffn/active_ffn:.1f}x more total than active")
print("\nCHALLENGE: Add a load-balancing aux loss")
print("and retrain to see uniform expert utilization.")
# Auxiliary load-balancing loss (Switch Transformer):
# def aux_loss(probs, top_i, num_experts, alpha=0.01):
# f = torch.bincount(top_i.flatten(), minlength=num_experts).float()
# f = f / f.sum()
# p = probs.mean(dim=0)
# return alpha * num_experts * (f * p).sum()
# Add this to your total loss:
# total_loss = lm_loss + aux_loss(probs, top_experts, num_experts=4)#When to Use MoE: The Decision Rubric
| Constraint | Pick |
|---|---|
| Training compute budget is the hard wall, want to maximize quality | MoE |
| GPU memory is the hard wall (fits dense in VRAM but not MoE) | Dense |
| Inference latency at batch=1 is critical | Dense |
| Inference throughput at high batch is critical | MoE with expert parallelism |
| Model needs to specialize across very different domains (code + math + dialogue) | MoE (experts can specialize) |
| You want max quality-per-active-parameter (model card looks good for inference cost) | MoE |
| You want max quality-per-total-parameter (memory-constrained edge) | Dense |
The frontier-lab math: at fixed training-compute budget, MoE consistently beats dense on quality benchmarks. That is why every 2024-2025 frontier release (GPT-4, Gemini 1.5 Pro, Mixtral, DeepSeek-V3) chose MoE. The cost is operational complexity at serving time.
#What Expert Parallelism Sends Over the Wire
When experts sit on different GPUs, every MoE layer has to move token vectors to their experts and back. The amount of data is a short formula.
Two practical notes. If two of a token's experts sit on the same remote device, some frameworks send the vector only once, which makes V smaller. And routing is rarely uniform, so the busiest link sets the speed, which is why load balancing matters for communication as well as for quality.
#Key Takeaways
- MoE decouples total parameters from active compute. Replace each FFN with E experts plus a top-k router. Total params grow with E; per-token compute grows with k. The k/E ratio is the lever that gives you more knowledge at the same FLOPs budget.
- The router is a tiny softmax-over-experts plus top-k selection. Trained jointly with the rest of the network via standard backprop. No expert-specialization labels needed; experts discover their niches through gradient descent.
- Load balancing is the central training problem. Without an auxiliary loss, one expert hogs every token and the rest atrophy. The Switch Transformer aux loss (α·E·Σf_e·p_e with α≈0.01) is the standard fix and makes MoE trainable in practice.
- MoE wins at training-FLOPs budget; dense often wins at inference latency. Frontier labs use MoE because they are training-compute-constrained. Single-user edge serving still favors dense models because MoE's all-to-all communication overhead doesn't amortize at batch=1.
- Modern MoE stacks shared experts plus fine-grained routed experts. DeepSeek-V3 uses 256 routed experts plus a few always-active shared experts, with top-6 or top-8 routing. The architecture trick that lets a 671B-total / 37B-active model match GPT-4-class behavior on academic-budget compute.
#Quick Check
What is the primary purpose of the auxiliary load-balancing loss in an MoE training run?