Search

Search papers and lessons

Switch Transformers: Scaling to Trillion Parameter Models

William Fedus, Barret Zoph, Noam Shazeer · 2021

Switch Transformer sends each token to one expert and adds training fixes, so a language model can grow to 1.6 trillion parameters and pre-train several times faster than dense T5 at equal compute per token.

On this page

  • Colour = topic mix
  • Architectures
  • Calculus
  • Probability
  • Neural network basics
  • Linear algebra
  • Efficiency
  • Sign in to see your progress

TL;DR

Mixture of experts (MoE) layers hold many feedforward networks, called experts, and a router that sends each token to a few of them. The model can then have many more parameters than a dense model, while each token only pays for the experts it uses. MoE had worked well in machine translation, but it was hard to build, expensive to communicate, and unstable to train. The Switch Transformer makes the simplest routing choice: each token goes to exactly one expert. It then adds a balancing loss, runs the router in float32 so the rest of the model can use bfloat16, and shrinks the weight initialization. The authors train models up to 1.6 trillion parameters and report pre-training speedups of up to 7 times over dense T5 at the same compute per token.

Where you'll see it: the sparse feedforward layers of the Switch Transformer models, and any language model that routes each token to a single expert.

The problem

Making a language model bigger usually means making it do more work per token. A dense Transformer with twice the width costs roughly twice the arithmetic on every input. Kaplan et al. showed that loss falls as a power law in model size, data and compute, so bigger models really are better. The question the paper asks is whether parameter count can be a separate axis: add parameters while keeping the floating point operations (FLOPs) per example fixed.

Mixture of experts is the obvious tool for that. Shazeer et al. (2017) had used it in LSTM language models and machine translation, and GShard (Lepikhin et al., 2020) used an MoE Transformer to translate across 100 languages. The paper names three reasons adoption was still limited:

  • Complexity. The routing algorithm is more involved than a dense layer, and the output shapes depend on routing decisions at run time, which is awkward on accelerators that want static tensor shapes.
  • Communication. When experts live on different devices, tokens must be sent to the right device and sent back. That traffic can cost more than the arithmetic it saves.
  • Training instability. Routing is a hard, discrete choice at each layer. Low-precision formats such as bfloat16 make the router's softmax less accurate, and in the authors' experiments a plain bfloat16 model diverged.

Earlier MoE work also held a belief about routing. Shazeer et al. (2017) conjectured that the router needs at least two experts per token to get useful gradients, because it must compare two options to learn anything. The MoE Transformer that this paper compares against uses top-2 routing.

Key idea

Route each token to a single expert. The paper calls this a Switch layer, and it is the Switch Transformer's whole architectural change: the dense feedforward block in each Transformer layer (every other one, in most models here) is replaced by a set of experts and a router.

Dropping from two experts to one gives three benefits, which the paper lists directly:

  1. The router does less work, since each token is scored for one destination only.
  2. The batch capacity of each expert can be at least halved, because each token occupies one slot instead of two.
  3. The routing code is simpler and sends less data between devices.
flowchart LR
  T[Token representation] --> R[Router: scores for N experts]
  R -->|highest probability| E[Chosen expert]
  E --> M[Multiply by router probability]
  M --> O[Output to residual stream]
  R -.->|other experts skipped| X[Not run for this token]

The rest of the paper is about making that single choice work at scale: keeping experts from overflowing, spreading tokens evenly, and training stably in cheap number formats.

The method

Routing with one expert

For a token representation x\mathbf{x}, the router is a learned matrix WrW_r. It produces one logit per expert, h(x)=Wrxh(\mathbf{x}) = W_r \mathbf{x}, and a softmax over the NN experts gives probabilities:

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

The token is sent to the expert with the largest probability, and the layer output is that expert's output scaled by its probability:

y=pi∗(x) Ei∗(x),i∗=arg⁡max⁡ipi(x)y = p_{i^{*}}(\mathbf{x}) \, E_{i^{*}}(\mathbf{x}), \qquad i^{*} = \arg\max_i p_i(\mathbf{x})

Here EiE_i is the feedforward network of expert ii. The multiplication by pi∗p_{i^{*}} matters. The arg max choice has no gradient, but the probability does, so the loss can reach the router through it. Top-k MoE used a weighted sum over the k chosen experts instead, which this paper simplifies away.

