Learn › Paper Deep-Dives
·FREE·PAPER·9 min read

Mixture of Experts (MoE) from Scratch — Routing and Load Balancing in the Switch Transformer

A ground-up explanation of Mixture of Experts, the sparse architecture behind today's largest LLMs, built strictly from the Switch Transformer paper: the router math, expert capacity, the load-balancing loss, and the three tricks that make sparse training stable.

Key points

  • Mixture of Experts (MoE) selects different parameters for each incoming example, giving a sparsely-activated model with a constant computational cost per token.
  • The Switch Transformer trained a model with 1.6 trillion parameters stably and reported up to 7x faster pre-training than T5 with the same computational resources.
  • Switch routes each token to a single expert (k = 1), and is faster than top-2 MoE and, at small capacity factors, better on quality too.
  • Expert capacity equals tokens per batch divided by the number of experts, times the capacity factor; tokens beyond it skip the expert via the residual connection.
  • Training is stabilized by three tricks: casting only the router's internals to float32, lowering the initialization scale from 1.0 to 0.1, and expert dropout.
ModalitytextTaskarchitecture

Switch Transformers: Scaling to Trillion Parameter Models with Simple and Efficient Sparsity

Primary source — what this article is built on

undefined2021-01-11→undefined2026-08-125y 7mo later

Switch Transformers: Scaling to Trillion Parameter Models with Simple and Efficient SparsityWilliam Fedus, Barret Zoph, Noam Shazeer · 2021-01-11 · v3arXiv:2101.03961Paper page·PDF
undefined

In deep learning, models typically reuse the same parameters for all inputs. Mixture of Experts (MoE) defies this and instead selects different parameters for each incoming example. The result is a sparsely-activated model -- with outrageous numbers of parameters -- but a constant computational cost. However, despite several notable successes of MoE, widespread adoption has been hindered by complexity, communication costs and training instability -- we address these with the Switch Transformer. We simplify the MoE routing algorithm and design intuitive improved models with reduced communication and computational costs. Our proposed training techniques help wrangle the instabilities and we show large sparse models may be trained, for the first time, with lower precision (bfloat16) formats. We design models based off T5-Base and T5-Large to obtain up to 7x increases in pre-training speed with the same computational resources. These improvements extend into multilingual settings where we measure gains over the mT5-Base version across all 101 languages. Finally, we advance the current scale of language models by pre-training up to trillion parameter models on the "Colossal Clean Crawled Corpus" and achieve a 4x speedup over the T5-XXL model.


More Parameters, Same Compute

An ordinary neural network uses all of its parameters for every input. To make it smarter you add parameters, and every parameter you add makes each forward pass proportionally more expensive. That is the bargain dense models are stuck with.

Mixture of Experts (MoE) breaks the bargain: it selects different parameters for each incoming example. The result is a sparsely-activated model — an outrageous number of parameters, but a constant computational cost per token.

The 2021 paper Switch Transformer (Fedus, Zoph, Shazeer) simplified MoE to its bare minimum, trained a model with 1.6 trillion parameters stably, and reported up to 7x faster pre-training than T5 with the same computational resources (§Abstract). This article builds MoE from the ground up using that paper as the sole primary source.

The Metaphor: A Hospital Front Desk

A dense model is a hospital where one enormous generalist sees every patient — and the smarter you make the doctor, the slower every visit gets. In an MoE hospital, the front desk sends each patient to one specialist. You can grow the staff to 100 doctors while each patient still gets exactly one consultation. That is the whole trick.

The Intuition: Decouple Knowledge from Compute

The most parameter-heavy part of a Transformer block is the FFN (feed-forward network). The Switch Transformer replaces it with N copies — the experts — and passes each token through exactly one of them (Figure 2).

Scaling laws had studied three axes: model size, data, and compute. This paper proposes a fourth axis: increase the parameter count while keeping FLOPs per token constant (§2). The only added compute is the router itself, a lightweight O(dmodel×num experts)O(d_{model} \times \text{num experts}) operation (§3).

Mechanism, Part 1: The Router Picks Experts with a Softmax

Start with the standard MoE that preceded Switch (Shazeer et al. 2017, reviewed in §2.1). Given a token representation xx, the router computes logits h(x)=Wr⋅xh(x) = W_r \cdot x with a weight matrix WrW_r, then turns them into probabilities:

pi(x)=eh(x)i∑jNeh(x)jp_i(x) = \frac{e^{h(x)_i}}{\sum_{j}^{N} e^{h(x)_j}}
(1)

