Skip to content

Chapter 4 · Mixture of Experts


4.1 Motivation: Decoupling Capacity from Compute ★★

\[y = \sum_{i=1}^{E} g_i(x)\, \mathrm{FFN}_i(x), \qquad \text{only } k \ll E \text{ of the } g_i(x) \text{ are non-zero}\]

Why MoE ★★

In a dense model, every token passes through all the parameters. As Chapter 1, Section 1.8 explained, inference costs about \(2N\) FLOPs per token and total training compute is about \(6ND\). This means the model's capacity (how much knowledge it can hold) and its per-token compute are tightly bound together: to make the model remember more you add parameters, and adding parameters proportionally increases per-token compute and training cost.

MoE (Mixture of Experts) is designed to break this bond. It replaces the FFN in a Transformer block with \(E\) FFNs of the same structure but independent parameters, called experts, plus a very small router. For each token, the router picks only \(k\) experts (\(k\) much smaller than \(E\)) to process it; the output is a weighted sum of these experts' results, and the other experts don't compute anything for this token. In the formula, \(x\) is the token's hidden state, \(\mathrm{FFN}_i\) is the \(i\)-th expert, and \(g_i(x)\) is the weight the router gives it; only the \(k\) selected experts have non-zero weights.

This separates two parameter counts. The total parameter count is all experts plus the shared parts, which decides how much knowledge the model can store. The active parameter count is the parameters each token actually uses (the shared parts plus \(k\) experts), which decides per-token compute. Adding experts can multiply the total parameters while per-token compute stays almost the same. In practice, Switch Transformer (Fedus et al. 2021) sped up pretraining by up to 7 times at the same compute, and Mixtral 8x7B (Jiang et al. 2024) activates only 13B parameters per token yet matches or beats Llama 2 70B.

Why is it the FFN that becomes the experts? As Chapter 1, Section 1.6 explained, the FFN holds about two-thirds of each block's parameters, is considered the main place where knowledge is stored, and computes each token separately, which makes it a natural fit for "each token takes a different path". Attention stays dense and shared by all tokens, because its job is exchanging information between tokens, and it also determines the size of the KV cache.

The idea of MoE is old (Shazeer et al. 2017 proposed a sparsely gated MoE layer for LSTMs); GShard (Lepikhin et al. 2020) brought it to Transformers, and Switch Transformer pushed it to the trillion-parameter scale. The costs are just as clear, and the following sections cover them one by one: memory has to hold every expert, expert load becomes unbalanced, there is communication overhead across GPUs, and training is less stable.

Interview questions

  • ★★ What is the core idea of MoE, and why can it improve quality without increasing compute?
  • ★ Why does MoE replace the FFN rather than attention?

The number of experts as a new scaling axis ★

The scaling laws in Chapter 3, Section 3.6 mainly look at parameters, data and compute. MoE adds a new axis: increase the number of experts while keeping per-token compute fixed. Switch Transformer's experiments showed that with FLOPs per token held fixed, doubling the number of experts from 2 all the way to 256 kept lowering test loss and kept reducing the training steps needed to reach a given loss; the paper calls the number of experts the most efficient dimension along which they scaled the model. The reason is simple: each extra expert adds another block of parameters that can store knowledge, while the router's cost for scoring one more expert is negligible.

But the gains aren't unlimited. ST-MoE (Zoph et al. 2022), summarizing earlier experiments, noted that beyond roughly 256 experts, or equivalently below roughly 1% of experts activated, the marginal benefit of adding experts drops quickly. Meanwhile, more experts mean more memory, more communication and harder load balancing, and each expert receives fewer tokens per batch, which hurts hardware efficiency. So choosing the number of experts \(E\) and the number activated \(k\) is fundamentally a trade-off between model quality and system efficiency. The fine-grained experts of 4.4 take a different route: instead of simply adding more experts of the same size, they make experts smaller and activate more of them, getting more flexible combinations at the same compute.

Interview questions

  • ★ Does adding experts keep improving quality? How do you choose the number of experts?

Total vs active parameters ★★

A common interview question: why does Mixtral 8x7B have 47B total parameters rather than \(8 \times 7 = 56\)B, and 13B active parameters rather than 14B? Because only the FFN is copied 8 times; attention, the embeddings and the normalization layers are shared by all experts and counted once. The 8 experts' FFNs add up to about 45B and the shared parts to about 1.6B, about 47B in total. Each token picks 2 experts, so what's active is 2 experts' FFNs (about 11B) plus all the shared parts, about 13B. Using the estimate from Chapter 1, Section 1.8, each token's forward pass costs about \(2 \times 13\text{B} = 26\) GFLOPs, while a dense model with the same total parameters would need about 94 GFLOPs, roughly 3.6 times more.

