Mixture of Experts in LLMs: From Switch to DeepSeek-V3

Sparse MoE in PyTorch from scratch. Top-k routing, Switch Transformer load balancing, Mixtral, DeepSeek. Why MoE scales LLM parameters without scaling FLOPs.

Cover Image for Mixture of Experts in LLMs: From Switch to DeepSeek-V3

Different inputs can call for different kinds of prediction. Instead of sending every example through the same complete network, a mixture of experts lets a routing mechanism choose among smaller specialist networks. For LLMs, sparse routing means a token uses only part of the model's available parameters. Mixtral-8x7B uses 13 of its 47 billion parameters per token. DeepSeek-V3 activates 37 of 671 billion.

We build a small router to see how specialists divide the inputs. Its structure follows the mixtures described by Jacobs, Jordan, Nowlan and Hinton in 1991. Our four experts specialise on different regions, but removing the load-balancing loss leaves most idle.

This post picks up where the Combining Models tutorial left off. We implement a tiny sparse-MoE in PyTorch and trace routing from Switch Transformer's top-1 selection through Mixtral's top-2 to DeepSeek-V3's auxiliary-loss-free approach.

A working example: a tiny sparse MoE in 30 lines of PyTorch

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

class Expert(nn.Module):
    def __init__(self, d_in, d_hidden, d_out):
        super().__init__()
        self.fc1 = nn.Linear(d_in, d_hidden)
        self.fc2 = nn.Linear(d_hidden, d_out)
    def forward(self, x):
        return self.fc2(F.relu(self.fc1(x)))

class SparseMoE(nn.Module):
    def __init__(self, d_in, d_hidden, d_out, n_experts=4, top_k=2):
        super().__init__()
        self.n_experts, self.top_k = n_experts, top_k
        self.gate = nn.Linear(d_in, n_experts)
        self.experts = nn.ModuleList(
            [Expert(d_in, d_hidden, d_out) for _ in range(n_experts)])
    def forward(self, x):
        gate_probs = F.softmax(self.gate(x), dim=-1)            # (N, E)
        topk_vals, topk_idx = torch.topk(gate_probs, self.top_k, dim=-1)
        topk_w = topk_vals / topk_vals.sum(-1, keepdim=True)
        out = torch.zeros(x.size(0), self.experts[0].fc2.out_features)
        for k in range(self.top_k):
            for e in range(self.n_experts):
                m = (topk_idx[:, k] == e)
                if m.any():
                    out[m] = out[m] + topk_w[m, k:k+1] * self.experts[e](x[m])
        # Switch aux loss: encourage uniform expert utilisation
        f_i = torch.bincount(topk_idx[:, 0], minlength=self.n_experts).float()
        f_i = f_i / f_i.sum()
        P_i = gate_probs.mean(0)
        aux = self.n_experts * (f_i * P_i).sum()
        return out, aux

Open In Colab

That's it. A single linear layer (gate) that picks the top kk experts, plus a list of small expert networks. The auxiliary loss at the end is the load-balancing term Switch Transformer added to make sparse training stable, derived below. Trained on a 4-blob dataset with 4 experts and top-2 routing for 80 epochs, this hits 99.8% test accuracy:

Sparse MoE on 4-blob data: each expert spontaneously claims one of the four data regions

The right panel is the punchline. Each expert claims one of the four regions of input space without anyone telling it to. The blue cluster is handled by Expert 0, the red by Expert 1, the orange by Expert 2, the green by Expert 3. The 4-class classification task gets partitioned across the experts, not shared.

The leap from soft to sparse routing

The classical mixture of experts uses soft gating: the model output is p(t∣x)=∑kπk(x)p(t∣x,k)p(t \mid \mathbf{x}) = \sum_k \pi_k(\mathbf{x}) p(t \mid \mathbf{x}, k) with πk(x)\pi_k(\mathbf{x}) produced by a softmax. Every expert contributes to every prediction, weighted by the gate. The maths is clean and the gradients are well-defined.

