AI Logic

Mixture of Experts (MoE)

Mixture of Experts (Original)

Updated:

The structure of the original mixture of experts. Left: the overall structure, with three experts and a gating network that receive the same input, and the output of one expert selected using the gate's softmax probabilities. Right: an example of distributing the error of one training case so that experts closer to the target learn it with greater responsibility

Background and overview

The mixture of experts (MoE) is a method that combines several small networks (experts) with a gating network that decides which expert to use for each input, so that the experts divide the training data among themselves and learn it. It was proposed in 1991 by Jacobs, Jordan, Nowlan, and Hinton in the paper "Adaptive Mixtures of Local Experts".

When a single large network is trained with backpropagation on several tasks of different nature together, weight changes made for one task can destroy the weights needed for another (the paper calls this "interference"). As a result, learning becomes slow and generalization suffers.

The paper therefore made the way of dividing up the tasks itself something to be learned. The gate looks at the input and decides "this case belongs to this expert", and when there is an error, only that expert's (and the gate's) weights are corrected. The weights of experts handling other cases are not touched, so interference does not occur. This is similar to a general hospital where the reception desk looks at the symptoms and sends the patient to the appropriate department. The doctors in each department see only their own patients and get better at them, and the reception desk also learns from experience "which department is good at which symptoms".

The key point of the paper lies in how the error is measured. If the error is defined not by summing the experts' outputs but by assuming that the gate stochastically selects one expert, the experts compete rather than cooperate, and each grows into a "local" expert responsible for part of the input space.

This idea was carried over into Sparsely-Gated MoE, used as a layer inside deep networks, and became the basis for large language models such as GShard, Switch Transformer, and Mixtral.

Theory

The system consists of nn expert networks and one gating network (left side of the figure above; Figure 1 in the paper). All are feedforward networks, and all experts and the gate receive the same input. All experts have the same number of outputs.

