AILearn AI
LearnGlossarySources
ID/EN
Learn AI — open material for learning AIEvery lesson cites its original sources.
★Advanced & Frontier Topics
  1. Efficient Inference: Quantization, Distillation, Pruning and Faster Decoding
  2. Mixture of Experts: Bigger Models at the Same Compute
  3. Distributed Training: Many GPUs, One Model
  4. Interpretability: Opening the Black Box
  5. AI Safety & Ethics: Bias, Hallucination, Alignment and Regulation
Modules
  1. ◎ AI Foundations
  2. ∿ Classical Machine Learning
  3. ⌬ Neural Networks
  4. ↘ Training Results & Evaluation
  5. ▦ Deep Learning Architectures
  6. ✎ Large Language Models
  7. ◐ Image Generation
  8. ♪ Audio & Speech AI
  9. ◈ Multimodal, Video & 3D
  10. ↻ Reinforcement Learning
  11. ⚙ ML Development & MLOps
  12. ★ Advanced & Frontier Topics
Learn/Advanced & Frontier Topics

Mixture of Experts: Bigger Models at the Same Compute

How sparse Mixture-of-Experts layers route each token to a few expert networks, why that decouples parameter count from compute, and the practical issues: load balancing, capacity, memory and communication.

Advanced~24 min·5 references
Key terms
Mixture of Experts (MoE)TransformerParameterScaling lawsModel parallelismSoftmax

Scaling laws say bigger models are better — but in a normal (dense) Transformer every Parameter is used for every token, so doubling parameters doubles the compute per token. A Mixture of Experts (MoE) breaks that link: it holds many parameters but activates only a few for each token. Mixtral 8×7B has ~47B parameters yet uses ~13B per token; DeepSeek-V3 has 671B total with 37B active. Many frontier LLMs are believed to use MoE for exactly this reason: more knowledge capacity at roughly the inference cost of a much smaller model.

≈
Analogy: a hospital with a triage desk
A big hospital employs dozens of specialists, but each patient sees only one or two of them. A triage nurse (the router) looks at each patient and sends them to the most suitable doctors (the experts). The hospital's total expertise is huge, yet each visit costs only a couple of consultations. Trouble starts if triage sends everyone to the same doctor — the queue explodes while others sit idle. That is the load-balancing problem.

How an MoE layer works

In a Transformer block, the feed-forward network (FFN) holds about two-thirds of the parameters. An MoE layer replaces that single FFN with N parallel FFNs — the experts — plus a small linear router (gating network). Attention layers stay shared.

  1. The router computes a score for every expert from the token's hidden vector x: logits = W_r · x.
  2. Keep only the top-k experts (e.g. k = 2 of 8) and turn their scores into weights with a Softmax.
  3. Send the token to those k experts only; the other experts do no work for this token.
  4. Combine the expert outputs as a weighted sum. Different tokens in the same sentence can use different experts, in every layer.
y = Σ_{i ∈ TopK(x)} gᵢ(x) · Eᵢ(x), gᵢ(x) = softmaxᵢ( TopK( W_r · x ) )
Compute per token ≈ k experts' worth of FFN FLOPs; parameters ≈ N experts' worth.
In words: “the layer's output is a weighted average of only the k chosen experts' outputs, with weights from a softmax over the router's top-k scores”. All other experts are skipped for this token.
Symbols(hover a symbol in the formula)
y
output vector of the MoE layer for one token
Σ_{i ∈ TopK(x)}
sum over only the k experts selected for token x
gᵢ(x)
gate weight of expert i for this token (the chosen weights sum to 1)
Eᵢ(x)
output of expert i, an ordinary FFN applied to x
softmaxᵢ
softmax over the kept scores, taking entry i
TopK
keep the k largest scores, drop (mask out) the rest
W_r
router weight matrix: d_model → N experts
x
the token's hidden vector
▸Worked example
8 experts, k = 2. Router scores W_r · x = [1.0, 2.5, 0.3, −0.5, 1.2, 0.0, 2.1, −1.0] TopK → experts 2 (2.5) and 7 (2.1) g = softmax([2.5, 2.1]) = [0.599, 0.401] If E₂(x) = [1, 0] and E₇(x) = [0, 2]: y = 0.599 · [1, 0] + 0.401 · [0, 2] = [0.599, 0.80] Only 2 of 8 FFNs were computed.
Loading interactive…
A Mixtral-style MoE block. Walk through it and watch one token: attention is shared, then the router lights up only 2 of the 8 experts. Tap an idle expert to see why it still costs memory, and Load-balancing loss to see how collapse is prevented.

