AI Logic

Mixture of Experts (MoE)

Sparsely-Gated MoE

Updated:

The structure of Sparsely-Gated MoE. Left: the flow of a language model with an MoE layer placed between two LSTM layers. Right: the inside of the MoE layer, where the gate determines weights with noisy top-k selection and a softmax, and the outputs of the two selected experts are combined as a weighted sum

Background and overview

Sparsely-Gated MoE (sparsely-gated mixture of experts) is a layer that prepares many small networks (experts) and, for each input, has a gating network select only a few (kk) of them to compute. It was proposed by Shazeer et al. in 2017. Even when the number of parameters is increased greatly, the computation per input hardly increases.

An ordinary neural network uses all its parameters for every input. As a result, making the model larger increases the computation proportionally. When both the data and the model are scaled up, the training cost grows roughly quadratically.

This motivated "conditional computation", which runs only part of the network depending on the input. It resembles a hospital where the receptionist looks at the symptoms and sends the patient to only a few of dozens of specialists. Adding more doctors (experts) does not change the effort to examine one patient.

The idea of mixing the outputs of several experts with a gate goes back to the 1991 mixture of experts. This paper uses it as a single layer inside a deep network, makes the gate sparse (setting the weights of most experts to 0) to save computation, and adds techniques to run it efficiently on large GPU clusters. As a result, it trains language models with MoE layers of up to 137 billion parameters inserted between LSTM layers.

This layer became the basis of later large-scale MoE models such as GShard, Switch Transformer, and Mixtral.

Theory

An MoE layer consists of nn experts E1,…,EnE_1, \dots, E_n and a gating network GG (right of the figure above). In the paper, every expert is a fully connected network of the same shape with one hidden layer (with separate weights).

The output for an input x\boldsymbol{x} is given by the following equation (Eq. (1) of the paper).

y=βˆ‘i=1nG(x)i Ei(x)\boldsymbol{y} = \sum_{i=1}^{n} G(\boldsymbol{x})_i \, E_i(\boldsymbol{x})

Here G(x)iG(\boldsymbol{x})_i is the weight of expert ii and Ei(x)E_i(\boldsymbol{x}) is the output of expert ii. Experts with G(x)i=0G(\boldsymbol{x})_i = 0 need not be computed, so only the kk experts with nonzero weights have to be evaluated.

The gate is built with noisy top-kk selection (Noisy Top-K Gating).

  1. Multiply the input by the weights WgW_g to get a score for each expert.
  2. Add Gaussian noise to the scores. The noise magnitude is also learned, with separate weights WnoiseW_{\text{noise}}.
  3. Keep only the top kk scores and set the rest to βˆ’βˆž-\infty.
  4. Apply a softmax. Experts set to βˆ’βˆž-\infty get a weight of 0, and the weights of the remaining kk sum to 1.

In equations (Eqs. (3)–(5) of the paper):

G(x)=Softmax(KeepTopK(H(x),k))G(\boldsymbol{x}) = \mathrm{Softmax}\bigl(\mathrm{KeepTopK}(H(\boldsymbol{x}), k)\bigr) H(x)i=(xWg)i+Ξ΅iβ‹…Softplus((xWnoise)i),Ξ΅i∼N(0,1)H(\boldsymbol{x})_i = (\boldsymbol{x} W_g)_i + \varepsilon_i \cdot \mathrm{Softplus}\bigl((\boldsymbol{x} W_{\text{noise}})_i\bigr), \qquad \varepsilon_i \sim \mathcal{N}(0, 1)

KeepTopK(v,k)\mathrm{KeepTopK}(\boldsymbol{v}, k) keeps the top kk entries of v\boldsymbol{v} unchanged and sets the others to βˆ’βˆž-\infty. Softplus is used to make the noise magnitude positive.