So the name "8x7B" only means "8 experts, with each path the size of a 7B model"; it isn't 8 independent 7B models glued together. Newer names are more direct: in Qwen3-235B-A22B, for example, A22B means "22B activated".

Interview questions

  • ★★ Why does Mixtral 8x7B have 47B total and 13B active parameters?

4.2 Routing and Gating ★★

\[h = W_r\, x \in \mathbb{R}^{E}, \qquad \mathcal{T} = \mathrm{TopK}(h, k), \qquad g_i = \begin{cases} \dfrac{\exp(h_i)}{\sum_{j \in \mathcal{T}} \exp(h_j)}, & i \in \mathcal{T} \\[2mm] 0, & i \notin \mathcal{T} \end{cases}, \qquad y = \sum_{i \in \mathcal{T}} g_i\, \mathrm{FFN}_i(x)\]

Top-k gating ★★

The router is just a linear layer. \(x\) is the token's hidden state as it enters the MoE layer (\(d\)-dimensional), and \(W_r\) is the \(E \times d\) routing matrix; think of each expert as having a \(d\)-dimensional "centroid", so \(h_i\) is the dot product between the token and expert \(i\)'s centroid, measuring how well the token suits that expert. \(\mathrm{TopK}(h, k)\) takes the \(k\) highest-scoring experts, forming the set \(\mathcal{T}\). A softmax over just these \(k\) scores gives the weights \(g_i\), and all other experts get weight 0. The final output \(y\) is the weighted sum of the selected experts' outputs, added back to the residual stream through the residual connection. The router has only \(E \times d\) parameters, negligible compared with the whole model.

There are several variants in practice. The formula above is "pick the top-k first, then softmax over the selected experts" (as in Mixtral), so the selected weights sum to 1. Another is "softmax over all \(E\) experts first, then keep the top-k probabilities" (as in GShard and Switch), optionally renormalized. Both pick the same experts; they differ in the scale of the weights and in the gradients. DeepSeek-V3 instead computes each expert's affinity score with a sigmoid and then normalizes among the selected experts.

How does the router learn? Top-k selection itself is discrete and not differentiable. But the selected experts' outputs are multiplied by \(g_i\), which is a differentiable function of \(h\), so gradients reach the router through \(g_i\): if an expert's output helped lower the loss, the gradient raises its weight, and the router will tend to send similar tokens to it in the future. Experts that weren't selected get no gradient from this token. Even Switch Transformer, with \(k = 1\), multiplies the expert output by the gate value precisely so the router gets a training signal. (Early work by Shazeer et al. 2017 also added noise to the logits to encourage exploration.)

How to choose \(k\)? \(k = 1\) (Switch) is cheapest in compute and communication, but each token has only one path, so a routing mistake is costly. \(k = 2\) (GShard, Mixtral) is more stable and works better, because combining several experts is smoother. Fine-grained MoE picks 8 out of 128–256 small experts (see 4.4). The larger \(k\), the more compute and communication per token.

Interview questions

  • ★★ Write down the top-k gating formula for MoE.
  • ★ Top-k selection isn't differentiable, so how does the router get gradients?
  • ★ What are the pros and cons of top-1 vs top-2 routing?

Implementing the MoE forward pass ★

# x: [T, d] tokens in the batch;  W_r: [E, d] router;  experts: list of E FFNs
logits = x @ W_r.T                            # [T, E] router scores
topk_val, topk_idx = logits.topk(k, dim=-1)   # [T, k] chosen experts for each token
gates = softmax(topk_val, dim=-1)             # [T, k] weights over the chosen k
y = zeros_like(x)
for e in range(E):
    tok, slot = where(topk_idx == e)          # which tokens chose expert e, and in which slot
    if len(tok) == 0:
        continue
    out = experts[e](x[tok])                  # run expert e only on its own tokens
    y[tok] += gates[tok, slot, None] * out    # weighted add back to each token's output
# the load-balancing loss (4.3) is computed from softmax(logits) over all E experts

"Write an MoE layer by hand" is a common interview coding question, and the code above is the most direct version. It has five steps: the router scores each token; each token takes its top-k experts; a softmax over the chosen \(k\) scores gives the weights; tokens are grouped by expert, so each expert processes only the tokens that chose it; finally the expert outputs are multiplied by the weights and added back at each token's position. The \(P_i\) needed by the load-balancing loss (see 4.3) comes from a softmax over all \(E\) experts.

The code also exposes the core engineering difficulty of MoE: the number of tokens each expert receives isn't fixed and changes at every step. GPUs are best at large, regularly shaped matrix multiplications, but here we loop \(E\) times, each time processing a small, varying number of tokens, which launches many small kernels and is very inefficient. Production implementations usually first reorder tokens by expert ID (permute) so each expert's tokens sit contiguously in memory, then compute all experts at once with a single grouped GEMM, and finally put the results back in the original order (unpermute). If expert capacity is used (see 4.3), each expert's input is padded or truncated to a fixed length in exchange for regular shapes. Across multiple GPUs, the "group by expert" step becomes the all-to-all communication of 4.6.

