Switch Transformers: Scaling to Trillion Parameter Models with Simple and Efficient Sparsity
The Switch Transformer simplifies mixture-of-experts routing to top-1, balances load with an expert capacity and an auxiliary loss, and pre-trains up to 7x faster than T5 at equal FLOPs per token. This page recomputes the paper's numbers and simulates capacity overflow.
On this page
- At a glance
- Background: why MoE stayed on the sidelines
- Method: the Switch layer
- Routing: from top-k to top-1
- Expert capacity and overflow
- The load-balancing loss
- Hands-on: capacity factor, dropped tokens and the balancing loss (a toy simulation)
- Keeping a sparse model stable
- Experiments and conclusions
- Equal FLOPs: Switch against MoE and dense models
- More experts are better, with diminishing returns
- Downstream tasks: fine-tuning, distillation and multilingual
- Toward a trillion parameters
- Recomputing the paper’s numbers
- Reading notes: where the paper does not add up
- Limits, and what came next
- What to take from this paper
- Further reading
- FAQ
Fedus, Zoph and Shazeer’s paper (on arXiv in January 2021, published in JMLR in April 2022) starts from a puzzle: mixture of experts (MoE) showed great promise as early as 2017, so why had it not become mainstream? Could it be made simple enough? Their answer is the Switch Transformer: route each token to one expert instead of at least two, and keep training stable with a few plain measures: an expert capacity, a balancing loss, selective precision and so on. At the same FLOPs per token as T5, the 64-expert Switch-Base reaches T5-Base’s pre-training quality in about one seventh of the wall-clock time, and the paper says the 1.6-trillion-parameter Switch-C pre-trains about 4 times faster than T5-XXL.
This page reads the paper itself: its assumptions, equations and experiments, and what it leaves unclear. To build intuition for MoE first, with experiments whose parameters you can change, read the wiki page Mixture of Experts. Every number here was checked against the paper, and whatever can be recomputed with code has been (see “Recomputing the paper’s numbers”); the few places where the paper does not agree with itself are collected in “Reading notes”.
At a glance
| Item | Content |
|---|---|
| Paper | Fedus, Zoph, Shazeer (Google), JMLR 23 (2022) 1-40; arXiv:2101.03961, this page cites v3 |
| Problem | MoE works but is held back by complexity, communication costs and training instability (the abstract’s words) |
| Core changes | Top-1 routing (the Switch layer); a fixed expert capacity; a load-balancing loss (); selective precision, smaller initialization, expert dropout |
| Key results | At equal FLOPs, 64-expert Switch-Base matches T5-Base in about 1/7 of the time (Figure 5); faster than top-2 MoE at capacity factor 1.0 (Table 1); the 1.6T-parameter Switch-C (Table 9) |
| Costs | One to two orders of magnitude more parameters, all of which must fit in memory, plus communication; the largest model, Switch-XXL, can still be unstable |
Background: why MoE stayed on the sidelines
In a dense model every token passes through all parameters: double the parameters and the compute per token (FLOPs) roughly doubles too. The scaling laws of Kaplan et al. (2020) tie quality to parameters, data and compute (see the Scaling Laws explainer). The Switch paper proposes another axis: more parameters at constant FLOPs per token. Its hypothesis is that the parameter count, independently of the total compute, is a dimension worth scaling on its own. MoE does exactly this: replace the FFN with parallel experts and let each token visit only a few of them, so the parameters grow by about times while the compute per token barely changes.
MoE is not new. Shazeer et al. (2017) inserted MoE layers between LSTM layers and set the best results of the time in language modeling and machine translation; GShard (Lepikhin et al., 2020) put MoE into the Transformer and improved translation across 100 languages. But the paper opens by noting that MoE was not widely adopted because of three obstacles: complexity, communication costs and training instability. Switch simplifies each of them.
Method: the Switch layer
Routing: from top-k to top-1
An MoE layer replaces one FFN of the Transformer block with parallel experts (each an FFN) and a router. The router is a matrix that produces logits for a token representation , and a softmax turns them into one probability per expert (Equation 1 of the paper):
Take the experts with the highest probability, call their index set , and the layer output is the weighted sum of their outputs (Equation 2):
Shazeer et al. (2017) had conjectured that was necessary: only by comparing at least two experts can the router get a meaningful gradient. Ramachandran and Le (2018) later found that, with many routing layers, the lower layers needed a larger . Switch goes the other way and sets , that is, , and the output is the chosen expert’s output times its probability. The gate value still multiplies the output, and the router’s gradient flows back through that one probability, so choosing a single expert is trainable. The paper calls an MoE layer with a Switch layer and lists three benefits:
- Less routing computation: each token needs only one expert; the router is just a matrix whose cost grows linearly with the number of experts, which is small.
- The batch (capacity) each expert needs can be at least halved, since each token occupies one slot in one expert.
- A simpler implementation and less communication.
The Switch layer replaces the FFN in a Transformer block; attention is unchanged, and every token is routed independently. Switch-Base, Switch-Large and Switch-XXL replace every other FFN layer (the Expert Freq. column of Table 9 is 1/2); Switch-C replaces every layer.
Expert capacity and overflow
The paper implements the model in Mesh-TensorFlow on TPUs, where all tensor shapes must be fixed at compile time, while the routing outcome is only known at run time. So every expert gets a fixed capacity, the number of tokens it can process in one step: divide the tokens of a batch evenly among the experts and multiply by a capacity factor (Equation 3):
A capacity factor above 1 is slack for imbalance. When an expert receives more tokens than its capacity, the extra tokens are dropped at this layer: they skip the expert and their representation passes unchanged through the residual connection to the next layer. When an expert receives fewer tokens, the empty slots are padded with zeros and the computation happens anyway, just wasted. So the capacity factor is a dial: raise it and fewer tokens are dropped, but padding wastes compute and memory and enlarges the data sent across devices; lower it and the opposite happens.
The paper reports that typically under 1% of tokens are dropped, that it did not observe a dependence on the number of experts, and it credits a large enough balancing coefficient for this; it also notes that a low drop rate is important for scaling sparse models.
The load-balancing loss
The capacity is only a safety net; to make the load even in the first place you need an auxiliary loss. For a batch with tokens and experts, the paper defines two vectors: is the fraction of tokens assigned to expert and is the mean probability the router gives expert (Equations 5 and 6):
The auxiliary loss is their dot product times (Equation 4); every Switch layer contributes one, added to the total loss:
How to read it:
- comes from an argmax and is not differentiable; is differentiable. The gradient flows only through , with size : the more tokens an expert receives, the harder its routing probability is pushed down.
- With perfectly uniform routing and , so after multiplying by the loss is exactly . The factor keeps the value independent of the number of experts (the paper’s explanation).
- If every token’s routing distribution is the same (), the loss becomes . By the Cauchy-Schwarz inequality , with equality only for the uniform distribution. A more intuitive reading: is an “effective number of experts”, so is the number of experts divided by the effective number; a value of 2 means only half of the experts are working.
- : the paper swept powers of 10 from to and found that this value balances the load quickly without overwhelming the main cross-entropy objective.
Hands-on: capacity factor, dropped tokens and the balancing loss (a toy simulation)
The paper does not give a curve of how many tokens are dropped at a given balancing loss, so here is one computed with NumPy that connects capacity factor, dropped tokens and the loss. Setup: experts and a group of tokens (64 per expert on average). Each trial first draws a shared routing distribution for the group: uniform, or a skewed one drawn from a Dirichlet distribution (the smaller the concentration , the more skewed). Every token then picks an expert independently according to , we count what each expert receives, and whatever exceeds the capacity is dropped; each setting averages 400 trials. In this setup , so the balancing loss divided by is about .
"""Capacity factor, dropped tokens and the load-balancing loss (a toy)."""
import numpy as np
rng = np.random.default_rng(0)
CFS = (1.0, 1.25, 1.5, 2.0)
TRIALS = 400
def dropped(P, T, cf):
"""Share of tokens that overflow their expert (Eq. 3), top-1 routing.
P: (trials, N) routing distributions; each token goes to one expert
drawn from its row of P.
"""
N = P.shape[1]
cap = int(T / N * cf)
counts = np.array([rng.multinomial(T, p) for p in P])
return np.maximum(counts - cap, 0).sum(axis=1).mean() / T
def row(label, P, T, loss=True):
N = P.shape[1]
first = f"{(N * (P ** 2).sum(axis=1)).mean():9.2f}" if loss else ""
cells = "".join(f"{100 * dropped(P, T, cf):8.1f}" for cf in CFS)
print(f" {label:<16}{first:>9}{cells}")
def head(first):
print(f" {'':<16}{first:>9} dropped tokens (%), capacity factor")
print(f" {'':<16}{'':>9}" + "".join(f"{cf:8}" for cf in CFS))
N, T = 64, 4096 # experts, tokens in one routing group
print(f"N={N} experts, T={T} tokens per group ({T // N} per expert)")
head("N*sum(P^2)")
row("uniform", np.full((TRIALS, N), 1 / N), T)
for c in (50, 10, 3, 1):
row(f"Dirichlet c={c}", rng.dirichlet(np.full(N, c), TRIALS), T)
collapsed = np.zeros((TRIALS, N))
collapsed[:, 0] = 1
row("collapsed", collapsed, T)
print("\nUniform routing, different group sizes")
head("")
for per in (16, 64, 256, 1024):
row(f"{per} per expert", np.full((TRIALS, N), 1 / N), per * N, loss=False)
Output (NumPy, fixed seed 0):
N=64 experts, T=4096 tokens per group (64 per expert)
N*sum(P^2) dropped tokens (%), capacity factor
1.0 1.25 1.5 2.0
uniform 1.00 5.0 0.1 0.0 0.0
Dirichlet c=50 1.02 7.5 1.0 0.1 0.0
Dirichlet c=10 1.10 13.3 5.2 1.7 0.1
Dirichlet c=3 1.33 22.9 14.1 8.4 2.9
Dirichlet c=1 1.98 36.9 28.8 22.4 13.6
collapsed 64.00 98.4 98.0 97.7 96.9
Uniform routing, different group sizes
dropped tokens (%), capacity factor
1.0 1.25 1.5 2.0
16 per expert 9.8 2.2 0.3 0.0
64 per expert 4.9 0.1 0.0 0.0
256 per expert 2.5 0.0 0.0 0.0
1024 per expert 1.2 0.0 0.0 0.0
- Even perfectly uniform routing drops tokens. At capacity factor 1.0, uniform routing still drops 5.0%: each expert receives 64 tokens on average, the random fluctuation has a standard deviation of about 7.9 (binomial), half of the experts exceed the mean, and the expected overflow is about 5% of the tokens. At 1.25 (capacity 80) only 0.1% remains. This is why the capacity factor has to exceed 1.
- Skew makes drops climb fast. At capacity factor 1.25, (about 58 effective experts) drops 5.2%, 1.33 drops 14.1%, and 1.98 (about 32 effective experts) drops 28.8%. The loss rises a little while the drops rise a lot.
- The capacity factor is a hedge. A factor of 2.0 brings the drops at 1.33 down to 2.9%, at the price of half the slots being empty under uniform routing. Table 1 of the paper also shows that a smaller capacity factor (1.0, 1.25) makes Switch faster: padded computation and communication are not free.
- Complete collapse is a disaster. When all tokens go to one expert (last row, ), 97% to 98% are dropped: only that one expert’s capacity (64 to 128 tokens) gets used.
- Bigger groups are steadier. Under uniform routing, going from 16 to 1024 tokens per expert lowers the drops at factor 1.0 from 9.8% to 1.2% (second table of the output); the relative fluctuation shrinks like . With uniform routing, 64 tokens per expert and factor 1.25 only 0.1% is dropped, which is consistent with the paper’s “typically < 1%”.
- Limits. The tokens in the toy are drawn independently; real routing is an argmax decided by content, and neighbouring tokens often have correlated loads, so real curves will differ. The table shows magnitudes and trends and is not data from the paper. Later, ST-MoE (Zoph et al., 2022) reported that dropping 10% to 15% of tokens during fine-tuning did not noticeably hurt SuperGLUE quality, so how much dropping is too much depends on the stage and the task. To change the parameters yourself and watch routing go out of balance, use the router lab on the wiki page Mixture of Experts.
Keeping a sparse model stable
Sparse models are harder to train than dense ones: routing is a hard choice, which invites instability, and low-precision bfloat16 magnifies numerical problems in the router softmax. The paper (Section 2.4) offers three remedies, and the table puts each beside its evidence. All of it comes from small, short experiments (32-expert models trained for a few thousand steps, or fine-tuning after pre-training on 34B tokens), and apart from Table 3, which uses 3 seeds, there are no error bars from repeated runs, so read these as directions rather than precise effect sizes.
| Remedy | What it does | Evidence in the paper |
|---|---|---|
| Selective precision | Only the inside of the router is cast to float32; the dispatch and combine tensors are cast back to bfloat16, so no float32 tensor goes through the all-to-all | Table 2 (32 experts, early in training): float32 -1.718 (1160 examples/s); pure bfloat16 diverged, -3.780 (1390); selective precision -1.716 (1390) |
| Smaller initialization | Weights are drawn from a truncated normal with standard deviation ( is the number of input units); the default scale is reduced to 0.1 | Table 3 (32 experts, 3.5k steps, 3 seeds): mean quality -2.72 with standard deviation 0.01; default initialization -3.60 with 0.68 |
| Expert dropout | During fine-tuning, dropout is 0.1 in non-expert layers and raised to 0.4 inside the expert FFNs | Table 4, below |
| Router noise | During training the router’s input is multiplied by random jitter to encourage exploration (Appendix C) | Table 11: argmax -1.471, softmax sampling -1.570, input dropout -1.480, input jitter -1.468 |
All qualities are negative log perplexities; closer to 0 is better. Input jitter beats argmax by only 0.003 and the paper gives no error, while softmax sampling is clearly worse. Table 4 shows fine-tuning results of Switch-Base pre-trained on 34B tokens of C4:
| Model (dropout) | GLUE | CNNDM | SQuAD | SuperGLUE |
|---|---|---|---|---|
| T5-Base (0.1) | 82.9 | 19.6 | 83.5 | 72.4 |
| Switch-Base (0.1) | 84.7 | 19.1 | 83.7 | 73.0 |
| Switch-Base (0.2) | 84.4 | 19.2 | 83.9 | 73.2 |
| Switch-Base (0.3) | 83.9 | 19.6 | 83.4 | 70.7 |
| Switch-Base (0.1, 0.4 in experts) | 85.2 | 19.6 | 83.7 | 73.0 |
Raising dropout in all layers together gives mixed results at 0.2 and clearly worse ones at 0.3 (GLUE 83.9, SuperGLUE 70.7). Raising only the dropout inside the experts (0.4) gains 0.5 on GLUE and 0.5 on CNNDM over the all-0.1 setting and leaves SQuAD and SuperGLUE unchanged. The paper says this helps on all four tasks; the table directly shows the first two.
The paper also records attempts that did not work:
- No-Token-Left-Behind (Appendix B). Overflowing tokens are iteratively rerouted to their second-choice expert, so almost no token is dropped. The authors expected better quality and more stable training and found “no empirical benefits”; their guess is that once the network has learned an association between tokens and experts, sending a token to its second choice hurts.
- Switch layers inside attention (Appendix A, Table 10). Replacing the Q, K, V projection matrices with Switch layers gave better quality after 100k steps in float32 (FFN only -1.548, attention only -1.524, both -1.513) but lower speed (1480, 1330, 1240 examples/s); compared at the same 16 hours of training the three are about equal (-1.614, -1.606, -1.607), and training diverged in bfloat16, so it was not adopted.
Experiments and conclusions
Equal FLOPs: Switch against MoE and dense models
Table 1 is the paper’s central table. All models use 128 experts, an expert layer every other layer and 32 TPUv3 cores. Switch-Base has the same FLOPs per token as T5-Base; the top-2 MoE-Base has more, because each token goes through two experts. The pre-training objective is T5’s masked language modeling (15% of tokens dropped and replaced by one sentinel token), quality is the negative log perplexity (in nats), and the threshold is -1.50 (chosen arbitrarily, the paper says): how many hours does each model need to reach it?
| Model | Capacity factor | Quality after 100k steps | Hours to -1.50 | Speed (examples/s) |
|---|---|---|---|---|
| T5-Base | n/a | -1.731 | not reached in 100k steps | 1600 |
| T5-Large | n/a | -1.550 | 131.1 | 470 |
| MoE-Base (top-2) | 2.0 | -1.547 | 68.7 | 840 |
| Switch-Base | 2.0 | -1.554 | 72.8 | 860 |
| MoE-Base (top-2) | 1.25 | -1.559 | 80.7 | 790 |
| Switch-Base | 1.25 | -1.553 | 65.0 | 910 |
| MoE-Base (top-2) | 1.0 | -1.572 | 80.1 | 860 |
| Switch-Base | 1.0 | -1.561 | 62.8 | 1000 |
| Switch-Base+ | 1.0 | -1.534 | 67.6 | 780 |
- At capacity factor 2.0 the MoE is faster. The top-2 MoE spends more compute and needs 68.7 hours against Switch’s 72.8, and its quality after 100k steps is slightly better (-1.547 against -1.554).
- At 1.25 and 1.0 Switch is faster. The MoE hours divided by the Switch hours are 1.24 and 1.28 (recomputed below). Switch’s speed rises as the capacity factor falls (860, 910, 1000), while the MoE’s does not (840, 790, 860); the paper admits that the MoE slowing down when going from 2.0 to 1.25 is unexpected, and a footnote warns that speed depends on both the algorithm and implementation details.
- A bigger Switch is better still. Scaling Switch-Base up to the MoE’s speed (Switch-Base+, hidden size 768 raised to 896) reaches -1.534 after 100k steps, better than every other model in the table.
- Equal-FLOPs Switch is not a faster machine; it learns more per example. Switch-Base (capacity factor 1.0) processes only 62.5% as many examples per second as T5-Base (1000 against 1600), because routing, all-to-all communication and padding all take time; it wins because each example and each step teach it more. T5-Large (3.4 times T5-Base’s FLOPs per sequence, Table 9: 425B against 124B) needs 131.1 hours, 2.09 times Switch-Base’s.
More experts are better, with diminishing returns
At constant FLOPs, adding experts steadily improves quality (Figure 4): from T5-Base (equivalent to one expert) doubling up to 256 experts (14.7B parameters), the test loss falls monotonically. The 64-expert Switch-Base reaches, after about 60k steps, the quality T5-Base only has after about 450k steps, a 7.5x gain in steps (the paper’s text swaps the two step counts; this page follows the right panel of Figure 4); in time (Figure 5) it is about 1/7. Returns diminish: in Table 7 the pre-trained Switch-Base models (16, 32, 64, 128 and 256 experts; the table does not state the number of training steps) beat T5-Base’s quality by 0.131, 0.162, 0.192, 0.204 and 0.209, so each doubling adds 0.031, 0.030, 0.012 and 0.005. The paper also says at the start of Section 5 that adding experts without limit has diminishing returns, which is why one also scales dimensions such as and , and that calls for model parallelism. Appendix D has good news as well: even models with only 2, 4 or 8 experts beat a FLOP-matched T5-Base (Figure 12), so no supercomputer is needed.
Downstream tasks: fine-tuning, distillation and multilingual
Fine-tuning. The baselines are two well-tuned dense models, T5-Base (223M) and T5-Large (739M), each paired with a FLOP-matched Switch model (Switch-Base 7B, Switch-Large 26B, both with 128 experts). All models are pre-trained for 550k steps on C4 with repeated text within examples removed, with tokens per batch (576B tokens in total), then fine-tuned for 16k steps on each task; they are evaluated on the validation set every 200 steps and the peak is reported. The differences between Switch and its T5 counterpart in Table 5 (recomputed below):
- Switch-Base beats T5-Base on 10 of 11 tasks; Switch-Large against T5-Large is 9 wins, 1 tie and 1 loss.
- The largest gains are on TriviaQA (closed-book QA, +6.2 and +7.4), Winogrande (+6.7 and +3.9) and SuperGLUE (+4.4 and +2.0), which the paper summarizes as significant gains on both reasoning and knowledge-heavy tasks. ARC has two regressions: Switch-Base is 2.7 below T5-Base on ARC-Challenge and Switch-Large is 2.8 below T5-Large on ARC-Easy.
- For the largest model, the paper adds in Section 5.6 and Appendix E that Switch converts upstream gains better into knowledge tasks than into reasoning tasks: Figure 13 shows that at the same upstream perplexity Switch does better than dense models on TriviaQA while dense models are often better on SuperGLUE; the authors themselves say more statistics are needed to confirm the observation.
- Each task has a single number (the peak on the validation set) and no variance; gaps within one point (Switch-Large +0.7 on GLUE, +0.5 on SQuAD) are not enough to conclude anything.
Distillation. Sparse models are inconvenient to deploy, so the paper (Section 4.2) distills them into FLOP-matched dense models. Two ideas stack: initialize the student from the teacher’s non-expert weights (those layers have the same shapes anyway), and use a loss that mixes 0.25 of the teacher’s probabilities with 0.75 of the ground-truth labels. Recomputed from Table 6, plain distillation keeps only 2.6% of the quality gain, adding the initialization gives 19.8% and adding the mixed loss 29.2%; initializing from the non-expert weights without distilling gives -1.639, slightly worse than T5-Base’s -1.636. In Table 7, with teachers from 1.1B to 14.7B parameters and a 223M T5-Base student, the share of the gain kept lies between 27% and 37% and generally falls as the teacher grows; in Table 8, a fine-tuned SuperGLUE model keeps about 30% as well.
Multilingual. The paper (Section 4.3) pre-trains the FLOP-matched mSwitch-Base and mT5-Base on mC4 (101 languages). After 1M steps, all 101 languages improve in negative log perplexity; measured in steps, the mean speedup to mT5-Base’s final quality is 5x, and 91% of languages see at least 4x.
Toward a trillion parameters
Section 5 explains how to push to a trillion parameters by combining data, model and expert parallelism. A Switch layer routes a batch of tokens locally on each core, uses an all-to-all to send tokens to the cores that hold their experts, and sends results back after the computation; the tensor size communicated is ( experts of capacity ). The two large models are designed differently (Table 9): Switch-XXL has the same FLOPs as T5-XXL and needs model parallelism at the cost of extra communication; Switch-C uses expert parallelism only, with no model parallelism, so its width, depth and head count are much smaller than T5-XXL’s.
| Model | Parameters | FLOPs/seq | Layers | Experts | Expert freq. | Quality at 250k steps | Quality at 500k steps |
|---|---|---|---|---|---|---|---|
| T5-XXL | 11B | 6.3T | 24 | n/a | n/a | -1.147 | -1.095 |
| Switch-XXL | 395B | 6.3T | 24 | 128 (Table 9 prints 64, see Reading notes) | 1/2 | -1.086 | -1.008 |
| Switch-C | 1571B | 890B | 15 | 2048 | 1 | -1.096 | -1.043 |
- An advantage in steps. Switch-XXL at 250k steps (-1.086) already beats T5-XXL at 500k (-1.095), and Switch-C at 250k (-1.096) matches T5-XXL at 500k (-1.095). The paper says Switch-C is 4 times faster than T5-XXL, but the table has only two points, 250k and 500k steps, and all it can verify is about 2x; the paper does not say whether 4x counts steps or wall-clock time, and the table has no time per step, so it cannot be recomputed. Footnote 10 adds that T5-XXL was pre-trained on an older C4 containing duplicated snippets, so the reported quality gap is only a lower bound.
- Stability. The paper says Switch-C had no instability at all, while Switch-XXL, with more FLOPs per sequence, was occasionally unstable, so it was not pre-trained for the full 1M steps.
- Downstream. Using a Switch-XXL checkpoint that saw only about 503B tokens (roughly half the text T5-XXL saw) in multi-task training: SQuAD validation 89.7 (the paper gives 91.3 as the best at the time), SuperGLUE test 87.5 (T5 got 89.3, the best at the time was 90.0), ANLI 65.7 (previous best 49.4); on closed-book QA, Natural Questions 34.4 (against 32.8), Web Questions 41.0 (against 37.2) and TriviaQA 47.5 (against 42.9), all above the previous T5-XXL. The paper itself points out an oddity: Switch-C has an upstream perplexity close to Switch-XXL’s but only 87.7 on SQuAD against Switch-XXL’s 89.6, which it takes to show that the relationship between fine-tuning quality, FLOPs per token and parameter count is not yet understood.
Recomputing the paper’s numbers
The script below enters only data from the paper’s tables; all arithmetic is done in the script: the parameter counts of Table 9 (recomputed from the architecture hyperparameters), the speed ratios of Table 1, the differences of Table 5, the distillation numbers of Tables 6 to 8 and the quality gaps of Table 9.
"""Recompute numbers from the Switch Transformers paper (arXiv v3, JMLR 2022).
Only the paper's own tables go in; the arithmetic is done here.
"""
V = 32128 # T5 vocabulary size
def params(d, ff, glu, layers, freq, experts, heads, dkv=64):
"""Parameter count in billions: tied embeddings, no biases or norms."""
attn = 4 * d * heads * dkv
ffn = (3 if glu else 2) * d * ff # GEGLU has three matrices, ReLU two
n_ffn = 2 * layers # encoder and decoder
n_sw = round(n_ffn * freq) # FFN layers replaced by Switch layers
total = V * d # shared embedding
total += layers * attn + layers * 2 * attn # encoder, decoder (+cross)
total += (n_ffn - n_sw) * ffn
total += n_sw * (experts * ffn + d * experts) # experts and router
return total / 1e9
# Table 9: (name, d_model, d_ff, GEGLU, layers, expert freq, experts, heads,
# parameters in the paper, in billions)
T9 = [
("T5-Base", 768, 2048, True, 12, 0, 0, 12, 0.2),
("T5-Large", 1024, 2816, True, 24, 0, 0, 16, 0.7),
("T5-XXL", 4096, 10240, True, 24, 0, 0, 64, 11),
("Switch-Base", 768, 2048, True, 12, 1 / 2, 128, 12, 7),
("Switch-Large", 1024, 2816, True, 24, 1 / 2, 128, 16, 26),
("Switch-XXL", 4096, 10240, True, 24, 1 / 2, 64, 64, 395),
("Switch-XXL", 4096, 10240, True, 24, 1 / 2, 128, 64, 395),
("Switch-C", 2080, 6144, False, 15, 1, 2048, 32, 1571),
]
print("Parameters (B): recomputed vs Table 9")
for name, d, ff, glu, L, fr, e, h, paper in T9:
mine = params(d, ff, glu, L, fr, e, h)
tag = f"{name} ({e} experts)" if e else name
print(f" {tag:<26} {mine:8.2f} {paper:7}")
# Table 1: head-to-head, 128 experts, 32 TPUv3 cores
rows = [ # model, capacity factor, quality@100k, hours to -1.50, ex/s
("T5-Large", None, -1.550, 131.1, 470),
("MoE-Base", 2.0, -1.547, 68.7, 840),
("Switch-Base", 2.0, -1.554, 72.8, 860),
("MoE-Base", 1.25, -1.559, 80.7, 790),
("Switch-Base", 1.25, -1.553, 65.0, 910),
("MoE-Base", 1.0, -1.572, 80.1, 860),
("Switch-Base", 1.0, -1.561, 62.8, 1000),
]
moe = {cf: h for m, cf, _, h, _ in rows if m == "MoE-Base"}
print("\nTable 1: hours to Neg. Log Perp. -1.50, Switch vs MoE (top-2)")
for m, cf, q, h, s in rows:
if m == "Switch-Base":
print(f" capacity {cf:<4} Switch {h:5.1f} h, MoE {moe[cf]:5.1f} h"
f" -> MoE/Switch = {moe[cf] / h:.2f}")
print(f" T5-Large / Switch-Base(1.0) = {131.1 / 62.8:.2f}")
print(f" throughput, Switch-Base(1.0) / T5-Base = {1000 / 1600:.3f}")
print(f" FLOPs/seq, T5-Large / T5-Base = {425 / 124:.2f}")
# Table 5: fine-tuning scores of T5-Base, Switch-Base, T5-Large, Switch-Large
T5 = {
"GLUE": (84.3, 86.7, 87.8, 88.5),
"SQuAD": (85.5, 87.2, 88.1, 88.6),
"SuperGLUE": (75.1, 79.5, 82.7, 84.7),
"Winogrande": (66.6, 73.3, 79.1, 83.0),
"XSum": (18.7, 20.3, 20.9, 22.3),
"ANLI R3": (51.8, 54.0, 56.6, 58.6),
"ARC Easy": (56.7, 61.3, 68.8, 66.0),
"ARC Chal.": (35.5, 32.8, 35.5, 35.5),
"Web QA": (26.6, 27.4, 27.7, 31.3),
"Natural QA": (25.8, 26.8, 27.6, 29.5),
"Trivia QA": (24.5, 30.7, 29.5, 36.9),
}
print("\nTable 5: Switch minus its FLOP-matched T5 (base, large)")
for task, (tb, sb, tl, sl) in T5.items():
print(f" {task:<11} {sb - tb:+5.1f} {sl - tl:+5.1f}")
# Tables 6 to 8: how much of the sparse model's gain the dense student keeps
dense, top = -1.636, -1.444 # T5-Base and the 3.8B Switch-Base
print("\nTable 6: share of the quality gain kept (paper: 3%, 20%, 29%)")
for name, q in (("distillation", -1.631), ("+ init non-expert", -1.598),
("+ 0.75 hard/soft mix", -1.580)):
print(f" {name:<21} {(q - dense) / (top - dense) * 100:4.1f}%")
print(f" SuperGLUE (Table 8): {(76.6 - 74.6) / (81.3 - 74.6) * 100:.1f}%"
" (paper: 30%)")
# Table 7: sparse teachers of 1.1B to 14.7B distilled into 223M T5-Base
teacher = [-1.505, -1.474, -1.444, -1.432, -1.427]
student = [-1.587, -1.585, -1.579, -1.582, -1.578]
size = [1.1, 2.0, 3.8, 7.4, 14.7] # billions of parameters, as in the paper
paper = [(37, 82), (32, 90), (30, 95), (27, 97), (28, 99)]
print("\nTable 7: Switch-Base with 16 to 256 experts, distilled to T5-Base")
gains = [round(a - dense, 3) for a in teacher]
print(" teacher gain over T5-Base:", gains)
print(" extra gain per doubling:",
[round(y - x, 3) for x, y in zip(gains, gains[1:])])
print(" recomputed size (B):",
[round(params(768, 2048, True, 12, 1 / 2, e, 12), 2)
for e in (16, 32, 64, 128, 256)])
print(" gain kept; compression with 0.223B and with 0.2B")
for a, b, n, (g, c) in zip(teacher, student, size, paper):
gain = (b - dense) / (a - dense) * 100
print(f" {n:>4}B gain {gain:4.1f}% (paper {g}%) compression"
f" {(1 - 0.223 / n) * 100:4.1f}% / {(1 - 0.2 / n) * 100:4.1f}%"
f" (paper {c}%)")
# Table 9, the 250k / 500k columns
xxl = {"250k": -1.147, "500k": -1.095}
sw = {"Switch-XXL": {"250k": -1.086, "500k": -1.008},
"Switch-C": {"250k": -1.096, "500k": -1.043}}
print("\nTable 9: gain over T5-XXL (Neg. Log Perp.)")
for name, v in sw.items():
print(f" {name:<10} @250k {v['250k'] - xxl['250k']:.3f}"
f" @500k {v['500k'] - xxl['500k']:.3f}")
print(f" T5-XXL from 250k to 500k: {xxl['500k'] - xxl['250k']:.3f}")
print(f" FLOPs/seq, Switch-XXL / Switch-C = {6.3e12 / 890e9:.1f}")
print(f" parameters, Switch-C / Switch-XXL = {1571 / 395:.1f}")
Output:
Parameters (B): recomputed vs Table 9
T5-Base 0.22 0.2
T5-Large 0.75 0.7
T5-XXL 11.00 11
Switch-Base (128 experts) 7.42 7
Switch-Large (128 experts) 27.12 26
Switch-XXL (64 experts) 201.26 395
Switch-XXL (128 experts) 394.54 395
Switch-C (2048 experts) 1571.31 1571
Table 1: hours to Neg. Log Perp. -1.50, Switch vs MoE (top-2)
capacity 2.0 Switch 72.8 h, MoE 68.7 h -> MoE/Switch = 0.94
capacity 1.25 Switch 65.0 h, MoE 80.7 h -> MoE/Switch = 1.24
capacity 1.0 Switch 62.8 h, MoE 80.1 h -> MoE/Switch = 1.28
T5-Large / Switch-Base(1.0) = 2.09
throughput, Switch-Base(1.0) / T5-Base = 0.625
FLOPs/seq, T5-Large / T5-Base = 3.43
Table 5: Switch minus its FLOP-matched T5 (base, large)
GLUE +2.4 +0.7
SQuAD +1.7 +0.5
SuperGLUE +4.4 +2.0
Winogrande +6.7 +3.9
XSum +1.6 +1.4
ANLI R3 +2.2 +2.0
ARC Easy +4.6 -2.8
ARC Chal. -2.7 +0.0
Web QA +0.8 +3.6
Natural QA +1.0 +1.9
Trivia QA +6.2 +7.4
Table 6: share of the quality gain kept (paper: 3%, 20%, 29%)
distillation 2.6%
+ init non-expert 19.8%
+ 0.75 hard/soft mix 29.2%
SuperGLUE (Table 8): 29.9% (paper: 30%)
Table 7: Switch-Base with 16 to 256 experts, distilled to T5-Base
teacher gain over T5-Base: [0.131, 0.162, 0.192, 0.204, 0.209]
extra gain per doubling: [0.031, 0.03, 0.012, 0.005]
recomputed size (B): [1.07, 1.98, 3.79, 7.42, 14.66]
gain kept; compression with 0.223B and with 0.2B
1.1B gain 37.4% (paper 37%) compression 79.7% / 81.8% (paper 82%)
2.0B gain 31.5% (paper 32%) compression 88.8% / 90.0% (paper 90%)
3.8B gain 29.7% (paper 30%) compression 94.1% / 94.7% (paper 95%)
7.4B gain 26.5% (paper 27%) compression 97.0% / 97.3% (paper 97%)
14.7B gain 27.8% (paper 28%) compression 98.5% / 98.6% (paper 99%)
Table 9: gain over T5-XXL (Neg. Log Perp.)
Switch-XXL @250k 0.061 @500k 0.087
Switch-C @250k 0.051 @500k 0.052
T5-XXL from 250k to 500k: 0.052
FLOPs/seq, Switch-XXL / Switch-C = 7.1
parameters, Switch-C / Switch-XXL = 4.0
- Parameter counts reproduce from the hyperparameters. The embedding is shared, attention has four matrices, the FFN uses GEGLU (three matrices) or ReLU (two matrices), and every Switch layer has experts plus a router. T5-XXL comes to 11.00B and Switch-C to 1571.31B (paper: 1571B); Switch-Base comes to 7.42B, which matches the 7410M of Table 8. Switch-Large comes to 27.12B against the paper’s 26B, and I did not find the reason.
- Switch-XXL should have 128 experts in Table 9. With the 64 experts printed in the table the count is only 201.26B; with 128 experts it is 394.54B, matching the paper’s 395B; the checkpoint Google released on Hugging Face is called switch-xxl-128, which also says 128.
- The speed ratios of Table 1 reproduce, and a difference in basis shows up. The MoE-to-Switch ratios of hours are 0.94, 1.24 and 1.28. The text and Figure 6 say Switch-Base is 2.5 times faster than T5-Large, while Table 1 at the -1.50 threshold gives : one is read off a curve, the other uses a fixed threshold.
- The distillation percentages reproduce. The 3%, 20% and 29% of Table 6 correspond to 2.6%, 19.8% and 29.2%; the retained shares of Table 7 come out within 0.5 percentage points of the paper’s; Table 8 gives 29.9%. The compression rates agree only when the student is rounded to 0.2B (81.8%, 90.0%, 94.7%, 97.3%, 98.6% against the paper’s 82%, 90%, 95%, 97%, 99%); with the exact 223M the first row is 79.7%, not 82%.
- The quality gaps of Table 9. Switch-XXL beats T5-XXL by 0.061 (250k steps) and 0.087 (500k); Switch-C by 0.051 and 0.052. T5-XXL itself improves by only 0.052 from 250k to 500k steps, so Switch-XXL’s lead of 0.061 at 250k steps is larger than what T5-XXL gains from 250k more steps of training.
Reading notes: where the paper does not add up
These are things noticed while reading, listed so that citations can avoid them. Most are typos or differences in basis and do not affect the paper’s main conclusions, but when quoting a specific number, trust the table.
| Where | What the paper says | What checking shows |
|---|---|---|
| Table 9 | Switch-XXL has 64 experts | 395B parameters corresponds to 128 experts; 64 would give only about 201B |
| Section 5.6 text | At 250k steps both Switch variants beat T5-XXL by “more than 0.061” | Table 9: Switch-XXL by 0.061, Switch-C by 0.051 |
| Sections 5.6 and 8 | Switch-XXL has about 10 times the FLOPs per sequence of Switch-C | Table 9: 6.3T / 890B = 7.1 times |
| Section 3.1 | ”Switch-Base (64 experts) at step 60k matches T5-Base at step 450k”, with the two step counts swapped in the sentence | Right panel of Figure 4: Switch at about 60k steps matches T5-Base at about 450k, 7.5x |
| Section 3.3, Figure 6 | Switch-Base is 2.5 times faster than T5-Large | Table 1 at the -1.50 threshold gives 2.09 times; different basis |
| Abstract, Table 9 caption | Switch-C is 4 times faster than T5-XXL | The table only lets us check 250k against 500k steps, about 2x; the basis of 4x is not stated and there is no time per step, so it cannot be recomputed |
| Table 11 caption | ”lower is better” | The metric is negative log perplexity, where higher is better, and the text also says input jitter is best (-1.468) |
| Table 7 | Compression of 82%, 90%, 95%, 97%, 99% | With the exact 223M it is 79.7%, 88.8%, 94.1%, 97.0%, 98.5%; the paper computes with 0.2B |
| Table 4 and Section 2.4 | Expert dropout helps on all four small tasks | In the table GLUE and CNNDM each gain 0.5, SQuAD and SuperGLUE are unchanged |
Limits, and what came next
The limits the paper itself lists in Section 8: the stability of the largest models is unsolved (Switch-XXL can still become unstable; the authors tried regularizers and adapted gradient clipping and say it “remains unsolved”); upstream quality does not always predict downstream quality (see Switch-C against Switch-XXL on SQuAD above); only homogeneous experts were used, only language was tested, and it was not combined with sparse attention.
A few things to keep in mind when reading, which are the reader’s cautions rather than the paper’s conclusions:
- The comparison holds FLOPs per token equal, not memory, parameters or cost. The paper admits in Section 7 that Switch is better partly because of its parameter count, by design, and adds that it is also more sample efficient and faster on the same compute. With one to two orders of magnitude more parameters, inference needs all experts in memory, and communication and scheduling get more complicated (see the wiki pages Mixture of Experts and Distributed Training).
- The speed comes from TPUv3 and a Mesh-TensorFlow implementation, and footnote 5 itself says speed depends on both the algorithm and the implementation; the numbers do not carry over directly to GPUs and other parallelism schemes.
- Fine-tuning results are single runs, peaks on the validation set, and the ablations of Tables 2 to 4 and 11 were not repeated.
- “7x faster pre-training” does not mean “7x better downstream”: in Table 5 many tasks differ little, and ARC even regresses.
After this paper MoE returned as a mainstream direction, but along different routes. did not become the standard: Mixtral picks 2 of 8 experts and DeepSeek-V3 picks 8 of 256 routed experts plus 1 shared expert (see the explainers of Mixtral and DeepSeek-V3). Load balancing evolved too: DeepSeek-V3 balances mainly with a bias (keeping only a tiny sequence-level auxiliary loss) and drops no token in training or inference. On stability, ST-MoE (Zoph et al., 2022), in which all three Switch authors took part, introduced the router z-loss and scaled a sparse model to 269B parameters. What Switch left behind is more basic: routing can be very simple, capacity and the balancing loss are two ends of one problem, and the hard part of sparse models lies mostly in systems and numerics, not in the structure itself.
What to take from this paper
- It splits the risks of MoE into three small problems that can be handled separately. Routing (), load (capacity plus the balancing loss) and numerics (selective precision, small initialization, expert dropout); none is complicated, and together they make MoE scale.
- The basis is equal FLOPs, not equal parameters or memory. Parameters are free in the FLOPs sense; memory and communication are not.
- Capacity factor and balancing loss are two ends of one problem. The loss flattens the routing and the capacity catches what is still uneven; this page’s simulation shows that the drop rate is very sensitive to , and the capacity factor chooses a point between dropping tokens and wasting compute.
- Upstream gains do not turn into downstream gains automatically. The comparison of Switch-C and Switch-XXL, and the regression on ARC, both say: look at the downstream task itself.
Further reading
- Wiki: Mixture of Experts has the routing equations, the capacity factor, a router lab whose parameters you can change, and a comparison of Mixtral and DeepSeek-V3; Modern LLM Architecture places MoE in the whole architectural evolution; Distributed Training covers data, model, pipeline and expert parallelism.
- Other explainers in this series: Mixtral of Experts, DeepSeek-V3 and Scaling Laws for Neural Language Models.
- Shazeer et al., Outrageously Large Neural Networks: The Sparsely-Gated Mixture-of-Experts Layer (2017): the sparsely-gated MoE layer and the original top-k routing.
- Lepikhin et al., GShard: Scaling Giant Models with Conditional Computation and Automatic Sharding (2020): MoE in the Transformer with automatic sharding.
- Zoph et al., ST-MoE: Designing Stable and Transferable Sparse Expert Models (2022): a design guide to the stability and transfer of sparse models.
- The paper: Fedus, Zoph and Shazeer, Switch Transformers: Scaling to Trillion Parameter Models with Simple and Efficient Sparsity (JMLR 23, 2022); the equations, tables and quotes on this page come from arXiv v3.
FAQ
- How does the Switch Transformer differ from an ordinary MoE?
- Only the routing differs: each token is sent to exactly one expert (top-1, which the paper calls a Switch layer), where earlier MoE layers picked at least two. The output is the chosen expert's output times the probability the router gave it, so the router still receives gradients. The paper argues that this needs less routing computation, at least halves the batch each expert needs, and simplifies the implementation and the communication. In Table 1 (128 experts; Switch has the same FLOPs as T5-Base, top-2 MoE has more), Switch reaches the target quality faster than top-2 MoE at capacity factors 1.25 and 1.0 (65.0 and 62.8 hours against 80.7 and 80.1), but not at 2.0 (72.8 hours against 68.7).
- What is the capacity factor, and what happens to dropped tokens?
- Each expert processes at most (tokens per batch / number of experts) x capacity factor tokens (Equation 3). A token over the limit skips the expert and reaches the next layer through the residual connection. A larger factor drops fewer tokens but pads empty slots with zeros, wasting compute, memory and communication. The paper reports that typically under 1% of tokens are dropped during training. In this page's toy simulation (64 experts, uniform routing, 64 tokens per expert on average), a factor of 1.0 drops 5.0% and a factor of 1.25 drops 0.1%; the more skewed the routing, the more is dropped.
- How is the load-balancing loss computed, and which coefficient is used?
- The loss is alpha x N x sum of f_i x P_i. Here f_i is the fraction of tokens sent to expert i (an argmax, so not differentiable) and P_i is the router's mean probability for expert i (differentiable). With perfectly uniform routing f_i = P_i = 1/N and the loss equals alpha, which is why N is in the formula: it keeps the value independent of the number of experts. The paper swept alpha over powers of 10 from 10^-1 to 10^-5 and chose 10^-2, which flattens the load quickly without overwhelming the main cross-entropy objective.
- How does the Switch Transformer keep a sparse model stable?
- Three measures. Selective precision: only the inside of the router runs in float32 while the rest stays in bfloat16; on a 32-expert model pure bfloat16 diverged (-3.780), selective precision reached -1.716 against -1.718 for float32, at 1390 against 1160 examples per second. A smaller initialization: scaling the initial weights to 0.1x of the default cut the standard deviation of quality over 3 seeds from 0.68 to 0.01. Expert dropout: during fine-tuning only the dropout inside the experts is raised to 0.4 while other layers keep 0.1. The largest model, Switch-XXL, still became unstable from time to time, and the paper lists this as unsolved.
- Is a mixture of experts a free lunch?
- No. Switch compares models with equal FLOPs per token, but with one to two orders of magnitude more parameters (7.4B for Switch-Base against 223M for T5-Base); at inference all experts must fit in memory, and routing adds all-to-all communication. The paper records other costs too: at equal FLOPs, Switch-Base processes only 62.5% of T5-Base's examples per second (1000 against 1600), sparse models overfit more easily when fine-tuned, and the largest model did not fully convert its upstream gain into downstream results: Switch-XXL scored 87.5 on SuperGLUE (test), below T5's 89.3, although that checkpoint had seen only about half as much pre-training data.