Sparse Mixture of Experts: Routing, Load Balancing & Expert Parallelism

Conditional computation: a router picks a few experts per token. You can increase total expert parameters while keeping activated expert FFN compute small, but distributed systems may pay in communication and scheduling.

Advanced · Undergraduate mathematics · about 20 minutes

Reading map and next steps

Intuition

The idea in plain words, before the symbols.

A sparse mixture of experts (MoE) is a layer that uses conditional computation: each token is sent to a small subset of expert networks, and the rest stay idle for that token (Shazeer et al., 2017).

Instead of running the same dense MLP for every token, you keep a large set of expert MLPs and a small router that decides which experts each token should use. This gives you:

  • Capacity: many parameters in total, spread across many experts.
  • Low computation per token: only kk experts run for each token.

It also brings new problems. Uneven routing can overload some experts, leave the rest of the batch waiting for them (stragglers), or force tokens to be dropped. When experts sit on different devices, tokens must be sent between devices. In MoE, sparsity is as much a systems problem as a modelling choice.

Study prompts for this section: Intuition
Study prompts

Each button copies a prompt about this section to your clipboard, for an AI assistant you already use. Nothing is sent by this site.

Mathematics

Definitions, assumptions and the derivation.

Router probabilities

Let a token hidden state be h∈Rdh\in\mathbb R^d. A linear router produces logits and probabilities:

z=Wrh,p(e∣h)=softmax(z)e.z = W_r h,\qquad p(e\mid h)=\mathrm{softmax}(z)_e.

Top-k gating (sparse activation)

Let S=TopK(p(⋅∣h),k)S=\mathrm{TopK}(p(\cdot\mid h), k). Only experts in SS run:

MoE(h)=∑e∈Sp~e fe(h),p~e=p(e∣h)∑j∈Sp(j∣h).\mathrm{MoE}(h)=\sum_{e\in S}\tilde p_e\,f_e(h),\qquad \tilde p_e = \frac{p(e\mid h)}{\sum_{j\in S} p(j\mid h)}.

Load balancing (avoid expert collapse)

Left alone, a router tends to favour a few experts, which then get trained more and favoured further. Shazeer et al. (2017) add routing noise and auxiliary losses to keep usage balanced. The Switch Transformer form (Fedus et al., 2022) uses, over a batch:

  • fif_i: fraction of tokens assigned to expert ii
  • PiP_i: average gating probability for expert ii

and:

LLB=NE∑i=1NEfi Pi.\mathcal L_{\text{LB}} = N_E\sum_{i=1}^{N_E} f_i\,P_i.

Here NEN_E is the number of experts. The loss equals 1 when routing is perfectly uniform and grows when tokens and router probability pile onto the same experts; it is added to the training loss with a small coefficient (0.01 in Fedus et al.).

Uniform loads do not necessarily give its smallest value, because the hard counts fif_i need not match the average probabilities PiP_i. With two experts and top-1 routing, four tokens whose router probabilities are (0.51,0.49)(0.51, 0.49) three times and (0.01,0.99)(0.01, 0.99) once give f=(0.75,0.25)f=(0.75, 0.25), P=(0.385,0.615)P=(0.385, 0.615) and LLB=0.885\mathcal L_{\text{LB}}=0.885. What the loss supplies is a gradient: ∂LLB/∂Pi=NEfi\partial\mathcal L_{\text{LB}}/\partial P_i = N_E f_i. Measured in PP, it is largest for the experts that received the most tokens, so a descent step shifts router probability, on balance, toward less-loaded experts: it lowers ∑ifiPi\sum_i f_i P_i. The router reaches PP only through each token's softmax, so in a single step one busy expert's average probability can still rise.

Expert capacity (selected is not always served)

Top-k routing only proposes token-expert assignments. A serving or training system may also cap each expert at a finite number of token slots for the batch. In the Switch Transformer, every expert gets the same capacity, set by a capacity factor cc (Fedus et al., 2022):

C=c⋅tokens in the batchNE.C = c\cdot\frac{\text{tokens in the batch}}{N_E}.

A capacity factor above 1 leaves room for uneven routing, at the cost of memory and computation spent on empty slots. If expert ee can accept CeC_e assignments, then an assignment (t,e)(t,e) is served only while:

load(e)<Ce.\mathrm{load}(e) < C_e.

Once the expert is full, later assignments to that same expert overflow unless the implementation has an explicit rerouting or fallback rule. The important distinction is:

TopK(p(⋅∣ht),k)chooses candidates; capacity chooses which candidates run.\mathrm{TopK}(p(\cdot\mid h_t), k)\quad\text{chooses candidates; capacity chooses which candidates run.}

The interactive demo uses a deliberately simple dispatch rule: process tokens in batch order, fill each expert's slots, and mark later assignments to full experts as overflowed. Real implementations can add different overflow, padding or rerouting policies, but they still have to account for finite expert capacity.

Under this first-come rule, each expert ends with min⁡(De,Ce)\min(D_e,C_e) assignments, where DeD_e counts the assignments that name expert ee. That number does not depend on the order of the batch; which assignments overflow does. The practice after the demo reorders a small batch: the loads and the number of overflows stay the same, but one token loses both of its experts.

Expert parallelism

Large MoE models place different experts on different devices. Each MoE layer then sends every token's hidden state to the devices that hold its selected experts and sends the results back, usually as two all-to-all exchanges between devices (Lepikhin et al., 2021). This communication grows with the number of tokens and with kk, and it is one reason a sparse model can be slower in wall-clock time than its computation count suggests. The MoE serving page looks at this cost in detail.

Study prompts for this section: Mathematics
Study prompts

Each button copies a prompt about this section to your clipboard, for an AI assistant you already use. Nothing is sent by this site.

Code

The same calculation as runnable code, in the notation of the derivation.

import numpy as np

rng = np.random.default_rng(0)
E, d, T = 8, 16, 2000  # experts, hidden dim, tokens

W = rng.standard_normal((E, d))  # router weights
h = rng.standard_normal((T, d))  # token hidden states

z = h @ W.T
p = np.exp(z - z.max(axis=1, keepdims=True))
p = p / p.sum(axis=1, keepdims=True)

top = p.argmax(axis=1)  # top-1 routing
freq = np.bincount(top, minlength=E) / T  # f_i
P = p.mean(axis=0)                         # P_i

L_lb = E * float(np.sum(freq * P))
print("freq f_i:", np.round(freq, 3))
print("mean gate P_i:", np.round(P, 3))
print("load-balancing loss:", round(L_lb, 3))
Study prompts for this section: Code
Study prompts

Each button copies a prompt about this section to your clipboard, for an AI assistant you already use. Nothing is sent by this site.

Demo

Change an input, predict the result, and see which quantities respond.

ExploreChange one control at a time and name what responds.An optional observation guide follows the demo.

Explore Sparse Mixture of Experts: Routing, Load Balancing & Expert Parallelism

Loading the interactive demo…

Observation guide

Optional and ungraded. Opening a guide saves nothing.

Choose what to inspect in Sparse Mixture of Experts: Routing, Load Balancing & Expert Parallelism, then open its guide.

Use the demo to predict whether a small batch's top-k token-expert assignments fit inside the experts' slots. The top-k candidates are visible from the start; the final loads and overflowed assignments are shown after you answer. It is a small teaching model, not a trained router or a load-balancing simulator.

Study prompts for this section: Demo
Study prompts

Each button copies a prompt about this section to your clipboard, for an AI assistant you already use. Nothing is sent by this site.

Practice

Fill four tokens' top-2 expert slots in batch order, then in a different order. Predict whether the loads change, and which tokens lose their experts.

Loading the exercise…
In focus

Concept: Sparse Mixture of Experts: Routing, Load Balancing & Expert Parallelism

What is the smallest example of Sparse Mixture of Experts you can work through by hand, and what does it show?

BeforeScaled Dot-Product Attention & Transformer LayersNextLong Context Engineering: RoPE Scaling, KV Compression & Memory Optimization
DetailsEfficiency

After the first pass

Go deeper

Optional material for a second reading. Sources are always shown; the other panels open from their headings or from these links, and closing one keeps what you wrote or revealed.
What to look for in each sectionChoose a section and what you expect to see in it, then read short advice.

Section by section

Choose what to look for in each section