Expert capacity

Tensor shapes on TPUs must be fixed before the program runs, yet routing is decided at run time. The paper handles this with a fixed capacity per expert:

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

Take a batch of 4,096 tokens, 64 experts and a capacity factor of 1.25. Each expert can process 409664×1.25=64×1.25=80\frac{4096}{64} \times 1.25 = 64 \times 1.25 = 80 tokens. If the router sends 100 tokens to one expert, the first 80 are processed and the other 20 are dropped. A dropped token skips the expert and passes through the residual connection unchanged. The paper reports that drop rates were typically below 1 percent once the balancing loss below was in place.

A capacity factor above 1.0 leaves slack for uneven routing, but slack costs compute and memory on every expert, used or not. Table 1 below compares capacity factors of 1.0, 1.25 and 2.0.

A differentiable load-balancing loss

Left alone, the router tends to send most tokens to a few favourite experts, and the rest sit idle. The paper adds an auxiliary loss to each Switch layer. For NN experts and a batch B\mathcal{B} of TT tokens, define two vectors. The first is the fraction of tokens actually dispatched to each expert:

fi=1T∑x∈B1{argmax p(x)=i}f_i = \frac{1}{T} \sum_{x \in \mathcal{B}} \mathbb{1}\{\text{argmax}\, p(x) = i\}

The second is the average router probability given to each expert:

Pi=1T∑x∈Bpi(x)P_i = \frac{1}{T} \sum_{x \in \mathcal{B}} p_i(x)

The loss is

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

Under perfectly uniform routing, every fif_i and every PiP_i equals 1/N1/N, so the sum is N⋅(1/N)2=1/NN \cdot (1/N)^2 = 1/N, and multiplying by NN gives 1. The factor NN keeps the loss's scale the same whatever the number of experts. The coefficient is α=10−2\alpha = 10^{-2}, which the authors found large enough to balance load and small enough not to disturb the main cross-entropy objective. They swept α\alpha from 10−110^{-1} to 10−510^{-5}.

Only PiP_i is differentiable. fif_i comes from a hard arg max, so it carries no gradient. The loss still works because pushing PiP_i down for overloaded experts moves the router, and the router moves the hard choices.

Worked example. Take N=4N = 4 experts and a batch where the router gives every token the probabilities (0.7,0.1,0.1,0.1)(0.7, 0.1, 0.1, 0.1).

  1. Every token's arg max is expert 1, so f=(1,0,0,0)f = (1, 0, 0, 0).
  2. The average probabilities are P=(0.7,0.1,0.1,0.1)P = (0.7, 0.1, 0.1, 0.1).
  3. ∑ifiPi=1×0.7=0.7\sum_i f_i P_i = 1 \times 0.7 = 0.7.
  4. The loss is α⋅4⋅0.7=2.8 α\alpha \cdot 4 \cdot 0.7 = 2.8\,\alpha. With α=0.01\alpha = 0.01, that is 0.0280.028.

Under uniform routing the same calculation gives α⋅4⋅4⋅(0.25×0.25)=α=0.01\alpha \cdot 4 \cdot 4 \cdot (0.25 \times 0.25) = \alpha = 0.01. The collapsed router pays nearly three times as much, so the gradient pushes it back toward balance.

Stable training in bfloat16

Three changes make the model trainable in cheaper formats.

Selective precision. Only the router's computation is cast to float32, and only on the device that performs it. The dispatch and combine tensors are cast back to bfloat16 before any all-to-all communication, so no float32 data crosses the network. Table 2 shows the effect on a 32-expert model early in training:

ModelQuality (neg. log perplexity, higher is better)Speed (examples per second)
Switch-Base in float32-1.7181160
Switch-Base in bfloat16-3.780 (diverged)1390
Switch-Base with selective precision-1.7161390

The selective version matches float32 quality at bfloat16 speed.

Smaller initialization. Weights are drawn from a truncated normal distribution with standard deviation s/n\sqrt{s / n}, where nn is the fan-in and ss is a scale. The usual Transformer uses s=1.0s = 1.0. The paper recommends s=0.1s = 0.1. Table 3 shows the difference on a 32-expert model after 3.5k steps, averaged over three seeds:

Initialization scaleAverage qualityStd. dev. across seeds
0.1x-2.720.01
1.0x-3.600.68

