VerifiedarXiv:2101.0396133 min
Sparsity · Scaling

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

Send each token to just one of many expert networks, and you can add experts (and the parameters that come with them) without adding compute per token.

A Switch Transformer keeps many copies of each feed-forward block, called experts, and a small learned router that sends every token to exactly one of them. Adding experts adds parameters, while the work done on each token stays at one expert.

Explaining the paperSwitch Transformers: Scaling to Trillion Parameter Models with Simple and Efficient SparsityFedus, Zoph, Shazeer · Google · JMLR 2022 · arXiv:2101.03961 ↗

The largest model in the paper has 1.6 trillion parameters and spends about a seventh of the compute per sequence of a dense model 143 times smaller.

Language models improve predictably as they get bigger, across several orders of magnitude (the scaling laws of Kaplan and collaborators measure this). In an ordinary Transformer, every parameter takes part in the computation for every token, so doubling the parameters doubles the floating-point operations (FLOPs) per token, in training and again every time the model is served.

A mixture of experts, an idea from Jacobs and collaborators in 1991, breaks that link. The network keeps many sub-networks, the experts, and a gate that decides which of them process a given input; the rest sit idle for that input. Mixtures of experts had worked in machine translation (Shazeer and collaborators in 2017 and 2018, and GShard in 2020), but the Switch paper lists three reasons they had not spread: complexity, communication costs, and training instability. Fedus, Zoph and Shazeer at Google simplified the routing to one expert per token and trained models up to 1.6 trillion parameters with it.

The page follows the method in the order it is built: the router and the decision to use one expert, why the router still gets a gradient, the auxiliary loss that keeps experts evenly used, the fixed expert capacity that makes routing fit static-shape hardware, the three training fixes, and then the results, from the expert-count sweep to the trillion-parameter models and distillation back to a dense model.

Why a dense Transformer pays for every parameter

Each Transformer layer has two sublayers. Attention mixes information between tokens; the feed-forward network (FFN) then transforms each token on its own with two or three matrix multiplies. In T5-Base, the 223-million-parameter baseline of this paper, each FFN has three 768 × 2048 matrices (the gated GEGLU variant), 4.7 million weights, and the 24 FFN blocks (12 in the encoder, 12 in the decoder) hold 113 million of the 223 million parameters. Every token that passes through a layer is multiplied by the same FFN weights.

Conditional computation makes the set of weights that run depend on the input. Switch replaces the FFN in a layer with NN FFNs of the same shape, the experts, and a router that sends each token to one of them. The parameter count then grows with NN, while each token still passes through one FFN's worth of arithmetic.

A hospital with many specialists works the same way. Each patient is triaged to one specialist, so a visit takes the time of one consultation however large the staff grows, while the hospital still has to employ and house every specialist. The model's equivalent of payroll is memory: every expert's weights must be stored on some accelerator even though each token uses one.

Switch-Base puts experts in every other FFN layer, 12 of the 24. Each extra expert adds one 4.7M-weight FFN to each of those 12 layers, 56.6 million parameters, so a model with EE experts has 223M + (E − 1) × 56.6M parameters. That count gives 1.1B at 16 experts, 3.8B at 64 and 14.7B at 256, the sizes the paper reports. In the figure, watch the third bar while you drag: the FLOPs per token stay at one expert, plus a router whose cost grows with the expert count.

Figure 1 · parameters without compute
64
Drag the number of experts in the Switch-Base family from 1 (dense T5-Base) to 256. Parameters and the bfloat16 memory to hold them grow together. The FLOPs per token stay at one expert's FFN; the thin amber cap on that bar is the router, 768 × E multiply-adds per Switch layer, about 1% of an expert at 64 experts and 4% at 256.

At the top of the paper's range, Switch-C has 1,571 billion parameters and uses about 890 billion FLOPs per training sequence; the dense T5-XXL has 11 billion parameters and uses 6.3 trillion. Switch-C has 143 times the parameters and does 0.14 times the arithmetic. The abstract's phrase "constant computational cost" refers to FLOPs per token only. Memory grows with the number of experts, and because the experts live on different accelerators, every routed token has to be sent over the network to its expert and back. Sparsity buys parameters with memory and bandwidth. (Memory is the same constraint behind ZeRO, from the same period.)

Mixture of experts and the router

The router is one weight matrix WrW_r of shape dmodel×Nd_{\text{model}} \times N. For a token representation xx (a vector of length dmodeld_{\text{model}}), it computes one score, a logit, per expert, and a softmax turns the scores into probabilities:

h(x)=Wr⋅x,pi(x)=eh(x)i∑j=1Neh(x)jh(x) = W_r \cdot x, \qquad p_i(x) = \frac{e^{h(x)_i}}{\sum_{j=1}^{N} e^{h(x)_j}}h(x)=Wr⋅x,pi(x)=eh(x)i∑j=1Neh(x)j\begin{gathered} h(x) = W_r \cdot x, \\ p_i(x) = \frac{e^{h(x)_i}}{\sum_{j=1}^{N} e^{h(x)_j}} \end{gathered}
(1)

The number pi(x)p_i(x) is the gate value of expert ii for this token. (The paper writes Wr⋅xW_r \cdot x; Shazeer's x⋅Wgx \cdot W_g is the same product with the matrix laid out the other way.) A mixture-of-experts layer picks a set T\mathcal{T} of experts for the token and sums their outputs, each scaled by its gate value:

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

Here Ei(x)E_i(x) is expert ii's FFN applied to the token. The gate value has two jobs in (2). It decides membership in T\mathcal{T} (the experts with the largest gate values are chosen), and it multiplies the chosen expert's output. The paper points out that the second job is what makes the router differentiable: the loss depends on pi(x)p_i(x) through that multiplication, so the router weights receive a gradient.

The sparsely-gated MoE of Shazeer and collaborators (2017) chose the top kk experts with k≥2k \ge 2. Its authors conjectured that the router has to compare at least two experts per token to get a useful gradient, so k=1k = 1 would leave it unable to learn, and later work by Ramachandran and Le found higher kk important in the lower layers of models with many routing layers.

How the Switch layer routes each token

A Switch layer sets k=1k = 1. Each token goes to the expert with the largest gate value and to no other, so (2) becomes

y=pi∗(x) Ei∗(x),i∗=arg⁡max⁡i pi(x)y = p_{i^\ast}(x)\, E_{i^\ast}(x), \qquad i^\ast = \arg\max_i\, p_i(x)y=pi∗(x) Ei∗(x),i∗=arg⁡max⁡i pi(x)\begin{gathered} y = p_{i^\ast}(x)\, E_{i^\ast}(x), \\ i^\ast = \arg\max_i\, p_i(x) \end{gathered}

The paper lists three gains over k=2k = 2. The router computation shrinks, because each token is routed to a single expert. Each expert's batch, its capacity, can be at least halved, because every token now occupies one seat instead of two. And the implementation gets simpler and sends less data between devices. Against a top-2 MoE with the same 128 experts (Table 1), Switch-Base processed more examples per second at every capacity factor tried (how much room each expert gets beyond an even share of the tokens, defined in the capacity section below): 860 against 840 at 2.0, 910 against 790 at 1.25, and 1,000 against 860 at 1.0.

In the figure, the token's position along the top line stands in for its representation. The bars are the router's softmax over six experts. Drag the token across a border between regions and the chosen expert jumps; the gate value on the winner stays below 1 everywhere.

Figure 2 · top-1 routing
A token x reaches the router, which scores six experts with a softmax (the bars). Only the argmax expert's FFN runs; the other five do no work for this token. The winning gate value pi(x)p_i(x) is a probability below 1, and it multiplies the expert's output. Drag the token, or let it sweep.

A worked example with Switch-Base shapes: dmodel=768d_{\text{model}} = 768 and 128 experts, so WrW_r is 768×128768 \times 128 and produces 128 logits per token. Suppose expert 57 wins with p57=0.31p_{57} = 0.31. Expert 57's FFN maps the token to a 768-vector, that vector is multiplied by 0.31 and added to the token through the residual connection, and the other 127 experts do nothing for this token. The full layer, including the tokens that do not get a seat (covered in the capacity section), looks like this:

# one Switch feed-forward layer, top-1 routing
# x: [T, d_model] token representations; W_r: [d_model, N]; E[i]: expert i's FFN
logits = to_float32(x @ W_r)       # [T, N]  router runs in float32 (selective prec.)
p      = softmax(logits, axis=-1)  # gate values p_i(x), eq (1), over ALL N experts
expert = argmax(p, axis=-1)        # [T]  which expert: no gradient through this
gate   = p[arange(T), expert]      # [T]  that expert's probability: has a gradient

cap = int(T / N * capacity_factor) # seats per expert, eq (3)
out = zeros_like(x)                # a token that gets no seat adds nothing here
for i in range(N):                 # in practice: one batched einsum, not a loop
    seat = where(expert == i)[:cap]          # first cap tokens routed to i
    out[seat] = gate[seat, None] * E[i](x[seat])   # eq (2) with k = 1
y = x + out                        # residual: dropped tokens pass through as x

Two lines of that listing come up again below. The to_float32 cast is the selective-precision fix from the stability section. The cap variable fixes how many tokens each expert can take per batch, which is how a data-dependent routing decision fits on hardware that needs every tensor shape known in advance.

Why one expert still gives the router a gradient

The argmax that picks i∗i^\ast is a step function: it is flat almost everywhere and jumps at the borders, so its derivative is zero wherever it exists. No gradient flows through the choice of expert. The gradient comes through the other factor, pi∗(x)p_{i^\ast}(x), which multiplies the expert output. Write δ\delta for the gradient of the loss with respect to the layer output yy. Then

∂L∂pi∗=δ⋅Ei∗(x)\frac{\partial L}{\partial p_{i^\ast}} = \delta \cdot E_{i^\ast}(x)

a single number that says whether scaling this expert's output up would raise or lower the loss. The softmax in (1) passes it to every logit:

∂pi∗∂hi∗=pi∗ (1−pi∗),∂pi∗∂hj=− pi∗ pj(j≠i∗)\frac{\partial p_{i^\ast}}{\partial h_{i^\ast}} = p_{i^\ast}\,(1 - p_{i^\ast}), \qquad \frac{\partial p_{i^\ast}}{\partial h_j} = -\,p_{i^\ast}\, p_j \quad (j \ne i^\ast)∂pi∗∂hi∗=pi∗ (1−pi∗),∂pi∗∂hj=− pi∗ pj(j≠i∗)\begin{gathered} \frac{\partial p_{i^\ast}}{\partial h_{i^\ast}} = p_{i^\ast}\,(1 - p_{i^\ast}), \\ \frac{\partial p_{i^\ast}}{\partial h_j} = -\,p_{i^\ast}\, p_j \quad (j \ne i^\ast) \end{gathered}

In the routing example above, say the product δ⋅E57(x)\delta \cdot E_{57}(x) is −0.8: a larger contribution from expert 57 would have lowered the loss. With p57=0.31p_{57} = 0.31, and for another expert jj with pj=0.02p_j = 0.02,

∂L∂h57=−0.8×0.31×0.69=−0.171,∂L∂hj=−0.8×(−0.31×0.02)=+0.005\frac{\partial L}{\partial h_{57}} = -0.8 \times 0.31 \times 0.69 = -0.171, \qquad \frac{\partial L}{\partial h_j} = -0.8 \times (-0.31 \times 0.02) = +0.005∂L∂h57=−0.8×0.31×0.69=−0.171,∂L∂hj=−0.8×(−0.31×0.02)=+0.005\begin{gathered} \frac{\partial L}{\partial h_{57}} = -0.8 \times 0.31 \times 0.69 = -0.171, \\ \frac{\partial L}{\partial h_j} = -0.8 \times (-0.31 \times 0.02) = +0.005 \end{gathered}

A gradient-descent step raises the logit of expert 57 and lowers the others, and since h=Wr⋅xh = W_r \cdot x, the change to expert 57's router weights is a step along xx itself, so tokens similar to this one score higher for expert 57 next time. Had the expert's output hurt (a positive product), the same derivatives would give expert 57's logit a positive gradient, and the step would lower it.

So why did Shazeer and collaborators expect k=1k = 1 to fail? Their gate is

G(x)=Softmax(KeepTopK(H(x),k))G(x) = \mathrm{Softmax}(\mathrm{KeepTopK}(H(x), k))

where KeepTopK sets every logit outside the top kk to −∞-\infty before the softmax. With k=1k = 1, one logit survives, and the softmax of a single number is exactly 1 whatever that number is. The gate is the constant 1, and a constant has zero derivative. With k=2k = 2, the two survivors get weights σ(ha−hb)\sigma(h_a - h_b) and 1−σ(ha−hb)1 - \sigma(h_a - h_b), which do depend on the logits. Switch reverses the order: softmax over all NN logits first, argmax second. The kept gate is then a probability below 1 with derivative p(1−p)p(1-p).

The figure puts the three orderings side by side for four experts. Drag the logit of expert 1 and read the slope of the curve on the right, which is the gradient the router gets through expert 1's gate. In the Switch ordering the curve rises smoothly once expert 1 is selected. In top-1-then-softmax it is a flat line at 1. In top-2-then-softmax it is a smooth sigmoid again.

Figure 3 · where the router gradient comes from
2.00
Four experts; the logits of experts 2 to 4 are fixed at 1.2, 0.5 and −0.4. Left: logits and the weight that multiplies each expert's output. Right: expert 1's weight as a function of its logit h1h_1, with the tangent at the current value. The jump where expert 1 becomes the argmax has no derivative in any mode. Switch the ordering with the buttons and drag h1h_1.

At the default h1=2h_1 = 2, the Switch ordering gives expert 1 a gate of 0.567 with slope 0.245. Switch to top-1-then-softmax and the gate reads exactly 1 with slope 0 at every value of h1h_1 where expert 1 wins. The router in that ordering learns nothing from the expert's output; the only remaining signal would come from extra terms such as a load-balancing loss.

The load-balancing loss

Hard routing can collapse. If one expert gets slightly more tokens early on, it gets more gradient updates, becomes slightly better, wins the argmax for more tokens, and the routing concentrates on a few experts while the rest receive almost nothing. Unused experts are parameters that cost memory and do no work. Switch adds an auxiliary loss to the language-modeling loss, one per Switch layer, computed over 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)

