Notes
All notes

MoE vs dense: paying only for the experts you use

Every dense transformer pays for its full brain on every token. A 70B model does ~70B worth of work whether the token needs poetry or arithmetic — and training it costs \(C \approx 6ND\) FLOPs no matter how rarely most of that knowledge fires. Mixture of Experts breaks that coupling: keep a huge library of small networks, but run only two or three of them per token. You get the capacity of a giant with the bill of a much smaller model — plus a router you now have to keep honest.

This post derives the MoE layer, counts its FLOPs against dense, and shows why load balancing (not the gating math) is where these models live or die. For the production war story — fine-grained experts, shared experts, and aux-loss-free balancing at 671B scale — see DeepSeek (AI Engg #18); for the transformer background, see the deep learning guide.

The dense baseline: every weight fires

A dense FFN block is two matrices with a nonlinearity between them:

\[ \text{FFN}(x) = W_2\,\sigma(W_1 x), \qquad |W| \approx 2\,d\,d_{ff} \]

Every token multiplies through all of it. A forward pass costs about one multiply-add per parameter, so per-token inference FLOPs track the active count one-to-one:

\[ \text{FLOPs/token} \approx 2\,P_{\text{active}} \]

and for a dense model \(P_{\text{active}} = P_{\text{total}}\). That equality is the whole problem: quality scales with total parameters (Chinchilla: train compute \(C \approx 6ND\)), but latency, energy, and serving cost scale with the same number. You cannot buy knowledge without also buying the per-token bill.

The MoE layer: route, then compute

An MoE layer replaces the single FFN with \(N\) small FFNs — the experts — plus a learned router that picks \(k \ll N\) of them per token:

\[ y = \sum_{i=1}^{N} G(x)_i\,E_i(x), \qquad G(x) = \mathrm{softmax}(\mathrm{TopK}(W_g\,x)) \]

\(W_g\) scores every expert for this token, \(\mathrm{TopK}\) zeroes out all but the best \(k\), and softmax renormalizes over the survivors. Each expert is just a small FFN, so the layer’s total parameters grow with \(N\) while its per-token cost grows only with \(k\):

\[ P_{\text{total}} \propto N, \qquad P_{\text{active}} \propto k, \qquad \frac{\text{cost}}{\text{capacity}} \approx \frac{k}{N} \]

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=4pt, minimum width=2.0cm, minimum height=0.7cm, align=center, font=\rmfamily\small},
  a/.style={->, thick}]
  \node[b, fill=blue!10] (tin) at (-4.5,0) {token $x$};
  \node[b, fill=orange!30, minimum width=2.6cm, minimum height=1.6cm] (ffn) at (-1.4,0) {one big FFN\\all weights fire};
  \node[b, fill=green!12] (tout) at (1.6,0) {$y$};
  \draw[a] (tin) -- (ffn); \draw[a] (ffn) -- (tout);
  \node[font=\rmfamily\small\bfseries] at (-1.4,1.9) {dense};
  \node[b, fill=blue!10] (xin) at (3.4,1.4) {token $x$};
  \node[b, fill=gray!12] (r) at (5.6,1.4) {router};
  \node[b, fill=orange!30] (e1) at (4.5,0) {$E_1$};
  \node[b, fill=gray!10] (e2) at (6.0,0) {$E_2$};
  \node[b, fill=orange!30] (e3) at (7.5,0) {$E_3$};
  \node[b, fill=gray!10] (e4) at (9.0,0) {$E_4$};
  \node[draw, thick, circle, minimum size=0.9cm, font=\rmfamily\small, fill=green!12] (s) at (6.75,-1.9) {$+$};
  \draw[a] (xin) -- (r);
  \draw[a] (r) -- (e1); \draw[a] (r) -- (e3);
  \draw[a] (e1) -- (s); \draw[a] (e3) -- (s);
  \node[font=\rmfamily\small\bfseries] at (6.75,2.3) {MoE: 2 of 4 fire};
\end{tikzpicture}

The lit experts change per token — that is the entire bet. A French verb token and a Python snippet route to different specialists, and neither pays for the other.

Active versus total: where the savings show up

Because only \(k\) experts compute, a MoE model behaves at inference like a dense model of its active size while knowing as much as its total size:

Model Experts (active) Total params Active per token Active fraction
Llama-2 70B (dense) — 70B 70B 100%
Mixtral 8x7B 8 (top-2) 47B ~13B ~28%
DeepSeek-V3 256 + shared (top-8) 671B 37B ~5.5%
\begin{tikzpicture}[font=\rmfamily,
  bar/.style={draw, thick, minimum height=0.55cm},
  lbl/.style={font=\rmfamily\scriptsize}]
  \node[lbl, anchor=east] at (-0.2,2.2) {dense 70B};
  \fill[orange!45] (0,1.95) rectangle (7,2.45);
  \node[lbl] at (3.5,2.2) {100\%};
  \node[lbl, anchor=east] at (-0.2,1.2) {Mixtral};
  \fill[orange!45] (0,0.95) rectangle (1.96,1.45);
  \draw[thick, black!50] (0,0.95) rectangle (7,1.45);
  \node[lbl] at (3.5,1.2) {13B of 47B};
  \node[lbl, anchor=east] at (-0.2,0.2) {DeepSeek-V3};
  \fill[orange!45] (0,-0.05) rectangle (0.39,0.45);
  \draw[thick, black!50] (0,-0.05) rectangle (7,0.45);
  \node[lbl] at (3.5,0.2) {37B of 671B};
  \node[lbl, text=black!60] at (3.5,-0.6) {orange = weights that fire per token};
\end{tikzpicture}

Two consequences fall straight out of the picture. Compute follows the orange: Mixtral matches ~70B dense quality at roughly a fifth of the per-token FLOPs. Memory follows the outline: all 47B (or 671B) of weights must still sit in VRAM, so MoE trades cheap arithmetic for expensive capacity — great when you are FLOP-bound, painful when you are memory-bound on a single GPU.

The part that breaks: load balancing

The router has a degenerate strategy available: send everything to one expert, let it become a decent dense model, and starve the rest. Untouched experts get no gradients and never recover — router collapse. Two mechanisms prevent it.

First, an auxiliary loss that rewards even usage. With \(f_i\) the fraction of tokens sent to expert \(i\) and \(P_i\) its mean gate probability:

\[ \mathcal{L}_{aux} = \alpha\,N \sum_{i=1}^{N} f_i\,P_i \]

Uniform routing minimizes it (\(f_i = P_i = 1/N\) gives the minimum \(1/N\) per term pair… precisely, the sum is minimized when load is perfectly balanced). It is added to the language-model loss with a small \(\alpha\) — big enough to keep experts alive, small enough not to fight the actual objective. DeepSeek’s later trick keeps the same goal but drops the loss: a per-expert bias added to the routing scores, nudged up when an expert is under-loaded and down when it is over-loaded, so the main loss stays clean.

Second, expert capacity: each expert processes at most a fixed number of tokens per batch,

\[ \text{capacity} = \frac{T \cdot k}{N} \times \text{capacity factor}, \]

and overflow tokens are dropped (passed through on the residual stream, unprocessed). Capacity is what makes the compute bill predictable — without it, one popular expert could eat the whole batch.

y, gates = moe_forward(x, W1, W2, W_gate, k=2)
load = (gates > 0).sum(axis=0)      # tokens routed to each expert
print("tokens per expert:", load)
# tokens per expert: [210 110 133  85 129 121 131 105]
cap = T * k // N                    # 128 with capacity factor 1.0
dropped = np.maximum(load - cap, 0).sum()
print(f"capacity/expert: {cap}, dropped tokens: {dropped}")
# capacity/expert: 128, dropped tokens: 91

Expert 0 hogs 210 of 512 tokens while the rest idle near the ideal 128 — and 91 tokens fall off the end. That is the failure mode in miniature: without a balancing force, the router’s rich get richer and a sixth of the batch goes unprocessed.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  t/.style={draw, thick, circle, minimum size=0.5cm, font=\rmfamily\scriptsize},
  e/.style={draw, thick, rounded corners=4pt, minimum width=2.0cm, minimum height=0.7cm, font=\rmfamily\small, align=center},
  a/.style={->, thick}]
  \node[t, fill=blue!12] (a1) at (0,2.4) {};
  \node[t, fill=blue!12] (a2) at (0,1.6) {};
  \node[t, fill=blue!12] (a3) at (0,0.8) {};
  \node[t, fill=blue!12] (a4) at (0,0) {};
  \node[t, fill=blue!12] (a5) at (0,-0.8) {};
  \node[t, fill=red!20] (a6) at (0,-1.6) {};
  \node[e, fill=orange!25] (ea) at (4.2,1.2) {expert A\\3 / 3 slots};
  \node[e, fill=gray!10] (eb) at (4.2,-0.8) {expert B\\2 / 3 slots};
  \draw[a] (a1) -- (ea); \draw[a] (a2) -- (ea); \draw[a] (a3) -- (ea);
  \draw[a] (a4) -- (eb); \draw[a] (a5) -- (eb);
  \draw[a, red!70!black, dashed] (a6) -- (ea);
  \node[font=\rmfamily\scriptsize, text=red!70!black] at (2.1,-2.2) {over capacity: dropped};