The smaller scale reduces both the average loss and the spread between runs. The authors used this initialization from a 223M-parameter model up to models over a trillion parameters.

Expert dropout. Fine-tuning on small tasks can overfit a model with many more parameters than its dense baseline. The paper uses a dropout rate of 0.1 on non-expert layers and 0.4 inside the expert feedforward layers during fine-tuning. Table 4 shows this setting gives the best GLUE score (85.2, against 82.9 for dense T5-Base and 84.7 for Switch-Base with uniform 0.1 dropout), ties the best CNNDM score, and lands within 0.2 of the best SQuAD and SuperGLUE scores. Raising dropout uniformly to 0.3 hurts.

Parallelism

Switch Transformers puts all cores on the data dimension and sets the number of experts equal to the number of cores. Each core holds one expert, and tokens move between cores in an all-to-all exchange, which sends a tensor of size E × C × d_model in bfloat16 for each forward pass. For Switch-C, the 1.6-trillion-parameter model, the authors use only expert parallelism, which avoids the all-reduce costs of splitting each matrix across devices. The lesson on GPU Memory Hierarchy gives the general reason data movement often dominates the cost of such layers.

Results

Pre-training speed

Table 1 compares Switch-Base with a dense T5-Base and an MoE Transformer, all on 32 TPUv3 cores with 128 experts. The measure is the time to reach a negative log perplexity of -1.50.

ModelCapacity factorQuality after 100k stepsHours to thresholdExamples per second
T5-Base—-1.731not reached1600
T5-Large—-1.550131.1470
MoE-Base2.0-1.54768.7840
Switch-Base2.0-1.55472.8860
MoE-Base1.0-1.57280.1860
Switch-Base1.0-1.56162.81000
Switch-Base+1.0-1.53467.6780

Switch-Base at capacity factor 1.0 reaches the threshold in 62.8 hours, against 80.1 for MoE-Base at the same factor. The paper also reports that the MoE model's speed does not improve monotonically with capacity factor, which it attributes to implementation details. Switch-Base+ widens the model until its speed matches the MoE model, and then has the best quality per step of any model in the table.

On a step basis, a 64-expert Switch-Base at step 60k matches the quality T5-Base reaches at step 450k, a 7.5x speedup. On a wall-clock basis it reaches that quality in about one seventh of the time. Figure 4 scales the number of experts by doubling from 2 up to 256, reaching 14.7B parameters, at the same FLOPs per token as the 223M T5-Base; quality improves at each step as experts are added.

Against a bigger dense model

T5-Large applies 3.5 times more FLOPs per token than Switch-Base, and Switch-Base is still more sample efficient and reaches the same quality about 2.5 times faster in wall-clock time. The authors then build Switch-Large, FLOP-matched to T5-Large, which scales further still.

Fine-tuning

The FLOP-matched Switch models were pre-trained for 550k steps with 2202^{20} tokens per batch, then fine-tuned on each task. Table 5 gives the validation scores.

ModelGLUESQuADSuperGLUEWinogrande (XL)
T5-Base84.385.575.166.6
Switch-Base86.787.279.573.3
T5-Large87.888.182.779.1
Switch-Large88.588.684.783.0

The largest gains are on SuperGLUE (4.4 points over T5-Base, 2 over T5-Large) and Winogrande. Two tasks do not improve: ARC Challenge for Switch-Base, and ARC Easy for Switch-Large.

Distillation

Serving a model with 3.8 billion parameters is costly, so the paper distills Switch-Base into a dense T5-Base with 223M parameters. Using the non-expert weights for initialization and a loss that is 0.25 teacher probabilities and 0.75 ground-truth labels, it keeps about 30 percent of the sparse model's gain over T5-Base, with about one twentieth of the parameters. Across teachers from 1.1B to 14.7B parameters, the student keeps 37 percent of the gain at 82 percent compression, and 28 percent at 99 percent compression.

Multilingual pre-training

On mT5's 101-language mC4 mixture, the Switch model beats the FLOP-matched dense baseline on every language. The mean step speedup over mT5-Base is 5x, and 91 percent of languages reach mT5-Base's final perplexity at least 4x faster.

Trillion-parameter models

Table 9 lists the large models:

ModelParametersFLOPs per sequenceExperts
T5-XXL11B6.3T—
Switch-XXL395B6.3T64
Switch-C1571B890B2048

