Mixture of Experts (MoE)

Dive into Deep Learning · §11.7

Sparse Mixture-of-Experts (MoE) Transformers
stored vs. active capacity · top-k routing · fixed-capacity buffers · auxiliary loss vs. bias control · fine-grained & shared experts

Breaking the Lockstep Between Capacity and FLOPs

Motivation

  • Dense Transformer: Every token multiplies every weight matrix (N_{\text{active}} = N_{\text{total}}).
  • Sparse Mixture of Experts (MoE): Replaces each block’s FFN (8d^2 of 12d^2 params) with a bank of E parallel FFN experts and routes each token to only its top-k experts (1 \le k \ll E).
  • Frontier scale: DeepSeek-V3 stores 671\text{B} parameters while activating only 37\text{B} per token.

Top-k Routing Inside a Mixture-of-Experts Layer

MoE Layer Anatomy

  • Linear router (\mathbf{W}_r \in \mathbb{R}^{d \times E}): Maps token \mathbf{x} \in \mathbb{R}^d to expert probabilities \mathbf{p}(\mathbf{x}) = \mathrm{softmax}(\mathbf{x}\mathbf{W}_r) \in \Delta^{E-1}.
  • Sparse top-k selection: Picks the index set \mathcal{T}_k(\mathbf{x}) \subset \{1, \dots, E\} of the k highest-scoring experts and forms the weighted sum: \mathrm{MoE}(\mathbf{x}) = \sum_{e \in \mathcal{T}_k(\mathbf{x})} p_e(\mathbf{x}) \, \mathrm{FFN}_e(\mathbf{x})
  • Zero work on unselected experts: The remaining E - k experts sit in memory without performing a single FLOP for token \mathbf{x}.
image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

Stored (N_total) vs. Active (N_active) Parameters

Parameter Accounting

In an L-block MoE with E routed SwiGLU experts of intermediate width w (3 d w weights per expert) and E_{\text{shared}} always-active shared experts:

        ours:   2.1M in experts, 0.264M active per token, ratio  7.9x
 DeepSeek-V3:   656B in experts,  23.1B active per token, ratio 28.4x
Mixtral 8x7B:  45.1B in experts,  11.3B active per token, ratio  4.0x
              with attention and embeddings: 46.7B stored, 12.9B active
Resource / Bottleneck Governed By Why
Training & Prefill FLOPs N_{\text{active}} Each token executes only k + E_{\text{shared}} experts (C \approx 6 N_{\text{active}} D)
GPU VRAM Capacity N_{\text{total}} All E + E_{\text{shared}} experts must reside in device HBM
Batched Decode Bandwidth N_{\text{active}} \to N_{\text{total}} At batch size B \gg E/k, the union of tokens touches nearly all E experts

How the Router Learns Through Discrete Top-k Selection

Router Gradients

  • Differentiable gate p_e(\mathbf{x}): For each selected expert e \in \mathcal{T}_k(\mathbf{x}), the chain rule differentiates through the scalar weight p_e(\mathbf{x}): \frac{\partial \mathcal{L}}{\partial p_e(\mathbf{x})} = \bigl(\nabla_{\mathrm{MoE}(\mathbf{x})} \mathcal{L}\bigr)^\top \mathrm{FFN}_e(\mathbf{x})
  • Critical k = 1 renormalization pitfall: If you renormalize when k = 1, then g_{e^*} = p_{e^*} / p_{e^*} \equiv 1, making \partial \mathrm{MoE}(\mathbf{x}) / \partial \mathbf{W}_r = \mathbf{0} so the router never learns.

Fixed-Capacity Buffers and Token Dropping

Compiled Dispatch

  • Static buffer capacity S (\gamma \ge 1): Compiled GPU/TPU kernels allocate a static buffer of shape (E, S, d) with: S = \left\lceil \gamma \cdot \frac{n k}{E} \right\rceil where \gamma = 1.25 provides a 25\% slack cushion above uniform load.
  • Overflow and token dropping: Any assignment with queue position \text{rank} \ge S is dropped to a dummy overflow slot and passes unchanged through the residual stream.