It multiplies two vectors. fif_i is the fraction of the batch's tokens whose argmax is expert ii, the actual traffic:

fi=1T∑x∈B1{arg⁡max⁡p(x)=i}f_i = \frac{1}{T} \sum_{x \in \mathcal{B}} \mathbb{1}\{\arg\max p(x) = i\}
(5)

and PiP_i is the average router probability for expert ii over the same tokens:

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

Both would equal 1/N1/N under perfectly even routing. The two are combined because only one of them can carry a gradient. fif_i is a count of argmax outcomes, a step function of the router weights, so autodiff treats it as a constant. PiP_i is an average of softmax outputs and is differentiable. All of the loss's gradient goes through PP, and since ff is held fixed, the gradient with respect to each PiP_i is

∂ loss∂Pi=αNfi\frac{\partial\, \text{loss}}{\partial P_i} = \alpha N f_i

which is proportional to how busy expert ii already is. One token's probabilities sum to 1, so what moves the router is the difference between experts. Through the softmax, the gradient of the loss with respect to token xx's logit for expert jj is

∂ loss∂hj(x)=pj(x) (cj−cˉ),ci=αNfiT,cˉ=∑ici pi(x)\frac{\partial\, \text{loss}}{\partial h_j(x)} = p_j(x)\,(c_j - \bar c), \qquad c_i = \frac{\alpha N f_i}{T}, \quad \bar c = \sum_i c_i\, p_i(x)∂ loss∂hj(x)=pj(x) (cj−cˉ),ci=αNfiT,cˉ=∑ici pi(x)\begin{gathered} \frac{\partial\, \text{loss}}{\partial h_j(x)} = p_j(x)\,(c_j - \bar c), \\ c_i = \frac{\alpha N f_i}{T}, \quad \bar c = \sum_i c_i\, p_i(x) \end{gathered}

