Skip to content
ImagineWorld

Mixture-of-Experts

node_idnode-book_building-frontier-llm-from-scratch_chapter-11-mixture-of-experts
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num11
chapter_titleMixture-of-Experts
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Part IV — Modern LLM Architecture

Part III ended with a confession: the GPT we built is dense, so every parameter does work on every token, and making it more capable means making it proportionally more expensive. Mixture-of-Experts (MoE) breaks that link. It replaces the single feed-forward network with many parallel “experts” and a router that sends each token to only a few of them, so the model can hold an enormous number of parameters while activating only a small fraction per token. This is the single idea behind almost every flagship open model of the current generation — DeepSeek-V3, Qwen3, Llama 4, Kimi K2, gpt-oss — and DeepSeek’s particular formulation has become the template. This chapter builds a working MoE layer and then adds the refinements that make it competitive.

Recall the numbers from Chapter 1: DeepSeek-V3 has 671 billion parameters but activates only 37 billion per token; gpt-oss-120b activates 5.1 of 117 billion. The mechanism is conditional computation — different tokens use different parameters. Instead of one feed-forward network of hidden size H, an MoE layer has E expert networks, each a smaller feed-forward network, plus a router that picks the top k experts for each token. The token is processed only by its chosen experts; the rest sit idle. Total capacity scales with E; per-token cost scales with k. Pulling those two apart is the whole point.

The router is just a linear layer producing one score per expert, followed by a softmax. Each token keeps its k highest-scoring experts, runs them, and combines their outputs weighted by the (renormalized) router probabilities. An expert is exactly the SwiGLU feed-forward network from Chapter 8. The following layer is a complete, runnable MoE.

import torch, torch.nn as nn, torch.nn.functional as F
class Expert(nn.Module): # one expert = a SwiGLU FFN (Ch 8)
def __init__(self, d_model, hidden):
super().__init__()
self.gate = nn.Linear(d_model, hidden, bias=False)
self.up = nn.Linear(d_model, hidden, bias=False)
self.down = nn.Linear(hidden, d_model, bias=False)
def forward(self, x):
return self.down(F.silu(self.gate(x)) * self.up(x))
class MoE(nn.Module):
def __init__(self, d_model, hidden, n_experts, n_active, n_shared=1):
super().__init__()
self.n_active = n_active
self.router = nn.Linear(d_model, n_experts, bias=False) # scores
self.experts = nn.ModuleList(Expert(d_model, hidden)
for _ in range(n_experts))
self.shared = nn.ModuleList(Expert(d_model, hidden)
for _ in range(n_shared))
def forward(self, x): # x: (B, T, d_model)
B, T, C = x.shape
xf = x.view(-1, C) # (N, C): flatten tokens
probs = self.router(xf).softmax(dim=-1) # (N, E)
weights, picks = probs.topk(self.n_active, dim=-1) # (N, k)
weights = weights / weights.sum(dim=-1, keepdim=True) # renorm
out = torch.zeros_like(xf)
for e, expert in enumerate(self.experts):
tok, slot = torch.where(picks == e) # tokens for expert e
if tok.numel() == 0: continue
w = weights[tok, slot].unsqueeze(-1) # gate weights
out[tok] += w * expert(xf[tok]) # run + scatter
for shared in self.shared: # shared: always on
out += shared(xf)
return out.view(B, T, C)

Python — moe.py: a working Mixture-of-Experts layer

Drop this in place of the SwiGLU in the block from Chapter 8 and the model becomes sparse. The loop over experts is the conceptually clear version; at scale the experts live on different GPUs and tokens are shipped to them by an all-to-all communication step (Section 11.5). The two extra arguments — n_shared and the structure of how many experts exist versus how many fire — are where DeepSeek’s design choices enter.

11.3 DeepSeekMoE: Fine-Grained and Shared Experts

Section titled “11.3 DeepSeekMoE: Fine-Grained and Shared Experts”

Early MoE models (like the original Mixtral) used a handful of large experts and routed each token to two of them. DeepSeek’s formulation, DeepSeekMoE, makes two changes that together markedly improve the quality-per-parameter, and both are visible in the code above through the choice of n_experts, n_active, and n_shared:

  • Fine-grained experts. Split the experts into many smaller ones and route to more of them. Instead of 8 experts choosing 2, use 256 experts choosing 8. This gives the router far more combinations to specialize with — the number of ways to pick the active set explodes — at the same total parameter and compute budget. DeepSeek-V3 uses 256 routed experts with 8 active.
  • Shared experts. Reserve one or more experts that every token uses (the shared list above). These absorb the common, general-purpose computation that would otherwise be redundantly learned by every routed expert, freeing the routed experts to specialize. DeepSeek-V3 uses one shared expert alongside its 256 routed ones.

Figure 11.1 shows the resulting layer, and Table 11.1 compares the routing configurations across families — note how the field has converged on DeepSeek’s fine-grained, low-active-fraction recipe.