Vectorized Dispatch, Batched SwiGLU, and Gather

MoELayer Implementation

MoELayer.forward numbers each token’s queue position via one-hot cumulative sums, scatters tokens into buf (with slot E * S as a dummy overflow sink), runs all E experts in one batched bmm, and gathers results back:

e = idx.flatten()                              # (n*k,) selected expert indices
onehot = F.one_hot(e, E)                       # (n*k, E) assignment indicator
rank = (onehot.cumsum(0) * onehot).sum(1) - 1  # Queue position 0, 1, ... in expert e
slot = torch.where(rank < S, e * S + rank, E * S)  # Slot E*S absorbs dropped tokens
buf = x.new_zeros(E * S + 1, d)
buf[slot] = x.repeat_interleave(k, 0)
Y = self.run_experts(buf[:-1].reshape(E, S, d)).reshape(E * S, d)
Y = torch.cat([Y, Y.new_zeros(1, d)])[slot]    # Dropped slots read zero row
weights = P.gather(-1, idx)                    # (n, k) raw probabilities p_e(x)
out = (weights[..., None] * Y.reshape(n, k, d)).sum(1)

Plugging MoELayer into a TransformerBlock

MoELayer Implementation

blk = d2l.TransformerBlock(256, num_heads=8,
                           ffn_factory=lambda: MoELayer(256, 8, 2))
X = torch.randn(4, 100, 256)
d2l.check_shape(blk(X), X.shape)  # The expert layer fits into the block
moe = MoELayer(256, num_experts=8, num_active=2)
print(f'{d2l.num_params(moe)} parameters stored, '
      f'{active_params(moe)} active per token')
4198400 parameters stored, 1051136 active per token

Why Unbalanced Routing Occurs: Skew and Feedback

Routing Collapse

  • 1. Input distribution skew (t = 0): Frequent bytes (' ' is 18.9\% of WikiText-103, exceeding \gamma / E = 15.6\%) and shared mean representations push initial logits toward 1–2 experts.
  • 2. Rich-get-richer positive feedback: Busiest experts receive more gradient updates, lower loss faster, and are rewarded by \nabla_{\mathbf{W}_r}\mathcal{L} with higher p_e(\mathbf{x}), which can leave the idle experts with too few tokens to learn.

Remedy 1: Switch Auxiliary Load-Balancing Loss

Auxiliary Loss Balancing

  • Switch Transformer (Fedus et al., 2022) adds an auxiliary penalty \alpha \mathcal{L}_{\text{aux}} (\alpha = 0.01): \mathcal{L}_{\mathrm{aux}} = E \sum_{e=1}^{E} f_e \, \bar{p}_e
  • Because f_e is stop-gradient while \bar{p}_e is differentiable, \partial \mathcal{L}_{\text{aux}} / \partial \bar{p}_e = E f_e pushes down overloaded experts (f_e > 1/E), reaching its minimum \mathcal{L}_{\text{aux}} = 1 under uniform routing.

Remedy 2: Loss-Free Dynamic Router Bias Control

Loss-Free Balancing

  • DeepSeek-V3 loss-free bias controller (Wang et al., 2024): \mathcal{T}_k(\mathbf{x}) = \operatorname{argtop}_k\bigl(\mathbf{p}(\mathbf{x}) + \mathbf{b}\bigr), \qquad b_e \leftarrow b_e + \eta_b \, \mathrm{sign}\!\left(\frac{1}{E} - f_e\right)
  • Shifts only the \operatorname{argtop}_k selection threshold while keeping the gating weights p_e(\mathbf{x}) in \sum_{e \in \mathcal{T}_k} p_e(\mathbf{x})\,\mathrm{FFN}_e(\mathbf{x}) completely unbiased (zero gradient interference).

