AI Logic

Mixture of Experts (MoE)

GShard

Updated:

The structure of GShard's MoE Transformer. Left: the flow of the encoder, 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, where the gate computes probabilities with a softmax, selects the top 2, decides where to dispatch based on capacity and probability, and takes the weighted sum of the outputs of the two selected experts

Background and overview

GShard is a system for replacing every other feedforward layer of a Transformer with a mixture-of-experts (MoE) layer and automatically partitioning that model across thousands of devices for training. It was proposed by Lepikhin et al. at Google in 2020. A single model translates from 100 languages into English, and the 600-billion-parameter MoE Transformer was trained on 2048 TPU v3 cores in 4 days.

The name GShard originally refers to the software for partitioning a model across devices. The work has two parts.

  • The model: Based on Sparsely-Gated MoE, a gate that selects up to 2 experts per token (top-2 gating), with additions such as a cap on how much each expert receives (capacity).
  • The partitioning system: Leaving the model code as it is, one only annotates tensors with "replicate" or "split along this dimension", and the compiler (XLA) generates a single program that runs on all devices.

Larger models perform better, but compute cost, ease of programming, and efficiency on many devices become problems. With MoE, adding experts increases the parameter count while hardly increasing the computation per token. However, the huge expert weights must be distributed across many devices, and tokens must be sent to the responsible devices. GShard made it possible to handle both together.

The form of this MoE layer (top-2 gating, capacity, auxiliary loss) became the starting point for many later MoE models, such as Switch Transformer and Mixtral.

Theory

The MoE Transformer is an ordinary Transformer encoder and decoder with every other feedforward layer replaced by an MoE layer (left side of the figure above; Figure 3 in the paper). The other layers (attention, etc.) are unchanged.

An MoE layer consists of EE feedforward networks (experts) FFN1,…,FFNE\mathrm{FFN}_1, \dots, \mathrm{FFN}_E. The output for token xsx_s is given by the following formulas (Eqs. (1)–(3) in the paper).

Gs,E=GATE(xs),FFNe(xs)=woe⋅ReLU(wie⋅xs),ys=∑e=1EGs,e⋅FFNe(xs)G_{s,E} = \mathrm{GATE}(x_s), \qquad \mathrm{FFN}_e(x_s) = wo_e \cdot \mathrm{ReLU}(wi_e \cdot x_s), \qquad y_s = \sum_{e=1}^{E} G_{s,e} \cdot \mathrm{FFN}_e(x_s)

Each expert is a two-layer fully connected network with the same shape as an ordinary Transformer feedforward layer. Most values of the gate output Gs,EG_{s,E} are 0, with at most 2 nonzero. Tokens are not sent to experts with 0, and no computation is done for them.

The gate is computed for each group (SS tokens) in the following order (Algorithm 1 in the paper).

  1. Compute probabilities: Multiply by the weights wgw_g and take a softmax to obtain the probability gs,eg_{s,e} for each token and expert.
  2. Select the top 2: Select the expert e1e_1 with the highest probability and e2e_2 with the second highest, and renormalize their probabilities g1,g2g_1, g_2 to g1/(g1+g2)g_1/(g_1+g_2) and g2/(g1+g2)g_2/(g_1+g_2) so the two sum to 1.
  3. Dispatch to the first: If the number of tokens expert e1e_1 has received is below the capacity CC, the token is dispatched with weight g1g_1.
  4. Dispatch to the second at random: Only if expert e2e_2 is below capacity CC and a draw with probability 2g22 g_2 succeeds is the token dispatched with weight g2g_2.
  5. Compute the auxiliary loss: ℓaux\ell_{\text{aux}}, which measures imbalance in expert usage, is computed and added to the training loss.

For example, if the top 2 probabilities are 0.56 and 0.24, they are divided so that the two sum to 1, giving 0.7 and 0.3 (right side of the figure above). The token is dispatched to the first expert with weight 0.7, and to the second with probability 2×0.3=0.62 \times 0.3 = 0.6 and weight 0.3.

The auxiliary loss is the following ((13) in Algorithm 1).

ℓaux=1E∑e=1EceS⋅me,me=1S∑s=1Sgs,e\ell_{\text{aux}} = \frac{1}{E} \sum_{e=1}^{E} \frac{c_e}{S} \cdot m_e, \qquad m_e = \frac{1}{S} \sum_{s=1}^{S} g_{s,e}

