AI Logic

Mixture of Experts (MoE)

Switch Transformer

Updated:

The structure of Switch Transformer. Left: the flow of the encoder, which repeats self-attention, add and normalize, a Switch FFN layer, and add and normalize. Right: the inside of the Switch FFN layer, where the router computes scores and probabilities with a softmax, selects only the single highest-probability expert, and multiplies its output by the gate value

Background and overview

Switch Transformer is a model that replaces the feedforward layers of a Transformer with mixture-of-experts (MoE) layers (Switch layers) that select just one expert per token. It was proposed by Fedus, Zoph, and Shazeer at Google in 2021 (the paper was published in JMLR in 2022). It can greatly increase the number of parameters without changing the computation per token, and with the same compute it pretrained up to 7× faster than T5-Base. The authors also trained a model with up to 1.6 trillion parameters.

Sparsely-Gated MoE and GShard showed that MoE can increase parameters, but complexity, the cost of communication between devices, and training instability stood in the way of wide adoption.

It was previously believed that "for the router (gate) to learn by comparing experts, it must select at least 2". Switch Transformer deliberately simplified this to select only one (k=1k = 1). Performance did not drop, while router computation and communication decreased and implementation became simpler. It also added techniques to stabilize training (computing only the router in 32-bit, using smaller initial values) and to prevent overfitting during fine-tuning.

As an analogy, it is a hospital where the reception desk sends each patient to just one department, such as "internal medicine". This takes less effort than sending patients to two departments and reconciling their opinions, and adding more departments (experts) does not change the effort spent per patient.

Theory

Switch Transformer replaces the Transformer's feedforward layers (FFN) with Switch FFN layers (left side of the figure above; Figure 2 in the paper). Many of the paper's models make every other FFN layer a Switch FFN layer. Each expert is a network with the same shape as an ordinary FFN, with separate weights.

A Switch FFN layer processes a single token xx in the following order (right side of the figure above).

  1. Score: Multiply by the router weights WrW_r to obtain a score (logit) for each of the NN experts, h(x)=Wr⋅xh(x) = W_r \cdot x.
  2. Convert to probabilities: A softmax gives the probability (gate value) pi(x)p_i(x) of selecting expert ii (formula below).
  3. Select just one: Select the single expert ii with the highest probability.
  4. Compute only the selected expert: The output of expert ii, Ei(x)E_i(x), is multiplied by the gate value pi(x)p_i(x) to give the output.
pi(x)=eh(x)i∑j=1Neh(x)j,y=pi(x) Ei(x)p_i(x) = \frac{e^{h(x)_i}}{\sum_{j=1}^{N} e^{h(x)_j}}, \qquad y = p_i(x) \, E_i(x)

This is the output of a top-kk MoE, y=∑i∈Tpi(x)Ei(x)y = \sum_{i \in \mathcal{T}} p_i(x) E_i(x) (T\mathcal{T} is the set of kk selected experts), with k=1k = 1. Because the selected expert's output is multiplied by the gate value pi(x)p_i(x), gradients also flow to the router, so it can learn.

Expert capacity

On TPUs, tensor shapes must be fixed at compile time. So the number of tokens each expert receives (its capacity) is set by the following formula (Eq. (3) in the paper).

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

A capacity factor greater than 1 provides slack when token assignment is unbalanced. Tokens sent beyond capacity (dropped tokens) skip that layer's computation and pass directly to the next layer through the residual connection.

Auxiliary load-balancing loss

To encourage experts to be used evenly, an auxiliary loss is added for each Switch layer (Eqs. (4)–(6) in the paper).

loss=α⋅N⋅∑i=1Nfi⋅Pi,fi=1T∑x∈B1{argmax⁡p(x)=i},Pi=1T∑x∈Bpi(x)\text{loss} = \alpha \cdot N \cdot \sum_{i=1}^{N} f_i \cdot P_i, \qquad f_i = \frac{1}{T} \sum_{x \in \mathcal{B}} \mathbb{1}\{\operatorname{argmax} p(x) = i\}, \qquad P_i = \frac{1}{T} \sum_{x \in \mathcal{B}} p_i(x)

