AI Logic

Mixture of Experts (MoE)

BASE Layers

Updated:

The structure of BASE Layers. Left: the flow of a language model with one BASE layer inserted in the middle of the Transformer decoder layers. Upper right: the inside of the BASE layer, which computes affinities, assigns the same number of tokens to each expert, and mixes the output of the assigned expert into the residual with a sigmoid weight. Lower right: an example with 4 tokens and 2 experts comparing assignment that just picks the maximum with balanced assignment

Background and overview

BASE Layers (Balanced Assignment of Sparse Experts) is an MoE layer that solves the problem of assigning tokens to experts as a constrained optimization (a linear assignment problem) in which every expert receives exactly the same number of tokens. It was proposed by Lewis et al. at Facebook AI Research in 2021. Because the load is always balanced, it needs neither the auxiliary loss nor the capacity factor that earlier MoE methods required, and it can be added to a language model with no new hyperparameters.

Sparsely-Gated MoE, GShard, and Switch Transformer train a gate (router) to decide where each token goes. However, the gate tends to keep choosing the same few experts. This made several workarounds necessary: adding an auxiliary loss to balance the load and tuning its weight, and setting a capacity (an upper limit on the tokens one expert can receive) so that overflowing tokens are not computed. The auxiliary loss does not guarantee a balanced load, and tokens that overflow the capacity do not get processed by that layer.

BASE Layers instead uses an algorithm to decide the training-time assignment directly, so that the "total affinity between tokens and experts" is maximized under the constraint that balances the load. In hospital terms, it is like a reception desk that distributes patients so that the overall fit between patients and departments is as good as possible, under the rule that "every department takes the same number of patients so that popular departments are not overwhelmed". Each token uses only one expert.

Theory

A BASE layer consists of EE experts. Expert ee has a function fe(β‹…)f_e(\cdot) applied to each token (a stack of several feedforward layers with residual connections) and an expert embedding we∈RDw_e \in \mathbb{R}^D (DD is the model dimension).

When token hth_t is assigned to expert ata_t, the output of the BASE layer is given by the following formula (Eq. (1) in the paper).

Οƒ(htβ‹…wat) fat(ht)+ht\sigma(h_t \cdot w_{a_t}) \, f_{a_t}(h_t) + h_t

Οƒ\sigma is the sigmoid function. The expert's output is added to the original token (a residual connection) with a weight determined by the affinity between the token and the expert, htβ‹…wath_t \cdot w_{a_t}.

During training, the BASE layer proceeds in the following order (right side of the figure above; Figure 2 in the paper).

  1. Shuffle tokens: Each device (worker) sends equal numbers of its tokens to randomly chosen other devices.
  2. Measure affinities: The affinity htβ‹…weh_t \cdot w_e between each token and each expert is computed.
  3. Assign evenly: The assignment that maximizes the total affinity is found under the constraint that every expert receives the same number of tokens (formula below).
  4. Send to experts: Tokens are sent to the responsible devices according to the assignment. Each device holds one expert.
  5. Compute the experts and mix: The output is computed with Eq. (1).
  6. Return: Tokens are sent back to their original devices in their original order.

The assignment in step 3 is the following linear assignment problem (Eq. (2) in the paper).

max⁑aβˆ‘thtβ‹…watsubjectΒ toβˆ€e:Β βˆ‘t1{at=e}=TE\max_{a} \sum_{t} h_t \cdot w_{a_t} \qquad \text{subject to} \quad \forall e: \ \sum_{t} \mathbb{1}\{a_t = e\} = \frac{T}{E}

TT is the number of tokens. The paper solves this problem with Bertsekas's auction algorithm, which parallelizes well on GPUs. Solving it jointly over the tokens of all devices would be expensive, so each device solves a small problem over its own TT tokens and sends T/ET/E tokens to each expert. If the algorithm does not finish within a fixed number of iterations, it switches to greedy assignment.

The lower right of the figure above shows an example with 4 tokens and 2 experts. Simply choosing the expert with the highest affinity is unbalanced: 3 tokens go to E1E_1 and 1 to E2E_2. Maximizing the total affinity under the constraint of 2 tokens per expert assigns t1,t3t_1, t_3 to E1E_1 and t2,t4t_2, t_4 to E2E_2 (total 0.9+0.7+0.6+0.5=2.70.9 + 0.7 + 0.6 + 0.5 = 2.7).

At test time, this assignment is not used. Balancing would leak information about later tokens in the same batch (in a language model, future tokens that must not be seen yet) into the assignment. Instead, each token is greedily assigned to the expert with the highest affinity.

Why it can learn without an auxiliary loss

Why experts specialize without an auxiliary loss

In Eq. (1), the weight Οƒ(htβ‹…wat)\sigma(h_t \cdot w_{a_t}) applied to the expert's output is learned through the expert embedding wew_e (Section 3.1 of the paper).

  • If the expert's computation improves the prediction for that token, gradient descent moves htβ‹…wath_t \cdot w_{a_t} upward.
  • If it does not help, htβ‹…wath_t \cdot w_{a_t} moves downward.

