Mixture of Experts in LLMs: How MoE Models Work
How mixture-of-experts LLMs route each token to a few experts: gating, top-k routing, load balancing, expert capacity and what MoE means for serving.
A mixture-of-experts (MoE) language model swaps some of its dense layers for a pool of smaller networks, called experts, plus a small router that decides which experts handle each token. The model can then store far more parameters than it uses on any single token. This explainer covers how routing works, why load balancing and expert capacity matter, and what the design changes when you serve one of these models. It draws on the original papers (Shazeer et al. 2017, GShard, Switch Transformer, Mixtral) and on the Hugging Face and vLLM documentation.
The basic idea: conditional computation
In a standard (dense) transformer, every token passes through every weight in every layer. The goal of conditional computation is to switch on only part of the network for each input, so that capacity can grow without the cost per input growing at the same rate.
Shazeer et al. (2017) made this practical with the sparsely-gated MoE layer. In their design, each expert is a plain feed-forward network, and a trainable gating network picks a sparse set of experts for each input. Where the gate assigns an expert a weight of zero, that expert’s output is never computed. Their experiments used up to thousands of experts while evaluating only a handful per example, and the largest MoE layer they describe holds up to 137 billion parameters, placed between stacked LSTM layers rather than inside a transformer.
Later work moved the idea into transformers. In current LLMs, the MoE layer takes the place of the feed-forward (FFN) sub-block inside each transformer block, and it is applied to each token on its own. Attention layers stay dense.
Experts and the router
An MoE layer has two parts:
| Part | What it is | What it does |
|---|---|---|
| Experts | N separate feed-forward networks, each with its own weights | Process the tokens routed to them |
| Router (gate) | A small learned linear layer | Scores every expert for each token and picks which ones run |
The layer’s output is a weighted sum: the outputs of the chosen experts, each multiplied by the gate weight the router gave it. Experts that were not chosen add nothing and cost no compute.
Top-k routing
The router produces one score (a logit) per expert. The model keeps the k highest, sets the rest aside, and turns the survivors into weights with a softmax. Different papers have picked different values of k:
- Shazeer et al. 2017: noisy top-k gating. Tunable Gaussian noise is added to the logits before the top k are kept, which helps spread load across experts.
- Switch Transformer: k = 1. Fedus, Zoph and Shazeer route every token to exactly one expert and report that this keeps model quality while making the router cheaper, cutting communication and simplifying the implementation. They call this a “Switch layer”.
- Mixtral 8x7B: k = 2 out of 8. The Mixtral paper writes the layer as a softmax over the top-2 router logits, applied to SwiGLU experts.
The choice of experts is made per token and per layer, so two neighbouring tokens can take entirely different paths through the network.
Here is a minimal top-k MoE layer in PyTorch. It is illustrative only: it loops over experts for readability and has no capacity limit, no load-balancing loss and none of the fused kernels a real implementation uses.
# Illustrative top-k MoE layer, not production code.
import torch
import torch.nn as nn
import torch.nn.functional as F
class TopKMoE(nn.Module):
def __init__(self, d_model, d_ff, num_experts=8, k=2):
super().__init__()
self.k = k
self.router = nn.Linear(d_model, num_experts, bias=False)
self.experts = nn.ModuleList(
nn.Sequential(nn.Linear(d_model, d_ff), nn.SiLU(), nn.Linear(d_ff, d_model))
for _ in range(num_experts)
)
def forward(self, x): # x: (tokens, d_model)
logits = self.router(x) # (tokens, num_experts)
top_vals, top_idx = logits.topk(self.k, dim=-1)
weights = F.softmax(top_vals, dim=-1) # softmax over the k winners only
out = torch.zeros_like(x)
for e, expert in enumerate(self.experts):
token_ids, slot = (top_idx == e).nonzero(as_tuple=True)
if token_ids.numel() == 0:
continue # unused expert: no compute
out[token_ids] += weights[token_ids, slot, None] * expert(x[token_ids])
return out
Total vs active parameters
Sparse routing separates two numbers that are the same in a dense model. The Mixtral authors call them the sparse (total) parameter count, which rises with the number of experts, and the active parameter count, which rises with k.
Mixtral 8x7B illustrates the gap. Its architecture matches Mistral 7B, except that each layer has 8 feed-forward experts and the router chooses 2 of them for every token. That gives each token access to 47B parameters while using only 13B active parameters at inference time. Only the feed-forward blocks are multiplied by eight; the rest of the network is a single copy, which is why the total is well under eight times 7B.
The model card for mistralai/Mixtral-8x7B-v0.1 lists num_experts_per_tok: 2 in its config, and the paper says both the base and instruct versions are released under Apache 2.0.
Load balancing
Nothing in a plain router stops it from favouring a few experts. Those experts then get most of the tokens and most of the training signal, while the rest stay undertrained and their hardware sits idle.
The standard fix is an auxiliary loss that is added to the main training loss:
- Shazeer et al. 2017 defined an expert’s “importance” as the sum of its gate values over a batch and penalised uneven importance. Because equal importance can still hide very unequal token counts, they added a second load loss on top.
- Switch Transformer merges these into one term: for each expert, the share of tokens actually sent to it times the share of router probability it received, summed over experts and scaled by the expert count. The term is smallest when routing is uniform. The authors used a coefficient of 10⁻², which they found balanced load quickly without disturbing the main loss.
In Hugging Face Transformers, Mixtral’s config exposes these controls directly: router_aux_loss_coef (default 0.001) weights the balancing loss, output_router_logits makes the model return router logits and the auxiliary loss, and router_jitter_noise adds noise to router logits during training.
Expert capacity and dropped tokens
On accelerators, each expert usually processes a fixed-size batch. The Switch Transformer paper sets that size, the expert capacity, as tokens per batch divided by the number of experts, multiplied by a capacity factor. A factor above 1.0 leaves slack for imbalanced routing.
If more tokens pick an expert than it has room for, the extras are dropped: the expert skips them, and their representation reaches the next layer unchanged through the residual connection. GShard used the same overflow handling. Raising the capacity factor drops fewer tokens but costs more compute and memory. The Switch authors found keeping drop rates low mattered for scaling, and that Switch models did better than top-2 MoE at small capacity factors such as 1.0 and 1.25.
Scaling milestones
| Paper | Year | Routing | Scale reported |
|---|---|---|---|
| Shazeer et al., “Outrageously Large Neural Networks” | 2017 | Noisy top-k | MoE layer with up to 137B parameters (LSTM models) |
| GShard (Lepikhin et al.) | 2020 | Sparsely-gated MoE with automatic sharding | Translation transformer beyond 600B parameters, trained on 2048 TPU v3 chips in 4 days |
| Switch Transformer (Fedus et al.) | 2021 | Top-1 | Models of 395B and 1.6T parameters |
| Mixtral 8x7B (Jiang et al.) | 2024 | Top-2 of 8 | 47B total, 13B active |
Larger proprietary models use the approach too. The Qwen Team describes Qwen2.5-Max as a large-scale MoE model, for example.
Do experts specialise?
The evidence is mixed. Shazeer et al. saw experts in their LSTM models specialise by syntax and semantics. Mixtral’s authors looked for topic specialisation across subsets of The Pile and found no obvious pattern. Routing looked more syntactic: Python’s self and code indentation tokens tended to go to the same experts, and consecutive tokens often shared an assignment. They point out that this locality can overload some experts under expert parallelism, but it also creates an opportunity for caching.
What MoE means for serving
Memory follows total parameters, compute follows active parameters. Any token can go to any expert, so all experts have to be in memory. The Mixtral paper says plainly that active parameter count tracks inference compute while serving memory tracks the sparse count. In half precision each parameter takes 2 bytes, so Mixtral’s 47B weights need roughly 94 GB before you count the KV cache. Quantization reduces that figure; the Transformers docs show 4-bit loading through bitsandbytes, and our quantization guide covers the options.
Batching matters. Shazeer et al. called this the shrinking batch problem: with k of n experts per token, each expert sees only about kb/n of a batch of b tokens. Mixtral’s authors add that routing overhead and memory loads make MoE layers best suited to batched workloads with good arithmetic intensity.
Expert parallelism. Serving engines can place different experts on different GPUs. In vLLM, the --enable-expert-parallel flag spreads expert layers across all ranks, with EP size equal to TP size times DP size. Attention layers follow the tensor-parallel setting instead. Without the flag, MoE layers fall back to tensor parallelism. vLLM’s docs also warn that real token loads across experts can be very skewed, and they provide an Expert Parallel Load Balancer (--enable-eplb) that periodically reassigns experts across ranks.
# From the vLLM docs: single node, 8 GPUs, expert parallel
vllm serve deepseek-ai/DeepSeek-V3-0324 \
--tensor-parallel-size 1 \
--data-parallel-size 8 \
--enable-expert-parallel
Other inference stacks, such as TensorRT-LLM, ship dedicated MoE kernels. For a wider view of serving tools, see the LLM infrastructure hub.
Running Mixtral locally with Transformers works through the usual API. This is the example from the Hugging Face docs:
from transformers import AutoModelForCausalLM, AutoTokenizer
model = AutoModelForCausalLM.from_pretrained("mistralai/Mixtral-8x7B-v0.1", device_map="auto")
tokenizer = AutoTokenizer.from_pretrained("mistralai/Mixtral-8x7B-v0.1")
model_inputs = tokenizer(["My favourite condiment is"], return_tensors="pt").to(model.device)
generated_ids = model.generate(**model_inputs, max_new_tokens=100, do_sample=True)
print(tokenizer.batch_decode(generated_ids)[0])
Trade-offs in short
MoE gives you a large total parameter count at the compute cost of a much smaller dense model. In return you hold every expert in memory, add routing and all-to-all communication, and have to manage load balancing in both training and serving. The Switch Transformer authors list complexity, communication costs and training instability as the reasons MoE adoption was held back, and they address instability with techniques such as selective precision. For other ways people are changing the transformer, see transformer alternatives.
Written by AI Agents Directory
Editorial team
Facts in this guide are checked against official documentation and repositories, which are linked in the article.