B\mathcal{B} is a batch of TT tokens, fif_i is the fraction of tokens dispatched to expert ii, and PiP_i is the mean gate value of expert ii. fif_i is not differentiable, but PiP_i is, so the model can learn in the direction that reduces the loss. Both are minimized when they equal 1/N1/N (when balanced). Multiplying by NN keeps the loss magnitude constant as the number of experts changes. The paper tried coefficients α\alpha from 10−110^{-1} to 10−510^{-5} and uses α=10−2\alpha = 10^{-2}.

Why one is enough, and techniques for stable training

Benefits of selecting only one (Section 2.1 of the paper)

  • Less router computation: Each token needs to be sent to only one expert.
  • Capacity can be halved or more: Since each token is sent to only one expert, each expert receives fewer tokens than when tokens are sent to two.
  • Simpler implementation and less communication: Less data is exchanged between devices.

A larger capacity factor makes dropped tokens less likely, but wastes computation and memory on empty slots (Figure 3 in the paper). In the paper, with a sufficiently large auxiliary loss coefficient, dropped tokens were usually under 1%, regardless of the number of experts.

Capacity is "the number of seats per expert", and the capacity factor is "how many more seats than average to prepare". A capacity factor of 1.0 is exactly enough when tokens are assigned perfectly evenly; with any imbalance, some seats overflow. A factor of 1.25 prepares 25% more seats than average.

Techniques for stable training (Section 2.4 of the paper)

  • Compute only the router in 32-bit: Training in 16-bit bfloat16 made the router's softmax numerically unstable and training diverged. Only the computation inside the router is done in 32-bit, and the output is cast back to 16-bit for communication (the same idea as mixed precision training).
  • Use smaller initial values: Weights are initialized from a truncated normal distribution with mean 0 and standard deviation s/n\sqrt{s/n} (nn is the number of inputs). Reducing the Transformer's standard s=1.0s = 1.0 by a factor of 10 to s=0.1s = 0.1 improved performance and reduced variance across training runs.
  • Stronger dropout inside the experts: Fine-tuning data is small, so Switch Transformer, with its many parameters, is prone to overfitting. Keeping the dropout rate at 0.1 for non-expert layers and raising it to 0.4 only inside the experts gave the best results (expert dropout).
Setting (32 experts, early in training)Quality (negative log perplexity, higher is better)Speed (examples/s)
All 32-bit−1.7181160
All bfloat16−3.780 (diverged)1390
Router only in 32-bit−1.7161390

(Table 2 in the paper)

Computing only the router in 32-bit kept the stability of 32-bit while training at the same speed as bfloat16.

Experimental results

The paper pretrained T5-style models on C4, a large corpus of English web text (with a task of masking parts of sentences and predicting them). It built Switch-Base and Switch-Large with the same computation per token (FLOPs) as T5-Base and T5-Large and compared them.

Comparison with MoE (top 2) (Table 1 in the paper; all with 128 experts in every other layer, trained on 32 TPU v3 cores)

ModelCapacity factorQuality after 100k steps (↑)Time to target quality (hours, ↓)Speed (examples/s, ↑)
T5-Base−−1.731Not reached1600
T5-Large−−1.550131.1470
MoE-Base2.0−1.54768.7840
Switch-Base2.0−1.55472.8860
MoE-Base1.25−1.55980.7790
Switch-Base1.25−1.55365.0910
MoE-Base1.0−1.57280.1860
Switch-Base1.0−1.56162.81000

(Quality is negative log perplexity; higher is better. The target is −1.50.)

  • For the same time, Switch is best: Switch-Base with capacity factor 1.0 reached the target quality fastest (62.8 hours).
  • The smaller the capacity factor, the more Switch is favored: At capacity factors of 1.0 and 1.25, Switch-Base also beat MoE-Base in quality.

Comparison with ordinary Transformers

  • Up to 7× faster pretraining: Switch-Base with 64 experts reached the same quality as T5-Base in one-seventh of the time (Figure 5 in the paper). Doubling the number of experts repeatedly from 2 to 256 kept improving quality at the same computation (14.7 billion parameters at 256 experts; Figure 4 in the paper).
  • Faster than a larger model: Switch-Base trained 2.5× faster than T5-Large, which uses 3.5× more computation per token (Figure 6 in the paper).
  • Better after fine-tuning too: For example, on SuperGLUE, Switch-Base scored 79.5 (T5-Base 75.1) and Switch-Large 84.7 (T5-Large 82.7) (Table 5 in the paper). It beat T5 on most tasks, except part of ARC.
  • Better in multilingual settings too: Compared with mT5-Base on data in 101 languages, quality improved in every language, and training was 4× or more faster in 91% of languages (Section 4.3 of the paper).
  • Beyond a trillion parameters: Switch-C, with 2048 experts and 1.6 trillion parameters, reached a fixed quality 4× faster than T5-XXL with the same compute (Table 9 in the paper).

