Sign in

Mixture of Experts (MoE) Explained: How Sparse Models Scale

How Mixture of Experts works: routers, top-k routing, total vs active parameters, load balancing, and PyTorch code, from Mixtral to DeepSeek-V3.

DeepSeek-V3 has 671 billion parameters. For any single token it uses only 37 billion of them. Qwen3-235B-A22B has 235 billion and uses 22 billion. Both are Mixture of Experts (MoE) models, and the same idea sits inside Mixtral, gpt-oss and many other recent open-weight releases.

MoE is how teams make a model know much more without paying a matching bill on every token. This post covers how it works, where it came from, what goes wrong when you train and serve it, and a small PyTorch layer you can run yourself.

Dense vs sparse: the core idea

In a standard (dense) transformer, every token passes through every weight in every layer. Doubling the parameters roughly doubles the compute per token.

A sparse MoE transformer changes one part of the block. The feed-forward network (FFN) that follows attention is replaced by many parallel FFNs, called experts, plus a small router (also called the gating network). For each token, the router scores all the experts, picks the best few, and the token is processed only by those. Their outputs are mixed using the router's weights.

Diagram of a Mixture of Experts layer: inputs go to a router, which sends each token to two of several experts; their outputs are combined using the gating weights.

A Mixture of Experts layer: the router picks experts per token and combines their outputs. Figure 1 from "Mixtral of Experts" (Jiang et al., 2024), CC BY 4.0. See credits below.

A few things worth being precise about:

  • Experts live in the FFN, not in attention. In Mixtral, attention is shared by all tokens. Only the feed-forward block is split into 8 experts per layer.
  • Routing is per token and per layer. The same word can go to different experts in different layers, and neighbouring tokens can go to different experts.
  • Top-k routing. The router keeps the k highest-scoring experts. Mixtral uses k = 2 out of 8. Switch Transformer simplified this to k = 1.
  • Total vs active parameters. Total parameters are what you must store. Active parameters are what a token actually uses. Mixtral 8x7B has 47B total and 13B active. That is why "8x7B" does not mean 56B: the attention and embedding weights are shared, not replicated eight times.

Compute per token tracks the active count, and the model's capacity to store knowledge tracks the total count. That gap is the whole point of MoE.

A short history

1991: the original idea. Jacobs, Jordan, Nowlan and Hinton described a system of separate "expert" networks plus a gating network that decides which expert handles each training case, so that experts specialise and interfere less with each other [1].

2017: sparsely-gated MoE. Shazeer et al. made the idea practical for deep learning. They introduced a layer with up to thousands of feed-forward experts and a trainable gate that selects a sparse combination for each example, reporting more than 1000x model capacity with only minor losses in computational efficiency. They used up to 137 billion parameters, applied between stacked LSTM layers [2].

2020: GShard. Lepikhin et al. brought sparsely-gated MoE to Transformers and added annotation APIs plus an XLA compiler extension to shard the model automatically. They scaled a multilingual translation model beyond 600 billion parameters and trained it on 2048 TPU v3 accelerators in 4 days [3].

2021: Switch Transformer. Fedus, Zoph and Shazeer simplified routing to a single expert per token, which reduced communication and compute, and made training more stable. Models based on T5-Base and T5-Large reached up to 7x faster pre-training with the same computational resources, and the authors scaled up to trillion-parameter models [4].

2023 to 2024: open MoE goes mainstream. Mistral released Mixtral 8x7B under Apache 2.0: 8 experts per layer, 2 chosen per token, 47B total and 13B active parameters, with a 32k context window. The paper reports that it outperforms or matches Llama 2 70B and GPT-3.5 across the benchmarks it evaluated [5].

Six line charts comparing Mistral 7B and Mixtral 8x7B against Llama 2 7B, 13B and 70B on MMLU, knowledge, reasoning, comprehension, math and code, plotted against active parameters.

Mixtral 8x7B compared with the Llama 2 family, plotted against active parameters. Figure 3 from the Mixtral paper (CC BY 4.0).

2024: fine-grained and shared experts. DeepSeekMoE argued that "top-2 of 8" makes experts too coarse. Its two ideas: split experts into many smaller ones and activate more of them (finer-grained combinations), and set aside a few shared experts that every token uses, so the routed experts do not each have to relearn common knowledge [6]. DeepSeek-V3 builds on this: 671B total parameters, 37B activated per token. In its MoE layers (all but the first three), each layer has 1 shared expert and 256 routed experts, with 8 routed experts activated per token [7].

Other open-weight models use the same family of ideas too, for example Qwen3-235B-A22B (235B total, 22B activated) [8] and OpenAI's gpt-oss-120b (117B total, 5.1B active) [9].

