AI Logic

Mixture of Experts (MoE)

Expert Choice Routing

Updated:

The structure of Expert Choice routing. Left: the overall flow, which repeats a pair of a self-attention and feedforward layer and a self-attention and MoE layer. Right: the inside of the MoE layer, an example in which affinities for 6 tokens are computed with a softmax and each of 3 experts selects the 2 tokens with the highest affinity, so the number of experts used per token varies from 0 to 2

Background and overview

Expert Choice routing (assignment chosen by the experts) is an MoE routing method in which, instead of tokens choosing experts, each expert selects a fixed number of tokens with the highest affinity from the batch. It was proposed by Zhou et al. at Google in 2022 (NeurIPS 2022). The load is always balanced, and the number of experts used varies per token. Compared with the top-2 gating of GShard, pretraining converged more than twice as fast.

Earlier MoE methods (Sparsely-Gated MoE, GShard, Switch Transformer) have the token choose its top 1 or 2 experts (token choice). The paper points out three pitfalls of this approach.

  • Load imbalance: Tokens concentrate on some experts while others go unused. Adding an auxiliary loss does not guarantee balance; the paper observed that some experts were sent 20–40% more tokens than their capacity, and those excess tokens were dropped without being processed.
  • Insufficient specialization: Strengthening the auxiliary loss to balance the load tends to produce assignments that are balanced but not very effective.
  • The same computation for every token: Every token uses the same number (kk) of experts, so difficult and easy tokens receive the same amount of computation.

Expert Choice reverses the direction of choice. In hospital terms, instead of patients choosing departments, each department picks the same number of suitable patients from that day's patients. Since every department takes the same number, there is no uneven crowding, and patients with complex symptoms can be seen by several departments.

Theory

Expert Choice MoE layers replace the feedforward layer in every other Transformer layer (left side of the figure above; Section 3.4 of the paper). Each expert is a network with the same shape as an ordinary feedforward layer.

First, the number of tokens kk each expert selects (the bucket size) is determined by the following formula (Eq. (1) in the paper).

k=nΓ—cek = \frac{n \times c}{e}

nn is the number of tokens in the batch (batch size Γ— sequence length), ee is the number of experts, and cc is the capacity factor. cc represents how many experts a token is used by on average. With c=2c = 2, the total computation is the same as GShard, which selects the top 2.

The MoE layer processes the batch of tokens X∈RnΓ—dX \in \mathbb{R}^{n \times d} in the following order (Eqs. (2)–(4) in the paper).

  1. Measure affinities: Multiply by the expert embeddings WgW_g and take a softmax for each token to obtain the token–expert affinities SS.
  2. Experts select tokens: For each expert, select the top kk tokens with the highest affinity. Let II be the indices of the selected tokens, GG the corresponding affinities (gate values), and PP the one-hot version of II.
  3. Compute only the selected tokens: Each expert ii computes only the kk tokens it selected, Xin[i]X_{\text{in}}[i].
  4. Sum per token: For each token, the outputs of the experts that selected it are multiplied by the gate values and summed.
S=Softmax(Xβ‹…Wg),G,I=TopK(S⊀,k),P=Onehot(I)S = \mathrm{Softmax}(X \cdot W_g), \qquad G, I = \mathrm{TopK}(S^\top, k), \qquad P = \mathrm{Onehot}(I) Xin=Pβ‹…X,Xe[i]=GeLU(Xin[i]β‹…W1[i])β‹…W2[i]⊀X_{\text{in}} = P \cdot X, \qquad X_e[i] = \mathrm{GeLU}(X_{\text{in}}[i] \cdot W_1[i]) \cdot W_2[i]^\top Xout[l,d]=βˆ‘i,jP[i,j,l] G[i,j] Xe[i,j,d]X_{\text{out}}[l, d] = \sum_{i, j} P[i, j, l] \, G[i, j] \, X_e[i, j, d]

The softmax of S∈RnΓ—eS \in \mathbb{R}^{n \times e} is taken per token (per row), but TopK\mathrm{TopK} is taken per row of the transposed S⊀S^\top, that is, per expert, along the token dimension. This is the difference from conventional methods, which select the top experts per token. The GeLU activation function is GELU.

The right side of the figure above shows an example with 6 tokens, 3 experts, and c=1c = 1 (k=6Γ—1/3=2k = 6 \times 1 / 3 = 2). E1E_1 selects t1t_1 and t4t_4, which have high affinity, E2E_2 selects t2t_2 and t4t_4, and E3E_3 selects t3t_3 and t6t_6. As a result, t4t_4 is used by 2 experts and t5t_5 is selected by no expert. Every expert processes exactly 2 tokens, so the load is balanced.

A variant that caps the number of experts per token

The paper also tries a variant that caps at bb the number of experts that can select a single token (Section 3.3 of the paper). For the matrix A∈ReΓ—nA \in \mathbb{R}^{e \times n} representing the selection, it solves an entropy-regularized linear program.