The problem at LLM scale is FLOPs. If you have 64 experts and every one runs on every token, you're paying for 64 expert forward passes per token. The whole point of having 64 experts was to not run them all.

Shazeer et al. (2017), in "Outrageously Large Neural Networks", made the leap: pick only the top kk experts per token, set the rest to zero. The forward pass becomes y=∑k∈TopK(x)πk(x) Ek(x)y = \sum_{k \in \text{TopK}(\mathbf{x})} \pi_k(\mathbf{x})\, E_k(\mathbf{x}) with the gate weights re-normalised over the chosen subset. With k=2k = 2 out of 64 experts, you've cut compute by 32x and held capacity constant.

Sparse routing is hard to train. The argmax inside TopK\text{TopK} is non-differentiable, so the gating network can only learn through the gradient flowing through the weights πk\pi_k of the experts that happened to be picked. Experts that never get picked never get a gradient and never get better. This is the "rich get richer" problem and it's the central engineering challenge of sparse MoE.

Watching four experts crystallise

The most striking thing about training a sparse MoE is how fast specialisation emerges. Initialise the gating network at random, train for 80 epochs on the 4-blob data above, and snapshot the top-1 expert assignment at increasing epochs:

Top-1 expert territories crystallising from random at epoch 0 to clean 4-region partition by epoch 80

At epoch 0, the gating is essentially random. Three experts dominate by accident and one is barely active. By epoch 4 the territories are recognisable but messy: each expert is starting to favour one or two of the data clusters, and the boundaries are wobbly. By epoch 30 every expert owns one cluster, with sharp clean boundaries between them. By epoch 80 nothing visibly changes, just minor refinement at the boundaries.

The pattern is not coincidence. Once an expert gets even a small advantage on a particular subset of inputs, the gate routes more of those inputs to it, and the gradient signal makes that expert better on that subset, and the cycle compounds. The fundamental loop of MoE training is: gate routes → expert improves on routed inputs → gate routes more strongly. Specialisation is a fixed point of this dynamics, and it's reached fast.

When the loop breaks: load balancing and expert collapse

That same compounding loop has a failure mode. If one expert gets a big random head start, all the tokens flow to it, and the other experts never get to learn anything. The system collapses to a single dense network with extra dead weight.

To see this, train the same 4-expert model with top-1 routing and no auxiliary loss:

Without aux loss: expert 1 is completely dead (0% utilisation), expert 0 nearly so. With Switch's aux loss: perfectly uniform 25% each

In the left panel, expert 1 gets 0% of tokens. Expert 0 gets 4.5%. Two experts (orange and green) split everything else. The model still hits 96.8% training accuracy, but you've wasted the parameter budget on two experts that never learned anything.

Fedus et al. (2022), "Switch Transformer", fixed this with a single elegant addition. They define two quantities per expert ii: fif_i is the fraction of tokens routed to expert ii, and PiP_i is the average gate probability assigned to expert ii. The load-balancing loss is:

Laux=N⋅∑i=1Nfi⋅Pi\mathcal{L}_{\text{aux}} = N \cdot \sum_{i=1}^{N} f_i \cdot P_i

where NN is the number of experts. This loss is minimised when both fif_i and PiP_i are uniform at 1/N1/N, giving Laux=N⋅N⋅(1/N)(1/N)=1\mathcal{L}_{\text{aux}} = N \cdot N \cdot (1/N)(1/N) = 1. Imbalanced routing makes fif_i and PiP_i line up on the same experts, increasing the dot product. Adding αLaux\alpha \mathcal{L}_{\text{aux}} (with α\alpha typically 0.01 to 0.1) to the cross-entropy training loss is enough to keep all experts in the game. The right panel shows the result: every expert gets 24-25% of tokens, training accuracy lifts from 96.8% to 98.8%, and no parameters are wasted.

This is the shape of every sparse-MoE training loss in production today. Cross-entropy on the task plus a small auxiliary term that pushes routing toward uniformity.

The headline trade-off: top-1 vs top-2