Comparing Five Routing Regimes on WikiText-103

Load-Balancing Ablation

We train a 2-block, 8-expert Top-1 byte-level GPT (d = 128, \gamma = 1.25) for 800 steps across five routing configurations (two seeds each):

spaces: 18.9% of the validation bytes
  two runs each    loss     no drops    busiest   dropped
 initialization  5.63 5.49  5.63 5.49  2.5x 2.8x  22% 20%
   no balancing  1.75 1.81  1.70 1.73  3.3x 3.9x  24% 36%
  frozen router  1.71 1.72  1.67 1.67  2.8x 2.1x  14% 17%
 auxiliary loss  1.59 1.54  1.59 1.54  1.3x 1.2x   0%  0%
bias controller  1.58 1.56  1.57 1.55  1.3x 1.5x   0%  2%
  • Unbalanced & Initial Skew: Both initialization and no balancing send 2.4\text{--}3.9\times the even share (30\%\text{--}49\% of all tokens) to the single busiest expert and drop 20\%\text{--}36\% of assignments.
  • Both Remedies Cure Collapse: Both auxiliary loss (\alpha = 0.01) and bias controller (\eta_b = 0.01) hold peak expert load to 1.1\text{--}1.4\times the ideal share, cut drops to \le 1\%, and improve validation loss by \sim 0.10\text{--}0.15\text{ nats/byte}.

Visualizing Expert Load Shares Across Methods

Load Distribution

  • Sorted expert shares (busiest expert 1 to idlest expert 8): Under no balancing (C0), the top 3 experts take about 70\% of tokens while the idlest receives almost none.
  • Even utilization (1/8 = 12.5\%): Both the Switch auxiliary loss (C1) and the loss-free bias controller (C2) hug the horizontal black line of uniform 12.5\% utilization across all 8 experts.

IsoFLOP Setup: 8-Expert MoE vs. Matched Dense GPT

Controlled Benchmark Setup

Does sparse conditional capacity beat a dense Transformer at the exact same active parameters and per-token FLOPs? We compare our 2-block dense GPT against an 8-expert Top-1 MoE GPT (\gamma = 2) over 6{,}000 steps (49\text{M} bytes):

capacity = {'dense': None, 'MoE': 2}  # The dense model has no buffers
models = {name: small_gpt(len(data.vocab), capacity_factor=c)
          for name, c in capacity.items()}
for name, model in models.items():
    print(f'{name:>5}: {d2l.num_params(model) / 1e6:5.2f}M parameters, '
          f'{active_params(model) / 1e6:.2f}M active per token')
dense:  0.43M parameters, 0.43M active per token
  MoE:  2.26M parameters, 0.43M active per token
  • Identical active compute (0.43\text{M} active params/token): Each token executes the exact same number of attention and FFN matrix multiplications in both models.
  • 5.3\times stored parameter capacity: The MoE model stores 2.26\text{M} parameters (8 expert FFNs per layer instead of 1) while using a capacity factor \gamma = 2 so early frequent-byte bursts never drop assignments.

MoE Overtakes Dense GPT at Identical Active FLOPs

IsoFLOP Learning Curves

  • Early warm-up lag (steps 0\text{--}1{,}500): The MoE model starts slightly behind because each of the 8 experts sees only \sim 1/8 of the gradient updates per step and its output is scaled by p_e(\mathbf{x}) \approx 1/8.
  • Crossover and \sim 0.05\text{-nat} gain: Within the first 2{,}000 steps, specialized experts overtake the dense FFN and finish 0.05\text{ nats/byte} lower across seeds—matching the gain of tripling a dense model’s FLOPs.

run 1: dense 1.321, MoE 1.277; MoE ahead from step 2000, 0.0% dropped at the end
run 2: dense 1.327, MoE 1.265; MoE ahead from step 750, 0.0% dropped at the end

Fine-Grained Expert Segmentation and Shared Experts