so gradient descent lowers the logits of experts carrying more than the probability-weighted average load and raises the logits of lighter ones.

Worked example, four experts and eight tokens. The argmax sends 4, 2, 1 and 1 tokens to the experts, and the average router probabilities come out as follows:

f=(0.5, 0.25, 0.125, 0.125),P=(0.40, 0.30, 0.15, 0.15)f = (0.5,\ 0.25,\ 0.125,\ 0.125), \qquad P = (0.40,\ 0.30,\ 0.15,\ 0.15)f=(0.5, 0.25, 0.125, 0.125),P=(0.40, 0.30, 0.15, 0.15)\begin{gathered} f = (0.5,\ 0.25,\ 0.125,\ 0.125), \\ P = (0.40,\ 0.30,\ 0.15,\ 0.15) \end{gathered}

The sum of fiPif_i P_i is 0.2 + 0.075 + 0.01875 + 0.01875 = 0.3125; times NN = 4 it is 1.25, and times α\alpha = 0.01 the loss is 0.0125, against 0.01 for perfect balance. The gradients on PP are αNf\alpha N f = (0.02, 0.01, 0.005, 0.005). Take a token whose own probabilities equal PP. In units of αN/T\alpha N / T, its weighted average load cˉ\bar c is 0.3125. Expert 1's logit gradient is 0.40 × (0.5 − 0.3125) = +0.075, so gradient descent lowers that logit. Expert 2 gets 0.30 × (0.25 − 0.3125) = −0.019 and experts 3 and 4 get 0.15 × (0.125 − 0.3125) = −0.028, so their logits rise.

The factor NN fixes the loss's scale. Under uniform routing each of the NN terms is (1/N)2(1/N)^2, so the sum is 1/N1/N and the loss is

α⋅N⋅1N=α\alpha \cdot N \cdot \frac{1}{N} = \alpha

for any number of experts, from 8 to 2048. That value, α\alpha, is also the minimum. Because ff and PP come from the same router outputs, pushing tokens onto one expert raises both its fjf_j and its PjP_j, so their product grows; at full collapse onto one expert the loss is αN\alpha N. The paper chose α=10−2\alpha = 10^{-2} after sweeping 10−110^{-1} to 10−510^{-5} in powers of ten, because it balanced load quickly without interfering with the training loss.

Drag the routing from collapsed to uniform. The loss meter at the top moves between αN\alpha N and its floor α\alpha. The red strip under the axis is αNfi\alpha N f_i, the gradient on each PiP_i, largest for the busiest expert.

