Large Models & Agents/Mixture-of-Experts

Lesson 11.92,838 words

Mixture-of-Experts

A mixture-of-experts layer replaces one feed-forward network with many and a router that sends each token to only a few of them, so the parameter count and the per-token compute become separate dials. We derive the gated output, sparse top-kk routing softmax, the load-balancing loss that stops the router from collapsing onto a single expert, and expert/token capacity with dropping, then work the dimension-annotated tensor shapes and FLOP arithmetic.

╌╌╌╌

Scaling laws say loss keeps falling as a power law in parameter count , but the Transformer accounting ties every one of those parameters to per-token FLOPs: a dense forward pass touches all of them. A mixture-of-experts layer breaks that tie. It holds many feed-forward networks but routes each token through only a few, so the model can carry an order of magnitude more parameters at the same arithmetic cost, the design behind the largest language models in deployment.1

Conditional computation

A dense network applies the same weights to every input. Conditional computation instead activates an input-dependent subset of the network, so the parameters a token sees are a function of the token itself.2

The two costs decouple. Write for the total parameter count and for the number of expert sub-networks each token activates out of total. Dense computation is the special case ; sparse routing keeps fixed as grows.

A model with experts and active per token carries the feed-forward parameters of its dense twin while doing the same per-token arithmetic.

Dense (left) routes every token through all weights, so FLOPs track total parameters; sparse (right) activates of experts, holding FLOPs flat as grows.

The mixture-of-experts layer

The layer that realizes this replaces a single feed-forward block with of them, the experts, plus a small gating network (the router) that decides how much each expert contributes.3

The experts are ordinary position-wise FFNs: each is with its own weights and , exactly the two-layer FFN the Transformer already uses, replicated times. The router is a single linear map followed by a softmax. In a Transformer, the MoE layer drops in where the FFN sublayer sat, leaving attention untouched.

Dimension walk-through

Trace one token through the layer. With model width , expert hidden width , and experts routed top-:

The router costs multiply-adds, negligible against the per active expert. Routing top- runs two experts, so per-token FFN cost is MACs, independent of how many experts the layer holds. Adding experts grows the parameter store, not this number.

An MoE layer: the router scores the token , two experts fire, and their outputs combine by the gate weights into the output.

Sparse top- gating

A dense gate that runs every expert defeats the purpose. The fix is to keep only the highest-scoring experts and zero the rest before the softmax, so the combination has at most nonzero terms.1

A worked routing example

Take experts and top- routing. Suppose the router produces logits for one token. The two largest are and , so . Softmax over just those two:

with . The token's output is . Renormalizing over the survivors (rather than the full softmax over all four) matters: the full softmax would put on the dropped experts, and folding that mass back onto the top two is what keeps the gate a valid convex combination.

Why gate on the softmax, not a hard argmax

The gate values multiply the expert outputs, so gradients reach the router through the . If the router just picked an expert and passed the output through unweighted, and the routing decision would never learn. Weighting by makes the selection differentiable in the magnitude even though the discrete choice of is not. The original sparsely-gated layer adds tunable Gaussian noise to the logits before the top-,

which spreads tokens across experts during training (a token near a decision boundary lands on either side across steps) and gives the top- selection a smooth expected behaviour.1

Top- routing (): the router scores all four experts, keeps the two highest logits, and renormalizes the gate over just those before combining.

Setting routes each token to a single expert, the Switch simplification; is the common choice in GShard and Mixtral, giving the gate at least two gradients to weigh against each other per token.45 The figure below contrasts the two: top- passes the whole token to one expert; top- splits it across two by the renormalized gate.

Top- (left) sends the token to a single expert with gate ; top- (right) splits it across two experts weighted by with .

The load-balancing problem

Nothing in the gated objective forces the router to use all the experts. Early in training a few experts get slightly more gradient, the router prefers them, they improve faster, and the preference compounds.

The standard remedy is an auxiliary loss that rewards balanced assignment. For a batch of tokens and experts, let be the fraction of tokens routed to expert and the average gate probability mass it received.