Here pi(x)p_i(x) is "how much the router wants to send token xx to expert ii," and the N values sum to 1 — the same softmax you met in attention. Put in words: score every expert, make each score positive by exponentiating it, then give each expert its share of the total. Because the scores pass through an exponential first, an expert that scores only slightly higher ends up with a much larger share — the front desk forms strong preferences from weak evidence. Classic MoE keeps the top-kk experts and blends their outputs, weighted by these probabilities:

y=∑i∈Tpi(x)Ei(x)y = \sum_{i \in \mathcal{T}} p_i(x) E_i(x)
(2)

T\mathcal{T} is the set of chosen experts and Ei(x)E_i(x) is what expert ii computes on the token. Read it as "a weighted average of the chosen specialists' opinions, weighted by the front desk's confidence." Multiplying by pi(x)p_i(x) is what lets gradients flow into the router so it can learn (§2.1). Now look at which experts appear in that sum: only the chosen ones. The other N−k never enter the equation at all — a detail which says, in a single line, why sparsity is free. An expert you never evaluate costs you nothing, exactly like a doctor who was never paged.

FIG 1The router's output is exactly this softmax distribution — each bar is the probability of dispatching to one expert. Too flat and no specialization emerges; too sharp and a few experts absorb all the load. That tug-of-war is the central design problem of MoE

Mechanism, Part 2: Switch's Answer — Route to Just One

The 2017 conventional wisdom held that the router could only learn by comparing at least two experts, so k>1k > 1 was considered necessary. The Switch paper contradicts this head-on and routes each token to a single expert, k=1k = 1 (§2.1). Three benefits: (1) less routing computation, (2) each expert's batch — its capacity, defined below — can be at least halved, and (3) the implementation gets simpler and communication costs drop. The gate value from Equation (2) survives, so differentiability is preserved.

In Table 1 the paper runs a head-to-head against top-2 MoE under identical conditions (128 experts, 32 TPUv3 cores): Switch is faster, and at small capacity factors it wins on quality too (§2.3). The intuition that "you can't learn without a comparison" simply did not survive the experiment.

Every Expert Has a Fixed Seat Count

Now the unglamorous part that makes or breaks real MoE systems. TPUs require statically-shaped tensors, so the number of tokens each expert processes — its expert capacity — must be fixed in advance (§2.2):

expert capacity=tokens per batchnumber of experts×capacity factor\text{expert capacity} = \frac{\text{tokens per batch}}{\text{number of experts}} \times \text{capacity factor}
(3)

Divide the batch evenly across experts, then multiply by a slack ratio called the capacity factor. A factor of 1.0 means "exactly enough seats if routing is perfectly balanced"; 1.25 reserves 25% spare seats. Put in words, the right-hand side is just "patients per batch ÷ number of doctors × slack." Notice what is absent from it: no router probabilities, no token content. The seat count is decided before the model has looked at a single input, which is precisely why overflow is possible at all.

When routing is skewed and an expert overflows, the excess tokens skip the expert entirely and pass through the residual connection unprocessed — the paper calls these dropped tokens (§2.2). Raising the factor reduces drops but wastes compute and memory on empty seats. The paper stresses that keeping drop rates low matters for scaling, yet finds Switch performs best at small factors like 1.0–1.25 (§2.3).

The Load-Balancing Loss: Taxing the Popular Doctors

Left alone, the router converges on whichever few experts happened to be good early in training — every patient queuing for the same doctor. The fix is an auxiliary loss added to the model's main loss (§2.2). For a batch B\mathcal{B} of TT tokens and NN experts:

loss=α⋅N⋅∑i=1Nfi⋅Pi\text{loss} = \alpha \cdot N \cdot \sum_{i=1}^{N} f_i \cdot P_i
(4)

fif_i is the fraction of tokens actually dispatched to expert ii; PiP_i is the average router probability assigned to expert ii. The dot product is minimized when both are uniform (1/N1/N everywhere) — in other words, the more skewed the routing, the bigger the fine. Put in words, the sum multiplies "how many patients this doctor really got" by "how badly the front desk wanted to send them there," and adds that up over all doctors. A doctor who is high on only one of the two barely moves the total; it is the doctor who is high on both that makes the product explode — which is the concentration the loss is there to punish. The ff vector (an argmax) is not differentiable, but PP is, so gradients still reach the router. The factor NN keeps the loss scale constant as you vary the expert count. The coefficient α=10−2\alpha = 10^{-2} was chosen from a sweep of 10−110^{-1} to 10−510^{-5} as large enough to balance load quickly without interfering with the main language-modeling loss (§2.2).

