Search

Search papers and lessons

Outrageously Large Neural Networks: The Sparsely-Gated Mixture-of-Experts Layer

Noam Shazeer, Azalia Mirhoseini, Krzysztof Maziarz et al. · 2017

Shazeer et al. (2017) put a sparsely gated mixture of experts between LSTM layers, reaching 137 billion parameters while activating only a few experts per word.

On this page

  • Colour = topic mix
  • Probability
  • Calculus
  • Neural network basics
  • Linear algebra
  • Architectures
  • Efficiency
  • Sign in to see your progress

TL;DR

Through 2016 the usual way to get a better neural network was to make it bigger, and in a standard network every extra parameter costs compute on every input. Shazeer and colleagues at Google put a sparsely-gated mixture of experts (MoE) layer between two LSTM layers. The layer holds up to thousands of small feed-forward experts and a trainable gate that sends each word to only four of them. The model reached 137 billion parameters in its MoE layers and beat the best published language-modelling and translation results, at a lower cost per word than the dense models it beat.

Where you'll see it: the sparse expert layers that later large models use to add parameters without adding compute per token, which the 2021 Switch Transformer paper took into the Transformer architecture.

The problem

Scale had been the main engine of deep learning. Larger models trained on more data kept improving accuracy on text, images and audio. The catch is that a dense network uses every parameter on every example, so compute per example grows with model size. Training cost also grows with the number of examples, so as both grow the total cost rises faster than either alone. The paper calls this a roughly quadratic blow-up, and it argues that hardware gains could not keep up with it.

Conditional computation was the proposed way out: switch large parts of the network on or off for each example, so capacity grows while the work per example stays roughly flat. Many variants had been proposed, but none had yet shown large gains in capacity, training time or model quality. The paper gives five reasons:

  • GPUs are much faster at arithmetic than at branching, and most schemes turn whole chunks of the network on or off.
  • Large batches amortise the cost of loading and updating parameters. Conditional computation shrinks the batch seen by each active chunk.
  • Network bandwidth is a bottleneck. A GPU cluster can have thousands of times more compute than aggregate inter-device bandwidth.
  • Gating schemes often need extra loss terms to control sparsity and load balance, and these can hurt quality.
  • The earlier experiments used image datasets of up to 600,000 images, too small to train a model with billions of parameters.

The paper's claim is that it addresses all five at once.

Key idea

Think of a building with many specialists and a receptionist. The receptionist reads each request and forwards it to the two or four specialists best suited to it. The rest do nothing for that request. Adding specialists adds knowledge the building can hold, but it adds no work for any single request, as long as the receptionist stays cheap.

The MoE layer does exactly this with neural networks. It has nn expert networks E1,…,EnE_1, \dots, E_n, each a feed-forward network with its own weights, and a gating network GG whose output is a sparse vector with nn entries. The layer output is a weighted sum of the experts:

y=∑i=1nG(x)i Ei(x)y=\sum_{i=1}^{n}G(x)_{i}\,E_{i}(x)

Wherever G(x)i=0G(x)_i = 0 the expert is never evaluated, so the cost depends on how many experts are switched on, not on how many exist.

flowchart LR
  x["input x"] --> g["gating network G"]
  g -->|"weight for expert 2"| e2["expert 2"]
  g -->|"weight for expert 5"| e5["expert 5"]
  g -.->|"weight 0, not evaluated"| e1["expert 1"]
  e2 --> s["weighted sum y"]
  e5 --> s

The paper places the layer convolutionally inside a language model: a stack of LSTM layers, then the MoE, then another LSTM layer, then a softmax. The MoE is applied independently at each position in the text, so each word can use a different set of experts. In the trained translation model the experts became specialised by syntax or meaning. The paper's example is an expert in the encoder that fires when the indefinite article "a" introduces the direct object of a verb phrase indicating importance or leadership, as in "plays a central role" (Appendix E, Table 9).

The method

The gating network

The simplest gate is a softmax over a linear map, Gσ(x)=Softmax(x⋅Wg)G_\sigma(x)=Softmax(x\cdot W_g). It is dense: every expert gets a nonzero weight. The paper's gate adds two things, sparsity and noise:

H(x)i=(x⋅Wg)i+StandardNormal()⋅Softplus((x⋅Wnoise)i)H(x)_{i}=(x\cdot W_{g})_{i}+StandardNormal()\cdot Softplus\big((x\cdot W_{noise})_{i}\big) G(x)=Softmax(KeepTopK(H(x),k))G(x)=Softmax\big(KeepTopK(H(x),k)\big)

