6.1.4Scaling & Efficient Architectures

Mixture-of-Experts (MoE) architecture

2,229 words10 min readdifficulty · medium3 backlinks

WHAT is a Mixture-of-Experts?

The core distinction to burn in:

Quantity Meaning Scales with
Total (dense) params all experts stored NN
Active params / token what actually runs kk
Compute (FLOPs) forward cost per token kk, not NN

HOW does routing work? (Derivation from scratch)

We want, for each token embedding xRdx \in \mathbb{R}^d, to (1) pick which experts, and (2) blend their outputs.

Step 1 — Score every expert. Give the router a learnable weight matrix WgRN×dW_g \in \mathbb{R}^{N \times d}. The raw score (logit) for expert ii is the dot product: hi=(Wgx)ih_i = (W_g\, x)_i Why this step? A dot product measures alignment between the token and each expert's learned "preference vector" (row of WgW_g). High alignment → this expert is relevant.

Step 2 — Turn scores into probabilities. Apply softmax so scores are comparable and sum to 1: pi=ehij=1Nehjp_i = \frac{e^{h_i}}{\sum_{j=1}^{N} e^{h_j}} Why this step? We need normalized weights to combine expert outputs, and softmax is the smooth, differentiable way to convert "who is best" into weights.

Step 3 — Keep only the Top-kk. Let T\mathcal{T} be the set of indices of the kk largest pip_i. Zero out the rest: gi={pijTpjiT0otherwiseg_i = \begin{cases} \dfrac{p_i}{\sum_{j\in\mathcal{T}} p_j} & i \in \mathcal{T}\\[4pt] 0 & \text{otherwise}\end{cases} Why this step? Setting non-selected gates to 0 means those experts do zero computation — that's where the FLOP savings come from. Re-normalizing over T\mathcal{T} keeps the used weights summing to 1.

Step 4 — Combine expert outputs. y=iTgiEi(x)y = \sum_{i \in \mathcal{T}} g_i \, E_i(x) Why this step? We only evaluate the kk chosen experts Ei(x)E_i(x) and take a gate-weighted sum. This is the layer's output.

Figure — Mixture-of-Experts (MoE) architecture

The load-balancing problem (WHY MoE needs a helper loss)

Fix: an auxiliary load-balancing loss. For a batch, define:

  • fif_i = fraction of tokens routed to expert ii (dispatch fraction).
  • PiP_i = average router probability assigned to expert ii.

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

Why this exact form? It is minimized when both fif_i and PiP_i are uniform (=1/N=1/N), i.e. every expert gets an equal share. Using PiP_i (soft, differentiable) instead of only fif_i (from a hard argmax, non-differentiable) lets gradients actually flow to fix imbalance. The factor NN keeps the loss scale independent of expert count; α\alpha (e.g. 0.010.01) keeps it a gentle nudge, not the main objective.


Worked Examples


Common Mistakes (Steel-manned)


Recall Feynman: explain to a 12-year-old

Imagine a hospital with 64 specialist doctors. A dense model is like making every patient see all 64 doctors — accurate but insanely slow and expensive. MoE puts a smart receptionist (the router) at the door who looks at your problem and sends you to just the 2 best-matched doctors. The hospital still has all that expertise, but each patient only uses a tiny bit of it. To keep it fair, there's a rule so one popular doctor doesn't get all the patients while others sit idle (load balancing), and each doctor can only see so many patients per hour (capacity).


Active Recall Flashcards

#flashcards/ai-ml

What problem does MoE decouple that dense models tie together?
Model capacity (total parameters / knowledge) from per-token compute (FLOPs).
In an MoE layer, what does the router output before Top-k selection?
A softmax distribution pip_i over the NN experts from logits WgxW_g x.
Why re-normalize the gates over the Top-k set?
So the selected gate weights sum to 1, giving a proper weighted blend of expert outputs.
FLOPs per token in MoE scale with which quantity — NN or kk?
kk (active experts), not NN (total experts).
What is the "expert collapse" failure and its fix?
Router sends most tokens to a few experts (rich-get-richer); fixed by an auxiliary load-balancing loss.
Write the load-balancing loss and say when it's minimized.
Laux=αNifiPi\mathcal{L}_{aux}=\alpha N\sum_i f_i P_i; minimized when fi=Pi=1/Nf_i=P_i=1/N (uniform usage).
What is expert capacity CC and what happens when it's exceeded?
C=cap_factor×(tokens/N)C=\text{cap\_factor}\times(\text{tokens}/N); excess tokens are dropped and pass through the residual.
Why not use a hard argmax router instead of softmax?
Argmax is non-differentiable; softmax gives smooth gradients so the router can learn.
For k=2k=2, N=64N=64, 7M-param experts, how many active vs total expert params?
Active =2×7M=14=2\times7\text{M}=14M; total =64×7M=448=64\times7\text{M}=448M.
Where does the compute saving in MoE physically come from?
Non-selected experts get gate 0 and are never evaluated (zero FLOPs).

Connections

  • Feed-Forward Networks (Transformer FFN) — each expert is an FFN block.
  • Softmax and Gating Functions — the router's normalization step.
  • Scaling Laws — MoE moves along the capacity axis cheaply.
  • Sparse vs Dense Models — the fundamental design trade-off.
  • Load Balancing and Auxiliary Losses — keeping experts utilized.
  • Model Parallelism & Expert Parallelism — how experts are sharded across devices.
  • Conditional Computation — the general principle MoE instantiates.

Concept Map

fed into

parameterizes

dot product

softmax

keep k largest

renormalize

activates

weighted by

blended sum

only k run

N experts stored

decoupled from

Token embedding x

Router g of x

Weight matrix Wg

Logits hi

Softmax probs pi

Top-k set

Selected experts Ei

Gates gi

Output y

Knowledge capacity

Compute cost FLOPs

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Dekho, dense model mein har token ko poore network se guzarna padta hai — matlab saare parameters har token ke liye compute hote hain. Yeh accurate to hai par bahut mehenga. MoE ka jugaad simple hai: hum bahut saare chhote "expert" networks rakhte hain, par har token ke liye sirf 2 (ya 1) best experts ko chalate hain. Ek chhota sa "router" decide karta hai ki yeh token kis expert ko jaana chahiye — bilkul receptionist ki tarah jo patient ko sahi doctor ke paas bhejta hai.

Router kaam kaise karta hai? Pehle woh har expert ke liye ek score nikalta hai (WgxW_g x ka dot product), phir softmax se usko probability banata hai, phir Top-k experts choose karta hai aur baaki ko gate = 0 de deta hai. Gate 0 ka matlab woh expert compute hi nahi hota — yahi se FLOPs ki bachat aati hai. Selected experts ke outputs ko gate weights se multiply karke jod dete hain, bas ho gaya output.

Ek important point: total parameters badhte hain NN (experts ki sankhya) ke saath, par compute badhta hai kk (active experts) ke saath. Isliye MoE mein aap knowledge/capacity ko sasta mein badha sakte ho bina compute badhaye. Lekin ek problem hai — "rich get richer": ek popular expert ko saare tokens milne lagte hain aur baaki experts bekaar ho jaate hain. Iske liye ek load-balancing loss (αNfiPi\alpha N \sum f_i P_i) lagate hain jo sabko barabar kaam dilata hai. Aur har expert ki ek capacity hoti hai — usse zyada tokens aayein to extra tokens drop ho jaate hain.

Exam/interview ke liye yaad rakho: Route → Softmax → Top-k → Combine, aur "compute = k, capacity = N". Bas itna clear ho gaya to MoE tumhara pakka concept hai.

Go deeper — visual, from zero

Test yourself — Scaling & Efficient Architectures

Connections