The procedure for processing one case (case cc in the paper's notation) is as follows.

  1. Each expert ii computes an output vector oic\mathbf{o}_i^c from the input.
  2. The gating network computes a value xjx_j for each expert (the total weighted input to output unit jj).
  3. The gate values are turned into probabilities pjp_j with a softmax (formula below).
  4. A stochastic switch selects the output of one expert jj with probability pjp_j as the system's output.
pj=exp⁑(xj)βˆ‘iexp⁑(xi)p_j = \frac{\exp(x_j)}{\sum_i \exp(x_i)}

How the error is measured (Section 1 of the paper)

Earlier methods took the system output to be the gate-weighted sum of the expert outputs, βˆ‘ipicoic\sum_i p_i^c \mathbf{o}_i^c, and trained with the squared error against the target dc\mathbf{d}^c (Eq. 1.1).

Ec=βˆ₯dcβˆ’βˆ‘ipicoicβˆ₯2E^c = \Bigl\| \mathbf{d}^c - \sum_i p_i^c \mathbf{o}_i^c \Bigr\|^2

With this formula, each expert learns to "cancel the residual error left by the other experts". When one expert's weights change, the gradients of all the other experts change too, so the experts become strongly coupled and the solution tends to involve many experts in each case.

The paper instead assumes that the gate stochastically selects one expert, and makes the error "the expected squared error of the selected expert" (Eq. 1.2).

Ec=⟨βˆ₯dcβˆ’oicβˆ₯2⟩=βˆ‘ipic βˆ₯dcβˆ’oicβˆ₯2E^c = \bigl\langle \| \mathbf{d}^c - \mathbf{o}_i^c \|^2 \bigr\rangle = \sum_i p_i^c \, \| \mathbf{d}^c - \mathbf{o}_i^c \|^2

With this formula, each expert is required to produce the whole output, not the residual error. Even when the weights of other experts change, the sign of the error a given expert sees does not change.

In its experiments, the paper used the following error, which performs even better (Eq. 1.3).

Ec=βˆ’logβ‘βˆ‘ipic eβˆ’12βˆ₯dcβˆ’oicβˆ₯2E^c = -\log \sum_i p_i^c \, e^{-\frac{1}{2} \| \mathbf{d}^c - \mathbf{o}_i^c \|^2}

This is the negative log of the probability of producing the target dc\mathbf{d}^c (the negative log-likelihood) under a model that mixes Gaussian distributions, each centered on one expert's output, with the gate probabilities picp_i^c (a Gaussian mixture model).

Why the experts divide the work

The difference between Eq. 1.2 and Eq. 1.3 becomes clear by comparing their gradients with respect to the expert outputs (Eqs. 1.4 and 1.5 in the paper).

βˆ‚Ecβˆ‚oic=βˆ’2pic(dcβˆ’oic)(fromΒ Eq.Β 1.2)\frac{\partial E^c}{\partial \mathbf{o}_i^c} = -2 p_i^c (\mathbf{d}^c - \mathbf{o}_i^c) \qquad \text{(from Eq. 1.2)} βˆ‚Ecβˆ‚oic=βˆ’[piceβˆ’12βˆ₯dcβˆ’oicβˆ₯2βˆ‘jpjceβˆ’12βˆ₯dcβˆ’ojcβˆ₯2](dcβˆ’oic)(fromΒ Eq.Β 1.3)\frac{\partial E^c}{\partial \mathbf{o}_i^c} = -\left[ \frac{p_i^c e^{-\frac{1}{2} \| \mathbf{d}^c - \mathbf{o}_i^c \|^2}}{\sum_j p_j^c e^{-\frac{1}{2} \| \mathbf{d}^c - \mathbf{o}_j^c \|^2}} \right] (\mathbf{d}^c - \mathbf{o}_i^c) \qquad \text{(from Eq. 1.3)}

In Eq. 1.4, the weight on expert ii's gradient is just the gate probability picp_i^c. In Eq. 1.5, the weight in brackets (hereafter called the responsibility hich_i^c) expresses how close that expert is to the target compared with the other experts.

The right side of the figure above shows an example. Suppose that early in training the gate gives all three experts the same probability 1/31/3, and the distances from the target βˆ₯dβˆ’oiβˆ₯2\|\mathbf{d} - \mathbf{o}_i\|^2 are (0.4,2.0,4.0)(0.4, 2.0, 4.0). The responsibilities come to about (0.62,0.28,0.10)(0.62, 0.28, 0.10), and E1E_1, which is closest to the target, learns this case most strongly.

The paper states that when the gate probabilities are all equal at the start of training and every expert has βˆ₯dcβˆ’oicβˆ₯>1\|\mathbf{d}^c - \mathbf{o}_i^c\| > 1, the best-fitting expert learns most slowly under Eq. 1.4 and most quickly under Eq. 1.5. This is because the gradient of Eq. 1.4 is proportional to the error dcβˆ’oic\mathbf{d}^c - \mathbf{o}_i^c, so an expert already close to the target receives only a small update.

The gate is trained with the same error. Differentiating Eq. 1.3 with respect to the gate value xjx_j gives pjcβˆ’hjcp_j^c - h_j^c, so the gate learns to move the probability pjcp_j^c toward the responsibility hjch_j^c. In other words, an expert that was close to the target on a case becomes more likely to be selected for similar inputs. This creates a cycle of "being entrusted with more of the cases one is good at", and the experts specialize in parts of the input space.

The paper explains this method from two viewpoints. One is as a multilayer network split into parts (a modular version). The other is as competitive learning given inputs. In competitive learning, each unit's weights represent the mean of a Gaussian distribution, and the unit that best explains the data learns. This paper replaces each unit with "an expert network that computes the mean from the input", and has the gate decide the mixing proportions from the input as well (Section 2 of the paper).

Experimental results

The paper evaluated on speaker-independent four-class vowel discrimination. The inputs were the first and second formants (frequency features of the voice) of the vowels [i], [I], [a], and [Ξ›] spoken by 75 speakers (men, women, and children). The first 50 speakers were used for training and the remaining 25 for testing.

The comparison was between ordinary networks with one hidden layer (6 or 12 units) and mixtures of experts with 4 or 8 experts. Each expert was restricted to a very simple network that can only form linear boundaries. The numbers of parameters were matched to be nearly the same. Training used gradient descent with a constant learning rate and no momentum or similar (one update per pass over the training data), continuing until the mean squared error on the training data reached 0.08.

The results are as follows (Table 1 in the paper; each is the mean of 25 runs).

SystemTraining accuracyTest accuracyEpochs to reach criterionStd. dev. of epochs
4 experts88%90%112423
8 experts88%90%108312
Ordinary network (6 hidden units)88%90%220983
Ordinary network (12 hidden units)88%90%2435124
  • Accuracy is the same: The paper explains that on this data, moving the boundaries slightly does not change which cases are misclassified.
  • Learning is about twice as fast: The mixtures of experts reached the criterion in about half the epochs of the ordinary networks.
  • More experts is slightly faster: 8 experts were slightly faster than 4, while the ordinary networks became slower with more hidden units.

Looking at the course of training, all experts initially moved toward an average boundary for all four classes; then the symmetry broke, and the experts split and specialized in either the [i] and [I] pair or the [a] and [Ξ›] pair (Figure 3 in the paper). The slightly curved boundary between [a] and [Ξ›] was approximated by joining the linear boundaries of two experts (Figure 2).

In the paper, even with 4 or 8 experts available, in every run only 2 or 3 were ultimately used, and the mixing proportions of the remaining experts were effectively 0 for every case. That was sufficient for this task, but providing many experts does not mean all of them will be used. Later large-scale MoE methods add auxiliary losses to balance usage (see Sparsely-Gated MoE).

Practical considerations

  • All experts are computed: The system in this paper computes even experts with small gate probabilities. Computation grows with the number of experts, so to save computation, use the approach of Sparsely-Gated MoE, which computes only the top kk.
  • Match the error formula to the form of the output: Eq. 1.3 treats each expert's output as the mean of a Gaussian with variance 1. For classification, it is natural to make each expert's output class probabilities and mix those probabilities instead of Gaussians (the paper also computes accuracy by mixing the experts' class probability distributions with the gate proportions).
  • How to determine the output at test time: Training assumes "select one stochastically", but for prediction one must decide whether to use the expert with the highest probability or to mix the outputs with the gate proportions.
  • The gate should start out unbiased: The paper's experiments start from a state where the gate gives every expert the same proportion. If the gate is biased toward particular experts from the start, the other experts have little chance to learn.

Eq. 1.1 (summing the outputs and measuring the squared error) and Eqs. 1.2 and 1.3 look similar, but the training results differ greatly. If the outputs are mixed before measuring the error, the experts cooperate to produce one output instead of dividing the work, and they do not grow into local experts. When implementing, check that the form is "mix the per-expert errors", not "mix, then measure the error".

Comparison with other methods

Comparing the original mixture of experts with an ordinary network and the later sparse MoE from the same viewpoints gives the following.

MethodParts used per inputComputationHow experts learnMain uses
Ordinary network (MLP)AllProportional to the wholeNot divided (one network)General regression and classification
Mixture of experts (original, 1991)All experts computed, one selected by gate probabilityProportional to the number of expertsMade to compete via Eq. 1.3, dividing responsibilitiesProblems mixing small tasks of different nature
Sparsely-Gated MoE (2017)Only the top kk expertsProportional to kk (independent of the number of experts)Outputs summed with gate weights, usage balanced with auxiliary lossesAs a layer in deep networks, to greatly increase parameters

Rough guidelines for choosing:

  • When the data seems to split into several parts of different nature: The original mixture of experts learns where to split and solves each part with a simple expert. Looking at which expert handled which region can also give clues about the structure of the data.
  • To keep the computation of a large model down: The original computes all experts, so it is not suitable. Use Sparsely-Gated MoE, which uses only the top kk, or Switch Transformer, which uses only one.
  • To learn how MoE works from the basics: Understanding this article's idea first, that "the gate selects experts probabilistically and entrusts each with the cases it is good at", makes the meaning of routers in sparse MoE and of the techniques for balancing usage easier to grasp.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F
from tqdm import tqdm

"""
A small implementation of the mixture of experts (Jacobs et al. 1991)
Linear experts share the work of approximating a function made of two regions with different behavior
The error is Eq. 1.3 of the paper (negative log-likelihood of a Gaussian mixture)
"""

# Hyperparameters
num_experts = 4       # Number of experts n
epochs = 2000         # Number of epochs (one update over the whole dataset)
learning_rate = 0.05  # Learning rate

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

# Data: y = -2x for x < 0 and y = x - 1 for x >= 0 (the two regions behave differently)
torch.manual_seed(0)
x = torch.linspace(-1, 1, 400).unsqueeze(1)
y = torch.where(x < 0, -2 * x, x - 1) + 0.05 * torch.randn_like(x)
x, y = x.to(device), y.to(device)


class MixtureOfExperts(nn.Module):
  def __init__(self, in_dim, out_dim, num_experts):
    super().__init__()
    # Experts: simple networks that can only represent lines (kept simple, as in the paper's experiments)
    self.experts = nn.ModuleList([nn.Linear(in_dim, out_dim) for _ in range(num_experts)])
    # Gating network: outputs a value x_j for each expert
    self.gate = nn.Linear(in_dim, num_experts)
    # At the start of training, make the gate output the same probability for every expert
    nn.init.zeros_(self.gate.weight)
    nn.init.zeros_(self.gate.bias)

  def forward(self, x):
    p = F.softmax(self.gate(x), dim=1)                        # [B, n]: p_j = exp(x_j) / Ξ£ exp(x_i)
    o = torch.stack([e(x) for e in self.experts], dim=1)      # [B, n, out]: compute all experts
    return p, o


def moe_loss(p, o, d):
  # Eq. 1.3: E = -log Ξ£_i p_i exp(-1/2 ||d - o_i||^2) (computed stably with logsumexp)
  sq = ((d.unsqueeze(1) - o) ** 2).sum(dim=2)                 # [B, n]: ||d - o_i||^2
  return -torch.logsumexp(torch.log(p + 1e-12) - 0.5 * sq, dim=1).mean()


model = MixtureOfExperts(1, 1, num_experts).to(device)
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)

model.train()
for epoch in tqdm(range(epochs)):
  optimizer.zero_grad()
  p, o = model(x)
  loss = moe_loss(p, o, y)
  loss.backward()
  optimizer.step()

# Prediction: use the output of the expert with the highest probability
model.eval()
with torch.no_grad():
  p, o = model(x)
  best = p.argmax(dim=1)
  pred = o[torch.arange(len(x)), best]
  mse = F.mse_loss(pred, y).item()
  usage = torch.bincount(best, minlength=num_experts).tolist()
print(f"MSE: {mse:.4f}")
print(f"Number of examples handled by each expert: {usage}")  # Often only some of the experts are used

FAQ

Q. How does the original mixture of experts differ from the MoE in today's large language models?
A.

There are two major differences. First, the original computes all experts, whereas MoE since Sparsely-Gated MoE computes only the top kk selected by the gate (router), keeping computation down. Second, in the original the whole system was a single MoE, whereas today's MoE is used repeatedly as one layer inside a deep network (usually the feedforward layer of a Transformer).

Q. Why doesn't summing the outputs and measuring the squared error (Eq. 1.1) work?
A.

With Eq. 1.1, each expert learns to fill in "the residual error left by the other experts". When one expert changes, the gradients of all the other experts change, so the solution has the experts cooperating to produce one output, with many experts involved in each case. By making the error "the expected error of each selected expert" (Eqs. 1.2 and 1.3), the paper made the experts compete and divide the cases among themselves.

Q. How many experts should be used?
A.

In the paper's vowel discrimination task, 4 and 8 experts were tried, and 8 learned slightly faster. In both cases, however, only 2 or 3 were ultimately used. If a few more experts are provided than the number of "parts of different nature" in the problem, the proportions of unused experts naturally approach 0. Note that more experts means correspondingly more computation.

References

  1. Jacobs, R. A., Jordan, M. I., Nowlan, S. J., & Hinton, G. E. (1991). Adaptive Mixtures of Local Experts. Neural Computation, 3(1), 79–87.
  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.