Skip to content
LearnAI

4.3Mixture of Experts

How models like Mixtral, DeepSeek-V3 and Qwen3 hold hundreds of billions of parameters but use only a small fraction for each token, and what keeps their routers honest.

⏱ 13 minIntermediate

More knowledge, same compute

In a standard Transformer block, most parameters live in the feed-forward network (the MLPMLP (feed-forward network)A multi-layer perceptron: linear layers with nonlinear activations between them. Each Transformer block contains one.), not in attention. In Llama-3-8B, for example, each layer’s MLP has about 176 million weights against about 42 million for attention. Every token passes through all of them. That is a dense model: every parameter participates in every token.

Scaling laws say that bigger models learn more from the same data. But in a dense model, doubling the parameters doubles the cost of every token, in training and in inference. A Mixture of ExpertsMixture of Experts (MoE)An architecture in which each token is routed to a few of many 'expert' sub-networks, so total parameters can be huge while compute per token stays small. (MoE) breaks that link. It keeps many copies of the MLP, called experts, and for each token runs only a few of them. A small learned routerRouter (gating network)The small learned layer in a Mixture-of-Experts block that scores every expert for each token and picks the top-k experts that will process it. decides which.

The result is two different parameter counts. Total parameters measure capacity, what the model can store. Active parametersActive parametersIn an MoE model, the parameters actually used for a given token. Usually a small fraction of the total. measure how much compute each token costs. Mixtral 8x7B has about 47B total but 13B active parameters, so it runs at roughly the cost of a 13B dense model while drawing on far more stored knowledge.

ANALOGY· A clinic with a receptionist

A clinic employs eight specialists. Rather than having every patient see all eight (slow and expensive), a receptionist glances at each patient and sends them to the two specialists who seem most relevant. Each patient’s treatment combines those two opinions, weighted by how confident the receptionist was.

The specialists are the experts; the receptionist is the router; “two” is top-k. Problems appear quickly. If the receptionist sends everyone to the same popular specialist, a queue forms (load imbalance). If that specialist’s waiting room has limited seats, overflow patients are turned away (token dropping at a capacity limit). Some clinics also have a general practitioner that every patient sees regardless: that’s a shared expert.

Inside an MoE layer

For a token with hidden vector xx, the router is just a linear layer: it computes one score (logit) per expert, si=x⋅ris_i = x \cdot r_i, and turns them into probabilities with a softmax. It keeps the top-k experts, renormalizes their probabilities to sum to 1, runs the token through those k experts only, and adds up their outputs weighted by those gate values:

y=∑i∈TopK(s)gi Ei(x),gi=esi∑j∈TopK(s)esj.y = \sum_{i \in \text{TopK}(s)} g_i \, E_i(x), \qquad g_i = \frac{e^{s_i}}{\sum_{j \in \text{TopK}(s)} e^{s_j}} .

Everything else in the block (attention, normalization, the residual stream) is unchanged and shared. That’s why “8x7B” doesn’t mean 56B parameters: only the MLPs are replicated, eight times over. Attention and embeddings exist once.

Because the gate values gig_i multiply the expert outputs, the router receives gradients and learns which experts suit which tokens. Nobody tells it that one expert should handle code and another French; whatever division of labour emerges is learned.

INTERACTIVEAn animated MoE router
Experts
Top-k
Shared expert
Load balancing
router: softmax → top-2thedefbluedefblueloop42proofbigproofteaimportriver42riverweE19 (4 dropped)E27 (2 dropped)E35E40E53E60E73E85
Click a token to inspect its gate scores.perfectly even load (4.0)capacity = ⌈1.25 × 16×2 / 8⌉ = 5
Gate scores for “the” (softmax over all experts; outlined = top-k chosen)
21%E151%E20%E30%E43%E52%E62%E721%E8
step 0
Imbalance over training steps (busiest expert ÷ average; 1.0 = perfectly balanced)
1×3×press “Train” to watch the router evolve
Total params
46.7B
Mixtral-calibrated toy sizes
Active params / token
12.9B
28% of total
Busiest expert vs average
1.42×
measured on a 256-token batch
Dropped assignments
6 of 32
every token reached an expert
Aux loss α·E·Σ fᵢPᵢ
0.0108
α = 0.01; minimum 0.0100 when balanced
Method
no balancing
rich get richer
Sixteen tokens flow through a router to their top-k experts. Bars show each expert's load; the dashed red line is the capacity limit, and red segments are dropped assignments. Train the router for a few steps under each load-balancing method and watch the imbalance chart.

Things to try:

  1. Load balancing “None”, then Train 25 steps. The imbalance climbs: experts that start slightly popular get more tokens, get “better trained” and become even more popular. Real routers can collapse the same way.
  2. Switch to “Aux loss” and train again. The auxiliary loss penalizes uneven loads and the imbalance falls toward 1. Watch the gate scores of a token change: the loss works by reshaping the router’s probabilities.
  3. Now “Bias (aux-loss-free)”. Loads balance too, but the gate percentages are untouched; small bias numbers (shown above the gate bars) shift only which experts are selected.
  4. Drag the capacity factor to 1.0 with no balancing. Overloaded experts turn away tokens (red), and some tokens skip every expert. Raise it and the drops disappear, at the cost of reserving more buffer space.
  5. Watch the parameter readouts as you change experts, top-k and the shared expert. With 8 experts, top-2 and no shared expert, they reproduce Mixtral’s 46.7B total and 12.9B active.