What the router actually learns

You might expect "the maths expert" and "the biology expert". The Mixtral authors looked for that and did not find it. Expert assignment looked very similar for arXiv papers, PubMed abstracts and philosophy papers. What they did see was syntactic structure: tokens like self in Python or "Question" in English often went to the same expert, and indentation tokens were consistently assigned to the same experts [5].

Code and text samples where each token is highlighted with the colour of the first expert chosen by the router, shown for layers 0, 15 and 31 of Mixtral.

Each token is coloured by its first-choice expert at layers 0, 15 and 31. Figure 8 from the Mixtral paper (CC BY 4.0).

So experts are better thought of as learned, soft partitions of the model's capacity than as human-readable topics.

A minimal MoE layer in PyTorch

Here is a small, readable top-k MoE layer. It is written for clarity, not speed: real systems batch tokens per expert with fused kernels instead of looping in Python.

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


class Expert(nn.Module):
    """One expert = an ordinary transformer feed-forward block."""

    def __init__(self, d_model: int, d_hidden: int):
        super().__init__()
        self.up = nn.Linear(d_model, d_hidden)
        self.down = nn.Linear(d_hidden, d_model)

    def forward(self, x):
        return self.down(F.gelu(self.up(x)))


class TopKMoE(nn.Module):
    def __init__(self, d_model=64, d_hidden=256, n_experts=8, k=2):
        super().__init__()
        self.k, self.n_experts = k, n_experts
        self.router = nn.Linear(d_model, n_experts, bias=False)
        self.experts = nn.ModuleList(
            [Expert(d_model, d_hidden) for _ in range(n_experts)]
        )

    def forward(self, x):
        batch, seq, d = x.shape
        tokens = x.reshape(-1, d)                           # (T, d)

        probs = F.softmax(self.router(tokens), dim=-1)      # (T, E)
        weights, idx = probs.topk(self.k, dim=-1)           # (T, k)
        weights = weights / weights.sum(dim=-1, keepdim=True)  # renormalise over the chosen k

        out = torch.zeros_like(tokens)
        for e, expert in enumerate(self.experts):
            token_ids, slot = (idx == e).nonzero(as_tuple=True)
            if token_ids.numel() == 0:
                continue                                     # this expert got no tokens
            y = expert(tokens[token_ids])                    # only its own tokens
            out.index_add_(0, token_ids, y * weights[token_ids, slot].unsqueeze(-1))

        aux = load_balancing_loss(probs, idx, self.n_experts)
        return out.view(batch, seq, d), aux

Notice what the loop shows: each expert only ever sees the tokens routed to it, and the final output for a token is the weighted sum of its k expert outputs. Renormalising the top-k probabilities gives the same result as taking a softmax over just the selected logits, which is how Mixtral describes its gating [5].

The layer also returns an auxiliary loss. We need it because of the biggest practical problem in MoE.

Challenge 1: load balancing

Left alone, routers tend to collapse: a few experts get most tokens, get better because they train more, and so get even more tokens. The other experts are wasted, and in a distributed setup the overloaded devices become the bottleneck. This "routing collapse" was already noted in the 2017 work [2].

The classic fix is an auxiliary load-balancing loss. In the Switch Transformer formulation, with N experts, f_i the fraction of tokens dispatched to expert i, and P_i the average router probability given to expert i, the loss is α · N · Σ f_i · P_i, which is smallest when the load is uniform [4]. Switch used α = 0.01. Here is a version generalised to top-k:

def load_balancing_loss(probs, topk_idx, n_experts):
    """Switch-style auxiliary loss, generalised to top-k.

    probs:    (tokens, n_experts) router probabilities after softmax
    topk_idx: (tokens, k) experts chosen for each token
    Equals 1.0 when load is perfectly uniform; grows as routing collapses.
    """
    assigned = F.one_hot(topk_idx, n_experts).float()        # (T, k, E)
    f = assigned.sum(dim=1).mean(dim=0) / topk_idx.shape[1]  # share of assignments per expert
    P = probs.mean(dim=0)                                    # mean router probability per expert
    return n_experts * torch.sum(f * P)


layer = TopKMoE(d_model=64, d_hidden=256, n_experts=8, k=2)
x = torch.randn(4, 16, 64)
y, aux = layer(x)
loss = y.pow(2).mean() + 0.01 * aux   # task loss + alpha * aux
loss.backward()

Only P carries gradients (the top-k choice itself is not differentiable), so the loss nudges the router's probabilities towards a more even spread.