Here xx is the input vector, WgW_g and WnoiseW_{noise} are trainable matrices, kk is how many experts each input uses, and Softplus(z)=log⁡(1+ez)Softplus(z)=\log(1+e^{z}) is a smooth function that is always positive, so it works as a per-expert noise scale. KeepTopK(v,k)KeepTopK(v,k) keeps the kk largest entries of vv and replaces the rest with −∞-\infty. Softmax of −∞-\infty is zero, so every discarded expert gets gate value exactly 0.

Gradients still flow. The top-kk gate values have nonzero derivatives with respect to WgW_g, so the gate trains by ordinary backpropagation together with the rest of the model. The paper contrasts this with Bengio et al. (2015), who used boolean gates trained with a REINFORCE-style method. The noise term has a second job, load balancing, covered below.

The paper admits that the top-kk cut creates discontinuities in the gate's output. It reports that these had not caused problems in practice.

Keeping batches large

On GPUs, a layer runs efficiently only on large batches. If the gate sends each example to kk of nn experts, a batch of bb examples gives each expert only about kb/nkb/n examples. With b=1000b = 1000, k=4k = 4 and n=256n = 256, each expert sees about 15.6 examples. The paper's fix has two parts.

First, it mixes data parallelism with model parallelism. Suppose a model runs on dd devices, each with its own batch of bb examples. The standard layers and the gate are replicated, as in ordinary data parallelism. The experts are not replicated: each device holds a subset of them, and every expert receives the combined batch from all dd devices. Each expert then gets about kbd/nkbd/n examples, a factor of dd more than before, and the number of experts can be raised by adding devices.

Second, it exploits the time dimension. Because the same MoE is applied to every time step, and the time steps of the layer below can all be computed before the MoE runs, the MoE can process all positions as one large batch. The paper notes that a recurrent MoE, whose input depends on its own previous output, breaks this trick.

Network bandwidth is the third issue. Experts stay on their devices, so most traffic is the inputs and outputs of the experts. To keep the arithmetic-to-traffic ratio high, each expert is a feed-forward network with one hidden layer of thousands of ReLU units (1024 in the language models, 2048 in translation). An expert's computation per example grows with the product of its input and hidden sizes, while the data moved grows only with its input and output sizes, so a wider hidden layer does more arithmetic per byte moved.

Balancing the experts

The gate tends to collapse. The paper observes that it favours the same few experts, and those experts train faster and so get chosen even more. The paper rejects the hard constraints of earlier work and uses soft losses.

The first loss targets importance, the total gate weight an expert receives over a batch:

Importance(X)=∑x∈XG(x)Importance(X)=\sum_{x\in X}G(x) Limportance(X)=wimportance⋅CV(Importance(X))2L_{importance}(X)=w_{importance}\cdot CV\big(Importance(X)\big)^{2}

Here CVCV is the coefficient of variation, the standard deviation divided by the mean, and wimportancew_{importance} is a hand-tuned weight. The loss is small when all experts have equal total gate weight.

Equal importance does not guarantee equal numbers of examples. One expert may get a few examples with large weights while another gets many small ones, and that still causes memory and speed problems on distributed hardware. The paper therefore adds a second loss on load, the number of examples each expert actually receives. The count is discrete and cannot be differentiated, so the paper defines a smooth estimate. For each example and expert ii, P(x,i)P(x,i) is the probability that expert ii is in the top kk when fresh noise is drawn for expert ii and the other noise values are held fixed. This works out to:

P(x,i)=Φ((x⋅Wg)i−kth_excluding(H(x),k,i)Softplus((x⋅Wnoise)i))P(x,i)=\Phi\left(\frac{(x\cdot W_g)_i-kth\_excluding(H(x),k,i)}{Softplus((x\cdot W_{noise})_i)}\right)

where Φ\Phi is the standard normal cumulative distribution function and kth_excluding(H(x),k,i)kth\_excluding(H(x),k,i) is the kk-th largest value of H(x)H(x) with entry ii removed. The smooth load is Load(X)i=∑x∈XP(x,i)Load(X)_i=\sum_{x\in X}P(x,i), and the loss is Lload(X)=wload⋅CV(Load(X))2L_{load}(X)=w_{load}\cdot CV(Load(X))^2.