[!visual-conversion] Diagram, PDF 115 (printed 117). The note above the expert row reads “router sends token to its top-k experts (E2, E4 shaded)”. The idle experts are drawn dashed; E2, E4 and the shared expert are shaded.

flowchart TB
    t["token"] --> r["router (softmax, top-k)"]
    r --> E2["E2"]
    r --> E4["E4"]
    E1["E1"] ~~~ E2
    E3["E3"] ~~~ E4
    dots["…"] ~~~ E256["E256"]
    t --> sh["shared (always)"]
    E2 --> ws["weighted sum"]
    E4 --> ws
    sh --> ws
    ws --> out["output"]
    classDef idle stroke-dasharray: 4 3
    classDef active fill:#999
    class E1,E3,dots,E256 idle
    class E2,E4,sh active

Figure 11.1. A DeepSeekMoE layer. The router activates a few of many fine-grained experts (E2, E4 here, of 256), while one or more shared experts process every token. Outputs are combined by the router weights. Total parameters grow with the number of experts; per-token cost is set only by the few that fire plus the shared expert.

ModelRouted expertsActiveSharedBalancing
Mixtral 8×7B / 8×22B820auxiliary loss
Qwen3-235B12880auxiliary loss
gpt-oss-120b12840auxiliary loss
DeepSeek-V325681auxiliary-loss-free

Table 11.1 — MoE routing configurations across families

Configurations are approximate and vary by model size within a family. The direction of travel is unmistakable: more, smaller experts; a low active fraction; and, increasingly, DeepSeek’s bias-based balancing.

11.4 Load Balancing Without Hurting the Loss

Section titled “11.4 Load Balancing Without Hurting the Loss”

MoE has a characteristic failure mode: routing collapse. If a few experts get slightly favored early in training, they receive more tokens, train faster, become more attractive, and the router sends them still more — until most experts are starved and the model is effectively dense over a handful of them. Preventing this is the central engineering problem of MoE training.

The traditional fix is an auxiliary load-balancing loss added to the training objective, penalizing uneven expert usage so gradients push the router toward uniform load. It works, but it is a tax on the model: it fights the language-modeling objective, and tuning its strength is finicky — too weak and experts collapse, too strong and quality suffers. DeepSeek-V3’s notable contribution here is an auxiliary-loss-free scheme. Instead of a loss, each expert gets a learnable bias added to its router score; the bias is nudged up for underused experts and down for overused ones between steps, balancing load directly without ever perturbing the gradient of the main objective. The result is balanced experts and a cleaner loss — one of several reasons DeepSeek-V3 trained so efficiently.

Why this matters for you If you train an MoE and watch a few experts dominate while others go dead, you are seeing routing collapse. The bias-based balancer is a few lines — track each expert’s recent token count and adjust its router bias toward the target load each step — and it is far less fiddly than tuning an auxiliary loss coefficient. This is the kind of hard-won detail that separates an MoE that trains from one that does not.

A 256-expert layer does not fit on one GPU, so experts are spread across devices — expert parallelism. Each token must then be sent to whichever GPUs hold its chosen experts (an all-to-all “dispatch”), processed, and the results gathered back (an all-to-all “combine”). This communication can dominate the layer’s cost, which is why DeepSeek open-sourced a dedicated library for it. We cover the systems side properly in Chapter 19; for now, know that the clean per-expert loop in our code becomes, at scale, a carefully overlapped communication pattern.

The auxiliary-loss-free balancing of Section 11.4 is worth seeing in its real form, because the trick is subtle and the code makes it precise. Here is the essence of DeepSeek-V3’s Gate, reproduced — a router that adds a learned per-expert bias when choosing which experts to use, but uses the unbiased affinity when weighting their outputs:

class Gate(nn.Module):
def __init__(self, dim, n_experts, n_active):
super().__init__()
self.weight = nn.Parameter(torch.empty(n_experts, dim))
self.bias = nn.Parameter(torch.zeros(n_experts)) # balances load
self.topk = n_active
def forward(self, x):
scores = F.linear(x, self.weight).sigmoid() # per-expert affinity
# selection adds the bias; the WEIGHT below does not
idx = torch.topk(scores + self.bias, self.topk, dim=-1)[1]
weights = scores.gather(1, idx) # unbiased affinities
weights = weights / weights.sum(dim=-1, keepdim=True)
return weights, idx

Python — deepseek-ai/DeepSeek-V3 · model.py: Gate, essence (reproduced, MIT licence)

The single line scores + self.bias is the whole innovation. The bias enters only the topk that selects experts, so an overloaded expert can be made less attractive (its bias driven down) and an idle one more attractive (its bias driven up) — and the bias is adjusted by a simple rule between steps, not by a gradient from a balancing loss. But the weights actually used to combine the experts’ outputs come from scores alone, the true learned affinities, untouched by the balancing. Load is balanced without ever distorting the gradient the model learns from — the property Section 11.4 promised, in five lines. DeepSeek-V3’s full Gate adds group-limited routing (restricting each token to experts within a few groups, to bound communication), and its MoE class wraps routed and shared experts exactly as our layer does; the DeepEP library then makes the dispatch-and-combine efficient across hundreds of GPUs, as Chapter 19 details.