cec_e is the number of tokens that chose expert ee first, and mem_e is the mean probability of expert ee within the group. The training loss is the translation loss (negative log-likelihood) plus the auxiliary loss multiplied by a constant kk: L=ℓnll+k⋅ℓauxL = \ell_{\text{nll}} + k \cdot \ell_{\text{aux}}.

Load-balancing techniques and partitioning across devices

Each of the gating techniques serves two goals: "balancing the load across experts" and "enabling parallel computation on thousands of devices" (Section 2.2 of the paper).

  • Expert capacity: An upper limit is set on the number of tokens each expert processes. If a batch has NN tokens, the capacity is set to roughly N/EN/E. A token whose two selected experts have both exceeded capacity becomes an "overflowed" token, and its gate outputs are all 0. Such a token passes through the residual connection to the next layer without going through the MoE layer.
  • Local group dispatching: The tokens in a batch are split into GG groups, and the gate is computed independently (in parallel) for each group. Each group is allocated a share of each expert's capacity (2N/(G⋅E)2N/(G \cdot E)). Computing the gate sequentially, one token at a time, would leave most devices idle when there are millions of tokens and thousands of experts.
  • Auxiliary loss: If the gate always selects the same few experts, only those experts overflow and the others go unused. Ideally the mean of the squares of the fraction dispatched to each expert, ce/Sc_e/S, would be minimized, but cec_e is determined by the top-2 selection and is not differentiable. So one factor of the square is replaced by the differentiable mean probability mem_e.
  • Random routing of the second expert: Since the output is a weighted average of the selected experts, if the second weight is very small, not dispatching to it changes the output little. Dispatching to the second expert with probability proportional to its weight saves expert capacity.

Capacity can be compared to "the number of seats per restaurant". Even if customers crowd a popular restaurant (a frequently selected expert), those beyond the number of seats cannot get in. The auxiliary loss trains the host (the gate) to direct customers to less crowded restaurants too. Customers who could not get a seat (overflowed tokens) move on to the next place without eating anything (the residual connection).

Partitioning across devices

With GShard's annotations, one of the following is specified for each tensor in the model (Section 3.2 of the paper).

  • replicate: The same tensor is placed on every device. Used for weights outside the MoE layers (attention, etc.).
  • split: The tensor is split along a specified dimension, and each device holds a part. The expert weights in the MoE layers are split along the expert dimension.

In other words, the layers other than MoE use data parallelism, while the MoE layers place each expert on a different device (left side of the figure above). Where tokens are sent to the devices of their assigned experts (dispatch) and the results are returned to the original devices (combine), a communication pattern called AllToAll is used, in which each device splits its data and sends pieces to all devices. XLA's SPMD (running one program on all devices) partitioner inserts this communication automatically. Because there is only one program, compile time barely changes as the number of devices grows.

In the paper's measurements, memory per device stayed nearly constant as the number of experts grew, and scaling the model by 16× (from 128 to 2048 experts) increased the time per step by only 1.7× (Section 5 of the paper).

Experimental results

The paper evaluated on translation from 100 languages into English. It used about 13 billion parallel sentence pairs collected from the web and compared against translation models trained separately for each language (Transformers tuned per language). The amount of data varies greatly by language, from billions of pairs down to tens of thousands.

Models were compared by varying the number of experts (128, 512, or 2048 per MoE layer) and the number of layers (12 or 36, encoder and decoder combined). All were trained until they had seen 1 trillion tokens.

ModelParametersAverage BLEU over 100 languagesGain over per-language modelsTPU v3 core-yearsTraining days
MoE (2048 experts, 36 layers)600B44.3+13.522.44.0
MoE (2048 experts, 12 layers)200B41.3+10.57.51.4
MoE (512 experts, 36 layers)150B43.7+12.915.511.0
MoE (512 experts, 12 layers)50B40.0+9.24.93.5
MoE (128 experts, 36 layers)37B39.0+8.26.117.3
MoE (128 experts, 12 layers)12.5B36.7+5.91.95.4
Dense Transformer (96 layers)2.3B36.9+6.1about 235.5about 42
Per-language models (100)400M × 10030.8−−−