The load-balancing problem

Routing has a natural failure mode. Early in training, by chance, some experts are slightly better. The router sends them more tokens, they get more gradient updates, they improve faster, and the router prefers them even more. Left alone, many experts end up almost unused: you pay to store them and get nothing back. It is also bad for hardware. Experts usually live on different GPUs, and the busiest one sets the pace for everyone.

Capacity and token dropping. To keep computation predictable, systems such as GShard and the Switch Transformer give each expert a fixed buffer per batch: the capacity, usually the average load times a capacity factor like 1.25. Tokens routed to an expert that is already full are dropped for that expert. They aren’t deleted from the sequence; they simply skip the expert and continue through the residual connection, which quietly degrades quality. Many recent models avoid dropping entirely.

The auxiliary loss. The Switch Transformer adds a load-balancing lossLoad-balancing lossAn auxiliary training loss for Mixture-of-Experts models that penalizes uneven routing, pushing the router to spread tokens evenly across experts. to the training objective:

Laux=α⋅E⋅∑i=1Efi Pi,\mathcal{L}_{\text{aux}} = \alpha \cdot E \cdot \sum_{i=1}^{E} f_i \, P_i ,

where fif_i is the fraction of tokens actually sent to expert ii, PiP_i is the router’s average probability for expert ii, and α\alpha is a small weight (0.01 in the Switch paper). It is smallest when both are uniform. The catch: this loss pulls against the language-modeling loss. Too weak, and imbalance persists; too strong, and the router is forced to make worse choices just to stay even.

Auxiliary-loss-free balancing. DeepSeek-V3 adopts a different idea (Wang et al., 2024). Each expert gets a bias bib_i that is added to its score only when choosing the top-k. After each training step, the bias of every overloaded expert is lowered by a small amount γ\gamma and that of every underloaded expert is raised. The gate weights that multiply expert outputs still come from the unbiased scores, so balancing no longer distorts the gradients the router learns from. DeepSeek-V3 still keeps a tiny sequence-level balance loss as a safety net.

Finer experts and shared experts

The DeepSeekMoE paper (Dai et al., 2024) made two changes that most recent large MoEs have adopted in some form:

  • Fine-grained experts. Split each expert into several smaller ones and activate proportionally more of them. Same compute, but far more possible combinations of experts per token, so each expert can specialize more narrowly.
  • Shared experts. One or a few experts that every token always uses, bypassing the router. They absorb common knowledge (grammar, frequent patterns) so the routed experts don’t each have to relearn it.

DeepSeek-V3 combines both: per MoE layer, 256 small routed experts with 8 active, plus 1 shared expert.

Modelexperts per MoE layeractive per tokentotal paramsactive params
Mixtral 8x7B8246.7B12.9B
Qwen3-235B-A22B1288235B22B
DeepSeek-V3256 routed + 1 shared8 + 1671B37B
Kimi K2384 routed + 1 shared8 + 1about 1T32B

These figures come from each model’s paper, model card or config. The trend is clear: more, smaller experts, and a smaller active fraction (from about 28% for Mixtral to roughly 3–10% for the newest ones). Part 5 covers these model families in detail.

Serving an MoE: memory, compute and all-to-all

An MoE is cheap in compute but not in memory. Every expert must be loaded somewhere, because the next token might need any of them. DeepSeek-V3’s 671B parameters need hundreds of gigabytes even at 8 bits, while its per-token compute resembles a 37B dense model.

In big deployments, experts are spread across GPUs, which is called expert parallelism (see distributed training). Each MoE layer then needs two all-to-all exchanges: dispatch sends each token’s hidden vector to the GPUs holding its chosen experts, and combine brings the results back. This communication can rival the computation itself, which is why DeepSeek-V3 limits each token to experts on at most 4 nodes and overlaps communication with compute. Imbalanced routing hurts twice here: the busiest GPU sets the pace, and its links carry the most traffic.

Decoding also behaves differently. With a single sequence, each step touches only the active experts, so far fewer bytes are read than the total parameter count suggests. With large batches, different tokens pick different experts, and soon nearly every expert is read every step.

MATH CORNER · optionalGates, the aux loss and parameter counts, with small numbers

Top-2 gating. Four experts, router logits s=(2.0,1.0,0.5,−1.0)s = (2.0, 1.0, 0.5, -1.0). Softmax over all four: p≈(0.61,0.22,0.14,0.03)p \approx (0.61, 0.22, 0.14, 0.03). Top-2 picks experts 1 and 2. Renormalized gates: g1=0.61/0.83≈0.73g_1 = 0.61/0.83 \approx 0.73, g2≈0.27g_2 \approx 0.27. Output: y=0.73 E1(x)+0.27 E2(x)y = 0.73\,E_1(x) + 0.27\,E_2(x). Experts 3 and 4 are never computed.