A short history

  • 1991 — Adaptive mixtures of local experts (Jacobs, Jordan, Nowlan & Hinton): a gating network softly combines several small networks.
  • 2017 — Sparsely-gated MoE (Shazeer et al.)[1]: noisy top-k gating between LSTM layers with thousands of experts and up to 137B parameters, showing sparse conditional computation works at scale.
  • 2020 — GShard[2]: MoE Transformers for translation sharded across 2,048 TPU cores, introducing expert capacity and automatic sharding.
  • 2021 — Switch Transformer (Fedus et al.)[3]: simplified routing to top-1, a simple load-balancing loss, bf16 training stability tricks; up to 7× faster pretraining than a dense T5 baseline at equal compute, and trillion-parameter models.
  • 2024 — Mixtral 8×7B (Jiang et al.)[4]: open-weights decoder LLM with 8 experts and top-2 routing in every layer; matched or beat Llama 2 70B on most benchmarks while using ~13B active parameters.

Load balancing and capacity

Left alone, routers collapse: a few experts get slightly better early, receive more tokens, get even better, and the rest starve. Training adds an auxiliary load-balancing loss that is minimised when tokens are spread evenly. For efficient batched hardware execution, each expert also gets a fixed capacity — the maximum number of tokens it accepts per batch. Tokens routed to a full expert overflow and are dropped (they skip the layer through the residual connection), so capacity is a trade-off between wasted compute and dropped tokens.

L_aux = α · N · Σᵢ fᵢ · Pᵢ capacity = capacity_factor × (tokens_per_batch / N) × k
Switch-style balancing loss: fᵢ = fraction of tokens sent to expert i, Pᵢ = mean router probability for expert i. It equals α when perfectly uniform.
In words: Read the first part as “penalise the router when the experts that receive many tokens are also the ones it gives high probability” — it is smallest when traffic is uniform. The second part sets how many token slots each expert has per batch; tokens beyond that are dropped.
Symbols(hover a symbol in the formula)
L_aux
auxiliary load-balancing loss, added to the main language-model loss
α
alpha, small weight of the auxiliary loss (e.g. 0.01)
N
number of experts
Σᵢ
sum over all experts i = 1 … N
fᵢ
fraction of the batch's tokens actually dispatched to expert i
Pᵢ
average router probability given to expert i over the batch
capacity_factor
slack above a perfectly even split (e.g. 1.0–1.25)
tokens_per_batch
tokens processed in the batch
k
experts per token (top-k)
▸Worked example
N = 4, α = 0.01 Uniform: fᵢ = Pᵢ = 0.25 → N · Σ fᵢPᵢ = 4 · (4 · 0.0625) = 1 → L_aux = 0.01 Collapsed: f = [1, 0, 0, 0], P = [0.7, 0.1, 0.1, 0.1] → 4 · 0.7 = 2.8 → L_aux = 0.028 Capacity: 1,024 tokens, N = 8, k = 2, factor 1.25 → 1.25 × 128 × 2 = 320 slots per expert

The trade-off: compute vs memory

MetricDense ~13BMixtral 8×7B (MoE)Dense ~47B
Total parameters13B~47B47B
Active per token13B~13B47B
FLOPs per token1×≈ 1×≈ 3.6×
Memory for weights (FP16)26 GB~94 GB94 GB
QualityBaselineClose to much larger dense modelsHigh
MoE saves compute, not memory: all experts must be loaded because any token may need any of them.

At scale, experts are spread across GPUs (expert parallelism, a form of Model parallelism), and every MoE layer needs two all-to-all communications — send tokens to their experts' GPUs and bring results back. Fast interconnects are therefore essential. And despite the name, experts rarely become human-readable “topic specialists”: the Mixtral authors found little routing specialisation by domain (math vs biology vs philosophy) and more by syntax and token type, such as Python indentation or common words.

The knobs

knobnumber of experts (N)
What it is
How many expert FFNs each MoE layer contains.
↑ If you increase it
More total parameters and capacity at the same per-token compute; quality improves with diminishing returns, but memory, communication and load-balancing difficulty grow.
↓ If you decrease it
Simpler, smaller, easier to serve; approaches a dense model as N → 1.
Typical values
8–64 per layer; some recent models use 100+ small “fine-grained” experts plus shared experts.
knobtop-k (experts per token)
What it is
How many experts process each token.
↑ If you increase it
Smoother, often better quality and more stable training; compute per token grows linearly with k.
↓ If you decrease it
k = 1 (Switch) is cheapest and simplest, but each token relies on a single expert and routing is noisier.
Typical values
1 (Switch), 2 (GShard, Mixtral), up to ~8 among many fine-grained experts.
knobcapacity_factor
What it is
Slack on each expert's token buffer relative to a perfectly even split.
↑ If you increase it
Fewer dropped tokens, but more padding, wasted compute and memory.
↓ If you decrease it
Efficient, but more tokens overflow and skip the expert computation, hurting quality.
Typical values
1.0–1.25 in training, higher (≥ 2) or dropless implementations at inference.
knobaux loss coefficient α
What it is
Weight of the load-balancing loss relative to the language-modelling loss.
↑ If you increase it
More uniform expert usage, but routing is forced toward uniformity even when some experts would genuinely be better — main loss suffers.
↓ If you decrease it
Router freedom, but risk of collapse onto a few experts.
Typical values
≈ 0.01 (Switch Transformer).