Switch-XXL is FLOP-matched to T5-XXL but has far more parameters. Switch-C uses expert parallelism only, so its width and depth are much smaller than T5-XXL's, and its per-token compute is lower. At 500k steps, the negative log perplexity on C4 is -1.008 for Switch-XXL and -1.043 for Switch-C, against -1.095 for T5-XXL. The paper summarises the 4x speedup over T5-XXL as the result for Switch-C.

Switch-C showed no training instability at its scale. Switch-XXL was sometimes unstable, which is why the authors stopped it short of 1M steps. Downstream, a partly trained Switch-XXL reached a SQuAD validation score of 89.7 against a state of the art of 91.3, and an average SuperGLUE test score of 87.5 against 90.0. The authors note that the pre-training gains did not fully carry over to reasoning benchmarks.

Why it mattered

The paper made a simple claim with evidence: routing each token to one expert, with a balancing loss and a few stability fixes, is a dependable way to add parameters without adding compute per token. It reported a trained and measured model with 1.6 trillion parameters, and it laid out a concrete recipe: single-expert routing, a balancing loss, selective precision, small initialization and expert dropout.

The paper also showed that the parameter axis has limits. Gains on pre-training loss did not always carry to reasoning fine-tuning, and the authors name this as open work.

Reading guide

Read the paper in this order, with the lessons that cover each prerequisite:

  1. Section 1, Introduction. Needs Mixture of Experts and Transformer. The scaling motivation builds on Neural Scaling Laws.
  2. Section 2.1, Simplifying sparse routing. Needs Softmax and Feedforward Neural Network. The single-expert choice is the subject of Switch Routing.
  3. Section 2.2, Efficient sparse routing. The capacity formula and the balancing loss need Load-Balancing Loss.
  4. Section 2.4, Training and fine-tuning. Expert dropout uses Dropout. The cross-entropy objective is in Cross-Entropy Loss.
  5. Section 3, Scaling properties. Needs Neural Scaling Laws and Power Law.
  6. Section 4, Downstream results. Needs Exploring the Limits of Transfer Learning (T5) for the baselines, Masked Language Modeling for the pre-training objective, and Transfer Learning for the fine-tuning setup. The distillation section needs Knowledge Distillation.
  7. Section 5, Parallelism. The communication costs are explained by GPU Memory Hierarchy.

Check yourself

QuestionIn a Switch layer, how many experts does one token run through, and what does the layer output for it?Show answer

One expert. The router computes a softmax over all experts, picks the arg max, and the layer returns that expert's output multiplied by the router probability for it. The multiplication keeps the router differentiable, so the loss can train the routing choice.

QuestionA batch has 4,096 tokens, there are 64 experts, and the capacity factor is 1.25. The router sends 100 tokens to one expert. How many are dropped?Show answer

The capacity is (4096 / 64) × 1.25 = 80 tokens. The expert processes 80 and drops 100 − 80 = 20. Dropped tokens skip the expert and pass through the residual connection unchanged.

QuestionWhy does the balancing loss multiply the sum of f times P by N?Show answer

Under uniform routing, each f_i and P_i equals 1/N, so the sum is 1/N. Multiplying by N makes the loss equal to α under uniform routing, whatever the number of experts. The loss scale then stays comparable when the expert count changes, so one value of α works across model sizes.

QuestionA 64-expert model trained in bfloat16 diverges. Using only the paper's remedies, what would you try, and what does each address?Show answer

Cast only the router's computation to float32 on the local device, which keeps the softmax accurate without sending float32 tensors across the network. Reduce the initialization scale from 1.0 to 0.1, which the paper found improves quality and reduces variance across seeds. Check the load-balancing loss so that a few experts do not take most tokens and overflow.

QuestionIn the paper's SuperGLUE experiment, a student distilled from a fine-tuned 7.4B sparse teacher keeps about 30 percent of the teacher's gain over the dense baseline. Roughly how many parameters does the student have compared with the teacher?Show answer

The student is a 223M-parameter T5-Base, against 7.4B for the teacher. That is about 3 percent of the teacher's size, which is the compression the paper reports for this setting. The 30 percent refers to the share of the quality gain over the dense baseline, not to the share of parameters or quality overall.

Sources

Read the full paper

William Fedus, Barret Zoph, Noam Shazeer, 2021. arXiv:2101.03961