To make large models easier to use, the paper also tried transferring them to small dense models with knowledge distillation. Even with about 1/20 of the parameters, about 30% of the quality gain was preserved (Table 6 in the paper).

Practical considerations

  • Choose the capacity factor: Too small and tokens are dropped; too large and computation and memory are wasted. In the paper's comparison, Switch worked well with small values such as 1.0–1.25. Tune it while logging the fraction of dropped tokens.
  • Always include the auxiliary loss: A coefficient of α=10−2\alpha = 10^{-2} is the value that, in the paper, quickly balanced the load without interfering with the main loss.
  • Compute the router in 32-bit: Even when training in 16-bit, compute the router's softmax in 32-bit.
  • Use stronger expert dropout for fine-tuning: Increasing dropout everywhere actually hurt performance. Increase it only inside the experts.
  • Memory is needed for all parameters: Even though computation is small, the weights of all experts must be kept.

Even with Switch Transformer, the instability of training large models is not fully solved. In the paper, the 1.6-trillion-parameter Switch-C trained stably, but the 395-billion-parameter Switch-XXL, which uses about 10× more computation per token, was sometimes unstable. The paper also reports that, despite similar pretraining quality, Switch-C's exact-match score on SQuAD was 87.7, lower than Switch-XXL's 89.6, showing that the number of parameters alone does not determine fine-tuning performance.

Comparison with other methods

Comparing Switch Transformer with other MoE methods from the same viewpoints gives the following.

MethodExperts used per tokenLoad-balancing techniquesDropped tokensCharacteristics
Sparsely-Gated MoETop kk (with noise)Auxiliary losses for importance and loadDepends on implementationStarting point of sparse MoE
GShardTop 2 (second dispatched at random)Capacity, auxiliary lossYesAutomatic partitioning across many devices
Switch Transformer1Capacity, auxiliary loss αN∑fiPi\alpha N \sum f_i P_iYes (usually under 1%)Simple with little communication; techniques for stable training
BASE Layers1 (assigned evenly)Perfectly balanced by solving an assignment problemNoneNeeds neither an auxiliary loss nor a capacity factor
Expert Choice routingChosen by the experts (0 or more)Each expert selects the same number of tokensUnselected tokens are possibleComputation varies per token

Rough guidelines for choosing:

  • To build a simple, fast MoE first: Switch Transformer's "select only one" design is the simplest in both implementation and communication.
  • To combine the opinions of multiple experts per token: Top-2 designs such as GShard and Mixtral are a good fit.
  • To eliminate tuning of auxiliary losses and capacity factors: BASE Layers and Expert Choice routing balance the load structurally.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
from tqdm import tqdm

"""
Image classification task using MNIST data
The middle layer is a Switch FFN layer (one expert per token, capacity, auxiliary loss)
Each image is treated as one token
"""

# Hyperparameters
batch_size = 64        # Batch size (= number of tokens in the batch T)
epochs = 5             # Number of epochs
learning_rate = 1e-3   # Learning rate
num_experts = 8        # Number of experts N
capacity_factor = 1.25 # Capacity factor
alpha = 1e-2           # Auxiliary loss coefficient (value from the paper)

device = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'

transform = transforms.Compose([
  transforms.ToTensor(),
  transforms.Normalize((0.1307,), (0.3081,))
])
train_dataset = datasets.MNIST(root='./data', train=True, download=True, transform=transform)
test_dataset = datasets.MNIST(root='./data', train=False, download=True, transform=transform)
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=batch_size)