Conditional computation: a router picks a few experts per token. You can increase total expert parameters while keeping activated expert FFN compute small, but distributed systems may pay in communication and scheduling.

Choose what to look for (no demo yet)01 / Intuition
Illustration of tokens routed sparsely into expert blocks with load imbalance and routing paths.
What to look for

Start with the picture, metaphor, or geometric mechanism.

Choose first

Choose what you expect to see in this section of Sparse Mixture of Experts: Routing, Load Balancing & Expert Parallelism.

Questions to ask of the pictureChoose a part of the picture and what you expect, then read short advice.

Looking at the picture

Questions to ask of the picture

Conditional computation: a router picks a few experts per token. You can increase total expert parameters while keeping activated expert FFN compute small, but distributed systems may pay in communication and scheduling.

4 of 4 sections writtenNo live demo yet
Question

Which part of the picture should you look at first?

Choose first

Pick the part of the picture you expect to explain Sparse Mixture of Experts: Routing, Load Balancing & Expert Parallelism.

Sources

References for this page

A reference shows where an idea comes from; it does not vouch for every step on this page.
paper · 2017Outrageously Large Neural Networks: The Sparsely-Gated Mixture-of-Experts LayerShazeer et al.
Why it is cited

Introduces the sparsely gated mixture-of-experts layer: a trainable, noisy top-k gate runs only a few of many expert networks per input, with auxiliary losses that balance how much each expert is used (ICLR 2017).

Open source
paper · 2022Switch Transformers: Scaling to Trillion Parameter Models with Simple and Efficient SparsityFedus, Zoph, and Shazeer
Why it is cited

Routes each token to a single expert (top-1), defines expert capacity through a capacity factor, drops tokens that overflow it, and uses the auxiliary load-balancing loss N·Σ f_i P_i (Journal of Machine Learning Research 23, 2022).

Open source
paper · 2021GShard: Scaling Giant Models with Conditional Computation and Automatic ShardingLepikhin et al.
Why it is cited

Shards a mixture-of-experts transformer across 2048 TPU cores, placing experts on different devices and exchanging tokens between them, to train a 600-billion-parameter translation model (ICLR 2021).

Open source
What each claim rests on1 claim, each with its sources, where it appears on this page, and its caveats.

Claims and sources

Conditional computation: a router picks a few experts per token. You can increase total expert parameters while keeping activated expert FFN compute small, but distributed systems may pay in communication and scheduling.

Checked against the cited passages

The checks were made by this site, not by an independent reviewer.

Sparse MoE layers use a learned router to choose top-k experts per token, so total expert parameters can grow while active expert compute stays bounded by k; in the cited MoE/Switch designs, load-balancing losses and expert-capacity mechanisms manage skew, overload, dropped tokens, and dispatch/communication costs.
What the sources support

Shazeer defines trainable sparse/noisy top-k gating, many expert FFNs with only selected experts evaluated, and importance/load losses for imbalance. Fedus supports Switch top-1 routing, expert capacity/capa...

Where to see it on this page
Equation 1
z=Wrh,p(e∣h)=softmax(z)e.z = W_r h,\qquad p(e\mid h)=\mathrm{softmax}(z)_e.
Equation 2
MoE(h)=∑e∈Sp~e fe(h),p~e=p(e∣h)∑j∈Sp(j∣h).\mathrm{MoE}(h)=\sum_{e\in S}\tilde p_e\,f_e(h),\qquad \tilde p_e = \frac{p(e\mid h)}{\sum_{j\in S} p(j\mid h)}.
Caveat

This covers routing, load balancing and capacity. The math, code and demo are small illustrations: they do not measure throughput, quality, expert specialization, communication or serving cost, and do not sh...

StatusChecked against the cited passages.

Shazeer supports trainable sparse/top-k MoE gating: only selected experts run, enabling large total expert parameters with limited active compute, plus importance/load balancing for skew. Fedus supports Switch top-1 routing, expert capacity/capacity-factor overflow tradeoffs, dropped tokens, the f_i/P_i auxiliary load loss, and reduced-but-present dispatch/all-to-all communication costs.

Explain it without the pageWrite your own explanation before asking for feedback. Your draft and any hints stay while this page is open.

