6.1.6Scaling & Efficient Architectures

Load balancing in MoE

3,281 words15 min readdifficulty · medium5 backlinks

What Is Load Balancing in MoE?

Why do we need it?

  • Without balancing: The gating network (router) can converge to a degenerate solution where it sends most tokens to a small subset of experts. The remaining experts receive almost no gradient signal and fail to learn.
  • With balancing: All experts are trained on diverse data, develop specialized skills, and the model uses its full parameter budget efficiently.

The Load Balancing Problem from First Principles

Step 1: How Routing Works

Recall the MoE gating function. For token x\mathbf{x}, we compute gating scores for NN experts:

gi(x)=softmax(Wgx)ig_i(\mathbf{x}) = \text{softmax}(\mathbf{W}_g \mathbf{x})_i

where gi(x)g_i(\mathbf{x}) is the probability of routing to expert ii. In Top-K routing (typically K=2K=2), we pick the KK experts with highest gig_i and normalize:

g~i(x)={gi(x)jTopKgj(x)if iTopK0otherwise\tilde{g}_i(\mathbf{x}) = \begin{cases} \frac{g_i(\mathbf{x})}{\sum_{j \in \text{TopK}} g_j(\mathbf{x})} & \text{if } i \in \text{TopK} \\ 0 & \text{otherwise} \end{cases}

The output is:

y=iTopKg~i(x)Ei(x)y = \sum_{i \in \text{TopK}} \tilde{g}_i(\mathbf{x}) \, E_i(\mathbf{x})

Step 2: Why Collapse Happens

The gating network Wg\mathbf{W}_g is learned via gradient descent on the main task loss. Early in training, random initialization might make expert 1 slightly better at some common pattern. The router sends more tokens to expert 1, it gets more gradient, improves faster, attracting even more tokens—a feedback loop. Experts 2-8 starve.

Step 3: Measuring Load Imbalance

Define the fraction of tokens routed to expert ii over a batch of BB tokens:

fi=1Bb=1B1[expert iTopK for token b]f_i = \frac{1}{B} \sum_{b=1}^{B} \mathbb{1}[\text{expert } i \in \text{TopK for token } b]

Perfectly balanced: fi=K/Nf_i = K/N for all ii (if Top-2 out of 8 experts, each expert should see 2/8=25%2/8 = 25\% of tokens on average).

Collapsed: f10.9f_1 \approx 0.9, f20.1f_2 \approx 0.1, f3f80f_3 \ldots f_8 \approx 0.

Load Balancing Loss: Derivation from Scratch

The standard approach comes from the Switch Transformer (and the related GShard) paper. The key insight: we want two things balanced simultaneously, and we need a term that is (a) minimized by a uniform distribution and (b) differentiable through the router weights.

The Two Quantities We Track

Define, over a batch of BB tokens with NN experts:

  • fif_i: fraction of tokens actually dispatched to expert ii (this is a hard count, non-differentiable):
fi=1Bb=1B1[expert iTopK for token b]f_i = \frac{1}{B} \sum_{b=1}^{B} \mathbb{1}[\text{expert } i \in \text{TopK for token } b]
  • PiP_i: average routing probability the router assigns to expert ii (this is differentiable through Wg\mathbf{W}_g):
Pi=1Bb=1Bgi(xb)P_i = \frac{1}{B} \sum_{b=1}^{B} g_i(\mathbf{x}_b)

The Switch Transformer Auxiliary Loss

  Laux=αNi=1NfiPi  \boxed{\;\mathcal{L}_{\text{aux}} = \alpha \cdot N \sum_{i=1}^{N} f_i \cdot P_i\;}

where α\alpha is a hyperparameter (typically 0.010.01).

Key takeaways (corrected mental model):

  • The loss does not magically become minimal at fi=Pi=1/Nf_i = P_i = 1/N as an unconstrained dot product. Its purpose is achieved dynamically: gradients scale with load fif_i and push PiP_i down for busy experts.
  • At the training fixed point, if the router equalizes probabilities (Pi1/NP_i \approx 1/N) and dispatch equalizes (fiK/Nf_i \approx K/N), the loss settles to αNN(K/N)(1/N)=αK\alpha N \cdot N \cdot (K/N)(1/N) = \alpha K, a small constant. Imbalance raises it above this.

Total Training Loss

Ltotal=Ltask+Laux\mathcal{L}_{\text{total}} = \mathcal{L}_{\text{task}} + \mathcal{L}_{\text{aux}}

The router now optimizes a trade-off: route tokens to the best expert for the task (minimize Ltask\mathcal{L}_{\text{task}}) while keeping load balanced (minimize Laux\mathcal{L}_{\text{aux}} by not over-concentrating probability on already-busy experts).

Alternative: Capacity Factor and Token Dropping

Some MoE implementations (like Switch Transformer) also use a capacity factor CC:

Expert Capacity=CBN\text{Expert Capacity} = C \cdot \frac{B}{N}

How it works:

  • If C=1.0C=1.0, each expert can handle exactly B/NB/N tokens (perfect balance).
  • If an expert's assignments exceed capacity, excess tokens are dropped (their representation passes through as a residual, bypassing the expert).
  • Dropping creates back-pressure: if expert 1 is overloaded, tokens get dropped, the model performs worse on those tokens, and gradients discourage over-routing to expert 1.

Why this helps:

  • Hard constraint: physically prevents one expert from taking all tokens.
  • Encourages the router to explore under-utilized experts.
  • Trade-off: dropping tokens can hurt performance if CC is too low. Typical values: C[1.0,1.5]C \in [1.0, 1.5].

Common Hyperparameters

Hyperparameter Typical Value Purpose
α\alpha (aux loss weight) 0.01 Trade-off between task loss and balance
Capacity factor CC 1.0 - 1.5 Buffer for load variation
Top-K 1 or 2 Number of experts per token

Why α=0.01\alpha = 0.01? Empirically tuned. Too high: router flattens probabilities to satisfy balance and ignores which expert is best (hurts accuracy). Too low: load collapse returns. 0.010.01 is a robust sweet spot.

When Load Balancing Isn't Enough

  1. Very small batch sizes: With B=16B=16 and N=8N=8 experts (Top-2), stochastic imbalance is unavoidable. Solution: accumulate stats over micro-batches, or increase BB.
  2. Highly skewed data: If 90% is English and 10% is code, an early-specialized expert may dominate. Solution: data-aware balancing or accept mild imbalance if task performance improves.
  3. Sparse expert gradients: Experts fed by few tokens get noisy updates. Solution: increase capacity factor CC or use gradient accumulation.
Recall Explain to a 12-Year-Old

Imagine a group project with 8 friends and a team leader (the router) who hands out tasks. Left alone, the leader might dump ALL the drawing on Alex just because Alex started well. Alex gets overloaded and the other 7 never learn to draw.

Load balancing is like the teacher watching a tally sheet of who got how many tasks. If Alex's tally is huge, the teacher gives the leader a nudge proportional to Alex's tally: "stop preferring Alex so much." The nudge is bigger for whoever is most overloaded. Since the leader's preferences must add up to 100%, pulling preference away from Alex automatically gives more to the quiet friends — so they finally get tasks and learn.

The clever bit: the tally itself (how many tasks each got) is just a number the teacher reads — the teacher only changes the leader's preferences, and changes them harder for the busiest person. That's exactly how the MoE auxiliary loss works.

Connections

  • Mixture of Experts (MoE) Architecture: The base architecture; load balancing is essential for MoE at scale.
  • Top-K Routing in MoE: The routing mechanism that creates the load imbalance problem.
  • Switch Transformer: Source of the αNfiPi\alpha N \sum f_i P_i auxiliary loss and capacity factor.
  • GShard: Related importance/load auxiliary losses for large sharded MoE.
  • Expert Capacity and Token Dropping: The hard-constraint alternative to the soft auxiliary loss.
  • MoE Training Dynamics: How MoE models converge, including balancing effects.
  • Gradient Routing in MoE: How gradients flow through the router (only via PiP_i).

#flashcards/ai-ml

What is the core problem that load balancing solves in MoE?
Without load balancing, a few experts receive most tokens and dominate training, while other experts collapse into uselessness, wasting parameters and compute. Load balancing ensures all experts receive roughly equal training signal and develop diverse skills.
State the Switch Transformer auxiliary load-balancing loss.
Laux=αNi=1NfiPi\mathcal{L}_{\text{aux}} = \alpha \cdot N \sum_{i=1}^{N} f_i \cdot P_i, where fif_i is the fraction of tokens dispatched to expert ii (non-differentiable count), PiP_i is the average router softmax probability for expert ii (differentiable), NN is the number of experts, and α0.01\alpha \approx 0.01. Note α\alpha is already inside, so total loss is Ltask+Laux\mathcal{L}_{\text{task}} + \mathcal{L}_{\text{aux}} (not Ltask+αLaux\mathcal{L}_{\text{task}} + \alpha\mathcal{L}_{\text{aux}}).
Which term in the auxiliary loss carries gradients, and what is that gradient?
Only PiP_i carries gradients (softmax is differentiable). fif_i is a hard dispatch count and is treated as a constant. The gradient is Laux/Pi=αNfi\partial\mathcal{L}_{\text{aux}}/\partial P_i = \alpha N f_i, i.e., proportional to the measured load of expert ii.
Why is it wrong to say ifiPi\sum_i f_i P_i is minimized at the uniform point fi=Pi=1/Nf_i=P_i=1/N?
Under the true constraints ifi=K\sum_i f_i = K and iPi=1\sum_i P_i = 1, the dot product ifiPi\sum_i f_i P_i is minimized at a corner — concentrating all PP-mass on the smallest-ff expert — not at uniformity. The loss works not by being minimal at uniform, but as a feedback controller: its gradient αNfi\alpha N f_i pushes probability away from overloaded experts, and softmax redistributes it.
Why use the cross term fiPif_i P_i rather than fi2\sum f_i^2 or Pi2\sum P_i^2 alone?
fi2\sum f_i^2 alone is non-differentiable (no gradient from the hard count). Pi2\sum P_i^2 alone regularizes only router confidence and ignores the actual dispatched load that causes real compute imbalance. The cross term couples the measured hard load fif_i (as a constant scaling) to the differentiable PiP_i, so the corrective gradient on each PiP_i scales directly with observed overload.
What does "perfectly balanced" mean in Top-K routing?
Each expert receives fi=K/Nf_i = K/N of tokens on average. For Top-2 out of 8 experts, each should see 2/8=25%2/8 = 25\%.
What is the capacity factor CC and how does it enforce balance?
Expert capacity =CB/N= C \cdot B/N. Tokens assigned beyond capacity are dropped (pass through as residual). Overloaded experts drop tokens, hurting performance, so gradients discourage over-routing. Typical C[1.0,1.5]C \in [1.0, 1.5].
What happens if α\alpha is set too high (e.g., 1.0)?
The auxiliary gradient αNfi\alpha N f_i becomes huge, flattening router probabilities toward uniform regardless of which expert is best per token. Experts become mediocre generalists and performance can fall below a dense base

Concept Map

computes softmax scores

early bias

leads to

causes

adds

encourages

prevents

target f_i equals K over N

measures imbalance

applied to

achieves

Gating network router

Top-K routing

Feedback loop

Expert collapse

Wasted parameters and compute

Load balancing

Auxiliary loss

Uniform token distribution

Fraction f_i per expert

Full expert utilization

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Dekho, MoE yaani Mixture of Experts mein hume ek problem aati hai jise samajhna bahut zaroori hai. Socho ek restaurant hai jismein 8 expert chefs hain, lekin ek gating system hai jo 90% customers ko sirf 2 chefs ke paas bhej deta hai. Wo 2 chefs overworked ho jaate hain aur baaki 6 chefs khaali baithe rehte hain. Yahi hoti hai "expert collapse" — router ek feedback loop mein fas jaata hai, jahan jo expert shuruaat mein thoda better hota hai, usko zyada tokens milte hain, wo aur fast improve karta hai, aur aur tokens attract karta hai. Baaki experts starve ho jaate hain, unko gradient signal hi nahi milta, aur wo useless reh jaate hain.

Ab load balancing yahi problem solve karta hai. Iska core idea simple hai — hum chahte hain ki saare experts ko roughly equal training signal mile taaki har expert apni-apni diverse aur complementary skills develop kare. Iske liye ek auxiliary loss add ki jaati hai, jaise Switch Transformer wali Laux=αNifiPi\mathcal{L}_{\text{aux}} = \alpha \cdot N \sum_i f_i \cdot P_i. Yahan fif_i batata hai ki kitne fraction tokens actually expert ii ko gaye (ye hard count hai, non-differentiable), aur PiP_i average routing probability hai (jo differentiable hai, isiliye gradient iske through flow karta hai). Perfectly balanced situation wo hoti hai jab har expert ko K/NK/N fraction tokens milte hain — jaise Top-2 out of 8 mein har expert ko 25% tokens.

Ye matter kyun karta hai? Kyunki agar load balance nahi hoga to aap apne poore parameter budget ka waste kar rahe ho — aapne 8 experts banaye lekin sirf 2 hi kaam kar rahe hain, matlab compute aur memory sab bekaar. Load balancing ensure karti hai ki model apni full capacity efficiently use kare, saare experts specialize karein, aur scaling ka jo faayda hum MoE se lena chahte the wo actually mile. Isiliye jab bhi tum large efficient models padho, ye concept core hai — bina iske MoE ka poora structure hi collapse kar jaata hai.

Go deeper — visual, from zero

Test yourself — Scaling & Efficient Architectures

Connections