\end{tikzpicture}

The full layer, runnable

The code mirrors the gating equation exactly — score, top-\(k\), renormalize, weight, sum:

import numpy as np

def softmax(z):
    z = z - z.max(axis=-1, keepdims=True)
    e = np.exp(z)
    return e / e.sum(axis=-1, keepdims=True)

def moe_forward(x, W1, W2, W_gate, k=2):
    """One MoE layer. x: (T, d); W1: (N, d_ff, d);
    W2: (N, d, d_ff); W_gate: (N, d)."""
    logits = x @ W_gate.T                          # (T, N) affinity
    topk = np.argpartition(logits, -k, axis=1)[:, -k:]
    gates = np.zeros_like(logits)
    take = np.take_along_axis(logits, topk, axis=1)
    gates[np.arange(len(x))[:, None], topk] = softmax(take)
    h = np.maximum(np.einsum("td,nfd->tnf", x, W1), 0)
    out = np.einsum("tnf,ndf->tnd", h, W2)
    return np.einsum("tn,tnd->td", gates, out), gates

One honest comment on the snippet: it evaluates all \(N\) experts to keep the math readable. Production inference evaluates only the top-\(k\) — skipping the rest is precisely the FLOP saving, and implementing the skip is an indexing exercise, not a math change. (The load numbers above came from this exact function with a biased gate.)

Dense vs MoE, head to head

Dense MoE
Params that compute per token all of them top-\(k\) experts (+ router)
Params stored in VRAM all of them all of them
Per-token FLOPs \(\approx 2P_{\text{total}}\) \(\approx 2P_{\text{active}}\)
Throughput per GPU lower at equal quality higher (less math per token)
Cross-device traffic tensor-parallel collectives all-to-all dispatch + combine
Training failure modes familiar (divergence, LR) router collapse, dropping, imbalance
Fine-tuning the whole model learns router can freeze into old habits
Wins when memory-bound, small batches FLOP-bound, large deployments

The all-to-all row deserves a sentence. Experts usually live on different devices (expert parallelism), so every MoE layer ships tokens to their experts’ GPUs and ships results back — two all-to-all exchanges per layer. At small scale that fabric cost can erase the FLOP win; MoE pays off when arithmetic dominates communication, i.e. big models and big batches.

Pitfalls

QQuestionSelf-check

A MoE layer has \(N = 8\) experts, top-\(k\) with \(k = 2\), batch \(T = 1024\) tokens, capacity factor \(1.0\). What is each expert’s capacity, and what happens to the 129th token routed to an expert? If the router sends every token to expert 0, what do the aux-loss terms \(f_i\) and \(P_i\) look like, and which direction does the loss push?

ASolution

Capacity is \(T \cdot k / N = 1024 \cdot 2 / 8 = 256\) tokens per expert. The 129th… rather, any token past the 256th routed to the same expert is dropped: it skips the expert computation and flows through on the residual connection. If everything goes to expert 0, then \(f_0 = 1\) and \(f_{i>0} = 0\), while \(P_0 \approx 1\) and the rest \(\approx 0\) — so \(\mathcal{L}_{aux} = \alpha N (1 \cdot 1 + 0) = 8\alpha\), versus the balanced minimum \(\alpha N \cdot N \cdot (1/N)(1/N) = \alpha\). The gradient pushes gate probability mass (and hence tokens) away from expert 0 toward the starved experts until \(f_i \approx P_i \approx 1/N\).

QQuestionSelf-check

Mixtral 8x7B has 47B total parameters and ~13B active per token. A dense 13B model uses less VRAM and no all-to-all communication. Why is Mixtral better than a dense 13B, and when would you still pick the dense 13B?

ASolution

Mixtral’s 13B active parameters are drawn from a 47B library chosen per token, so each token gets specialists rather than generalists — its quality tracks ~70B dense models, far above any dense 13B, while its per-token FLOPs match the 13B. Pick the dense 13B when you are memory-bound (it fits where 47B does not), when cross-device all-to-all bandwidth is scarce, or when you need simple single-GPU fine-tuning without router dynamics.