Aux loss. Four experts, top-1 routing, α=0.01\alpha = 0.01. Suppose a batch gives

expertfif_i (share of tokens)PiP_i (mean probability)fiPif_i P_i
10.5000.400.2000
20.2500.300.0750
30.1250.150.0188
40.1250.150.0188

Laux=0.01×4×0.3125=0.0125\mathcal{L}_{\text{aux}} = 0.01 \times 4 \times 0.3125 = 0.0125. Perfect balance (fi=Pi=0.25f_i = P_i = 0.25) gives 0.01×4×0.25=0.01000.01 \times 4 \times 0.25 = 0.0100, the minimum. The gradient flows through PiP_i, lowering the probability of overloaded experts. (fif_i comes from a hard top-k choice and has no gradient.)

Bias-based selection. With biases bib_i, the selection uses si+bis_i + b_i but the gate uses sis_i. After each step: bi←bi−γ sign(loadi−load‾)b_i \leftarrow b_i - \gamma\,\text{sign}(\text{load}_i - \overline{\text{load}}).

Where Mixtral’s numbers come from. Each expert is a SwiGLU MLP with three 4096×143364096 \times 14336 matrices: 3×4096×14336≈1763 \times 4096 \times 14336 \approx 176M parameters per expert per layer, or 5.645.64B per expert across 32 layers. The non-expert parameters (attention, embeddings, norms, router) are about 1.6B. So

total≈1.6+8×5.64≈46.7B,active≈1.6+2×5.64≈12.9B.\text{total} \approx 1.6 + 8 \times 5.64 \approx 46.7\text{B}, \qquad \text{active} \approx 1.6 + 2 \times 5.64 \approx 12.9\text{B}.

In code

A minimal top-k MoE layer. Real implementations group tokens by expert to run one batched matrix multiply per expert, and use custom kernels for dispatch and combine.

import torch, torch.nn as nn, torch.nn.functional as F

class MoE(nn.Module):
    def __init__(self, d, d_ff, n_experts=8, k=2):
        super().__init__()
        self.k = k
        self.router = nn.Linear(d, n_experts, bias=False)
        self.experts = nn.ModuleList(
            nn.Sequential(nn.Linear(d, d_ff), nn.SiLU(), nn.Linear(d_ff, d))
            for _ in range(n_experts))

    def forward(self, x):                        # x: (tokens, d)
        probs = F.softmax(self.router(x), dim=-1)
        gate, idx = probs.topk(self.k, dim=-1)   # (tokens, k)
        gate = gate / gate.sum(-1, keepdim=True)
        y = torch.zeros_like(x)
        for e, expert in enumerate(self.experts):
            tok, slot = (idx == e).nonzero(as_tuple=True)
            if tok.numel():                      # only tokens routed here
                y[tok] += gate[tok, slot, None] * expert(x[tok])
        # Switch-style balance loss: fraction routed × mean probability
        f = F.one_hot(idx, probs.shape[-1]).float().sum((0, 1)) / idx.numel()
        aux = probs.shape[-1] * (f * probs.mean(0)).sum()
        return y, aux
COMMON MISCONCEPTIONS
  • “Mixtral 8x7B has 56B parameters.” Only the MLPs are replicated. Attention, embeddings and norms are shared, so the total is about 46.7B, and about 12.9B are active per token.
  • “An MoE needs less memory than a dense model of equal quality.” It needs memory for all experts. Its saving is compute per token, not storage.
  • “Each expert is a topic specialist: one for biology, one for law.” Analyses such as the Mixtral paper’s found no obvious topic-based assignment. Routing tends to follow lower-level patterns, such as syntax and token types, and often sends consecutive tokens to the same experts.
  • “Each token goes to one expert per model.” Routing happens independently in every MoE layer. A token may use completely different experts in layer 3 and layer 30.
  • “Load balancing is only about fairness.” It is about efficiency and quality: unbalanced experts waste capacity, overloaded ones drop tokens, and in expert-parallel serving the busiest GPU slows down the whole batch.

Check your understanding

0/5 answered
  1. Q1.An MoE model has 16 experts per layer and routes each token to its top-2. Compared with a dense model whose MLP equals one expert, what happens to compute per token and to memory?

  2. Q2.Why does an MoE router tend to collapse onto a few experts without intervention?

  3. Q3.With DeepSeek-V3's auxiliary-loss-free balancing, what does the per-expert bias change?

  4. Q4.With 8 experts, top-2 routing, a batch of 64 tokens and capacity factor 1.0, what is each expert's capacity, and what happens to token #17 routed to an expert that already holds that many tokens?

  5. Q5.In expert-parallel inference, why does each MoE layer need all-to-all communication?

Further reading

Progress is saved in this browser only.
Type to search across all lessons and glossary terms.