Practice · Sparse Mixture of Experts: Routing, Load Balancing & Expert Parallelism

Try the idea in your own words

Conditional computation: a router picks a few experts per token. You can increase total expert parameters while keeping activated expert FFN compute small, but distributed systems may pay in communication and scheduling.

Concept · Selected for practice

Sparse Mixture of Experts: Routing, Load Balancing & Expert Parallelism

What it rests on: Sources: Outrageously Large Neural Networks: The Sparsely-Gated Mixture-of-Experts Layer; Switch Transformers: Scaling to Trillion Parameter Models...

Context and links
Choose a task

Explain the mechanism

For Sparse Mixture of Experts: Routing, Load Balancing & Expert Parallelism: What is the smallest example of Sparse Mixture of Experts you can work through by hand, and what does it show? Explain your answer, including what changes, why, and which assumption matters.

No answer yet

A rough first thought is enough. Your draft stays when you change tasks.

Your draft stays on this page and is cleared when you leave or reload.

A little help · Explain

Open one hint at a time. These are suggestions, not your answer or a grade.

0 of 3 hints shown for this question.

    Clearing your answer keeps this help record. Outside help is your own report; this page cannot check it.

    Where am I stuck? (optional)
    Your own description, not an automatic diagnosis

    Choose one, or leave this unspecified. Select it again to clear it.

    Take your draft to a feedback conversation

    No AI feedback runs here. You can copy a prompt to use elsewhere; nothing is sent automatically. Review the text before sharing, and leave out private information.

    Write an attempt before copying a feedback prompt.

    A draft, or an AI reply to it, is not a test of what you have learned. To check that, try a different case later without help.

    Ask about this pagePick one item on this page and copy a prompt about it into an AI assistant you already use. Notes you write here stay in this browser.
    Ask about this pageClose
    ConceptSparse Mixture of Experts: Routing, Load Balancing & Expert ParallelismSources: Outrageously Large Neural Networks: The Sparsely-Gated Mixture-of-Experts Layer; Switch Transformers: Scaling to Trillion Parameter Models...rng = np.random.default_rng(0)

    Your question

    Choose what your question is about

    Pick the idea, equation, source, code, claim, misconception or demo state you want to ask about. The prompt you copy includes it, so the answer can stay on that item.
    Next local actionNo local draft saved yet

    Open the draft below to save one note and next action in this browser.

    conceptEfficiency

    Sparse Mixture of Experts: Routing, Load Balancing & Expert Parallelism

    Starting question

    What is the smallest example of Sparse Mixture of Experts you can work through by hand, and what does it show?

    SourcesCheck the 3 cited sources listed under Sources.Notes can be saved for this item
    Points of view on this item

    Fixed prompts generated from this item. They are not comments from people or independent reviews.

    Learner’s first stepAsk what would make "Sparse Mixture of Experts: Routing, Load Balancing & Expert Parallelism" feel predictable rather than familiar.
    Assumption

    The 3 cited sources must support this exact item, not just the surrounding topic.

    Source-checking summary

    Connect the definition to one equation, piece of code or demo before widening the discussion.

    Proposed experiment

    Change one input, then check that the same relationship holds in the mathematics, the code and the demo.

    Next action

    You can state the mechanism in your own words

    Evidence4 checks
    ObservationChecking for a saved observation
    ActionReady for one action
    PromptLearner prompt ready to copy
    Go to this item
    01ObservationChecking what this browser has saved
    02EvidenceChecking for a saved observation
    03SourcesCheck the 3 cited sources listed under Sources.
    04Next stepSave one next action
    Local action draftNo local draft saved yetOpen when you are ready to write one next action
    Local action draft

    This draft stays in this browser and is attached to this item only.

    No local draft saved.
    Evidence to inspect
    • What the 3 cited sources say about this exact item
    • The definition, its prerequisites, and a contrasting concept
    • The equation or code that makes the concept concrete
    • One demo state that shows what stays the same as the inputs change
    What would resolve this
    • You can state the mechanism in your own words
    • You can name the prerequisite that would clear up the confusion
    • You can predict how the result changes when one input changes
    Reference idconcept/concept-notebook/efficiency/mixture-of-experts concept:efficiency/mixture-of-experts