Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path →
Switch Transformer,
explained.
Mixture-of-experts promised something almost too good — a model with vastly more parameters that costs no more to run per token, because only a slice of it fires each time. But it was fiddly and unstable, and few could scale it. The Switch Transformer made it work by doing less: send each token to just one expert. That single simplification, plus two careful tricks to keep it balanced, carried the design to a trillion parameters. Here's the routing, and the math that keeps it honest.
What changes against top-k routing: one expert per token
Rung 1 sends each token to several experts and combines their outputs, on the argument that the gate needs a comparison to learn from. This rung's change is to send each token to exactly one, and to show that the argument was wrong.
Everything gets simpler at once, and the savings compound rather than adding: one expert's arithmetic per token instead of two or more, one set of activations to route rather than several, and — the part that dominates at scale — each token crosses the network to one destination, so the communication volume the routing generates is cut proportionally. Simplicity here is not elegance, it is the difference between a mechanism that scales across a large cluster and one that does not.
Two pieces of bookkeeping make top-1 safe, and both are worth knowing because they are where MoE models actually misbehave. Expert capacity caps how many tokens any one expert will accept in a batch, so a popular expert cannot stall everything behind it. And when that cap is hit, the excess tokens are dropped — they skip the expert layer entirely and pass through the residual connection unmodified. That is a real and slightly alarming property to hold on to: in a production MoE, some tokens receive less computation than others, determined by what else happened to be in the batch. The capacity factor is the dial trading wasted compute against how often that happens. Stated in units, this is the configuration that took the family past a trillion total parameters while keeping per-token compute tractable.
The MoE promise
A mixture of experts replaces a transformer's single feed-forward layer with many parallel ones — the experts — and a small router that decides which expert each token should use. The payoff is sparse activation: the model can carry an enormous number of parameters, but each token only touches a few of them, so the compute per token barely rises. Capacity grows without the usual proportional cost in FLOPs.
The catch, before this paper, was that MoE was hard to train. Routing to two or more experts per token added complexity and communication overhead, gradients were noisy, and — worst of all — routers collapsed, funneling most tokens to a handful of favored experts while the rest sat idle. Switch Transformer's contribution was to make MoE simple and stable enough to scale reliably, and its central move was counterintuitive: route less, not more.
Give each token exactly one expert, add a loss that keeps experts evenly used and a capacity limit that keeps them balanced — and mixture-of-experts finally scales.
Top-1 routing
Earlier MoE work insisted you needed at least two experts per token — the belief was that routing needed a comparison to produce useful gradients. Switch Transformer challenged that and used top-1 routing: the router scores the experts for a token, and the token goes to the single highest-scoring one. Nothing else.
The simplification pays off three ways. Routing computation halves or better. The all-to-all communication that shuffles tokens to their experts across devices shrinks. And the implementation gets dramatically cleaner — one expert per token means fixed, predictable tensor shapes. The router still produces a probability for the chosen expert, which is used to weight the expert's output so gradients flow back to the router. Less machinery, same learning signal.
The balancing loss
Left to itself, a router develops favorites — a rich-get-richer loop where a few experts get most tokens, train faster, and get chosen even more, while the rest waste their parameters. Switch counters this with a load-balancing auxiliary loss, added to the training objective, that is minimized only when tokens spread evenly across experts. With N experts, fi the fraction of tokens routed to expert i, and Pi the router's mean probability for expert i:
The product fi·Pi couples how many tokens an expert actually gets to how confident the router is about it, and the sum is smallest when both are spread uniformly (each 1/N), giving N·N·(1/N)² = 1. Pile everything onto one expert and it climbs toward N. Because it is differentiable through Pi, minimizing it during training actively pushes the router toward even utilization. The runnable version below computes it for balanced and skewed loads.
Capacity and dropping
The balancing loss is a soft nudge; hardware needs a hard guarantee. On real accelerators every expert must be given a fixed-size buffer, so Switch sets an expert capacity — the maximum tokens one expert will process in a batch — as tokens-per-expert times a tunable capacity factor:
If routing still sends an expert more tokens than its capacity, the overflow tokens are dropped — they skip the expert entirely and pass through unchanged via the residual connection. A capacity factor above 1 adds slack to reduce dropping, at the cost of wasted compute on padding; below 1 saves compute but drops more. It is the explicit lever that trades a little accuracy for guaranteed, hardware-friendly balance.
How a Switch layer routes, trains and scales, step by step
Fedus, Zoph and Shazeer build the Switch Transformer on T5, the text-to-text encoder-decoder, and change only the feed-forward layers. A token's trip through the model and through training looks like this.
- Replace feed-forward layers with Switch layers. In most configurations every other feed-forward block becomes a Switch layer: N expert feed-forward networks plus a router. Attention and everything else stay dense.
- Route in float32. The router multiplies each token's representation by Wr, applies a softmax over experts, and sends the token to the single highest-probability expert. The model runs in bfloat16, but the router's input is cast to float32 inside the router and the result cast back before dispatch. A routing decision rests on small differences between scores, and the exponentials in the softmax amplify rounding error; the paper calls this fix selective precision.
- Allocate fixed buffers. Each expert gets capacity = (tokens per batch ÷ experts) × capacity factor slots. Accelerators need static tensor shapes, so the buffer size is fixed before anyone knows how tokens will route.
- Dispatch, drop, compute, return. An all-to-all exchange sends tokens to the devices holding their experts. Tokens beyond an expert's capacity are dropped: they skip the expert and continue on the residual connection. Each expert's output is multiplied by its router probability before it returns, and that multiplication is the path by which the router receives gradient.
- Balance with an auxiliary loss. Add α·N·Σ fi·Pi with α = 10^−2, where fi is the fraction of tokens sent to expert i and Pi the mean router probability for it.
- Initialize small. Weights are drawn from a truncated normal with standard deviation √(s/n), n being the fan-in, and the scale s is cut from T5's 1.0 to 0.1. The authors found this improved quality and sharply reduced variation between runs.
- Pre-train like T5. The same C4 corpus and span-corruption objective, against T5 baselines with the same FLOPs per token, so any gain is bought with parameters rather than compute.
- Fine-tune with expert dropout. A sparse model has a huge parameter count relative to a small fine-tuning set, so it overfits. The paper uses a dropout rate of 0.1 in the non-expert layers and 0.4 inside the experts.
- Lay the model out across devices. Data parallelism splits the batch, model parallelism splits each weight matrix across cores, and expert parallelism puts different experts on different cores. Switch-C, 1.6T parameters with 2,048 experts, uses only data and expert parallelism, which keeps its computation per token small; Switch-XXL, 395B parameters with 64 experts, combines all three to match the FLOPs per token of T5-XXL.
Why one expert is enough
The earlier argument for top-2 was that a router needs to compare experts to learn. The Switch layer still gives it a signal, because the chosen expert's output is scaled by its own probability: if the choice helped, the gradient raises that probability, and if it hurt, it lowers it. In exchange, top-1 halves the expert computation of top-2, roughly halves the tokens crossing the network, and lets each expert's buffer be smaller.
The router, the gated output and the total loss
Wr— the router weights;h(x)— one logit per expert;N— the number of experts.i*— the single chosen expert. The token's output is that expert's output times its own router probability. Without that factor the argmax would be a dead end for gradients; with it, the router learns whether boosting the chosen expert lowered the loss.fi— the fraction of the batch's tokens dispatched to expert i, a count with no gradient;Pi— the mean of pi over the batch, which is differentiable, so the balancing gradient flows only through Pi.α— small enough not to swamp the language-model loss LLM, large enough to keep routing even.
At the extremes: with perfectly uniform routing every fi and Pi is 1/N and the auxiliary term equals α. If one expert took every token with probability near 1, it would approach α·N. Capacity adds a hard limit on top of this soft one: with a capacity factor of 1.0 and uneven routing, some tokens are dropped no matter what the loss says.
What the Switch experiments measured
Every comparison holds FLOPs per token fixed against a T5 model, so the added parameters are the only change. Pre-training is on C4 with span corruption, and quality is measured as negative log perplexity.
| Comparison | Result |
|---|---|
| Switch-Base, 64 experts, against T5-Base | Reaches T5-Base's final quality at step 60k instead of 450k, 7.5× fewer steps; up to 7× faster in wall-clock time |
| Number of experts at fixed FLOPs | Quality keeps improving as experts are added, the most efficient axis tested |
| Top-1 Switch against top-2 MoE at the same FLOPs | Switch better on a speed-quality basis, especially at low capacity factors of 1.0 to 1.25 |
| Multilingual: 101 languages against mT5-Base | Gains in all 101; 91% of languages at least 4× faster |
| Switch-C, 1.6T parameters, against T5-XXL | Reaches T5-XXL's pre-training quality about 4× faster |
| Distilling into a dense T5-Base | Keeps about 30% of the sparse model's quality gain |
The sample-efficiency result is the headline: up to about 7× faster to a target quality than a dense model at equal compute. Selective precision did what it was meant to: in the paper's comparison, a float32 router inside a bfloat16 model trained as stably as full float32 at bfloat16 speed, while a pure bfloat16 router diverged.
Negative results and limits
Switch-XXL, at 395B parameters, suffered sporadic training instability that Switch-C did not. Fine-tuning overfit, which is why expert dropout exists. Better pre-training perplexity carried over clearly to knowledge-heavy question answering but less reliably to reasoning-heavy fine-tuning tasks. And distillation recovered only part of the gain, so sparsity cannot be cashed out into a small dense model afterwards. One historical claim needs correcting: top-1 routing made sparse training simpler, but it did not become the standard. Mixtral routes each token to 2 of 8 experts, DeepSeek-V3 to 8 of 256 routed experts plus a shared one, and many current MoEs are dropless, computing every routed token rather than dropping overflow.
What the authors admit, and what happened next
Two problems are reported honestly and both proved durable. Training instability: sparse models diverge more readily than dense ones at scale, and part of the mitigation is numerical — keeping the router's own arithmetic in higher precision than the rest of the model, because a routing decision is a discrete choice made from a small difference and is therefore unusually sensitive to rounding. And fine-tuning overfits more easily than the dense equivalent, which is intuitive once stated: a very large parameter count fine-tuned on a small task dataset has a lot of capacity to memorise with.
The paper also explores distilling a sparse model back down to a dense one and reports recovering only part of the gain — an honest negative result that delimits the claim. Sparsity is not a free lunch you can cash out into a small dense model afterwards.
How it held up: top-1 routing did not become the default. Most current mixture-of-experts models send each token to several experts — Mixtral to two of eight, DeepSeek-V3 to eight routed experts plus a shared one — and many train without dropping tokens. What survived is the case that sparse models scale at matched FLOPs, expert capacity as the unit of serving cost, and the auxiliary balancing loss, which DeepSeek-V3 then largely replaced with a bias-based, loss-free scheme. Worth noting the comparison that made the paper persuasive was at matched FLOPs rather than matched parameters — which is the correct comparison for this architecture and also the one that makes its numbers incomparable with dense-model headline figures, a confusion that persists in how MoE models are marketed.
Route, balance, and drop
The three mechanisms that make Switch work, in a handful of functions. Top-1 routing sends a token to the argmax expert; the load-balancing loss reads 1.0 at perfect balance and climbs when the load skews (2.8 here for all-to-one across four experts); expert capacity scales with the capacity factor; and tokens beyond capacity are dropped — all eight going to one expert with capacity four means four are dropped. Change the routing or the capacity factor and watch the loss and the drops respond.
Write the body of load_balance_loss. Everything else in the file is
already written; this is the function the paper is about. Press ▶ Run to check it against
the 5 assertions below — they start red.
- Top-1 routes a token to its highest-scoring expert
- Load-balance loss is 1.0 at perfect balance
- Load-balance loss penalizes imbalance
- Capacity scales with the capacity factor
- Tokens over capacity are dropped
Scaling to a trillion
With routing simplified and stabilized, the numbers got large. The Switch Transformer scaled to 1.6 trillion parameters — a headline figure at the time — while keeping the compute per token comparable to a far smaller dense model, because only one expert fires per token. That is the whole point of sparsity made concrete: parameters and FLOPs, usually chained together, come apart.
| Dimension | Switch behavior |
|---|---|
| Parameters | Grow with the number of experts — into the trillions. |
| Compute per token | Roughly constant — one expert runs, whatever the expert count. |
| Sample efficiency | Reached a target quality up to ~7× faster than a dense model at equal compute, in the paper's results. |
| Memory / comms | The real cost — experts must live in memory and tokens shuffle between devices. |
The trade is honest: you pay in memory and cross-device communication for parameters you activate only sparsely. But for large-scale training, spending memory to buy quality-per-FLOP was exactly the right exchange — and it reframed how people thought about scaling.
Why it mattered
Switch Transformer took mixture-of-experts from a finicky research idea to a scalable, practical technique, and the modern MoE models that followed — from open trillion-scale releases to the sparse layers rumored inside frontier systems — build on its ideas: sparse routing to a few experts, an auxiliary balancing loss, and capacity limits. Its specific choices have been revised since — many newer systems route to more than one expert, and some drop the auxiliary loss, but the skeleton is the same.
Its lasting idea is the decoupling itself. For years, "bigger model" meant "more compute," full stop. Sparse expert routing broke that identity, letting parameter count and per-token compute scale on separate dials. That is why mixture-of-experts is now a central tool for building very large models economically — and Switch Transformer is the paper that made the tool dependable.
The capacity factor is a live production knob: raise it and fewer tokens are dropped (better quality, more wasted compute on padding); lower it and you save compute at some accuracy cost. Balancing that trade is part of tuning any MoE deployment.
Questions people ask about Switch Transformer
What capacity factor does the Switch Transformer use?
Expert capacity is the number of tokens each expert can accept per batch: tokens per batch divided by the number of experts, multiplied by the capacity factor. The Switch paper studied factors of 1.0, 1.25 and 2.0 and found that Switch layers work well at low factors, around 1.0 to 1.25, which keeps the computation wasted on empty buffer slots small. A token routed to an expert that is already full is dropped from that layer: it skips the expert and passes through unchanged on the residual connection. Raising the factor drops fewer tokens but pads more; lowering it saves memory and compute but drops more. Dropless implementations later removed the trade-off by computing every routed token.
Does the Switch Transformer use a router z-loss?
No. The router z-loss was introduced in ST-MoE (Zoph and colleagues, 2022), a follow-up whose authors include William Fedus and Noam Shazeer. It adds a small penalty on the squared log of the sum of exponentiated router logits, which keeps the logits small and makes the router's softmax less sensitive to rounding error. The Switch Transformer handled router instability differently: it computed the router in float32 inside an otherwise bfloat16 model, which the paper calls selective precision, and it shrank the initialization scale to a tenth of T5's. ST-MoE reported that the z-loss stabilized training without the quality loss of some other fixes it tried.
Is top-1 routing still the standard for mixture-of-experts models?
No. The Switch Transformer showed in 2021 that sending each token to a single expert trains well and simplifies the system, and that result held up. But most recent large mixture-of-experts models route each token to more than one expert: Mixtral uses 2 of 8 experts per layer, and DeepSeek-V3 uses 8 of 256 routed experts plus one shared expert that every token passes through. Many also avoid dropping tokens altogether, using dropless kernels or balancing schemes so that every routed token is computed. Top-1 is a valid point on the trade-off between compute per token and quality, not the default.
Why does the Switch router need float32 precision?
Because routing is a discrete choice made from small differences between expert scores, passed through a softmax whose exponentials magnify rounding errors. In bfloat16, those errors were enough to make large sparse models diverge. The Switch paper's fix is selective precision: cast the router's input to float32 inside the router, compute the softmax and the routing decision there, and cast the result back to bfloat16 before dispatching tokens. Only the small router computation pays the float32 cost, and no float32 tensors are sent between devices, so in the paper's comparison the model kept bfloat16 speed while training as stably as a float32 model.
Why do Switch Transformers overfit during fine-tuning, and what is expert dropout?
A Switch model has many times the parameters of a dense model with the same compute per token, while fine-tuning datasets are small, so there is a lot of capacity available to memorize them. The authors' remedy is expert dropout: a dropout rate of 0.1 in the shared, non-expert layers and a much higher rate of 0.4 inside the expert feed-forward layers. That regularizes the parameters responsible for the overfitting while leaving the rest of the network alone, and it improved results on the fine-tuning benchmarks compared with using one dropout rate everywhere. It is one of several training adjustments the paper needed to make sparse models behave.
4 questions to test what you just read
Work each one out before you open it — a number, a prediction or a reason, not a definition. Producing the answer is what makes it stick. Your progress is kept on this device.
A batch has 4,096 tokens, 64 experts and a capacity factor of 1.25. How many slots does each expert get, and what fraction of all slots is padding if routing is perfectly even?
Show answer
4,096 / 64 = 64 tokens per expert, × 1.25 = 80 slots. Perfectly even routing fills 64 of every 80, so 20% of the slots are padding, the price of slack for uneven batches.
An expert with capacity 80 is sent 100 tokens. What happens to the extra 20, and does the model notice?
Show answer
The 20 overflow tokens skip that expert and leave the layer equal to their input, via the residual connection. Nothing errors: those tokens simply got less computation in that layer, decided by what else happened to be in the batch.
Why does the balancing gradient flow through P_i but not through f_i?
Show answer
fi counts argmax decisions, a step function with zero gradient almost everywhere. Pi averages softmax probabilities, which are smooth in Wr. Lowering Pi for an overloaded expert lowers its logits, which eventually changes the argmax and so changes fi too.
A Switch layer has 128 experts, each the size of T5-Base's feed-forward block. Roughly how many times more feed-forward parameters does it hold, and how much more feed-forward compute does each token use?
Show answer
About 128× the parameters but about 1× the compute: each token runs exactly one expert, plus a router that is a single small matrix multiply. That gap is why the paper compares at matched FLOPs, not matched parameters.
One model, many experts
Sparsity: route each token to a few experts and buy parameter count without paying for it at inference. 2017 idea, 2026 frontier default.
- 1Mixture of Experts2017
- 2Switch Transformer2022
- 3DeepSeek-V32024
- 4DeepSeek-V42026
- 5Qwen4-Coder2026
Explore the topic
See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.
More Paper Breakdowns
- Attention Is All You NeedThe paper that introduced the Transformer — the architecture underneath GPT, BERT, Claude, and Gemini. Self-attention, Query/Key/Value, multi-head attention, positional encoding, and the real BLEU results, explained in depth with analogies and animated visuals, not just equations.Read →
- BERTThe paper that made "pre-train once, fine-tune anywhere" the default for NLP. Bidirectional context, masked language modeling, next-sentence prediction, the [CLS]/[SEP] tokens, and the GLUE sweep — explained with analogies, not just equations.Read →
- Chain-of-Thought PromptingShow a model a few worked examples with their reasoning and it starts solving problems it used to fail. Why reasoning emerges only at scale, the GSM8K jump, zero-shot "Let's think step by step", and how CoT seeded modern reasoning models.Read →
- LoRAThe paper that made fine-tuning affordable. Freeze the giant pretrained model and train two tiny low-rank matrices instead — up to 10,000x fewer trainable parameters, no extra inference latency, and swappable per-task adapters. The road to QLoRA and PEFT.Read →
- Direct Preference OptimizationRLHF without the RL. Align a model to human preference pairs with one simple classification-style loss — no separate reward model, no unstable reinforcement learning. Why "your LM is secretly a reward model", and how DPO became the default alignment method.Read →
- ChinchillaThe compute-optimal scaling law that said models were too big. Parameters and training tokens should scale together — ~20 tokens per parameter — so a 70B model trained on 1.4T tokens beat the 280B giants. Why every model since trains on trillions of tokens.Read →