Mixture-of-Experts solves the capacity problem: the model can be vast yet cheap to run per token. But a large MoE still has the second cost of Chapter 10’s GPT — a key/value cache that grows with context and dominates memory at inference. The next chapter attacks exactly that, with the second of DeepSeek’s signature innovations: Multi-head Latent Attention.

11.6 Worked Example: Routing a Token Through the Experts

Section titled “11.6 Worked Example: Routing a Token Through the Experts”

A mixture-of-experts layer replaces one big feed-forward network with many smaller ones and a router that sends each token to just a few. Watching a single token flow through makes the mechanism concrete: the router scores every expert, the top few are selected, their outputs are weighted by the router’s confidence and summed:

def moe_forward(x, gate, experts, k=8):
scores = x @ gate.T # router logit per expert
top = scores.topk(k, dim=-1) # pick k experts per token
w = F.softmax(top.values, dim=-1) # weight the chosen experts
out = sum(w[:, j:j+1] * experts[top.indices[:, j]](x)
for j in range(k))
return out # sum of k expert outputs

Python — moe/route.py: top-k routing and combine (illustrative)

The decisive property is that the cost of this layer is set by k, the number of experts activated, not by the total number of experts available. A layer with 256 experts but k = 8 runs only eight feed-forward networks per token — the same compute as a model with eight experts, but with the knowledge capacity of 256. This is the entire bargain of sparsity (quantified in Section 45.6): the parameter count, and thus the model’s capacity, scales with the expert count, while the per-token compute scales only with k. The price is the routing itself, including the load-balancing problem of Section 11.4 that DeepSeek-V3’s bias-based scheme (Section 45.7) solves so cleanly.

Capacity scales with experts, cost scales with k Top-k routing decouples how much a model knows from how much it computes per token. Add experts to grow capacity; the forward pass still runs only k of them. That decoupling is why every frontier model in this book is a mixture of experts.

11.7 Fine-Grained Experts and the Shared Expert

Section titled “11.7 Fine-Grained Experts and the Shared Expert”

The mixture-of-experts of Section 11.6 is the textbook version; the form used in DeepSeek-V3 and GLM-5.2 refines it in two ways that together improve specialization without raising the per-token compute. The first is fine-grained experts: rather than a few large experts, split each into several smaller ones and activate proportionally more of them. With more, smaller experts the router has many more combinations to choose from for each token, allowing finer specialization at the same active-parameter budget — eight of two hundred and fifty-six small experts is far more expressive than two of eight large ones, for the same compute.

The second refinement is the shared expert: one expert (or a small number) that every token passes through, alongside the routed ones. The intuition is a division of labor. Common, broadly useful computation — the patterns nearly every token needs — is handled once by the shared expert, which frees the routed experts to specialize on the narrower patterns that distinguish tokens from one another, rather than each redundantly relearning the common case. Together these give DeepSeekMoE its character: many fine-grained routed experts for specialization, plus a shared expert for the common ground, all at a fixed activated-parameter cost (Section 45.6). Both choices appear directly in the configurations dissected in Chapters 44 and 45, and both are now widely adopted across the open MoE models.

More, smaller experts; plus one for everyone Fine-grained experts give the router more combinations and finer specialization at the same compute; a shared expert handles the common case so the routed ones need not relearn it. Together they define the modern MoE used by DeepSeek-V3 and GLM-5.2.

The central training hazard of a mixture of experts is routing collapse. Early in training, the router (Section 11.4) may by chance favor a few experts; those experts then receive most of the tokens, get most of the training, and improve faster — which makes the router favor them even more. This rich-get-richer feedback loop concentrates all the work on a handful of experts while the rest languish unused, and an MoE whose experts have collapsed this way has squandered its capacity, behaving like a much smaller dense model wearing an expensive costume.

The classic remedy is an auxiliary load-balancing loss: an extra term added to the objective that penalizes imbalance in how tokens are distributed across experts, actively pushing the router to spread them evenly. This works, but it has a cost — the auxiliary loss pulls against the main language-modeling objective, trading a little quality for balance. DeepSeek-V3’s refinement (Section 45.7) is to achieve balance without an auxiliary loss, by adjusting a per-expert bias that nudges routing toward underused experts without adding a competing term to the loss. Either way, load balancing is not an optional nicety but a precondition for a mixture-of-experts model to work at all: the entire premise of MoE — many experts, each specializing (Section 11.7) — depends on the tokens actually reaching all of them, and preventing collapse is what keeps the architecture’s promised capacity from quietly evaporating during training.

Balance is a precondition, not a nicety Without intervention, MoE routing collapses onto a few experts in a rich-get-richer loop, wasting capacity. An auxiliary balancing loss spreads tokens evenly at some cost to the objective; DeepSeek’s bias adjustment balances without that cost. Either way, balance is what makes MoE work.