The catch is that a strong auxiliary loss adds gradients that fight the language-modelling objective. Wang et al. proposed loss-free balancing: add a per-expert bias to the routing scores before the top-k selection, and adjust that bias after each step based on recent load, with no extra gradient [10]. DeepSeek-V3 adopted this strategy: the bias is used only to decide which experts are picked, while the gate values that scale expert outputs still come from the original scores. After each step the bias is lowered for overloaded experts and raised for underloaded ones by a small speed γ (0.001 for most of training). DeepSeek-V3 still keeps a very small sequence-wise balance loss to prevent extreme imbalance inside a single sequence [7].

n_experts, k, gamma = 8, 2, 0.001
router = torch.nn.Linear(64, n_experts, bias=False)
bias = torch.zeros(n_experts)          # updated by a rule, not by gradient descent

def route(tokens):
    scores = torch.sigmoid(router(tokens))           # DeepSeek-V3 uses sigmoid affinities
    _, idx = (scores + bias).topk(k, dim=-1)         # bias only affects WHICH experts win
    gate = scores.gather(1, idx)                     # gate values use the unbiased scores
    return idx, gate / gate.sum(-1, keepdim=True)

# after every training step:
idx, gate = route(tokens)
load = F.one_hot(idx, n_experts).sum(dim=(0, 1)).float()
bias -= gamma * torch.sign(load - load.mean())       # overloaded: down, underloaded: up

This is a simplified sketch of the idea, not DeepSeek's training code.

Challenge 2: expert capacity and dropped tokens

On accelerators, tensors need fixed shapes, so each expert is given a fixed capacity: roughly (tokens in the batch ÷ number of experts) × a capacity factor. If more tokens are routed to an expert than it can hold, the extras are dropped: that layer's computation is skipped and the token passes on through the residual connection. A larger capacity factor wastes fewer tokens but costs more compute and communication [4]. Good load balancing matters partly because it keeps this trade-off cheap.

Challenge 3: memory

Sparse compute does not mean sparse memory. Every expert might be needed by some token in a batch, so all the weights must be resident. Mixtral's 47B parameters take roughly 94 GB in 16-bit precision just for weights, even though a token touches only 13B. MoE saves FLOPs per token, but not VRAM. Quantisation and offloading help, but memory is usually the first thing that bites when you deploy.

Challenge 4: communication and expert parallelism

At large scale, experts are spread across GPUs (expert parallelism). Each layer then needs an all-to-all: tokens travel to the GPUs hosting their chosen experts, get processed, and travel back. This can dominate step time. DeepSeek-V3 limits each token to at most 4 nodes during training (node-limited routing) to cap cross-node traffic [7]. For serving, its report describes a decoding deployment unit of 40 nodes with 320 GPUs, using redundant copies of heavily loaded experts and low-latency point-to-point transfers for the all-to-all [7]. The Mixtral paper adds that routing shows positional locality (consecutive tokens often hit the same experts), which can cause expert over-subscription under expert parallelism but can also be exploited for caching [5].

Challenge 5: inference serving

Mixtral's authors note that the model gives faster inference at low batch sizes and higher throughput at large batch sizes [5]. In practice, serving MoE is a systems problem: routing imbalance creates stragglers, small batches touch many experts and become memory-bandwidth-bound, and you need engines with MoE-aware kernels and parallelism. This is why inference engineering for MoE is a skill in demand.

Try a real MoE model

You can load Mixtral through Hugging Face Transformers. The mistralai/Mixtral-8x7B-Instruct-v0.1 model is Apache 2.0, and you will need roughly 90+ GB of GPU memory in bf16 (or a quantised variant for smaller hardware).

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

model_id = "mistralai/Mixtral-8x7B-Instruct-v0.1"
tok = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
    model_id,
    torch_dtype=torch.bfloat16,   # newer Transformers versions also accept dtype=
    device_map="auto",            # shard across available GPUs
)

print(model.config.num_local_experts, model.config.num_experts_per_tok)  # 8 2

messages = [{"role": "user", "content": "Explain top-2 routing in one paragraph."}]
inputs = tok.apply_chat_template(
    messages, add_generation_prompt=True, return_tensors="pt", return_dict=True
).to(model.device)
out = model.generate(**inputs, max_new_tokens=200)
print(tok.decode(out[0][inputs["input_ids"].shape[-1]:], skip_special_tokens=True))

For fine-tuning, the Mixtral config exposes output_router_logits and router_aux_loss_coef so the load-balancing loss can be added to your training loss.

MoE or dense?