The product pairs the (non-differentiable) routing count with the differentiable probability , so gradients flow into the router through while scales the penalty toward whichever experts are overloaded.4 The term nudges the router to shave probability off experts that are already crowded; the multiplier makes that push proportional to how crowded each is. At the uniform optimum the sum equals , scaled by .

For example, with , a fully collapsed router that sends every token to expert has and , so . A uniform router has , giving . The collapsed state costs more, and the gradient points away from it.

The coefficient is small, in Switch, so the balancing pressure never dominates the task loss; it only breaks the symmetry that would otherwise let the router collapse. Too large an forces uniform routing regardless of the token distribution, which discards the specialization the experts could learn.

A second mechanism bounds the damage when balance still fails. Each expert is given a fixed capacity, and tokens beyond it are dropped past the layer through the residual connection.

Capacity has to be fixed ahead of time because the expert weight tensors are allocated as dense buffers for the batched matmul, so the buffer size cannot depend on the data-dependent routing counts. With tokens, experts, and , each expert holds slots. A perfectly uniform batch fills of them and wastes per expert to padding; a skewed batch overflows the crowded experts and drops their excess. The capacity factor provides headroom against skew, at the cost of padded compute.

Load balancing: tokens spread evenly under the auxiliary loss (left); under collapse (right) one expert overflows its capacity and the excess tokens are dropped.

An alternative inverts the decision. Token-choice routing has each token pick its experts; expert-choice routing has each expert pick its top- tokens, which guarantees perfect balance by construction (every expert fills exactly its capacity) at the price that some tokens may be chosen by many experts and others by none.6

Architectures

The same gated layer appears in a line of progressively simpler and larger models.

Sparsely-gated MoE (2017). The first practical instance interleaved an MoE layer between stacked LSTM layers in a language and translation model, with up to experts and noisy top- gating (), reaching B parameters at the compute of a far smaller dense model.1

GShard (2021). Ported the MoE layer into the Transformer, replacing every other FFN sublayer with a top- MoE, and added the sharding and capacity machinery to train a B-parameter multilingual translation model across thousands of devices.5

Switch Transformer (2022). Simplified routing to : each token goes to exactly one expert. This halves the routing and communication cost of top-, and the paper shows that with the right capacity factor and auxiliary loss, top- matches or beats top- quality, scaling to T parameters.4

The two all-to-all shuffles are the crux of the distributed cost: the first (dispatch) sends each token to the device holding its expert; the expert runs locally; the second (combine) returns the weighted output to the token's home device. Because routing is data-dependent, the volume each device sends is uneven, and a single overloaded expert stalls the collective while the others wait. This is the communication reason to care about balance, on top of the wasted-capacity reason.

Expert parallelism across two devices: dispatch all-to-all sends each token to its expert's device, experts run locally, and combine all-to-all returns outputs.

The forward pass of one MoE layer makes the routing, dispatch, and combine explicit.

Algorithm:MoELayer(X,k)\textsc{MoELayer}(X, k) — sparse top-kk mixture-of-experts forward pass
  1. 1
    input batch X=(x1,,xT)X = (x_1, \dots, x_T); experts E1,,EEE_1, \dots, E_E; capacity CC
  2. 2
    loadi0\mathit{load}_i \gets 0 for each expert ii
    tokens assigned so far
  3. 3
    for each token xtx_t in XX do
  4. 4
    hWgxth \gets W_g\, x_t
    router logits
  5. 5
    Targ topk(h)\mathcal{T} \gets \argtop_k(h)
    the kk highest-scoring experts
  6. 6
    gsoftmax(hT)g \gets \softmax(h_{\mathcal{T}})
    renormalize over the survivors
  7. 7
    yt0y_t \gets 0
  8. 8
    for each expert ii in T\mathcal{T} do
  9. 9
    if loadi<C\mathit{load}_i < C then
    expert still has a free slot
  10. 10
    ytyt+giEi(xt)y_t \gets y_t + g_i \cdot E_i(x_t)
  11. 11
    loadiloadi+1\mathit{load}_i \gets \mathit{load}_i + 1
  12. 12
    else
  13. 13
    ytyt+xt/ky_t \gets y_t + x_t / k
    dropped: pass through residual
  14. 14
    return (y1,,yT)(y_1, \dots, y_T) and the batch loads for Laux\mathcal{L}_{\text{aux}}