Figure 4 · the load-balancing loss
imbalanced
Six experts, α=0.01\alpha = 0.01. Amber bars are the hard dispatch fractions fif_i, teal bars the mean router probabilities PiP_i, and the dashed line is 1/N1/N. The loss falls to α\alpha (not zero) when both are uniform and rises toward αN=0.06\alpha N = 0.06 as routing collapses. ff is a count with no gradient; the router is trained only through PP.

In code, for one layer:

# auxiliary load-balancing loss for one Switch layer, eq (4)
f   = one_hot(expert, N).mean(axis=0)  # [N] fraction of tokens sent to i, eq (5)
P   = p.mean(axis=0)                    # [N] mean router probability, eq (6)
aux = alpha * N * (f * P).sum()         # alpha = 1e-2; equals alpha when uniform
# f comes from argmax and is a constant to autodiff; every gradient goes through P.
# total loss = language-model loss + sum of aux over all Switch layers

The released mesh-tensorflow code writes the same quantity as the mean of P⋅fP \cdot f times N2N^2. The mean divides by NN, which leaves N∑fiPiN \sum f_i P_i: equation (4) without the factor α\alpha.

Expert capacity and dropped tokens

The number of tokens that pick a given expert changes from batch to batch. The TPUs this work ran on need every tensor shape fixed when the program is compiled, so each expert gets a fixed number of slots, its expert capacity:

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}expert capacity=(tokens per batchnumber of experts)×capacity factor\begin{aligned} \text{expert capacity} &= \left(\frac{\text{tokens per batch}}{\text{number of experts}}\right) \\ &\quad \times \text{capacity factor} \end{aligned}
(3)

The fraction is each expert's share under perfectly even routing. The capacity factor scales it. With 4,096 tokens, 128 experts and a factor of 1.25, each expert has 4096 / 128 × 1.25 = 40 slots, and the tensor shipped to the experts has shape [128 experts, 40 slots, 768]: 5,120 slots for 4,096 tokens, so at least 1,024 slots are padding even when routing is perfectly even. At a factor of 1.0 each expert has 32 slots, and an expert that 35 tokens choose processes 32 of them.

The other 3 tokens overflow. An overflowed token skips the expert: its combine weight is 0, so the FFN contributes nothing, and the token's representation continues to the next layer unchanged through the residual connection around the sublayer. It misses one FFN update in one layer and stays in the sequence. Switch takes this protocol from GShard. Unused slots are padding, memory and FLOPs spent on zeros. Raising the factor trades overflow for padding, and padding also enlarges the all-to-all communication between devices.

Drag both sliders. With skewed routing and a factor of 1.0, red tokens overflow the busiest expert; raise the factor and the overflow disappears while dashed empty slots appear in the quiet experts.

Figure 5 · expert capacity
1.00×
skewed
Twelve tokens, four experts, so an even share is 3. Each expert has a fixed column of capacity slots. Filled slots are processed tokens; dashed slots are padding; red tokens overflow, skip the expert and pass on through the residual connection. The capacity factor sets the column height; the skew slider piles tokens onto expert 1.

With the load-balancing loss in place, the paper reports that the fraction of dropped tokens is typically under 1 percent and does not depend on the number of experts. That makes small factors affordable, and Table 1 (128 experts, 32 TPUv3 cores) shows they are the best choice. The time to reach a negative log perplexity of −1.50 (higher, meaning less negative, is better) is 72.8 hours for Switch-Base at factor 2.0, 65.0 hours at 1.25, and 62.8 hours at 1.0, the fastest of all models in the table, at 1,000 examples per second. T5-Base did not reach −1.50 within the 100k steps trained, and T5-Large took 131.1 hours. The paper notes that small factors matter most for large models, where accelerator memory is the scarcest resource.

The authors also tried rerouting overflowed tokens to their second-choice expert ("No-Token-Left-Behind", Appendix B). It nearly eliminated drops and gave no measurable improvement; their guess is that sending a token to an expert it was not associated with does more harm than skipping one FFN.

Precision, initialization and dropout

Hard routing at every Switch layer makes large sparse models prone to unstable training. The paper uses three changes, and the first two improve quality and stability together.

Selective precision. Large models train in bfloat16, a 16-bit format, to halve memory and communication. Training a 32-expert Switch-Base entirely in bfloat16 diverged (Table 2: negative log perplexity −3.780). bfloat16 keeps float32's 8 exponent bits, so it covers the same range and nothing overflows, and the softmax subtracts its maximum before exponentiating in any case. What it gives up is precision: 7 mantissa bits instead of 23, so neighbouring representable numbers are 2162^{16} (about 65,000) times further apart. Near a logit of 10, bfloat16 can only represent steps of 0.0625. The paper says only that bfloat16 "can exacerbate issues in the softmax computation" of the router; the rounding is the likely mechanism, since the exponentials amplify logit errors and the argmax flips on small differences. The fix runs only the router's local computation in float32 and casts the dispatch and combine tensors back to bfloat16 before the all-to-all, so no float32 tensor crosses devices. The result reached −1.716, matching float32's −1.718, at bfloat16's 1,390 examples per second against float32's 1,160.