(From Figure 6 and Table 3 of the paper. Higher BLEU is better. Core-years are the number of cores × training time (years). The dense Transformer was trained with GPipe.)

  • Bigger translates better: The largest, 600-billion-parameter model was the best, with average BLEU 13.5 higher than the per-language models.
  • Cost grows much less than parameters: Increasing parameters 16× from 37 billion to 600 billion raised the training cost (core-years) only about 3.6×, from 6.1 to 22.4.
  • Cheaper than a large dense model: A 96-layer dense Transformer cost more than 10× as much (about 235.5 core-years) on the same 2048 cores, and its BLEU was also lower than the MoE models.
  • Diminishing returns from more experts: At 12 layers, going from 128 to 512 experts raised average BLEU by 3.3, but going from 512 to 2048 raised it by only 1.3.

The paper notes that adding experts helps especially for high-resource languages, while for low-resource languages a deep dense model that shares all parameters can be more advantageous.

Practical considerations

  • Overflowed tokens bypass the MoE layer: Tokens beyond capacity receive no expert computation in that layer. If the capacity is too small, many tokens bypass it; if it is too large, computation and memory are wasted.
  • The auxiliary loss cannot be omitted: Without it, the gate keeps selecting a few experts, their capacity overflows, and the other experts are not trained.
  • Compute the gate in parallel: Algorithm 1 is written as a loop over tokens one at a time, but in practice it is rewritten as tensor operations (einsum) and computed in parallel per group (Algorithm 2 in the paper).
  • Match the number of devices to the number of experts: For simplicity, the paper uses the same number of devices for training as there are experts (this is not required).
  • More communication: AllToAll communication to send tokens between devices is needed before and after each MoE layer. The cost of this communication grows slowly as the number of devices increases.

The paper also attempted to train an even larger 1-trillion-parameter model (2048 experts, 60 layers) with activations in bfloat16 (one of the 16-bit formats used in mixed precision training), but ran into several numerical stability problems that required manual intervention, so the results are not reported. The reported experiments were trained with both weights and activations in 32-bit floating point. The larger the MoE, the more attention training stability requires.

Comparison with other methods

Comparing GShard's MoE layer with the Sparsely-Gated MoE it was based on and with later MoE methods gives the following.

MethodExperts used per tokenLoad-balancing techniquesPlacementMain application
Sparsely-Gated MoETop kk (with noise)Auxiliary losses for importance and loadBetween LSTM layersLanguage modeling, translation
GShardTop 2 (second dispatched at random)Capacity, group-wise dispatch, auxiliary lossEvery other Transformer feedforward layerTranslation for 100 languages
Switch Transformer1Capacity, auxiliary lossTransformer feedforward layersLanguage model pretraining
Expert Choice routingExperts choose tokens (variable number)Each expert selects the same number of tokensTransformer feedforward layersLanguage model pretraining
MixtralTop 2Not described in the paperFeedforward layers of every layerLanguage model (open model)