In practice the per-token loop is a single batched gather/scatter: tokens are sorted by their chosen expert, dispatched in one all-to-all, processed as dense matrix multiplies inside each expert, and scattered back. The dense expert matmul operates on the padded buffer, so its shape and FLOP count are fixed at compile time regardless of the realized routing.

Practical issues

Sparse models trade their FLOP savings for a set of engineering and statistics problems the dense model never had.

Training instability. The router's argmax is discontinuous, so small logit changes flip a token between experts and produce loss spikes; the ST-MoE recipe adds a router -loss, , which penalizes large logits and keeps the softmax in a numerically stable range, the single most effective stabilizer reported.7 The term is the log-partition of the router softmax; squaring and minimizing it pulls the logits toward a smaller magnitude, so a single flip moves the gate values less and the loss surface stays smoother.

Fine-tuning. Sparse models overfit downstream tasks faster than dense ones of equal quality, because each expert sees only a fraction of the (already small) fine-tuning set; ST-MoE recommends fine-tuning a subset of parameters and a smaller auxiliary-loss weight.7

Expert specialization. Trained experts do specialize, though rarely along human-legible lines; in Mixtral the routing is largely uniform across experts and only weakly correlated with topic or syntax, so the gain comes from added capacity more than from clean division of labor.8

Sparse upcycling. Rather than train an MoE from scratch, copy a trained dense FFN into identical experts, add a fresh router, and continue training; the copies diverge under the load-balancing pressure, recovering most of the gain at a fraction of the from-scratch cost.

Inference routing cost. At serve time the FLOP savings are real but the full parameter set must be resident in memory, and the all-to-all dispatch adds latency and makes throughput sensitive to how evenly a batch happens to route. The binding constraint shifts from compute to memory and communication.

Mixtral (2024). A modern decoder-only LLM, Mixtral 8×7B, places experts with top- routing in every layer. It holds B total parameters but activates only B per token, matching or beating a B dense model at the inference cost of a B one.8

Dense vs sparse: the accounting

The three routing regimes differ only in , but that one number sets active parameters, communication, and the headline parameter count.

ModelRoutingActive params / tokenTotal paramsKey idea
Dense Transformerall FFNsone FFN per layer, every weight used
Switch Transformertop-up to Tone expert per token; cheapest routing
GShard / Mixtraltop-B / Btwo experts per token; more gate signal

The pattern is constant per-token cost with growing capacity: each row adds experts (total params) without adding much active compute, exactly the decoupling conditional computation promised. The figure below sizes the trade for one FFN sublayer: the dense block uses all its parameters every token; the sparse block stores times as many but touches only of them.

Dense FFN uses all its parameters per token (params = FLOPs); the MoE stores experts but activates , so params scale with while FLOPs scale with .

Fine-grained and shared experts

Goodfellow describes the classic gated mixture; the design that ships in the largest open models since makes two modifications to the top- layer, both aimed at getting more specialization out of the same active-parameter budget.9

Fine-grained experts. Instead of experts each of hidden width routed top-, split each expert into slices of width , giving small experts routed top-. The active-parameter count is unchanged — the same total hidden width fires per token — but the router now chooses from a much larger menu, so each token can assemble a more precise combination of specialists. The intuition is combinatorial: routing of small experts gives far more distinct expert-subsets than routing of large ones, and finer partitions let experts specialize more sharply.

Shared experts. A fine-grained MoE also keeps one or two shared experts that every token passes through, alongside the routed ones. The shared expert absorbs the common computation that all tokens need — the syntax and general structure that would otherwise be redundantly relearned by every routed expert — so the routed experts are freed to specialize on what actually differs between tokens. This removes the redundancy that makes plain MoE experts specialize only weakly.