The whole mechanism fits in ten lines of numpy pseudocode:

import numpy as np

def switch_route(x, W_r):            # x: (T, d_model)
    logits = x @ W_r                 # (T, N) score per expert
    probs  = softmax(logits)         # Eq (1): dispatch probabilities
    expert = probs.argmax(-1)        # Eq (2) with k=1: one destination
    gate   = probs.max(-1)           # gate value applied to the output
    f = np.bincount(expert, minlength=N) / len(x)   # actual load
    P = probs.mean(0)                                # mean probability
    aux_loss = alpha * N * (f * P).sum()             # Eq (4)
    return expert, gate, aux_loss

Three Tricks That Make Training Stable (§2.4)

1. Selective precision. Run the router in bfloat16 and its softmax blows up: the all-bfloat16 model diverged at a negative log perplexity of -3.780, while all-float32 was stable at -1.718 but slow (1,160 examples/sec, Table 2). Casting only the router's internals to float32 delivered both: -1.716 quality at 1,390 examples/sec. For background on these formats, see number formats.

2. Initialize at one tenth the scale. Dropping the initialization scale from s=1.0s = 1.0 to 0.10.1 improved a 32-expert model's early quality from -3.60 to -2.72 and collapsed the run-to-run standard deviation from 0.68 to 0.01 (Table 3). The same scheme worked from a 223M baseline up past one trillion parameters.

3. Dropout the experts, hard. With far more parameters than a FLOP-matched dense model, Switch overfits small fine-tuning sets faster. Using dropout 0.1 on non-expert layers but 0.4 inside the experts — expert dropout — gave the best results on four downstream tasks, e.g. GLUE 85.2 (Table 4).

FIG 2The more parameters a model has, the faster train and test error diverge on small data. Drag the degree slider to feel why Switch needed an aggressive 0.4 dropout inside its expert layers

So How Much Faster Is It?

Only numbers stated in the paper:

What the Paper Admits It Hasn't Solved

How This Is Used on the Job

From here on we leave the paper; this is the author's practical reading.

Who touches this, and when. ML engineers choosing an architecture for LLM pre-training, and inference-platform engineers designing serving for MoE models. Whenever a model card lists "total parameters" and "active parameters" separately, you are looking at exactly this article's NN experts and kk-way selection.

The parameter names you'll actually type. The paper's Appendix F pseudocode uses the vocabulary that stuck: num_experts, capacity_factor, expert_capacity, the auxiliary loss coefficient α\alpha, and the expert dropout rate. In training logs, always watch the dropped-token rate and the load skew across experts. The paper's defaults — α=10−2\alpha = 10^{-2}, capacity factor 1.0–1.25, float32 router — are still the standard starting point.

Pitfalls that cause incidents.

  1. Running the router in half precision. Table 2's divergence is not hypothetical. Even in a mixed-precision setup, keep the router softmax in float32.
  2. Misreading "constant compute" as "constant memory." FLOPs stay flat, but every expert's weights must sit in memory, and serving involves all-to-all communication across devices (§5.4). Distributed training covers the prerequisites.
  3. Fine-tuning small datasets with dense-model instincts. Overfitting arrives early; reach for strong regularization like expert dropout first.

If it comes up in an interview. "Why doesn't MoE cost more compute?" — each token passes through one expert (in Switch), and the router is only O(dmodel×N)O(d_{model} \times N). "Then why wasn't it everywhere already?" — complexity, communication cost, and training instability; Switch is the paper that answered all three at once with k=1 routing, reduced communication, and the stability recipe. If you can also sketch the load-balancing loss of Equation (4), you're done.

Takeaways

If you haven't read the Transformer itself yet, start with attention from scratch; for the serving-side story of giant models, continue to the KV cache.

🎬 Watch this explained (Manim, captioned)

References

  1. William Fedus, Barret Zoph, Noam Shazeer. (2021-01-11) Switch Transformers: Scaling to Trillion Parameter Models with Simple and Efficient Sparsity. arXiv:2101.03961Paper page·PDF

This article is written from the source paper above. Where they differ, the original is authoritative.

Published by TechAthletes · Editorial policy · How we cite · Corrections

Comments

Sign in to comment