Switch Transformer made an aggressive choice: route each token to exactly one expert. That's the simplest and cheapest option. Mixtral 8x7B (Jiang et al. 2024) walked this back to top-2: each token activates 2 of the 8 experts, with the gating network producing two weights that sum to 1. The trade-off:

Top-1 (Switch) vs Top-2 (Mixtral): top-2 lifts accuracy from 99.0% to 100.0% but doubles active params per token

On this toy task top-2 lifts accuracy by 1 percentage point, paying for it with roughly 2x the active parameters per token (132 vs 72). At LLM scale Mixtral chose this trade because the quality gap was larger than the toy data shows: top-1 routing makes individual training tokens depend on a single expert's gradient, which slows learning per parameter. Top-2 lets each token contribute to two experts, smoothing the optimisation landscape considerably.

The math is compute∝k\text{compute} \propto k and capacity∝Nexperts\text{capacity} \propto N_{\text{experts}}. You scale capacity (total parameters) by adding more experts. You scale compute (FLOPs per token) by raising kk. These are independent levers, and that's the whole pitch of sparse MoE: decoupling the parameter budget from the compute budget.

Why MoE scales LLMs

Take a fixed compute budget, say 13B active parameters per forward pass. A dense model gets exactly 13B parameters. A sparse-MoE model with top-2 routing and 8 experts gets 8×expert_params+router8 \times \text{expert\_params} + \text{router} total parameters but activates only 2×expert_params2 \times \text{expert\_params} per token. If each expert is roughly the size of the dense FFN block, the MoE has 4x the parameter count at the same compute.

At matched active compute, dense and MoE tie on this toy task. The MoE's advantage is its 2x total capacity in reserve, visible at LLM scale, not toy scale

The toy chart on the left is honest. At small scale, a dense MLP and a sparse MoE with matched active compute give essentially identical accuracy (98.4% vs 98.3%). The right chart shows the difference that matters at scale: dense has 420 total parameters; MoE has 884 total but uses only 460 per token. Doubling the parameter count for free changes nothing on a 4-blob toy task, but on a 1.4-trillion-token pretraining run it gives the model 2x the capacity to memorise patterns at the same training cost.

This is why every frontier open-weight model from 2024 onward is sparse-MoE: Mixtral 8x7B (47B total / 13B active), Mixtral 8x22B (141B / 39B), DBRX (132B / 36B), DeepSeek-V2 (236B / 21B), DeepSeek-V3 (671B / 37B), Qwen3 30B-A3B (30B / 3B). The ratios vary but the architecture is the same. Sparse MoE is now load-bearing infrastructure for LLMs, not a research curiosity.

DeepSeek-V3: the auxiliary-loss-free upgrade

The Switch aux loss has a cost: it nudges the model away from the routing the optimiser would have chosen on its own. For most of training that's fine because keeping experts alive is more valuable than perfect routing. But late in training, the aux loss starts dragging on quality.

DeepSeek-MoE / DeepSeek-V3 (2024) shipped two architectural refinements that have become widely copied:

Shared experts. Of the NN total experts, fix some small number (say 1-2) to always be active for every token. The shared experts learn the common-knowledge patterns; the routed experts handle the long tail of specialisation. In DeepSeek-V3 there's 1 shared expert plus 256 routed experts, with 8 routed experts active per token plus the shared one. This solves a subtle problem with pure sparse MoE: every expert is forced to relearn things that every token needs, wasting capacity.

Auxiliary-loss-free balancing. Instead of adding a loss term that fights the optimiser, DeepSeek introduced a per-expert bias on the routing logits that gets nudged up or down based on observed expert utilisation. Underutilised experts get their bias raised; overutilised ones get it lowered. The bias is updated as a running statistic, not as part of backpropagation, so it doesn't perturb the optimisation. Empirically, this gives Switch-equivalent load balancing with a measurable quality improvement.

A toy implementation of the auxiliary-loss-free trick fits in three lines:

# Maintain a per-expert routing bias, updated each step
bias = torch.zeros(n_experts)
target_load = 1.0 / n_experts
# In the forward pass:
gate_logits = self.gate(x) + bias  # Add bias before softmax
# After the step:
load = (topk_idx[:, 0].bincount(minlength=n_experts).float()
        / topk_idx.size(0))