max⁑A ⟨S⊀,A⟩+Ξ»H(A)s.t.βˆ€i:βˆ‘jβ€²A[i,jβ€²]=k,βˆ€j:βˆ‘iβ€²A[iβ€²,j]≀b,βˆ€i,j:0≀A[i,j]≀1\max_{A} \ \langle S^\top, A \rangle + \lambda H(A) \qquad \text{s.t.} \quad \forall i: \sum_{j'} A[i, j'] = k, \quad \forall j: \sum_{i'} A[i', j] \le b, \quad \forall i, j: 0 \le A[i, j] \le 1

H(A)H(A) is the sum of element-wise entropies. The paper solves this with Dykstra's algorithm (Ξ»=0.001\lambda = 0.001, up to 100 iterations) and selects the top kk from the resulting AA.

Why it works

The load is always balanced

Each expert selects exactly kk tokens. So every expert does the same amount of computation, and no tokens are dropped for exceeding capacity. No auxiliary loss is needed either; the paper's experiments do not use an auxiliary load-balancing loss. With top-2 gating, imbalanced load means waiting for the busiest expert, and a GShard step was 20% slower than Expert Choice (Section 4.2 of the paper).

Computation varies per token

The number of experts that select a given token varies from 0 to several. In the paper's 100M/64E model, most tokens were selected by 1–2 experts, 23% of tokens by 3–4, and about 3% by more than 4 (Figure 3 in the paper). The paper suggests the model learns to allocate more computation to important tokens.

To check whether this "variable number" matters, the paper compared variants with a cap on experts per token (Table 4 in the paper, average accuracy over 11 tasks).

MethodCap on experts per tokenAverage accuracy
Expert Choice (cap 2)283.2 Β± 0.4
Expert Choice (cap 3)384.0 Β± 0.4
Expert Choice (no cap)None84.0 Β± 0.2
Hash Layer (assignment by token ID)βˆ’81.3 Β± 0.1

A cap of 2 lowered accuracy by 0.8 points, while a cap of 3 matched no cap. Hash Layer, which assigns experts mechanically from token IDs, balances the load but performs worse, and the paper states that "balancing the load alone does not deliver all the benefits".

Expert Choice achieves load balance not as "a constraint imposed afterwards on token choice" but through "the direction of choice itself". BASE Layers also always balance the load, but they require solving an optimization problem, and each token uses only one expert. Expert Choice only selects the top kk, so it is computationally light and also lets the number of experts vary per token.

Experimental results

The paper pretrained on the same 1.6 trillion tokens of high-quality data as GLaM and evaluated by fine-tuning on 11 tasks selected from GLUE and SuperGLUE. The comparison was among Switch Transformer's top-1 gating (ST Top-1), GShard's top-2 gating (GS Top-2), and Expert Choice with capacity factor 2 (EC-CF2, with the same computation as GS Top-2). Models with about 100 million parameters per expert were trained with 16 to 128 experts, and an 8-billion-parameter-scale model (64 experts, 143 billion parameters in total) was also trained. The largest model was trained on 512 TPU v4 chips.

  • Pretraining converges more than twice as fast: EC-CF2 reached the same perplexity as GS Top-2 in less than half the steps. In addition, a GS Top-2 step is 20% slower, so the gap is even larger in wall-clock time (Figure 2(a) in the paper).
  • More experts is better: With expert size fixed, increasing the number of experts from 16 to 128 consistently lowered perplexity, and Expert Choice beat GS Top-2 at every count (Figure 2(b) in the paper).
  • Better even with a lower capacity factor: Even with the capacity factor reduced to 1 (the same computation as ST Top-1) or 0.5, perplexity was better than ST Top-1 (Figure 4(a) in the paper).

Average accuracy over the 11 fine-tuning tasks was as follows (Table 2 in the paper).

ModelST Top-1GS Top-2EC-CF2
100M/32E80.683.585.0
100M/64E78.482.284.0
100M/128E81.081.382.6
8B/64E88.990.392.6

(100M/32E means "32 experts of about 100 million parameters each")

EC-CF2 had the highest average at every scale, beating GS Top-2 by more than 2 points at 8B/64E. The 8B/64E EC-CF2 also beat an ordinary dense 8-billion-parameter model with about the same computation (average 89.2) by 3.4 points (Table 3 in the paper).

At the 100M scale, the model with the fewest experts, 32, gave the best results for both GS Top-2 and EC-CF2. The paper notes that better pretraining perplexity does not necessarily mean better fine-tuning performance.

Practical considerations

  • Hard to use as-is for autoregressive generation: The top-kk token selection looks at past and future tokens in the batch together. In language model inference, which generates one token at a time, future tokens do not exist yet, so it cannot be used as-is. The paper lists, as future work, gathering many sequences and selecting with tokens from the same sequence placed in different groups.
  • Selection breaks down with small batches: When the batch is very small at inference, the premise that each expert selects kk tokens also breaks down.
  • Some tokens are not selected: Tokens selected by no expert receive no computation from that MoE layer and proceed to the next layer through the residual connection only. The paper suggests that alternating MoE layers with ordinary layers mitigates this effect.
  • Memory is needed for all experts: As with other MoE methods, computation is kept down, but the number of parameters grows with the number of experts.