As a result, wew_e approaches the representations of "tokens for which that expert is useful", and tokens with high affinity become more likely to be assigned to it next time. Even without sending tokens to multiple experts, the experts gradually specialize in particular kinds of tokens.

Why tokens are shuffled

The tokens on one device are often consecutive parts of the same document and share a topic or domain. If they were assigned as they are, the per-device bias in tokens would affect the assignment, making it harder for experts to specialize by domain. So, before assignment, tokens are sent randomly to other devices to mix them (Section 3.2.1 of the paper).

BASE layers turn load balance from "something training aims for" into "a constraint on the assignment". Because balance is always guaranteed, every device does the same amount of computation and no time is spent waiting for slow devices. No tokens overflow the capacity and go uncomputed either.

Experimental results

The paper trained language models on about 100 billion tokens combining the RoBERTa training data and the English portion of CC100, and compared validation perplexity after training for the same time (about 2.5 days) on the same number of GPUs. The model is a 24-layer Transformer decoder (model dimension 2048), and the BASE layers total about 44 billion parameters. Unless otherwise noted, 128 V100 GPUs were used.

  • More efficient than ordinary models: It was compared with data parallelism (1.5 billion parameters) and with model parallelism using tensor parallelism (Megatron-LM) (about 3 billion and 6 billion parameters). On 8 GPUs it was on par with data parallelism, and on 32 and 128 GPUs it clearly outperformed both (Figure 3 in the paper).
  • On par with or better than other MoE methods: The authors reimplemented Sparsely-Gated MoE (top 2, 52.5 billion parameters) and Switch (52.5 billion parameters), both with 128 experts, for comparison. BASE (split into 3 layers, 44.4 billion parameters) performed about as well as Sparsely-Gated MoE and converged to a better perplexity than Switch (Figure 4 in the paper).
  • Even one layer helps: Inserting just one BASE layer had a large effect, and splitting it into 3 layers placed at equal intervals gave the best results. Placing a single layer after the last layer worked almost as well, suggesting it could be added on top of a pretrained model (Figure 6 in the paper).
  • Not very sensitive to expert size: Performance was good whether the experts were made small (18.8 billion parameters in total) or large (117 billion parameters in total) (Figure 5 in the paper).

The number of tokens processed per second during training was as follows (Table 2 in the paper, 128 GPUs).

ModelTokens/s
Data parallel600K
Model parallel (2-way)224K
Sparsely-Gated MoE292K
Switch469K
BASE545K
BASE Γ—2475K

Because BASE requires little communication between devices, training proceeds faster than with other methods that split a model across devices. A 43-billion-parameter model could be trained at 90% of the speed of 1.5-billion-parameter data parallelism.

How experts are used and how they specialize (Section 5 of the paper): Even with greedy assignment at test time, expert usage was reasonably balanced. It was less balanced than in models that use an auxiliary loss, but more balanced than the second expert of Sparsely-Gated MoE. Many experts were selected based on the type of the preceding token. For example, separate experts handled quantities (year, billion, etc.), numbers, possessives (his, its, etc.), and similar verbs (is, was, etc.) (Table 1 in the paper).

Practical considerations

  • The load is not balanced at test time: Since assignment is greedy at test time, expert loads can be skewed. The paper argues that this is unlikely to be a problem because inference has spare memory, as it does not store gradients or optimizer states.
  • The assignment takes time to compute: Solving the linear assignment problem adds computation. The paper also notes that inserting many expert layers makes the assignment cost large, and leaves faster approximate assignment methods for future work.
  • The assignment is solved per device: It is not the optimal assignment over the tokens of all devices combined, but an assignment balanced within each device's tokens.
  • Gradient clipping must be computed differently: When gradients are scaled down if their norm exceeds a threshold, all devices must use the same norm. To avoid extra communication, the paper computes the norm from the shared parameters only and scales all gradients by it.

The balanced assignment during training is decided by looking at the other tokens in the same batch. If this assignment is used for inference in a language model, information about future tokens that have not yet been generated leaks into the assignment. For inference (and validation), always assign greedily to the expert with the highest affinity. The implementation needs to switch the assignment method between training and inference.

Comparison with other methods

Comparing BASE Layers with other MoE methods from the same viewpoints gives the following.

MethodExperts used per tokenHow load is balancedNew hyperparametersOverflowing tokens left uncomputed
Sparsely-Gated MoETop kkAuxiliary losses (importance and load)Loss coefficients, kkPossible if a capacity is set
GShardTop 2Auxiliary loss, capacityLoss coefficient, capacityYes
Switch Transformer1Auxiliary loss, capacityLoss coefficient, capacity factorYes (usually under 1%)
BASE Layers1Always balanced by a linear assignment problem (during training)NoneNone (during training)
Expert Choice routingChosen by the experts (0 or more)Each expert chooses the same number of tokensCapacity factorTokens chosen by no expert are possible