bias = bias + lr_bias * (target_load - load)  # Underloaded -> bias up

The bias gets added to the gate logits (so it shifts routing) but is updated by a separate rule (so it doesn't see gradients). This is the same trick that ProGAN's exponential moving averages, batch normalisation's running statistics, and target networks in Deep Q-Networks all use: a parameter that the optimiser doesn't see, updated by a separate moving rule.

When sparse MoE makes sense, and when it doesn't

A short decision tree:

SituationReach for
You're scaling LLM total parameters and inference cost is the bottleneckSparse MoE (top-2 routing, shared experts, aux-loss-free balancing)
You're training a small model where parameter count isn't the constraintDense MLP / Transformer; MoE adds engineering complexity for no win
You have natural input regimes that need different sub-modelsSoft (dense) MoE (gradients are clean, no balancing tricks needed)
You're combining several different trained modelsStacking (see Combining Models)
You want one model on tabular dataGradient boosting (XGBoost, LightGBM); MoE is overkill

The dominant story for LLMs in 2026 is sparse MoE. The dominant story for tabular ML, image classification, and most non-LLM tasks is still dense models with the right inductive bias, possibly ensembled in the bagging/boosting/stacking sense. MoE is a scaling technique, and scaling matters most where the parameter budget runs to the hundreds of billions.

Foundations: the chain of papers

The architecture has a clear lineage. Each step solves a specific problem the previous step ran into.

Jacobs, Jordan, Nowlan, Hinton (1991), "Adaptive Mixtures of Local Experts", Neural Computation. The original mixture-of-experts paper from Hinton's group. Soft gating, jointly trained gate and experts, EM-style derivation. Every modern sparse-MoE design is a descendant of this idea.

Shazeer et al. (2017), "Outrageously Large Neural Networks", ICLR. The first sparse-MoE-in-a-Transformer paper. Introduced top-k gating and a "load balancing loss". 137-billion-parameter MoE language model in 2017, when GPT-2 (2019) had 1.5B. The paper's approach to the gradient problem of sparse routing is cited by every successor.

Fedus, Zoph, Shazeer (2022), "Switch Transformer", JMLR. Cleaned up the Shazeer et al. machinery into a simpler top-1 architecture, defined the auxiliary loss above, and demonstrated 1.6T-parameter scaling on T5. Most production MoE LLMs follow this paper's training recipe.

Lepikhin et al. (2021), "GShard", ICLR. Google's parallel work on scaling MoE Transformers across thousands of TPUs. Where Switch focused on the algorithm, GShard focused on the systems engineering: the SPMD compiler, expert parallelism, capacity factor enforcement.

Jiang et al. (2024), "Mixtral of Experts". The first widely-deployed open-weight sparse-MoE LLM. 8 experts, top-2 routing, 47B total / 13B active. Crystallised the production recipe and gave the open-source community a reference implementation.

Dai et al. (2024), "DeepSeekMoE". Introduced shared experts and fine-grained expert segmentation. The follow-up DeepSeek-V3 technical report (2024) added the auxiliary-loss-free balancing trick. Together these gave DeepSeek a state-of-the-art-quality open-weight model at a fraction of the training cost of comparable dense models.

Interactive Tools

  • LLM Cost Calculator: Estimate the cost difference between dense and MoE models per million tokens. The active-vs-total-parameter distinction is exactly what determines inference cost.
  • Distribution Explorer: The softmax over the gating network produces a Categorical distribution. Visualise how its entropy changes with the gate temperature.
  • Attention Visualizer: The other softmax in the block, with its own temperature slider. Attention routes over positions where the gate routes over experts, and both sharpen the same way.
  • Convolution Visualiser: Some MoE variants (Conv-MoE) replace the FFN with convolutional experts; useful intuition for the per-expert operation.

Stay in the loop

Get notified when new tutorials and deep-dives are published. No spam, unsubscribe anytime.

Related Posts

Frequently Asked Questions