Smaller initialization. Weights are drawn from a normal distribution with mean 0 and standard deviation

σ=s/n\sigma = \sqrt{s / n}

truncated so that values beyond two standard deviations are redrawn, where nn is the number of inputs to the weight matrix (its fan-in) and ss is a scale. The paper lowers ss from the usual 1.0 to 0.1, which divides σ\sigma by 10≈3.16\sqrt{10} \approx 3.16. For a 768-input matrix, σ\sigma drops from 0.036 to 0.011. Table 3 runs a 32-expert model for 3.5k steps with three seeds: the 0.1 scale averages −2.72 with a standard deviation of 0.01 across seeds; the 1.0 scale averages −3.60 with a standard deviation of 0.68. The same initialization trained every model from the 223M baseline to over a trillion parameters.

Expert dropout. Fine-tuning datasets are small, and a model with many more parameters than its dense counterpart overfits them faster. Each expert also sees only the tokens routed to it. The paper keeps the standard dropout rate of 0.1 in the non-expert layers and raises it to 0.4 only on the intermediate activations inside each expert's FFN; no expert is ever switched off as a whole. On GLUE (Table 4), T5-Base scores 82.9, Switch-Base with dropout 0.1 everywhere 84.7, with 0.2 everywhere 84.4, with 0.3 everywhere 83.9, and with 0.1 outside the experts and 0.4 inside 85.2.

Appendix C adds a fourth detail. The routing decision gets no training signal about how the token would have done with another expert, so the authors tried adding exploration: sampling from the softmax (−1.570), dropout on the router input (−1.480), and multiplicative jitter noise on the router input (−1.468), against −1.471 for plain argmax, and kept the jitter for all their models.

More experts at the same compute

Kaplan and collaborators scaled language models along parameters, data and compute together. Switch adds the expert count as a separate axis: at a fixed FLOPs per token, more experts mean more parameters. The paper's Figure 4 trains Switch-Base with 1, 2, 4, up to 256 experts for the same number of steps and reports the test loss. Each doubling of the expert count lowered the loss, with smaller gains at the high end: about 0.2 per doubling from 4 to 16 experts, 0.07 from 128 to 256.

Figure 6 · the expert-count sweep
64
Test loss against parameter count for Switch-Base with 1 to 256 experts, all with the same FLOPs per token and the same number of training steps. Loss values are read off the paper's Figure 4 (left), to about ±0.01; parameter counts follow 223M + (E − 1) × 56.6M. Drag the slider or click a point.