Rough guidelines for choosing:

  • To build an MoE with experts distributed across many devices: GShard's combination of capacity, groups, and auxiliary loss is the basic form. Many MoE implementations inherit it.
  • To reduce computation and communication further: Switch Transformer, which uses only one expert per token, is a good fit.
  • To eliminate tokens that overflow and bypass the layer: Expert Choice routing, where experts choose tokens, and BASE Layers, which assign tokens evenly, balance the load structurally, so no tokens overflow capacity.

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 GShard's top-2 gating (capacity, random dispatch of the second expert, auxiliary loss)
Each image is treated as one token and each batch as one group
"""

# Hyperparameters
batch_size = 64       # Batch size (= group size S)
epochs = 5            # Number of epochs
learning_rate = 1e-3  # Learning rate
num_experts = 8       # Number of experts E
capacity_factor = 2.0 # Capacity C = capacity_factor * S / E
aux_weight = 1e-2     # Auxiliary loss coefficient k

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 Top2MoE(nn.Module):
  def __init__(self, dim, hidden_dim, num_experts):
    super().__init__()
    self.num_experts = num_experts
    # Experts: FFN_e(x) = wo_e · ReLU(wi_e · x)
    self.experts = nn.ModuleList([
      nn.Sequential(nn.Linear(dim, hidden_dim), nn.ReLU(), nn.Linear(hidden_dim, dim))
      for _ in range(num_experts)
    ])
    self.w_gate = nn.Linear(dim, num_experts, bias=False)

  def forward(self, x):
    S, E = x.size(0), self.num_experts
    C = max(1, int(capacity_factor * S / E))               # Capacity
    g = F.softmax(self.w_gate(x), dim=1)                   # [S, E]: probabilities g_{s,e}
    top_g, top_e = g.topk(2, dim=1)                        # Top 2
    top_g = top_g / top_g.sum(dim=1, keepdim=True)         # Normalize the two to sum to 1
    g1, g2 = top_g[:, 0], top_g[:, 1]
    e1, e2 = top_e[:, 0], top_e[:, 1]

    # First: count in token order and dispatch if below capacity C
    mask1 = F.one_hot(e1, E).float()                       # [S, E]
    pos1 = torch.cumsum(mask1, dim=0) * mask1 - mask1      # Position at which each token arrived (0-based)
    keep1 = (pos1 < C).float() * mask1
    count1 = mask1.sum(dim=0)                              # c_e: number of tokens that chose it first

    # Second: during training, dispatch with probability 2 * g2 (always a candidate during evaluation)
    # Positions also count tokens that were not dispatched ((22) in Algorithm 1)
    mask2 = F.one_hot(e2, E).float()
    pos2 = torch.cumsum(mask2, dim=0) * mask2 - mask2 + count1.unsqueeze(0) * mask2
    keep2 = (pos2 < C).float() * mask2
    if self.training:
      keep2 = keep2 * (2 * g2 > torch.rand_like(g2)).float().unsqueeze(1)

    combine = keep1 * g1.unsqueeze(1) + keep2 * g2.unsqueeze(1)  # [S, E]: G_{s,e}

    # Compute only the selected tokens with each expert, weight them, and sum
    y = torch.zeros_like(x)
    for e, expert in enumerate(self.experts):
      idx = (combine[:, e] > 0).nonzero(as_tuple=True)[0]
      if idx.numel() > 0:
        y[idx] += combine[idx, e].unsqueeze(1) * expert(x[idx])

    # Auxiliary loss: (1/E) Σ_e (c_e / S) · m_e
    m = g.mean(dim=0)
    aux_loss = ((count1 / S) * m).mean()
    return y, aux_loss


class MoEClassifier(nn.Module):
  def __init__(self, dim=128):
    super().__init__()
    self.embed = nn.Sequential(nn.Flatten(), nn.Linear(28 * 28, dim), nn.ReLU())
    self.moe = Top2MoE(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.moe(h)
    return self.head(h + m), aux_loss  # Residual connection: for overflowing tokens, h passes through unchanged


model = MoEClassifier().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_weight * aux_loss  # L = l_nll + k * l_aux
    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. Is GShard the name of a model or of software?
A.

In the paper, GShard is the name of software for partitioning a model across devices (an annotation API and an extension to the XLA compiler). The model trained with it is called the "MoE Transformer". In practice, however, the combination of top-2 gating and capacity in this model is often referred to as "GShard's MoE" or "the GShard approach".

Q. Why is the second expert dispatched at random?
A.

The output is a weighted average of the selected experts, so when the second weight g2g_2 is small, adding the second expert's output changes the result little. Yet dispatching to it uses up expert capacity. So the second expert is dispatched with probability 2g22 g_2. When its weight is close to 0.5 (as important as the first), it is dispatched almost always, and when the weight is small it is rarely dispatched, saving capacity.

Q. What happens to tokens that overflow the capacity?
A.

For a token whose two selected experts have both exceeded capacity, the gate outputs are all 0 and it receives no MoE computation. Because there is a residual connection around the MoE layer, the token's vector passes to the next layer unchanged. Training does not stop, but the token gets no expert processing in that layer, so the capacity size and the auxiliary loss are used to keep overflowing tokens few.

References

  1. 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.
  2. Shazeer, N., Mirhoseini, A., Maziarz, K., Davis, A., Le, Q., Hinton, G., & Dean, J. (2017). Outrageously Large Neural Networks: The Sparsely-Gated Mixture-of-Experts Layer. ICLR 2017. arXiv:1701.06538.