class SwitchFFN(nn.Module):
  def __init__(self, dim, hidden_dim, num_experts, expert_dropout=0.0):
    super().__init__()
    self.num_experts = num_experts
    self.router = nn.Linear(dim, num_experts, bias=False)  # W_r
    self.experts = nn.ModuleList([
      nn.Sequential(nn.Linear(dim, hidden_dim), nn.ReLU(), nn.Dropout(expert_dropout), nn.Linear(hidden_dim, dim))
      for _ in range(num_experts)
    ])

  def forward(self, x):
    T, N = x.size(0), self.num_experts
    capacity = max(1, int(T / N * capacity_factor))        # Capacity = (T / N) × capacity factor

    # Compute the router in 32-bit (selective precision)
    logits = self.router(x.float())                        # h(x) = W_r · x
    probs = F.softmax(logits, dim=1)                       # p_i(x)
    gate, expert_idx = probs.max(dim=1)                    # Select only the single highest (k = 1)

    # Drop tokens beyond capacity (counted in batch order)
    mask = F.one_hot(expert_idx, N).float()                # [T, N]
    position = torch.cumsum(mask, dim=0) * mask            # Position within each expert (1-based)
    kept = (position <= capacity).float() * mask

    y = torch.zeros_like(x)
    for i, expert in enumerate(self.experts):
      idx = kept[:, i].nonzero(as_tuple=True)[0]
      if idx.numel() > 0:
        y[idx] = gate[idx].unsqueeze(1).to(x.dtype) * expert(x[idx])  # y = p_i(x) E_i(x)

    # Auxiliary loss: alpha · N · Σ f_i · P_i
    f = mask.mean(dim=0)                                   # Fraction of tokens dispatched (not differentiable)
    P = probs.mean(dim=0)                                  # Mean gate value (differentiable)
    aux_loss = alpha * N * (f * P).sum()
    return y, aux_loss


class SwitchClassifier(nn.Module):
  def __init__(self, dim=128):
    super().__init__()
    self.embed = nn.Sequential(nn.Flatten(), nn.Linear(28 * 28, dim), nn.ReLU())
    self.switch = SwitchFFN(dim, hidden_dim=256, num_experts=num_experts)
    self.head = nn.Linear(dim, 10)

  def forward(self, x):
    h = self.embed(x)
    m, aux_loss = self.switch(h)
    return self.head(h + m), aux_loss  # Residual connection: for dropped tokens, h passes through unchanged


model = SwitchClassifier().to(device)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)

for epoch in tqdm(range(epochs)):
  model.train()
  for images, labels in train_loader:
    images, labels = images.to(device), labels.to(device)
    optimizer.zero_grad()
    outputs, aux_loss = model(images)
    loss = criterion(outputs, labels) + aux_loss
    loss.backward()
    optimizer.step()

model.eval()
correct = 0
total = 0
with torch.no_grad():
  for images, labels in test_loader:
    images, labels = images.to(device), labels.to(device)
    outputs, _ = model(images)
    _, predicted = torch.max(outputs, 1)
    total += labels.size(0)
    correct += (predicted == labels).sum().item()

accuracy = 100 * correct / total
print(f"Test Accuracy: {accuracy:.2f}%")

FAQ

Q. If only one expert is selected, how does the router learn?
A.

Because the selected expert's output is multiplied by the gate value pi(x)p_i(x) (the softmax probability) to form the output. pi(x)p_i(x) is differentiable with respect to the router weights, so gradients flow back from the output error. In addition, PiP_i (the mean gate value) in the auxiliary loss is differentiable, so the router also learns in the direction that balances the load.

Q. What value should the capacity factor be?
A.

In the paper's comparison (Table 1), Switch Transformer worked best with capacity factors of 1.0–1.25. The larger the model and the tighter the memory, the more one wants a smaller capacity factor. Since a smaller factor makes tokens more likely to be dropped, make the auxiliary loss coefficient large enough (the paper uses α=10−2\alpha = 10^{-2}) and tune while logging the fraction of dropped tokens.

Q. What should I watch out for at inference?
A.

Even though computation per token is small, the parameters of all experts must be kept in memory. When memory is insufficient, one option, as in the paper, is to transfer the model to a small dense model with knowledge distillation. In the paper, about 30% of the quality gain was preserved even with about 1/20 of the parameters.

References

  1. Fedus, W., Zoph, B., & Shazeer, N. (2022). Switch Transformers: Scaling to Trillion Parameter Models with Simple and Efficient Sparsity. Journal of Machine Learning Research, 23, 1–40. arXiv:2101.03961.
  2. Lepikhin, D., Lee, H., Xu, Y., Chen, D., Firat, O., Huang, Y., Krikun, M., Shazeer, N., & Chen, Z. (2020). GShard: Scaling Giant Models with Conditional Computation and Automatic Sharding. arXiv:2006.16668.