Rough guidelines for choosing:

  • To avoid tuning auxiliary losses or capacity factors: BASE Layers can be added with no new hyperparameters.
  • Training where communication between devices is slow: Even one BASE layer is highly effective, and having few MoE layers reduces communication.
  • To keep assignment cheap, or to use the same assignment method at inference: Switch Transformer, which selects directly with a router, uses the same mechanism for training and inference.
  • To vary the computation spent per token: Expert Choice routing, which can use more experts for difficult tokens, 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 scipy.optimize import linear_sum_assignment
from tqdm import tqdm

"""
Image classification task using MNIST data
The middle layer is a BASE layer (balanced assignment during training, greedy assignment during evaluation)
Each image is treated as one token. No auxiliary loss and no capacity factor are used
"""

# Hyperparameters
batch_size = 64       # Batch size (= number of tokens T; must be divisible by the number of experts)
epochs = 5            # Number of epochs
learning_rate = 1e-3  # Learning rate
num_experts = 8       # Number of experts E

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, drop_last=True)
test_loader = DataLoader(test_dataset, batch_size=batch_size)


def balanced_assignment(scores):
  """From scores [T, E], return the assignment that gives T/E tokens to each expert and maximizes the total affinity (Eq. 2).
  The paper solves this with the auction algorithm on GPUs; here each expert is replicated T/E times
  and the same problem is solved with scipy's Hungarian-style solver"""
  T, E = scores.shape
  per_expert = T // E
  cost = -scores.detach().cpu().repeat_interleave(per_expert, dim=1)  # [T, T]: turn maximization into cost minimization
  rows, cols = linear_sum_assignment(cost.numpy())
  assign = torch.empty(T, dtype=torch.long)
  assign[torch.as_tensor(rows)] = torch.as_tensor(cols) // per_expert
  return assign.to(scores.device)


class BASELayer(nn.Module):
  def __init__(self, dim, hidden_dim, num_experts):
    super().__init__()
    # Expert f_e: a feedforward block with a residual connection (Section 4.1 of the paper)
    self.experts = nn.ModuleList([
      nn.Sequential(nn.LayerNorm(dim), nn.Linear(dim, hidden_dim), nn.ReLU(), nn.Linear(hidden_dim, dim))
      for _ in range(num_experts)
    ])
    # Expert embeddings w_e
    self.centroids = nn.Parameter(torch.randn(num_experts, dim) * 0.02)

  def forward(self, h):
    scores = h @ self.centroids.t()                    # Affinity h_t Β· w_e  [T, E]
    if self.training:
      assign = balanced_assignment(scores)             # Training: balanced assignment
    else:
      assign = scores.argmax(dim=1)                    # Evaluation: the expert with the highest affinity (greedy)
    out = h.clone()
    for e, expert in enumerate(self.experts):
      idx = (assign == e).nonzero(as_tuple=True)[0]
      if idx.numel() > 0:
        x = h[idx]
        f = x + expert(x)                              # f_e: block with a residual connection
        alpha = torch.sigmoid(scores[idx, e]).unsqueeze(1)
        out[idx] = h[idx] + alpha * f                  # Eq. (1): Οƒ(h_t Β· w_a) f_a(h_t) + h_t
    return out


class BASEClassifier(nn.Module):
  def __init__(self, dim=128):
    super().__init__()
    self.embed = nn.Sequential(nn.Flatten(), nn.Linear(28 * 28, dim), nn.ReLU())
    self.base = BASELayer(dim, hidden_dim=4 * dim, num_experts=num_experts)
    self.head = nn.Linear(dim, 10)

  def forward(self, x):
    return self.head(self.base(self.embed(x)))


model = BASEClassifier().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 loss is added
    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. Without an auxiliary loss, do experts really not become unbalanced?
A.

During training, the assignment constraint makes every expert receive the same number of tokens, so imbalance does not occur. At test time, the expert with the highest affinity is chosen, so imbalance is possible, but in the paper's measurements usage was reasonably balanced, though not as balanced as in models with an auxiliary loss. This is likely because every expert keeps being trained on the same number of tokens during training, so all of them become well trained.

Q. Why is the balanced assignment not used at test time?
A.

The balanced assignment depends on the other tokens in the same batch. In a language model, the assignment of a token would then depend on later (future) tokens, leaking information that must not be seen. Also, since inference generates one token at a time, there may be no other tokens to balance against. For these reasons, at test time each token is greedily assigned to the expert with the highest affinity.

Q. Isn't solving the assignment problem expensive?
A.

It can be. The paper uses the auction algorithm, which parallelizes well on GPUs, splits the problem into small per-device problems instead of combining the tokens of all devices, and switches to greedy assignment if it does not finish within a fixed number of iterations. Even so, assignment takes time, so BASE layers are meant to be used in small numbers (1 to 3 layers), and the paper leaves faster approximate methods for future work.

References

  1. Lewis, M., Bhosale, S., Dettmers, T., Goyal, N., & Zettlemoyer, L. (2021). BASE Layers: Simplifying Training of Large, Sparse Models. arXiv:2103.16716.
  2. Fedus, W., Zoph, B., & Shazeer, N. (2022). Switch Transformers: Scaling to Trillion Parameter Models with Simple and Efficient Sparsity. Journal of Machine Learning Research, 23, 1–40. arXiv:2101.03961.