In code: a minimal top-k MoE layer

python
import torch, torch.nn as nn, torch.nn.functional as F

class MoE(nn.Module):
    def __init__(self, d_model=512, d_ff=2048, n_experts=8, top_k=2):
        super().__init__()
        self.top_k = top_k
        self.router = nn.Linear(d_model, n_experts, bias=False)
        self.experts = nn.ModuleList(
            nn.Sequential(nn.Linear(d_model, d_ff), nn.GELU(), nn.Linear(d_ff, d_model))
            for _ in range(n_experts))

    def forward(self, x):                          # x: (tokens, d_model)
        logits = self.router(x)                    # (tokens, n_experts)
        top_w, top_i = logits.topk(self.top_k, dim=-1)
        top_w = F.softmax(top_w, dim=-1)           # renormalise over chosen experts
        out = torch.zeros_like(x)
        for e, expert in enumerate(self.experts):
            tok, slot = (top_i == e).nonzero(as_tuple=True)
            if tok.numel():
                out[tok] += top_w[tok, slot, None] * expert(x[tok])
        # Switch-style load-balancing loss (using each token's top-1 choice)
        probs = F.softmax(logits, dim=-1)
        frac = F.one_hot(top_i[:, 0], probs.size(-1)).float().mean(0)
        aux = probs.size(-1) * (frac * probs.mean(0)).sum()
        return out, aux                            # add 0.01 * aux to the main loss
Readable, not fast: real implementations group tokens per expert and use fused kernels and all-to-all communication.
!
Common pitfalls
“8×7B” is not 56B: attention and embeddings are shared, so Mixtral totals ~47B. Memory surprise: an MoE with 13B active parameters still needs memory for all 47B — plan VRAM by total, latency by active. Training instability: router logits can blow up; Switch and later work use router z-loss, lower-precision care and smaller initialisation. Fine-tuning: sparse models can overfit small datasets more than dense ones of equal compute. Batching: at small batch sizes, every expert may still be touched, so memory-bound decoding gains less than FLOP counts suggest.
▸Go deeper: why sparsity is a good bet

Compute-optimal scaling says loss falls with both parameters and training tokens. MoE lets you increase the parameter count — and therefore the model's capacity to store facts and patterns — without increasing the FLOPs spent on each token, so for a fixed training budget an MoE usually reaches a lower loss than a dense model. Variants keep evolving: fine-grained experts (many small experts, higher top-k), shared experts that every token uses for common knowledge, auxiliary-loss-free balancing with per-expert bias terms, and expert-choice routing, where experts pick their tokens instead of tokens picking experts[5].

Quiz

1.
An MoE layer has 8 experts with top-2 routing. Compared to one dense FFN of the same expert size, roughly how much FFN compute does each token use?
2.
What is the main purpose of the auxiliary load-balancing loss?
3.
You want to serve Mixtral 8×7B in FP16. Which statement about GPU memory is correct?
4.
You lower the capacity factor from 1.25 to 0.8 during training. What is the likely effect?
5.
What did the Mixtral authors observe about expert specialisation?
Score: 0/5

References

  1. [1]
    Outrageously Large Neural Networks: The Sparsely-Gated Mixture-of-Experts Layer
    PaperShazeer et al.2017arxiv.org
  2. [2]
    GShard: Scaling Giant Models with Conditional Computation and Automatic Sharding
    PaperLepikhin et al.2020arxiv.org
  3. [3]
    Switch Transformers: Scaling to Trillion Parameter Models with Simple and Efficient Sparsity
    PaperFedus et al.2021arxiv.org
  4. [4]
    Mixtral of Experts
    PaperJiang et al.2024arxiv.org
  5. [5]
    Mixture of Experts Explained
    ArticleHugging Face (Sanseviero et al.)2023huggingface.co
← Previous
Efficient Inference: Quantization, Distillation, Pruning and Faster Decoding
Next →
Distributed Training: Many GPUs, One Model