Modern MoE Design

  • 1. Fine-grained segmentation (DeepSeekMoE, Dai et al. 2024): Splitting E = 16 full-width experts (k = 2) into m E = 64 quarter-width experts (m k = 8) leaves both stored and active parameters unchanged while boosting active combinations from \binom{16}{2} = 120 to \binom{64}{8} \approx 4.4 \times 10^9.
  • 2. Always-active shared experts: Dedicating E_{\text{shared}} \ge 1 experts to run on every token absorbs common syntactic transformations so routed experts avoid redundancy.
image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

Expert Configurations of Frontier Open-Weights MoEs

Frontier Comparison

  • Coarse routing (Mixtral 8x7B, 2024): E = 8 full-width experts, top-2 active (47\text{B} total / 13\text{B} active, 3.6\times capacity ratio).
  • Fine-grained experts (Qwen3, DeepSeek-V3, gpt-oss): 128\text{--}256 narrow experts (w/d \in [0.29, 1.0]) with top-4 or top-8 routing achieve 11\times\text{--}23\times stored-to-active capacity; DeepSeek-V3 adds one shared expert.

Concept Check: MoE Capacity, Loss, and Data Budgets

Check Your Understanding

Work through these three MoE design calculations:

  1. Active expert fraction: A layer has E = 64 routed experts of width w, activates k = 6 per token, and includes E_{\text{shared}} = 2 always-active shared experts of the same width w. What fraction of the layer’s expert parameters executes for a single token?
  2. Evaluating the Switch auxiliary loss: In a 4-expert layer (E = 4), a minibatch routes 50\% of slots to expert 1 (f_1 = \bar{p}_1 = 1/2) and 1/6 to each of experts 2, 3, and 4 (f_e = \bar{p}_e = 1/6). What is \mathcal{L}_{\text{aux}} = E \sum_{e=1}^4 f_e \bar{p}_e?
  3. Tokens seen per expert: In our 6{,}000-step WikiText-103 run (64 \times 128 = 8{,}192 bytes/step), how many training bytes pass through the dense FFN versus each balanced expert of an 8-expert Top-1 MoE layer?

Answers:

  1. (k + E_{\text{shared}}) / (E + E_{\text{shared}}) = (6 + 2) / (64 + 2) = 8 / 66 \approx \mathbf{12.1\%} (plus the lightweight d \times 64 router matrix).
  2. \mathcal{L}_{\text{aux}} = 4 \times \bigl(\frac{1}{2}\cdot\frac{1}{2} + 3 \cdot \frac{1}{6}\cdot\frac{1}{6}\bigr) = 4 \times \bigl(\frac{1}{4} + \frac{1}{12}\bigr) = 4 \times \frac{1}{3} \approx \mathbf{1.333} (above the balanced minimum of 1.000).
  3. 6{,}000 \times 8{,}192 \approx \mathbf{49.2\text{M}\text{ bytes}} pass through the dense FFN, whereas each Top-1 expert sees only 49.2\text{M} / 8 \approx \mathbf{6.1\text{M}\text{ bytes}}—explaining why MoEs overfit quickly on tiny datasets and require large pretraining corpora.

Summary: Sparse Mixture-of-Experts Transformers

Key Takeaways

  • Top-k Conditional Compute: \mathrm{MoE}(\mathbf{x}) = \sum_{e \in \mathcal{T}_k(\mathbf{x})} p_e(\mathbf{x})\,\mathrm{FFN}_e(\mathbf{x}) decouples stored capacity N_{\text{total}} from per-token FLOPs N_{\text{active}}.
  • Static Buffers & Balancing: Fixed capacity S = \lceil \gamma n k / E \rceil plus Switch auxiliary loss or loss-free dynamic bias control b_e.
  • Fine-Grained Experts: Splitting E \to mE, k \to mk is the pattern of frontier MoEs; DeepSeek-V3 adds a shared expert.