Because the estimate is a sum of smooth normal-CDF values, its gradient with respect to the gate weights exists. Both gating matrices WgW_g and WnoiseW_{noise} are initialised to zero, so at initialisation the gate has no signal and only noise, which keeps the load roughly even during the first steps. The paper uses wimportance=wload=0.1w_{importance} = w_{load} = 0.1 for the language models and 0.010.01 for translation.

Hierarchical mixtures

When there are very many experts, a two-level design reduces the branching: a primary gate picks a sparse weighted set of groups, and each group is itself a small mixture with its own gate. The paper uses this for 256 to 4096 experts in the language models. Importance and load are then measured per (group, expert) pair. The paper also describes a "strictly balanced" gate, used in some of its translation experiments, which fixes each expert's batch size exactly. The authors say it was needed only because of infrastructure quirks that have since been fixed, and it required a learned threshold vector at inference (Appendix F).

Results

One billion word benchmark

The benchmark has about 829 million words of shuffled news sentences and a vocabulary of 793,471 words. The MoE models have two LSTM layers with a MoE between them, the layers use 512 units, and every expert has about 1 million parameters. Each model was held to about 8 million multiply-adds per word, excluding the softmax, and each word used 4 experts.

ModelTest perplexity (10 epochs)Parameters, excluding embedding and softmaxOps per word
Best published (LSTM 2x8192-1024)34.7151 million151 million
Low-budget MoE34.14,303 million8.9 million
Medium-budget MoE31.34,313 million33.8 million
High-budget MoE28.04,371 million142.7 million

The low-budget model beats the best published result while using about 6 percent of its computation, measured in ops per word. Table 7 gives the matched baselines. A dense LSTM of similar cost, LSTM-2048-512, reaches 44.7 perplexity. The 4096-expert hierarchical MoE reaches 34.1, about 24 percent lower, which is the figure the paper quotes. The high-budget model reaches 28.0, which the paper says is 18 percent lower than the published model after 10 epochs.

Efficiency is measured in TFLOPS per GPU, against an NVIDIA theoretical maximum of 4.29. Baselines ran at 1.07 to 1.29 TFLOPS per GPU. The low-computation MoE models ran at 0.74 to 0.90 (the 4-expert model, which could not use the parallelism fully, was lower), and the highest-computation MoE model at 1.56. In all MoE models the experts account for between 37 and 46 percent of the floating point operations.

100 billion word corpus

The second corpus is about 100 billion words of internal Google news. The paper tried MoE layers with 32 to 131,072 experts, all at about 8 million ops per word. Perplexity keeps improving up to 65,536 experts, a layer of about 68 billion parameters, which the paper reports as 39 percent lower than the computationally matched baseline after 100 billion words. At 131,072 experts it gets worse, which the paper attributes possibly to too much sparsity. At 65,536 experts the layer is 99.994 percent sparse, and the model still runs at 0.72 TFLOPS per GPU.

Machine translation

The translation model is a reduced version of GNMT (Wu et al., 2016). The encoder and decoder LSTM stacks drop from 9 and 8 layers to 3 and 2, and MoE layers with up to 2048 experts are inserted in both. Each expert is a 2-million-parameter feed-forward network. The total is about 8.7 billion parameters at 85 million ops per word, against GNMT's 278 million parameters and 214 million ops.

On WMT'14 English to French, the model reaches a BLEU score of 40.56 with longer training, against 39.22 for GNMT, a gain of 1.34. On English to German it reaches 26.03 against 24.91, a gain of 1.12. The paper notes that its models use no reinforcement learning refinement, which GNMT+RL does use, so these are gains over the plain GNMT baseline. On Google's production English to French data it gains 1.01 BLEU after one sixth of the training time.

A single multilingual MoE model trained on twelve language pairs gets 19 percent lower dev-set perplexity than the multilingual GNMT model. It beats that model on BLEU for 11 of the 12 pairs, by as much as 5.84 points on Korean to English. It loses on English to Korean, which the paper attributes to overtraining on a few oversampled rare-pair examples.

Balancing losses

On a language model with 256 experts, the paper compared loss weights (Table 6). With neither balancing loss, test perplexity is 39.8, the coefficient of variation of load is 3.01, and the most loaded expert gets 17.8 times the mean load. With either loss, or both, perplexity drops to about 35.6 and the worst-case load falls to between 1.07 and 1.47 times the mean. The paper reports that the choice of loss mattered much less than having at least one.

Why it mattered