For example, suppose there are 5 experts, k=2k = 2, and the scores after adding noise are (0.1,2.0,βˆ’0.5,1.15,0.3)(0.1, 2.0, -0.5, 1.15, 0.3). Keeping only the top 2 (the 2nd and 4th) and applying a softmax gives weights of about (0,0.7,0,0.3,0)(0, 0.7, 0, 0.3, 0), and the output is 0.7 E2(x)+0.3 E4(x)0.7\,E_2(\boldsymbol{x}) + 0.3\,E_4(\boldsymbol{x}). The other 3 experts are not computed.

The gate is trained by backpropagation together with the rest of the network. If k>1k > 1, the weights of the kk selected experts have nonzero gradients with respect to the gate weights, so the network can also learn which experts to use and how much.

When the number of experts is very large, a hierarchical MoE with a two-level gate is also used. The first-level gate selects groups of experts, and within each group a second-level gate selects experts.

Balancing expert utilization

When the gate is trained freely, it tends to keep choosing the same few experts. Experts that are chosen more often train faster and become even more likely to be chosen. To prevent this, the paper adds two terms to the loss.

  • Importance loss: makes the sum of each expert's gate weights over the batch (its importance) even across experts.
  • Load loss: makes the number of examples assigned to each expert (its load) even.

The importance loss is as follows (Eqs. (6) and (7) of the paper).

Importance(X)=βˆ‘x∈XG(x),Limportance(X)=wimportanceβ‹…CV(Importance(X))2\mathrm{Importance}(X) = \sum_{\boldsymbol{x} \in X} G(\boldsymbol{x}), \qquad L_{\text{importance}}(X) = w_{\text{importance}} \cdot \mathrm{CV}\bigl(\mathrm{Importance}(X)\bigr)^2

XX is the batch, CV\mathrm{CV} is the coefficient of variation (the standard deviation divided by the mean), and wimportancew_{\text{importance}} is a hand-tuned coefficient. The more the values vary, the larger CV\mathrm{CV} becomes, so minimizing this loss makes the experts used evenly.

Even with balanced importance, if there are "experts chosen by a few examples with large weights" and "experts chosen by many examples with small weights", the amount of computation (load) is not balanced. The number of examples is discrete and not differentiable, so the paper uses the gate noise to compute "the probability that expert ii is chosen" smoothly, and uses its sum as an estimate of the load. One reason for adding noise to the gate is to balance this load.

Without a loss that balances the load, only some experts are used and the remaining parameters are wasted. In distributed training, computation can concentrate on the GPUs holding particular experts and run them out of memory. The paper initializes WgW_g and WnoiseW_{\text{noise}} to 0 to balance the load at the start of training.

Scaling techniques and results in the paper

In an MoE layer, each expert receives only about kb/nkb/n of the bb examples in a batch. The more experts there are, the fewer examples each expert processes at once, and GPU efficiency drops (the paper calls this "the shrinking batch problem").

To address this, the paper combined data parallelism and model parallelism. Ordinary layers and the gate use data parallelism, with each GPU holding a replica, while the experts are not replicated: exactly one copy of each is distributed across the GPUs. The batches of dd GPUs are combined and sent to each expert, so each expert receives about kbd/nkbd/n examples, dd times more. In language models, the batch is also enlarged by passing the inputs of all time steps through the MoE layer as one large batch.

The main results of the paper are as follows.