The same data measured as a speedup: the 64-expert Switch-Base reached at step 60k the quality T5-Base reached at step 450k, 7.5 times fewer steps. A Switch step takes longer than a dense step with the same FLOPs, because it also computes the routing and moves tokens between devices. Measured by wall-clock time on 32 TPUv3 cores (the paper's Figure 5), the 64-expert model reached T5-Base's quality in one-seventh of the time. Against T5-Large, which spends 3.5 times the FLOPs per token, Switch-Base was still 2.5 times faster in wall-clock time (the paper's Figure 6).

Figure 7 · three measured speedups
The 64-expert Switch-Base against a dense baseline. The curve shapes are schematic; the crossing points are the paper's measurements: 60k against 450k steps (7.5x), one-seventh of the wall-clock time of T5-Base (7x), and 2.5x faster than T5-Large. Pick a comparison with the buttons.

The gains carry into fine-tuning. The FLOP-matched Switch models, pre-trained for 550k steps at 2202^{20} tokens per batch (576 billion tokens), improve SuperGLUE by 4.4 points over T5-Base and 2 points over T5-Large, with large gains on Winogrande, closed-book TriviaQA and XSum. The only tasks without gains are the ARC reasoning sets, where T5-Base beats Switch-Base on ARC Challenge and T5-Large beats Switch-Large on ARC Easy. On multilingual pre-training over 101 languages, mSwitch-Base improves on mT5-Base in all 101, with a mean step speedup of 5 times; 91 percent of languages get at least 4 times.

Reaching a trillion parameters

A trillion parameters have to be split across many accelerator cores, and there are three ways to split, which combine. Data parallelism gives each core a full copy of the weights and a different slice of the batch, and averages gradients once per step. Model parallelism, the approach of Megatron-LM, splits each weight matrix across cores, which must exchange partial results inside every layer. Expert parallelism places different experts on different cores; each Switch layer then needs an all-to-all exchange that sends every token to the core holding its expert and brings the result back. Experts are independent of each other, so they split cleanly. (In Section 5 of the paper, NN denotes the total number of cores, not the number of experts.)

The paper builds two large models that use the budget differently. Switch-C has 1,571 billion parameters: 15 layers, 2,048 experts at every layer, dmodel=2080d_{\text{model}} = 2080, built with expert parallelism only and no model parallelism, so its width and number of attention heads are much smaller than T5-XXL's. Switch-XXL has 395 billion parameters, 64 experts at every other layer, and T5-XXL's dimensions (dmodel=4096d_{\text{model}} = 4096); it combines data, model and expert parallelism and is FLOP-matched to T5-XXL at 6.3 trillion FLOPs per sequence. That is 7.1 times Switch-C's 890 billion.

In the figure, each model from the paper's Table 9 sits at its parameter count and FLOPs per sequence. Each Switch model sits directly to the right of the dense model it is FLOP-matched to. Select Switch-C, then Switch-XXL, and compare their quality readouts.

Figure 8 · parameters and compute in Table 9
Switch-C
Dense T5 and Switch models on log axes of parameters and FLOPs per sequence. Dashed lines join FLOP-matched pairs. The readout gives the negative log perplexity on C4 after 250k and 500k steps (less negative is better). Drag the slider or click a point.

Both large models beat T5-XXL. After 250k steps each improves on T5-XXL's negative log perplexity by more than 0.061; T5-XXL needed another 250k steps to improve by 0.052. After 500k steps Switch-XXL leads T5-XXL by 0.087 (−1.008 against −1.095), and Switch-C reaches a fixed perplexity about 4 times faster than T5-XXL.

Switch-XXL, with a quarter of Switch-C's parameters (395B against 1,571B, a ratio of 3.98), is the better model. Per step it beats Switch-C (−1.008 against −1.043 at 500k), and after fine-tuning it scores 89.6 exact match on SQuAD against Switch-C's 87.7. Stability favoured Switch-C: it trained with no instability at all, while Switch-XXL, the model with 7.1 times the FLOPs per sequence and the wider layers, was sometimes unstable even with the techniques above. The paper reports this as an observation and offers no mechanism.

Distilling the sparse model back to dense

Serving a sparse model means holding every expert in memory and running the all-to-all for every request. The paper therefore distills trained Switch models into the dense T5-Base: the small student is trained to match the large teacher's output distribution as well as the true labels.

Two changes made it work (Table 6, a 3.8B-parameter Switch-Base teacher at −1.444 and the 223M T5-Base student at −1.636). Distillation alone recovered 3 percent of the gap (−1.631). Initializing the student with the teacher's non-expert weights raised that to 20 percent (−1.598); this is possible because FLOP-matched models give the non-expert layers the same dimensions, so those weights copy over directly. Initialization without distillation gave no gain (−1.639). Weighting the loss 0.75 on the ground-truth labels and 0.25 on the teacher's probabilities raised it to 29 percent (−1.580). Hinton and collaborators got their best results with a considerably lower weight on the hard labels, the opposite balance.

The percentage is the fraction of the quality gap between the dense baseline and the sparse teacher that the student closes: 0 percent means the student is no better than a T5-Base trained normally, 100 percent means it matches the teacher. For the 3.8B teacher, (−1.580 + 1.636) / (−1.444 + 1.636) = 0.056 / 0.192 ≈ 0.29, the 29 percent in Table 6 (the paper's text rounds it to 30). Drag the teacher size: larger teachers widen the gap, and the student keeps a similar share of it.

Figure 9 · how much of the gap distillation keeps
3.8B
Table 7: Switch-Base teachers of 1.1B to 14.7B parameters distilled into the same 223M T5-Base with the best recipe. The amber box is the gap from T5-Base to the teacher; the teal fill is how far the student gets. Faint ticks mark the other teachers.

Compressing the 1.1B teacher by 82 percent kept 37 percent of its gain; compressing the 14.7B teacher by 99 percent kept 28 percent. Distilling a 7.4B Switch-Base fine-tuned on SuperGLUE into T5-Base gave 76.6, against 74.6 for T5-Base and 81.3 for the teacher, again 30 percent of the gap. In practice: train the sparse model for its sample efficiency, then ship a dense model of the original size that keeps a third or so of the improvement.

Provenance Verified against primary literatureHow we verify
Shazeer et al. (2017)The sparsely-gated mixture-of-experts layer: G(x) = Softmax(KeepTopK(H(x), k)), with every logit outside the top k set to -infinity before the softmax. Source of the conjecture that k > 1 is needed for the router to get a gradient.
Lepikhin et al. (2020), GShardExpert capacity and the overflow protocol Switch follows: a token over capacity skips the expert and continues on the residual connection. GShard trained its MoE in float32 throughout.
Raffel et al. (2019), T5 and mesh-tensorflowThe dense baselines, the C4 corpus, and the sharding library. In mesh_tensorflow/transformer/moe.py the load-balancing loss is the mean of P times f multiplied by experts squared (line 948), which equals Eq. (4) divided by alpha, and router noise is multiplicative jitter on the router input (lines 903-905).
Switch paper, App. C and Fig. 15The appendix text and Table 11 use multiplicative jitter on the incoming representation (best of four: -1.468); the Fig. 15 pseudo-code instead adds uniform noise to the router logits. This page follows the text and the released code.
Switch paper, Tables 6-7The Table 6 caption says the teacher has "100x more parameters"; 3,800M / 223M is about 17x (the text says about 1/20th). Table 7 prints compression of 82/90/95% for the 1.1B/2.0B/3.8B teachers, slightly above 1 - 223M/teacher (80/89/94%). This page quotes the printed numbers.
Hinton, Vinyals & Dean (2015)Knowledge distillation with soft targets. They got their best results with a considerably lower weight on the hard-label term; Switch weights it 0.75 against 0.25 for the teacher.
correctionShazeer et al. (2017) conjectured that routing each token to k > 1 experts is needed for the router to receive a useful gradient. That holds for their gating, which masks every logit outside the top k to -infinity before the softmax: at k = 1 the one surviving logit normalizes to exactly 1, a constant with zero derivative. Switch takes the softmax over all N experts first and the argmax second, so the kept gate is a probability below 1 whose derivative is p(1 - p), and k = 1 trains. Separately, the paper twice says Switch-XXL uses "nearly 10x" or "about 10x" the FLOPs of Switch-C; its own Table 9 gives 6.3T / 890B = 7.1x, which this page uses.

Questions you might still have

?

If only one expert runs per token, why does storing the others cost anything at inference?
Different tokens in a batch pick different experts, so across a batch every expert gets used and all of them must sit in accelerator memory. Sparsity cuts the FLOPs per token, not the memory footprint: the 64-expert Switch-Base needs 3.8B parameters in memory to do the per-token work of the 223M T5-Base. That is why the paper distills trained sparse models into dense ones for deployment.

?

Is the router trained with a special estimator because argmax is not differentiable?
No. It is trained by ordinary backpropagation. The gradient never passes through the argmax. The chosen expert's output is multiplied by its gate value, so the loss depends smoothly on that gate value, and the softmax passes that dependence back to every router logit and to the router weights.

?

Does a capacity factor of 1.0 mean no tokens are dropped?
No. A factor of 1.0 gives each expert exactly its even share of seats, and real routing is never exactly even, so the most popular expert overflows by a few tokens. With the load-balancing loss the paper reports drops are typically under 1 percent, and it still found the best speed-quality results at factors 1.0 and 1.25.

?

Why does the load-balancing loss multiply by N?
Under perfectly even routing each f_i and P_i is 1/N, so the sum of f_i times P_i is N times 1/N squared, which is 1/N. Multiplying by N makes the balanced value exactly alpha whether the layer has 8 experts or 2048, so one alpha (0.01) works across model sizes.

?

Is the 1.6-trillion-parameter Switch-C the best model in the paper?
No. The 395-billion-parameter Switch-XXL, which spends 7.1 times more FLOPs per sequence, reaches a better perplexity at the same step (-1.008 against -1.043 after 500k steps) and scores 89.6 on SQuAD against 87.7 for Switch-C. Switch-C was the one that trained without any instability.

?

How does this relate to Mixtral and other MoE models in use today?
Mixtral 8x7B (2024) routes each token to 2 of 8 experts per layer with G(x) = Softmax(TopK(x W_g)), which is Shazeer's mask-then-softmax order at k = 2. With two survivors the softmax gives each a weight that depends on the difference of their logits, so the router has a gradient without the Switch ordering.

Footnotes & further reading

  1. The paper: Fedus, Zoph, Shazeer, Switch Transformers: Scaling to Trillion Parameter Models with Simple and Efficient Sparsity (Google, JMLR 23, 2022). JAX code and the mesh-tensorflow router.
  2. The layer Switch simplifies: Shazeer et al., Outrageously Large Neural Networks: The Sparsely-Gated Mixture-of-Experts Layer (2017, arXiv), where the k ≥ 2 conjecture originates.
  3. Capacity and the overflow protocol: Lepikhin et al., GShard (2020).
  4. The dense backbone and the C4 corpus: Raffel et al., T5; the scaling framing of Kaplan et al. (2020).
  5. Other trillion-parameter-era infrastructure: Megatron-LM (model parallelism) and ZeRO (partitioned optimizer state).
  6. Distillation: Hinton, Vinyals & Dean, Distilling the Knowledge in a Neural Network (2015).
  7. A later top-2 MoE with mask-then-softmax gating: Jiang et al., Mixtral of Experts (2024).