Expert Choice selection is determined by comparison with the other tokens in the same batch. So which experts process a given token depends on the other tokens in the batch (including future tokens, in a language model). This is rarely a problem during training and fine-tuning, but when used to generate text one token at a time, the selection method must be changed so that future information does not leak.

Comparison with other methods

Comparing Expert Choice routing with conventional methods in which tokens choose, from the same viewpoints, gives the following.

MethodWho choosesExperts used per tokenHow load is balancedDropped tokensAutoregressive generation
Switch Transformer (Top-1)Tokens1Auxiliary loss and capacityDropped when capacity is exceededWorks as-is
GShard (Top-2)TokensUp to 2Auxiliary loss and capacityDropped when capacity is exceededWorks as-is
BASE LayersSolving an assignment problem1Always balanced by a linear assignment problem (during training)None (during training)Switches to greedy assignment at inference
Expert ChoiceExperts0 or more (average cc)Each expert selects the same kk tokensUnselected tokens are possibleDifficult as-is

Rough guidelines for choosing:

  • To make pretraining and fine-tuning efficient: Expert Choice converged faster than top-1 or top-2 gating at the same computation and also gave higher fine-tuning performance. It requires no tuning of auxiliary losses.
  • For models that generate text one token at a time: Token-choice designs such as Switch Transformer, GShard, and Mixtral use the same mechanism for training and inference.
  • To spend more computation on important tokens: Expert Choice, where the number of experts varies per token, is a good fit.

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 an MoE layer with Expert Choice routing (each expert selects the top k tokens from the batch)
Each image is treated as one token. No auxiliary loss is used
"""

# Hyperparameters
batch_size = 64       # Batch size (= number of tokens n)
epochs = 5            # Number of epochs
learning_rate = 1e-3  # Learning rate
num_experts = 8       # Number of experts e
capacity_factor = 2.0 # Capacity factor c (average number of experts used per token)

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 ExpertChoiceMoE(nn.Module):
  def __init__(self, dim, hidden_dim, num_experts):
    super().__init__()
    self.num_experts = num_experts
    self.w_gate = nn.Linear(dim, num_experts, bias=False)              # W_g: expert embeddings
    self.w1 = nn.Parameter(torch.randn(num_experts, dim, hidden_dim) * 0.02)
    self.w2 = nn.Parameter(torch.randn(num_experts, dim, hidden_dim) * 0.02)

  def forward(self, x):
    n, e = x.size(0), self.num_experts
    k = max(1, int(n * capacity_factor / e))                          # k = n Γ— c / e (Eq. 1)
    k = min(k, n)

    S = F.softmax(self.w_gate(x), dim=1)                              # [n, e]: softmax over each token
    G, I = S.t().topk(k, dim=1)                                       # [e, k]: top k tokens for each expert
    P = F.one_hot(I, n).float()                                       # [e, k, n]

    x_in = torch.einsum('ekn,nd->ekd', P, x)                          # X_in = P Β· X
    h = F.gelu(torch.einsum('ekd,edh->ekh', x_in, self.w1))           # GeLU(X_in[i] Β· W1[i])
    x_e = torch.einsum('ekh,edh->ekd', h, self.w2)                    # Β· W2[i]^T
    x_out = torch.einsum('ekn,ek,ekd->nd', P, G, x_e)                 # Eq. (4): sum per token

    experts_per_token = P.sum(dim=(0, 1))                             # Number of experts that selected each token (can be 0)
    return x_out, experts_per_token


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

  def forward(self, x):
    h = self.embed(x)
    m, _ = self.moe(h)
    return self.head(h + m)  # Residual connection: for tokens selected by no expert, h passes through unchanged


model = ECClassifier().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()
    loss = criterion(model(images), labels)  # No auxiliary load-balancing loss is added
    loss.backward()
    optimizer.step()

# Evaluation: images are classified independently, so batch-level selection does not leak future information
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. What happens to tokens that no expert selects?
A.

Their output from that MoE layer is 0, and they pass to the next layer unchanged through the residual connection. In the paper's setup, MoE layers are placed in every other layer and the ordinary feedforward layers in between process all tokens, so a token not selected by one MoE layer is still processed by other layers. The paper suggests that alternating MoE layers with ordinary layers mitigates the effect of skipped tokens.

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

The paper's main experiments use c=2c = 2, which makes the average computation per token the same as GShard's top-2 gating. With c=1c = 1, the computation matches Switch Transformer's top-1; perplexity is worse than with c=2c = 2, but still better than top-1 gating. Choose based on the trade-off between computation and performance.

Q. Can it be used for text-generating models like GPT?
A.

It is hard to use as-is. Since each expert compares and selects tokens within the batch, generating one token at a time would mean comparing against future tokens that do not exist yet. The paper also leaves application to autoregressive generation as future work. For models designed for generation, token-choice designs such as Switch Transformer and Mixtral are the norm.

References

  1. Zhou, Y., Lei, T., Liu, H., Du, N., Huang, Y., Zhao, V., Dai, A., Chen, Z., Le, Q., & Laudon, J. (2022). Mixture-of-Experts with Expert Choice Routing. 36th Conference on Neural Information Processing Systems (NeurIPS 2022). arXiv:2202.09368.
  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.