Interview questions

  • ★ Write the forward pass of an MoE layer. Why is it hard to make efficient in practice?

Do experts specialize by domain? ★

The name "expert" makes it tempting to think each expert handles one domain, say one for math and one for code. But the analysis in the Mixtral paper found no clear topic-based specialization: the share of tokens each expert receives is similar across different domains of The Pile (math, biology, philosophy, code and so on). Instead, there are patterns at the syntax and token level: words like self in Python and Question in English are often sent to the same expert, indentation tokens in code always go to the same expert, and consecutive tokens are often assigned the same expert. So MoE "experts" are better seen as computation branches the model learns on its own, split by some internal features, rather than domain experts in the human sense, and they are hard to interpret directly.

Interview questions

  • ★ Do MoE experts specialize by domain, such as math or code?

4.3 Load Balancing ★★

Why routing collapses ★★

Without any constraint, MoE training easily falls into routing collapse: most tokens are sent to a few experts while the rest sit almost idle. The cause is a "rich get richer" feedback loop. At the start of training the router is randomly initialized, and some experts happen to receive slightly more tokens. Experts that get more tokens get more gradient updates and become better; the router notices they work well and sends them even more tokens; so they get even more training, and so on. A few experts grow stronger and stronger, while the rest, receiving almost no tokens, never get trained well, so the router is even less likely to pick them.

Collapse has three consequences. First, wasted capacity: unused experts are parameters that occupy memory for nothing, and the model's effective capacity shrinks to something close to a small dense model, defeating the purpose of MoE. Second, poor compute efficiency: in expert parallelism (see 4.6), different experts live on different GPUs, the most heavily loaded GPU sets the speed of the whole layer, and the other GPUs just wait. Third, dropped tokens: if each expert has a capacity limit, tokens that don't fit into an overloaded expert are dropped (see below), which hurts quality.

Interview questions

  • ★★ Why does load imbalance happen in MoE, and what are its consequences?

Auxiliary load-balancing loss ★★

\[\mathcal{L}_{\text{aux}} = \alpha \cdot E \cdot \sum_{i=1}^{E} f_i\, P_i, \qquad f_i = \frac{1}{T}\sum_{t=1}^{T} \mathbb{1}\{\text{token } t \text{ is routed to expert } i\}, \qquad P_i = \frac{1}{T}\sum_{t=1}^{T} p_i(x_t)\]