The conclusion calls this the first work to demonstrate major gains from conditional computation in deep networks. The paper did not claim the approach was finished. It says the scaling to a trillion parameters should be possible by adding hardware, and that conditional computation may help in other domains once the training sets are large enough.

The idea shaped later work. Sparse expert layers became a common way to add parameters without a matching rise in compute per token, and the Switch Transformer paper, which Shazeer co-authored in 2021, applied the idea to Transformer models.

Reading guide

Read the paper in this order, using these prerequisite lessons:

  1. Section 1, Introduction and related work. Needs the idea of a mixture of experts and the notion of conditional computation. No formula is needed yet.
  2. Section 2, Structure of the layer. Needs Mixture of Experts for the weighted sum y=∑iG(x)iEi(x)y = \sum_i G(x)_i E_i(x) and feedforward networks for the experts. The gate uses a Softmax.
  3. Section 2.1, Gating network. Needs Softmax for the gate and Gaussian (Normal) Distribution for the Gaussian noise. Read the top-kk definition slowly, since it sets the rest of the paper.
  4. Section 3, Performance. Needs mini-batch training for why batch size matters. The shrinking batch problem is simple arithmetic: kb/nkb/n examples per expert.
  5. Section 4, Balancing. Needs Coefficient of Variation for CVCV and Gaussian (Normal) Distribution for the cumulative normal Φ\Phi in the load estimate.
  6. Section 5.1, Language modelling. Needs Language Model for perplexity, LSTM layers for the surrounding architecture and Rectified Linear Unit (ReLU) for the experts' hidden layers.
  7. Section 5.3, Machine translation. Needs the encoder-decoder idea, which the GNMT model uses. Use the BLEU metric only as a score.
  8. Appendix A, Load-balancing loss. Needs Gaussian (Normal) Distribution for the normal CDF, and Backpropagation to see why the estimator must be smooth.
  9. Appendix C and D, experimental details. Needs Stochastic Gradient Descent for the optimiser setup and the Adam family of methods, plus Rectified Linear Unit (ReLU).

Check yourself

QuestionIn the noisy top-k gate, what gate value does an expert outside the top k receive, and why?Show answer

It receives exactly 0. KeepTopK replaces its pre-softmax value with minus infinity, and softmax maps minus infinity to 0. That exact zero is what lets the layer skip evaluating the expert, so the computation depends on kk and not on nn.

QuestionPre-softmax values are (0,3,1,−2)(0, 3, 1, -2) with k=2k = 2 and no noise. What are the gate values?Show answer

The top two values are 3 and 1, so the others are set to minus infinity. The softmax over {3,1}\{3, 1\} gives e3/(e3+e1)e^3/(e^3+e^1) and e1/(e3+e1)e^1/(e^3+e^1). With e3≈20.09e^3 \approx 20.09 and e1≈2.718e^1 \approx 2.718, the sum is about 22.80, so the weights are about 0.881 and 0.119. The expert with value 0 and the expert with value −2-2 get weight 0 and are never evaluated.

QuestionWhy does the paper add a load loss on top of the importance loss?Show answer

Importance is the total gate weight an expert receives, but it ignores how many examples it receives. One expert can get few examples with large weights and another many with small weights, and both have equal importance. The number of examples drives memory use and step time on distributed hardware, so the load loss targets it directly, using a smooth estimate because a count cannot be differentiated.

QuestionA batch of 512 examples per device runs on 8 devices with k=2k = 2 and n=64n = 64 experts. How many examples does each expert see per step, with and without the data-and-model mixing?Show answer

Without mixing, each device's expert batch is kb/n=2⋅512/64=16kb/n = 2 \cdot 512 / 64 = 16. With mixing across all 8 devices, it is kbd/n=2⋅512⋅8/64=128kbd/n = 2 \cdot 512 \cdot 8 / 64 = 128, eight times larger. Adding devices raises the expert batch without shrinking it, which is what lets the number of experts grow with the cluster.

QuestionWhy does the paper say its highest-computation MoE model is the most efficient per GPU, at 1.56 TFLOPS?Show answer

Its experts are larger, with bigger matrices, so each expert does more arithmetic per byte of input and output that crosses the network. The paper attributes the higher efficiency to those larger matrices. Efficiency therefore depends on expert size and batch size, not only on the number of experts.

Sources

Read the full paper

Noam Shazeer, Azalia Mirhoseini, Krzysztof Maziarz et al., 2017. arXiv:1701.06538