Fine-grained plus shared experts. Every token passes through a shared expert (always on); the router additionally picks several fine-grained experts from a large pool, so active compute is unchanged but the routed menu is far larger.

These two changes, on top of the auxiliary-loss and capacity machinery derived above, are why modern MoE LLMs push the active-to-total ratio far lower than Mixtral's while keeping quality: a large pool of finely-sliced routed experts, a shared expert absorbing common work, and the same -loss and load-balancing machinery. The layer is the same ; only the granularity and a fixed always-on term changed.

Takeaways

  • Conditional computation activates an input-dependent subset of weights, so total capacity and per-token FLOPs () become separate dials.
  • A mixture-of-experts layer replaces one FFN with experts and a router, outputting ; it drops in where the Transformer FFN sat.
  • Sparse top- gating keeps the largest router logits, renormalizes the softmax over them, and zeroes the rest, so only experts run per token.
  • Without intervention the router collapses onto a few experts; the load-balancing loss is minimized at the uniform split .
  • A capacity factor caps tokens per expert and drops the overflow through the residual; expert-choice routing balances by construction.
  • The architectures simplify and grow: sparsely-gated LSTM MoE, GShard (top- Transformer, B), Switch (top-, T); experts are sharded by expert parallelism with two all-to-all shuffles per layer.
  • Sparse models need a router -loss for stability, need careful fine-tuning, and shift the serving bottleneck from compute to memory and communication.
  • Mixtral 8×7B (B total, B active, top-) is the canonical modern MoE, matching a B dense model at a fraction of the inference compute.
  • Modern designs: fine-grained experts (many thin experts, larger routed menu, same active budget) and shared experts (one always-on expert absorbing common computation) let modern MoE LLMs push the active-to-total ratio far below Mixtral's while keeping quality.

Footnotes

  1. Shazeer et al., Outrageously Large Neural Networks: The Sparsely-Gated Mixture-of-Experts Layer, ICLR 2017 — sparse noisy top- gating between LSTM layers, the load-balancing loss, and the first MoE at hundreds of billions of parameters. 2 3 4
  2. Goodfellow, Deep Learning, §12.4.3 — conditional computation and mixtures of experts: gating networks that activate input-dependent sub-networks to decouple capacity from per-example cost.
  3. Jacobs, Jordan, Nowlan & Hinton, Adaptive Mixtures of Local Experts, Neural Computation 1991 — the original mixture-of-experts: a gating network softly partitions the input space among specialist sub-networks trained jointly.
  4. Fedus, Zoph & Shazeer, Switch Transformers: Scaling to Trillion Parameter Models with Simple and Efficient Sparsity, JMLR 2022 — top- routing, the differentiable load-balancing loss, and scaling to T parameters. 2 3
  5. Lepikhin et al., GShard: Scaling Giant Models with Conditional Computation and Automatic Sharding, ICLR 2021 — top- MoE Transformer with capacity, automatic sharding, and all-to-all dispatch for a B-parameter translation model. 2
  6. Zhou et al., Mixture-of-Experts with Expert Choice Routing, NeurIPS 2022 — inverts routing so each expert selects its top tokens, guaranteeing perfect load balance without an auxiliary loss.
  7. Zoph et al., ST-MoE: Designing Stable and Transferable Sparse Expert Models, 2022 — the router -loss for training stability and a fine-tuning recipe for sparse models. 2
  8. Jiang et al., Mixtral of Experts, 2024 — a decoder-only LLM with experts and top- routing per layer, B total / B active parameters, matching a B dense model. 2
  9. Dai et al., DeepSeekMoE: Towards Ultimate Expert Specialization in Mixture-of-Experts Language Models, 2024 — fine-grained expert segmentation plus isolated shared experts, raising specialization at a fixed active-parameter budget.

╌╌ END ╌╌