MoE tends to win when:

  • You want the knowledge capacity of a very large model at the inference compute of a much smaller one.
  • You serve at high volume, where per-token compute dominates your cost.
  • You have the infrastructure to shard experts and handle all-to-all communication.

Dense is often simpler and better when:

  • You are memory-constrained (single GPU, edge, on-device). A dense 13B model is far easier to fit than a 47B MoE with a 13B active count.
  • You serve at small scale or low batch sizes, where loading many experts hurts.
  • You are fine-tuning on a small budget. MoE fine-tuning needs care with routing and balance.
  • You want a simpler stack with fewer failure modes.

Takeaways

  1. MoE replaces each FFN with many experts and a router that sends every token to the top-k of them.
  2. Total parameters set capacity; active parameters set per-token compute. Mixtral is 47B total, 13B active.
  3. Routing is learned and mostly syntactic, not "one expert per subject".
  4. Load balancing is the central training problem: from auxiliary losses (Switch) to bias-based, loss-free balancing (DeepSeek-V3).
  5. You save FLOPs, not memory. Communication and serving are where the engineering effort goes.
  6. Modern designs use many small experts plus shared experts (DeepSeekMoE).

Hiring note

Teams that build and serve large models, from training infrastructure to inference engineering, keep hiring for exactly these problems: routing, kernels, parallelism and serving. If that is the kind of work you want, browse the open roles at startups on JoinAStartUp jobs.

Watch: MoE token routing, with code

For a walkthrough of how tokens get routed to experts, with slides and a notebook, watch this video from the Hugging Face team:

Aritra from Hugging Face explains MoE token routing with slides and a Colab notebook. (YouTube)

Watch: "MoE Token Routing Explained: How Mixture of Experts Works (with Code)" by Hugging Face. https://www.youtube.com/watch?v=CDnkFbW-uEQ

Credits & references

Papers and model pages (facts in this post were checked against these primary sources):

  1. R. A. Jacobs, M. I. Jordan, S. J. Nowlan, G. E. Hinton. "Adaptive Mixtures of Local Experts." Neural Computation 3(1):79-87, 1991. https://doi.org/10.1162/neco.1991.3.1.79
  2. N. Shazeer et al. "Outrageously Large Neural Networks: The Sparsely-Gated Mixture-of-Experts Layer." 2017. https://arxiv.org/abs/1701.06538
  3. D. Lepikhin et al. "GShard: Scaling Giant Models with Conditional Computation and Automatic Sharding." 2020. https://arxiv.org/abs/2006.16668
  4. W. Fedus, B. Zoph, N. Shazeer. "Switch Transformers: Scaling to Trillion Parameter Models with Simple and Efficient Sparsity." 2021. https://arxiv.org/abs/2101.03961
  5. A. Q. Jiang et al. "Mixtral of Experts." 2024. https://arxiv.org/abs/2401.04088
  6. D. Dai et al. "DeepSeekMoE: Towards Ultimate Expert Specialization in Mixture-of-Experts Language Models." 2024. https://arxiv.org/abs/2401.06066
  7. DeepSeek-AI. "DeepSeek-V3 Technical Report." 2024. https://arxiv.org/abs/2412.19437
  8. Qwen team. Qwen3-235B-A22B model card. https://huggingface.co/Qwen/Qwen3-235B-A22B
  9. OpenAI. gpt-oss-120b model card. https://huggingface.co/openai/gpt-oss-120b
  10. L. Wang et al. "Auxiliary-Loss-Free Load Balancing Strategy for Mixture-of-Experts." 2024. https://arxiv.org/abs/2408.15664

Video:

  • "MoE Token Routing Explained: How Mixture of Experts Works (with Code)" by Hugging Face. https://www.youtube.com/watch?v=CDnkFbW-uEQ

Images:

  • Figure 1 (MoE layer diagram), Figure 3 (Mixtral vs Llama 2 by active parameters) and Figure 8 (routing visualisation): from "Mixtral of Experts" by Jiang et al. (Mistral AI), arXiv:2401.04088, licensed under Creative Commons Attribution 4.0 (CC BY 4.0, https://creativecommons.org/licenses/by/4.0/). Images are unmodified apart from format conversion and resizing for the web.

Code: the PyTorch snippets above were written for this post, and the Hugging Face model ids are mistralai/Mixtral-8x7B-Instruct-v0.1 and the base mistralai/Mixtral-8x7B-v0.1. The "Mixtral memory ≈ 94 GB" figure is our own arithmetic (47B parameters × 2 bytes).

More articles

Grok Bot x Cursor Hackathon Kochi: Date, Venue, Agenda and How to Register

Git in Pictures: A Visual Companion to the Git Course

All articles →