ExperimentResult
1B Word benchmark (language modeling)Increasing the number of experts while keeping computation roughly equal (about 8 million multiply-adds per time step), test perplexity dropped by 24% with 4096 experts
Same (also increasing computation)After 10 epochs of training, against the previous best result (34.7), an MoE model with about 4.4 billion parameters (excluding the embedding and softmax layers; the most computation-heavy one) reached 28.0
100-billion-word internal data (language modeling)Increasing to 65536 experts (68 billion parameters) lowered perplexity by 39%, but it got worse with 131072
Machine translation (WMT'14)BLEU of 40.56 for English→French and 26.03 for English→German, 1.34 and 1.12 higher than the compared GNMT

The 100-billion-word results show that the more data there is, the larger the benefit of adding experts.

MoE is a way of decoupling the number of parameters (how much the model can memorize) from the computation per input. However, the parameters of all experts must be kept in memory, and communication between GPUs also increases. Keep in mind that it yields a model that is "light on computation but heavy on memory".

In later work, using this layer in place of the feed-forward layers of the Transformer became mainstream. Switch Transformer sets k=1k = 1 to further reduce computation and communication, and Expert Choice balances load by letting the experts choose which inputs they receive.

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 on MNIST
The middle layer is an MoE layer with Noisy Top-K gating
'''

# hyperparameters
batch_size = 64       # batch size
epochs = 5            # number of epochs
learning_rate = 1e-3  # learning rate
num_experts = 8       # number of experts n
top_k = 2             # number of experts used per input k
w_importance = 0.1    # coefficient of the importance loss

# 'cuda' if CUDA is available, 'mps' on Apple Silicon, otherwise 'cpu'
device = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'

# dataset and loaders
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)


# Sparsely-Gated MoE layer
class MoE(nn.Module):
  def __init__(self, dim, hidden_dim, num_experts, k):
    super().__init__()
    self.k = k
    # experts: fully connected networks with one hidden layer
    self.experts = nn.ModuleList([
      nn.Sequential(nn.Linear(dim, hidden_dim), nn.ReLU(), nn.Linear(hidden_dim, dim))
      for _ in range(num_experts)
    ])
    # gate weights (initialized to 0 as in the paper)
    self.w_gate = nn.Parameter(torch.zeros(dim, num_experts))
    self.w_noise = nn.Parameter(torch.zeros(dim, num_experts))

  def forward(self, x):
    # H(x) = x W_g + noise Γ— Softplus(x W_noise) (noise only during training)
    logits = x @ self.w_gate
    if self.training:
      logits = logits + torch.randn_like(logits) * F.softplus(x @ self.w_noise)
    # keep only the top k, set the rest to -inf, then softmax
    topk_val, topk_idx = logits.topk(self.k, dim=1)
    masked = torch.full_like(logits, float('-inf')).scatter(1, topk_idx, topk_val)
    gates = F.softmax(masked, dim=1)  # [B, n]; experts not selected get 0

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

    # importance loss: CV(Importance)^2
    importance = gates.sum(dim=0)
    aux_loss = importance.var() / (importance.mean() ** 2 + 1e-10)
    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 = MoE(dim, hidden_dim=256, num_experts=num_experts, k=top_k)
    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


# training and evaluation
model = MoEClassifier().to(device)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)

# training loop
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) + w_importance * aux_loss
    loss.backward()
    optimizer.step()

# evaluation
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 value should k be?
A.

In the paper's language modeling experiments, 4 experts were used per input. Larger k means more computation, but k of 2 or more is considered better for training the gate (with k = 1, the selected expert's weight is always 1, so no gradient reaches the gate weights). The later Switch Transformer uses k = 1 with additional techniques.

Q. Why add noise to the gate?
A.

The main purpose is to balance the load across experts. With noise, "the probability that expert i is chosen" can be computed as a smooth function, so the load loss can be trained with backpropagation. Noise also makes the selected experts change more easily, which helps avoid a state where only some experts are used.

Q. Why is computation small despite so many parameters?
A.

Because only k of the n experts are computed for each input. For example, with 4096 experts and k = 4, a single input uses only about 0.1% of the expert parameters. However, the parameters of all experts must be kept in memory.

References

  1. 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. International Conference on Learning Representations (ICLR 2017). arXiv:1701.06538.
  2. Jacobs, R. A., Jordan, M. I., Nowlan, S. J., & Hinton, G. E. (1991). Adaptive Mixtures of Local Experts. Neural Computation, 3(1), 79–87.