The classic fix is to add an auxiliary loss on top of the language-modeling loss that penalizes unbalanced routing. The formula above is Switch Transformer's version (Fedus et al. 2021). \(T\) is the number of tokens in a batch, \(f_i\) is the fraction of tokens actually sent to expert \(i\), \(P_i\) is the router's average probability for expert \(i\) (\(p_i(x_t)\) is token \(x_t\)'s softmax probability for expert \(i\)), and \(\alpha\) is the loss coefficient; Switch uses 0.01. (With top-k routing, \(f_i\) is further divided by \(k\) for normalization.)

Why use the product of \(f_i\) and \(P_i\)? Because \(f_i\) is a counted fraction and not differentiable, while \(P_i\) is an average of softmax probabilities and is differentiable. Taking the derivative with respect to \(P_i\), the gradient is proportional to \(f_i\), so the more heavily loaded an expert, the harder its routing probability is pushed down, and tokens get pushed toward lightly loaded experts. When routing is perfectly uniform, \(f_i = P_i = 1/E\) and \(\sum_i f_i P_i = 1/E\); multiplying by \(E\) gives exactly 1, so the size of this loss doesn't change with the number of experts, and \(\alpha\) can be reused across configurations. A tiny extreme example: with only 2 experts and every token going to expert 1, \(f = (1, 0)\); if the average routing probabilities are \(P = (0.9, 0.1)\), the loss is \(\alpha \cdot 2 \cdot 0.9 = 1.8\alpha\), much larger than the uniform value \(\alpha\), and the gradient acts only on \(P_1\), pushing expert 1's probability down.

The auxiliary loss has a fundamental tension: its gradient conflicts with the language-modeling objective. If \(\alpha\) is too small, it can't stop collapse; if \(\alpha\) is too large, the router spreads tokens evenly for the sake of balance regardless of their content, experts can't specialize, and language-modeling quality drops. This is exactly the motivation for the auxiliary-loss-free method in 4.5.

Interview questions

  • ★★ Write down the auxiliary load-balancing loss and explain why it uses \(f_i \cdot P_i\).
  • ★ What happens if the load-balancing coefficient is too large or too small?

The scope of balancing ★

Load balancing has another easily overlooked design choice: over what scope \(f_i\) and \(P_i\) are counted. The scope can be a single sequence, a micro-batch, or the whole global batch (the tokens of all data-parallel replicas together). Different scopes give constraints of very different strength.

The smaller the scope, the stronger the constraint. If every sequence has to be balanced internally, then even a document that is pure code must spread its tokens evenly over all experts, and experts can't specialize by content. A common choice is to count within each micro-batch, but a micro-batch often holds only a few sequences whose content may come from a single domain, so the problem is similar.

The larger the scope, the looser the constraint. Counting over the global batch only requires overall balance: code tokens in one micro-batch may concentrate on a few experts, as long as other content in other micro-batches goes to other experts. The global-batch load-balancing loss adopted by Qwen3 (Qiu et al. 2025) follows this idea, aiming to leave room for expert specialization.

But too large a scope has risks too. Overall balance doesn't mean balance at every step and on every GPU. If all the tokens of one long sequence crowd onto a few experts, the GPUs holding those experts still become the bottleneck during actual computation. DeepSeek-V3 relies mainly on batch-level bias adjustment (see 4.5) while keeping a sequence-level balance loss with a tiny coefficient, precisely to prevent extreme imbalance within a single sequence. So choosing the scope is fundamentally a trade-off between expert specialization (quality) and per-step compute balance (efficiency).

Interview questions

  • ★ What difference does it make whether load balance is counted per sequence, per micro-batch or per global batch?

Expert capacity and token dropping ★

\[\text{capacity} = \mathrm{CF} \times \frac{k \cdot T}{E}\]

In many implementations (especially GShard and Switch on TPUs), the number of tokens each expert can process in a batch is capped; this is called the expert capacity. \(T\) is the number of tokens in the batch, \(k \cdot T / E\) is how many tokens each expert would get under perfectly uniform routing, and \(\mathrm{CF}\) is the capacity factor. The cap exists because the hardware and communication libraries want fixed-shape tensors: a fixed-size buffer has to be allocated for each expert in advance, and all-to-all communication is also more efficient that way.

If an expert receives more tokens than its capacity, the extra tokens are dropped: they skip the expert computation in this layer and pass unchanged to the next layer through the residual connection. Such a token gets no FFN processing in that layer, which hurts quality. A capacity factor above 1 (say 1.25) leaves some slack and reduces dropping, at the cost of useless computation on empty slots and more memory and communication bandwidth. Switch Transformer found that smaller capacity factors (1.0–1.25) already work well, and with the auxiliary loss usually fewer than 1% of tokens are dropped.

Dropping tokens causes an extra problem at inference: whether a token is dropped depends on the token distribution of other requests in the same batch, so the same input can produce different outputs in different batches. So the trend now is dropless MoE: MegaBlocks (Gale et al. 2022) uses block-sparse matrix operations to handle a different number of tokens per expert without a fixed capacity, and DeepSeek-V3, thanks to good load balancing, drops no tokens in either training or inference.

(There is also a reversed routing scheme called expert choice (Zhou et al. 2022): instead of each token picking \(k\) experts, each expert picks a fixed number of its highest-scoring tokens, so the load is perfectly balanced by construction and no auxiliary loss is needed. The cost is that some tokens may not be picked by any expert, and an expert has to see all the tokens in the batch before choosing, including later tokens of the same sequence, which breaks the causality of autoregressive generation; that's why mainstream decoder-only LLMs rarely use it.)

Interview questions

  • ★ What is expert capacity, and what happens to tokens that exceed it?
  • ★ What is the cost of setting the capacity factor high vs low?
  • ★ How do token-choice and expert-choice routing differ, and why do LLMs rarely use expert choice?

4.4 Fine-Grained and Shared Experts ★

\[y = x + \sum_{i=1}^{K_s} \mathrm{FFN}^{(s)}_i(x) + \sum_{i=1}^{N_r} g_i\, \mathrm{FFN}^{(r)}_i(x)\]

DeepSeekMoE (Dai et al. 2024) pointed out that conventional MoE (say, choosing 2 out of 8 or 16 experts) has two problems that limit how specialized experts can become. One is knowledge hybridity: with few experts, each one is forced to cover many different kinds of knowledge and can hardly specialize. The other is knowledge redundancy: some knowledge is needed by almost every token (such as basic grammar and common expressions), so different experts each have to learn it separately, wasting parameters on duplicates. It proposed two improvements for these two problems.

Fine-grained expert segmentation: split each expert into \(m\) smaller experts (each with \(1/m\) of the original FFN hidden dimension), and multiply the number of activated experts by \(m\). The total parameter count and per-token compute stay the same, but the number of possible expert combinations grows enormously. The paper's example: choosing 2 out of 16 experts gives only 120 combinations; splitting into 64 experts and choosing 8 gives 4,426,165,368. With more flexible combinations, each small expert can handle narrower, more specialized knowledge, and the pieces are combined as needed.

Shared expert isolation: set aside \(K_s\) experts as shared experts that every token always passes through, with no routing. In the formula, the second term is the shared experts, the third term is the weighted sum over the \(N_r\) routed experts (only the selected \(g_i\) are non-zero), and \(x\) is the residual. The shared experts absorb general knowledge, so the routed experts don't need to relearn it and can focus on their own specialized knowledge, reducing redundancy.

The cost is mainly on the engineering side. With more and smaller experts, routing overhead rises, each token is sent to more destinations, and all-to-all communication becomes more fragmented; each small expert's matrix multiplication is smaller, so GPU utilization drops, and special kernels such as grouped GEMM are needed to execute many small matrix multiplications together. The design is widely adopted: DeepSeek-V2/V3 both use fine-grained plus shared experts (V3 has 1 shared expert and 256 routed experts, choosing 8 per token). Qwen3's MoE also uses fine-grained experts (choosing 8 of 128) but drops the shared experts, showing that shared experts aren't strictly necessary and design choices still differ.

Interview questions

  • ★ What problems do DeepSeekMoE's fine-grained experts and shared experts each solve?
  • ★ Are finer-grained experts always better?

4.5 Auxiliary-Loss-Free Load Balancing ★

\[g_i = \begin{cases} s_i, & s_i + b_i \in \mathrm{TopK}\big(\{s_j + b_j\}_{j=1}^{N_r},\ k\big) \\ 0, & \text{otherwise} \end{cases}, \qquad b_i \leftarrow \begin{cases} b_i - \gamma, & \text{expert } i \text{ overloaded} \\ b_i + \gamma, & \text{expert } i \text{ underloaded} \end{cases}\]

As 4.3 explained, the auxiliary loss's gradient conflicts with the language-modeling objective, and a large coefficient hurts quality. DeepSeek-V3 adopts a load-balancing method that doesn't rely on a loss (Wang et al. 2024): each expert \(i\) gets a bias \(b_i\) that is used only for choosing experts, not for computing the weights. In the formula, \(s_i\) is the token's affinity score for expert \(i\); top-k selection uses \(s_i + b_i\), but the gate weight multiplied onto the expert's output is still determined by the original \(s_i\) (then normalized among the selected experts).

The bias isn't learned by gradient descent; it is adjusted like a feedback controller. At the end of each training step, the load of each expert over the whole batch is measured: overloaded experts have \(b_i\) decreased by \(\gamma\), and underloaded experts have \(b_i\) increased by \(\gamma\). \(\gamma\) is called the bias update speed (DeepSeek-V3 used 0.001, and set it to 0 for the final stretch of training). As an overloaded expert's bias keeps shrinking, it becomes harder and harder to select, and tokens naturally flow to idle experts until the load is balanced.

The benefit: load balancing is achieved entirely by adjusting "whom to choose", with no extra gradient interfering with the language-modeling objective, and the gate weights still reflect how well the token truly matches each expert. DeepSeek-V3 reports that this method keeps the load balanced while performing better than relying purely on auxiliary losses. To prevent extreme imbalance within a single sequence, DeepSeek-V3 still keeps a complementary sequence-level balance loss with a tiny coefficient (0.0001), together with routing that limits each token to at most 4 nodes (see 4.6). With this strategy, it drops no tokens in training or inference.

Method How it balances Interference with the LM objective Used by
Auxiliary loss Extra loss pushes router probabilities of overloaded experts down Yes; grows with the coefficient \(\alpha\) GShard, Switch Transformer
Capacity limit + token dropping Hard cap per expert; overflow tokens skip the expert No gradient conflict, but dropped tokens lose computation GShard, Switch Transformer (with the auxiliary loss)
Global-batch auxiliary loss Same loss, with loads counted over the whole global batch Yes, but a looser constraint that allows specialization Qwen3
Auxiliary-loss-free bias Per-expert bias shifts top-k selection, updated after each step None: the bias isn't trained by gradient and doesn't enter the gate weights DeepSeek-V3 (plus a tiny sequence-level loss)

Interview questions

  • ★ How does DeepSeek-V3's auxiliary-loss-free load balancing work, and why is it better than an auxiliary loss?
  • ★ Why is the bias used only for selecting experts and not for computing the gate weights?

4.6 Expert Parallelism and All-to-All Communication ★

each GPU: its own tokens → router picks k experts per token
   → all-to-all (dispatch): send each token to the GPUs that hold its experts
   → each GPU runs its local experts on the tokens it received
   → all-to-all (combine): send expert outputs back to the tokens' home GPUs
   → weighted sum by gate values → residual add → next layer

Large MoE models have too many experts to keep a copy on every GPU. Expert parallelism (EP) places different experts on different GPUs, so each GPU stores only some of the experts. Shared parts such as attention are still handled with data parallelism, tensor parallelism and so on (see Chapter 5, Sections 5.6–5.9).

The problem is that the experts a GPU's tokens need may live on other GPUs. So each MoE layer performs two all-to-all communications. The first is dispatch: each GPU sends its tokens to the GPUs that hold their target experts. After the experts compute, the second is combine: the results are sent back to the GPUs where the tokens came from and summed with the gate weights. That's two per layer in the forward pass, and two more in the backward pass. Roughly speaking, each token sends out \(k\) copies of its \(d\)-dimensional hidden state and receives \(k\) back, so communication grows in proportion to the number of tokens, \(k\) and the hidden dimension.

All-to-all is expensive because it is many-to-many communication where "every GPU exchanges data with every other GPU". Inside one machine, GPUs are linked by fast NVLink; across machines, traffic goes over networks like InfiniBand with several times less bandwidth. Once experts are spread across machines, communication easily becomes the bottleneck, sometimes taking longer than the expert computation itself. Load balance also directly affects efficiency: if some experts are hot, the GPUs holding them process far more tokens than the others, and the whole layer waits for the slowest GPU.

Common mitigations: limit how many nodes each token reaches, e.g. DeepSeek-V3 sends each token to at most 4 nodes, choosing nodes first and then experts within them, which cuts cross-machine traffic; overlap communication with computation, computing one chunk of data while another chunk is in flight (DeepSeek-V3 designed the DualPipe pipeline schedule for this); and good load balancing (4.3–4.5) to avoid straggler GPUs.

Interview questions

  • ★ What is expert parallelism, and why does it need all-to-all communication?
  • ★ Where is the communication bottleneck in MoE training, and how can it be mitigated?

Combining EP with other parallelism ★

In real systems, expert parallelism is always combined with other forms of parallelism, and different parts of the model are split differently: dense parts such as attention use data, tensor or pipeline parallelism (see Chapter 5, Sections 5.6–5.9), while MoE layers use expert parallelism. Why split them differently? Every token passes through the dense parts, so they are best split by data or by matrix; most of an MoE layer's parameters sit in the experts, so splitting by expert lets each GPU store only some of the experts, while each token only needs to visit \(k\) of them.

Training and inference are split differently, and within inference so are prefill and decode. At decode time the experts are usually spread more thinly, with only one or a few experts per GPU (DeepSeek-V3's decode deployment, for example, uses 320 GPUs for expert parallelism). This addresses exactly the issue covered in 4.8: at each decode step every request produces only one token, so to give each expert enough tokens to keep its GPU busy, many concurrent requests have to be pooled. The more thinly the experts are spread, the less expert weight each GPU has to store, so more memory is left for the KV cache and larger batches; the tokens from all requests that chose the same expert are sent to that GPU together and computed as one batch. It also shows that deploying a large MoE is fundamentally a distributed-systems engineering problem, not just a choice of model architecture.

Interview questions

  • ★ How are the different forms of parallelism usually combined when training and serving a large MoE?

4.7 Training Instability and Router Z-Loss ★

\[\mathcal{L}_z = \frac{1}{T}\sum_{t=1}^{T}\Big(\log \sum_{j=1}^{E} e^{h_j^{(t)}}\Big)^2, \qquad \mathcal{L} = \mathcal{L}_{\text{CE}} + c_B\, \mathcal{L}_{\text{aux}} + c_z\, \mathcal{L}_z\]

MoE models are more prone than dense models to loss spikes and even divergence. An important cause is the router: router logits can grow larger and larger during training, softmax contains an exponential, and in low-precision formats like bf16 the rounding errors of large values are amplified by the exponential. Meanwhile top-k selection is discrete, so a small perturbation of the logits can change which expert gets chosen, abruptly switching the token's computation path, which shows up as discontinuous jumps during training.

Switch Transformer's response was selective precision: compute the router in fp32 while keeping the rest in bf16, and use a smaller initialization scale. But ST-MoE (Zoph et al. 2022) found this wasn't enough at larger scales, so it proposed the router z-loss. In the formula, \(h_j^{(t)}\) is token \(t\)'s routing logit for expert \(j\), and \(\log \sum_j e^{h_j}\) is the log-sum-exp of the logits, roughly tracking the size of the largest logit. Squaring it as a penalty keeps the routing logits in a smaller range and reduces numerical error. The total loss is a weighted sum of the language-modeling loss, the load-balancing loss and the z-loss; ST-MoE uses \(c_z = 0.001\). In their experiments, the z-loss stabilized training without hurting quality, whereas the alternative (tighter update clipping) also stabilized training but clearly hurt quality.

(Two brief side notes: an MoE doesn't have to be trained from scratch; the FFN of an already-trained dense model can be copied into several experts as initialization, called sparse upcycling (Komatsuzaki et al. 2022). And MoE models overfit more easily than dense models when fine-tuned on small datasets; see the question in 4.9.)

Interview questions

  • ★ Why is MoE training less stable, and how does the router z-loss help?

4.8 MoE Inference Trade-offs ★★

\[\text{tokens per expert per step} \approx \frac{B \cdot k}{E}\]

Memory holds everything, compute uses a part ★★

The most striking feature of MoE at inference is that memory and compute are decoupled. Memory has to hold every expert, because the next token might be routed to any of them, while each token's computation uses only the active parameters. Take Mixtral 8x7B: its 47B parameters take about 94 GB in bf16, which doesn't fit on one 80 GB GPU, so you need either two GPUs or quantization; yet each token's compute is like that of a 13B dense model. DeepSeek-V3's 671B parameters take about 671 GB even in FP8, so it must be deployed across multiple GPUs or even machines, while each token activates only 37B.

So MoE trades "more memory" for "less compute". In the compute-bound prefill stage (see Chapter 1, Section 1.3), less compute directly means more speed. For decode, though, the picture is more complicated and depends on batch size.

Interview questions

  • ★★ At inference, what do an MoE model's memory and compute each depend on?

Batching effects ★★

As Chapter 1, Section 1.3 explained, decode is limited by memory bandwidth, and most of each step's time goes into reading weights from memory. For MoE, each step has to read the weights of "every expert selected by at least one token in this step".

With a very small batch (say, a single user), MoE has a big advantage. Only \(k\) experts per layer are used, so only those \(k\) experts plus the shared parts need to be read, close to the active parameter count. So as long as the whole model fits in memory, Mixtral generates at close to the speed of a 13B model, not a 47B one.

As the batch grows, the advantage gradually disappears. Different tokens in the batch are routed to different experts; with \(B\) tokens each choosing \(k\), soon almost every expert is chosen by at least one token at every step, so almost all the weights must be read each step, close to the total parameter count, about the same as a dense model of that size. Worse, each expert receives only about \(Bk/E\) tokens (see the formula), far fewer than the \(B\) tokens each weight matrix processes in a dense model. Each weight read does very little computation, so arithmetic intensity is low and the GPU's compute units are starved. To make MoE compute-bound and reach high throughput, you need a much larger batch than for a dense model (roughly \(E/k\) times larger).

This explains how MoE is typically deployed: in large-scale online serving, experts are spread across many GPUs with expert parallelism, and many concurrent requests are gathered into large batches, so every expert receives enough tokens and MoE's small per-token compute can fully turn into throughput and cost advantages (at inference DeepSeek-V3 also replicates heavily loaded experts to ease hot spots). Conversely, in local or single-user settings the bottleneck is mainly whether the model fits in memory, which is usually handled with quantization or by keeping some experts in CPU memory (offloading).

Interview questions

  • ★★ What are MoE's advantages and disadvantages at inference with small vs large batches?
  • ★ Why does MoE need larger batches to fully use the GPU?

MoE doesn't shrink the KV cache ★

One more point that's easy to miss: MoE sparsifies only the FFN, while the KV cache comes from attention. Attention in an MoE is still dense and shared by all tokens, so an MoE model's KV cache is exactly as large as that of a dense model with the same attention configuration; activating only a few experts doesn't shrink it (see Chapter 1, Section 1.5 for how the KV cache is computed).

This matters most with long contexts and large batches. Once MoE has pushed per-token FFN compute down, the KV cache becomes an even larger share of the memory footprint and bandwidth cost in decode. So MoE is usually paired with KV-efficient attention: DeepSeek-V2/V3 use MLA, and Qwen3-235B-A22B uses GQA (only 4 KV heads for 64 query heads). Think of the division of labor this way: MoE cuts the FFN's compute, GQA/MLA cut attention's KV cache, and the two are complementary.

Interview questions

  • ★ Does MoE reduce the KV cache? Why is MoE often paired with GQA or MLA?

Local deployment: quantization and expert offloading ★

On a single machine or consumer GPU with limited memory, the problem with MoE is that it "doesn't fit". The first fix is quantization (see Chapter 6, Section 6.5): compressing the weights to 4 bits brings Mixtral's 47B parameters down to about 24 GB, close to what a 24 GB consumer GPU can hold.

The second fix exploits MoE's sparsity through expert offloading: since each token uses only \(k\) experts per layer, keep most experts in CPU memory and copy the selected ones to the GPU only when needed. The problem is that PCIe bandwidth from CPU to GPU is more than an order of magnitude lower than GPU memory bandwidth, so copying an expert takes far longer than computing with it, and generation is slow. There are two common mitigations: cache recently used experts on the GPU, since, as 4.2 noted, consecutive tokens often choose the same experts, so the cache hit rate is decent; and predict which experts the next layer will need and start prefetching them while the current layer is computing. These methods suit single-user, low-throughput settings; with large batches almost every expert is used at every step (see above), and offloading loses its point.

Interview questions

  • ★ How do you run an MoE model locally when GPU memory is insufficient?

4.9 Dense vs MoE ★★

Dense MoE
Parameters used per token All of them Shared parts + \(k\) selected experts
Compute per token \(\propto\) total parameters \(\propto\) active parameters
Memory for weights \(\propto\) total parameters (= active) \(\propto\) total parameters (much larger than active)
Quality at equal training compute Baseline Better: more capacity for the same FLOPs
Quality at equal total parameters Better Worse: a 47B MoE is weaker than a 47B dense model
Training difficulty Stable and simple Load balancing, router instability, token dropping
Parallelism Data, tensor, pipeline Adds expert parallelism with all-to-all communication
Decode at small batch Reads all weights each step Reads only active experts: fast if the model fits
Decode at large batch Good GPU utilization Reads nearly all experts; needs much larger batches
Fine-tuning Straightforward More prone to overfitting on small datasets
Best fit Memory-limited, on-device, simple deployment Large-scale serving, best quality per training FLOP

The table boils down to one sentence: at equal training compute MoE is stronger; at equal total parameters dense is stronger. MoE essentially trades more parameters (memory) and a more complex system for less compute per token. So when compute is the main constraint, memory and engineering capacity are ample, and serving scale is large enough, MoE is the better choice, which is why most frontier models today use MoE. When memory is limited (on-device), concurrency is low, or simple deployment matters, a dense model is often more suitable.

Interview questions

  • ★★ Compare dense and MoE models. When would you choose MoE?
  • ★ What should you watch out for when fine-tuning an MoE model?

    MoE models overfit more easily than dense models when fine-tuned on small datasets: training loss goes lower while validation quality gets worse (Zoph et al. 2022). They found that updating only the non-MoE parameters (such as attention) works about as well as updating all parameters, while updating only the expert parameters works worse; MoE fine-tuning also tends to prefer smaller batches and higher learning rates.


4.10 Representative Models ★

Model Total params Active params Experts per MoE layer Routing Notable design
Mixtral 8x7B (Jiang et al. 2024) 47B 13B 8 Top-2 Coarse experts, no shared expert; matches or beats Llama 2 70B
DeepSeek-V3 (DeepSeek-AI 2024) 671B 37B 1 shared + 256 routed Top-8 routed, sigmoid scores, at most 4 nodes per token Auxiliary-loss-free balancing, no token dropping, MLA attention, first 3 layers dense
Qwen3-235B-A22B (Yang et al. 2025) 235B 22B 128 Top-8 Fine-grained experts, no shared expert, global-batch balancing loss
Qwen3-30B-A3B (Yang et al. 2025) 30B 3B 128 Top-8 Same design at small scale

These models show how MoE design has evolved. First, experts are getting more numerous and finer: from Mixtral's 2 out of 8 large experts, to Qwen3's 8 out of 128 and DeepSeek-V3's 8 out of 256. Second, sparsity keeps increasing: active parameters as a share of total parameters are about 28% for Mixtral, about 9% for Qwen3-235B and about 5.5% for DeepSeek-V3, so the same compute supports ever larger total capacity. Third, load balancing is evolving: from a strong auxiliary loss, to a global-batch auxiliary loss (Qwen3), to the bias-based auxiliary-loss-free method (DeepSeek-V3).

DeepSeek-V3's training cost is often discussed: full training (pretraining, context extension and post-training) took only about 2.788M H800 GPU hours, with pretraining done on 14.8T tokens. The most fundamental reason it was so cheap is MoE: 671B of total capacity, with only 37B parameters of compute per token. On top of that came a set of supporting system designs: FP8 mixed-precision training (see Chapter 5, Section 5.4) cut compute and memory costs; DualPipe overlapped all-to-all communication with computation; limiting each token to at most 4 nodes kept cross-machine communication under control; and auxiliary-loss-free balancing kept the load even across GPUs without dropping tokens. This shows that whether MoE's benefits materialize depends heavily on how well the system around it is designed.

Interview questions

  • ★ Describe the design of an MoE model you know well (e.g. DeepSeek-V3).
  • ★ Why was DeepSeek-V3 so cheap to train?
  • ★ How has MoE design been trending in recent years?