~/satyajit

Mixture of Experts, from scratch: the router, the balance and what 128 experts do with real text

mdjsonmcp

2026-06-10 · 49 min · transformers · mixture-of-experts · inference · qwen

A 2:53 narrated explainer, drawn in code. Every number and picture in it is this article's own; the sources are below.

› transcript

Hi, I'm Marshal. A mixture of experts keeps many feed-forward networks and runs a few per token. Who decides? Qwen3 has a hundred and twenty-eight experts in each of its forty-eight layers. For each token, a router picks eight of them. The rest sit idle for that token. The router scores every expert with one matrix and a softmax. It keeps the eight highest. Every other expert gets a weight of zero. The eight weights are rescaled so they add up to one. The token's output is those eight experts' outputs, weighted and summed. GShard put this layer inside the Transformer, in every other block, with two experts per token. Spread over devices, each token travels to its experts and back. Two exchanges in every layer. Hardware wants fixed shapes, so each expert gets a fixed number of slots. Busy experts overflow. Overflow tokens are dropped and ride the residual connection. More slots drop fewer, and empty slots still cost. Even routing fits a small buffer. That is why every mixture of experts fights for balance. Balance used to come from an extra loss that fights the main one. DeepSeek replaced it with a bias, used only to choose. Overloaded experts get their bias lowered, idle ones raised. No gradient touched. Where the balance is measured matters. Balanced per sequence, every domain spreads evenly. Balanced over a whole batch, experts specialise. Code and maths find their own experts. So I read a real router. Qwen3 on my 3090, every expert choice in all forty-eight layers, over code, prose, word problems and LaTeX. Pooled over all four, the load is a smooth slope. Almost every expert gets used. Split by domain, it breaks apart. Each domain leaves hundreds of experts untouched. In an average layer, prose never reaches about seventeen of the hundred and twenty-eight experts. Code and prose share almost none of their busiest experts. A batch reads the union of what its tokens chose. Eight users touch nearly forty-seven experts a layer, close to a random guess. Consecutive tokens from one sequence share experts, so sixty-four of them read only half the layer. Put that routing through a Switch-style buffer and a single sequence's batch loses half its expert work. Specialised models run without a fixed buffer. Balance over the whole corpus, and experts specialise. That is the trade every modern mixture of experts makes. A router that picks a few, a buffer that drops the overflow, and experts that learn their domain. Thanks for watching! Every source is in the full article. I'm Marshal. Bye!

Why read this

Essentialtop 10%

MoE from one MLP to 896 experts, with the papers' figures, a model that trains on a CPU, and Qwen3-30B-A3B's routing measured layer by layer on a 3090.

  • Runs on a laptop CPU
  • Interactive explanations
  • Evergreen reference

LLM architecturePractitioner guide

How this was scored
Is it new?
1 of 3: An incremental tweak
Can I trust it?
2 of 3: Measures key facts from files, code or configs
Can I run it?
3 of 3: Open, permissive, runs on reader hardware with instructions
Will I understand it?
3 of 3: Mechanism carried by interactives built from real code or data
Can I act on it?
2 of 3: A concrete recipe, numbers or comparison
Will it last?
3 of 3: Evergreen fundamentals
Does it affect many?
2 of 3: A widely used model, tool or lab release
Only here?
2 of 3: A teardown or measurement few others did

Score 78 of 100, ranked 39 of 773 rated articles. Each question is answered 0–3 by hand, and a 3 is rare. How articles are scored

Scaling a transformer the dense way welds two numbers together. Every parameter you add runs on every token, so doubling the feed-forward width doubles both what the model can store and the FLOPs it spends per token. You pay for the whole network on every token, whether the token needs it or not.

A mixture of experts (MoE) cuts the weld. Keep a large pile of parameters, and for each token run a small slice of them. A small router looks at the token and picks a few sub-networks, the experts, to handle it; the rest sit idle for that token. The model's parameter count and its per-token compute stop being the same number. Qwen3-30B-A3B, the model I measure at the end of this guide, stores 30.5 billion weights and runs about 3.3 billion of them per token.

This guide builds the layer from one MLP into a 200-line model that trains on a laptop CPU, follows routing from 2017 to 2026 with each paper's own figure, covers expert parallelism and what a server pays for, and then reads a real router: every expert choice Qwen3-30B-A3B made in all 48 layers over 32,768 tokens of code, prose, word problems and LaTeX, logged on an RTX 3090.

The shorter companion is the architecture page, Mixture-of-Experts, from the router to the all-to-all, which counts Hunyuan-A13B's 80.39B total and 12.75B active weights to the last one. Switch Transformers now points here for the full treatment.

The whole model, and the one block that changes

Here is the model we will build. The only thing that makes it a MoE is one swapped block. Tap the sparse MoE block to see its code:

Everything except that block is a standard decoder-only transformer: token and position embeddings, a stack of blocks, a final norm, an LM head. Attention is untouched. MoE replaces the feed-forward layer inside each block and nothing else, so the whole subject reduces to three questions: what is an expert, who decides which experts run, and how do you run only the chosen few.

An expert is an MLP

Start with what gets replaced. In a normal transformer block, after attention, every token goes through the same two-layer MLP: expand to 4 * n_embed, apply a nonlinearity, project back. That is the feed-forward network, and it holds about two thirds of a block's weights.

An expert is exactly that MLP:

class Expert(nn.Module):
    def __init__(self, n_embed, dropout=0.1):
        super().__init__()
        self.net = nn.Sequential(
            nn.Linear(n_embed, 4 * n_embed),
            nn.ReLU(),
            nn.Linear(4 * n_embed, n_embed),
            nn.Dropout(dropout),
        )
 
    def forward(self, x):
        return self.net(x)

The move is to keep num_experts copies of it instead of one. With 8 experts you have 8× the feed-forward parameters. If every token went through all 8 you would spend 8× the compute for a fat, slow FFN. The point is to run only top_k of them, say 2, per token: carry 8 experts' worth of parameters and pay for 2. Modern models use a SwiGLU expert with three matrices instead of two, which changes the parameter count (3 d dff3\,d\,d_\text{ff} instead of 2 d dff2\,d\,d_\text{ff}) and nothing about routing.

Who decides: the router

The router looks at a token's vector xx and produces a weight for each expert, mostly zero, so that only a few experts contribute. It is worth building in three attempts, because the naive versions explain why the real one looks the way it does.

Attempt 1: send every token to every expert, weighted. A linear layer maps the token to one logit per expert, a softmax turns them into weights, and the output is the weighted sum of all expert outputs:

g(x)=softmax(xWg),y=∑i=1Ng(x)i Ei(x)g(x) = \mathrm{softmax}(x W_g), \qquad y = \sum_{i=1}^{N} g(x)_i \, E_i(x)

WgW_g is the router's weight matrix (n_embed × num_experts) and EiE_i is the ii-th expert. This trains fine, and it is dense: every expert runs on every token. It is an expensive ensemble, not a sparse model.

Attempt 2: pick the single best expert. Take arg⁡max⁡\arg\max of the logits and run only that expert. Now it is sparse and cheap. But arg⁡max⁡\arg\max has zero gradient, so the router only learns about the expert it already chose and never gets a signal to try another. Routing freezes.

Attempt 3: top-kk, then softmax. Keep the largest kk logits, set the rest to −∞-\infty, then softmax. The −∞-\infty entries become exactly 0, so only kk experts contribute, as in attempt 2. The softmax over the survivors is smooth, so the loss reaches WgW_g through every gate that was used. This is the real router:

g(x)=softmax(KeepTopK(xWg, k)),KeepTopK(v,k)i={vivi in top k−∞otherwiseg(x) = \mathrm{softmax}\big(\mathrm{KeepTopK}(x W_g,\, k)\big), \qquad \mathrm{KeepTopK}(v, k)_i = \begin{cases} v_i & v_i \text{ in top } k \\ -\infty & \text{otherwise} \end{cases}

With k=2k = 2 and N=8N = 8, six of the eight gate weights are zero for every token and the two survivors sum to 1. Step one token through it: logits, keep the top two, softmax into gates, combine.

The bars are the per-expert logits. Top-2 keeps two, softmax turns them into weights, and the output is those two experts' outputs scaled by their gates and added. Later models reorder these steps (softmax over all experts first, then top-kk, then renormalise the survivors, which is what Qwen3 does; or a sigmoid per expert, which is what DeepSeek-V3 does), but every one of them has this shape: score, select, weight, sum.

Why the noise

The bare top-kk router needs one more piece in practice. Shazeer et al. (2017), the paper that made sparse gating work at scale, added learned, per-expert Gaussian noise to the logits before choosing:

H(x)i=(xWg)i+εi⋅softplus((xWnoise)i),εi∼N(0,1)H(x)_i = (x W_g)_i + \varepsilon_i \cdot \mathrm{softplus}\big((x W_{\text{noise}})_i\big), \qquad \varepsilon_i \sim \mathcal{N}(0, 1)

The noise scale is itself learned (a second linear layer WnoiseW_{\text{noise}}, through softplus to keep it positive). Early in training the router is random, and whichever experts happen to win first get all the gradient and pull ahead. The noise jitters the top-kk selection so borderline experts sometimes win, get some tokens and a chance to become useful. Hit resample noise in the widget above and watch which two experts win flip.

Left, a stack of recurrent layers drawn as pink boxes with an MoE layer between them at each time step. Right, the MoE layer opened: an input x goes to a green gating network and to n experts drawn as boxes. Experts 2 and n-1 are shaded as selected; the gating network's outputs G(x)2 and G(x)n-1 multiply those two experts' outputs, which are summed and passed up.
The layer as it first appeared: a sparsely gated MoE between stacked LSTM layers. The gating network picks experts 2 and n−1, and their outputs are weighted by G(x) and summed. Shazeer's largest layer held 131,072 experts and up to 137 billion parameters (Shazeer et al. 2017, Figure 1).

The paper also named the problem that every MoE server still fights, which it called the shrinking batch: if the router picks kk of nn experts for a batch of bb examples, each expert sees only about kb/nkb/n of them. Big matrix multiplies want big batches, and the router divides yours by n/kn/k. Keep that in mind for the serving section.

In code the router is four lines of real work:

class NoisyTopKRouter(nn.Module):
    def __init__(self, n_embed, num_experts, top_k):
        super().__init__()
        self.top_k = top_k
        self.route = nn.Linear(n_embed, num_experts)   # gate logits
        self.noise = nn.Linear(n_embed, num_experts)   # per-expert noise scale
 
    def forward(self, x):
        logits = self.route(x)
        noisy = logits + torch.randn_like(logits) * F.softplus(self.noise(x))
 
        top_logits, idx = noisy.topk(self.top_k, dim=-1)     # the chosen experts
        sparse = torch.full_like(noisy, float("-inf"))
        sparse.scatter_(-1, idx, top_logits)                 # keep top-k, rest -inf
        return F.softmax(sparse, dim=-1), idx

scatter_ writes the kept logits back into a tensor of -inf at the indices topk chose; after the softmax those -inf slots are 0. The router returns the gate weights and the chosen indices, and the indices tell the next stage which experts to run.

The sparse forward pass

Now the part that earns the word sparse. For each token we have gate weights and the indices of its top-kk experts. We want to run each expert on only the tokens routed to it, scale by the gate, and add the result back. The straightforward way loops over experts and masks out the tokens that picked each one:

class SparseMoE(nn.Module):
    def __init__(self, n_embed, num_experts, top_k):
        super().__init__()
        self.router = NoisyTopKRouter(n_embed, num_experts, top_k)
        self.experts = nn.ModuleList([Expert(n_embed) for _ in range(num_experts)])
 
    def forward(self, x):
        gates, idx = self.router(x)            # (B,T,N), (B,T,k)
        out = torch.zeros_like(x)
 
        flat_x = x.view(-1, x.size(-1))        # (B*T, C)
        flat_gates = gates.view(-1, gates.size(-1))
        flat_out = out.view(-1, x.size(-1))
 
        for i, expert in enumerate(self.experts):
            mask = (idx == i).any(dim=-1).view(-1)   # tokens routed to expert i
            if mask.any():
                y = expert(flat_x[mask])             # run on its tokens only
                flat_out[mask] += flat_gates[mask, i:i+1] * y
        return out

The mask = (idx == i).any(dim=-1) line is the dispatch. It is true for exactly the tokens that have expert i somewhere in their top-kk. We gather those tokens, run the expert once on all of them, scale each by its gate and scatter-add back into the output. A token routed to experts 2 and 5 gets contributions from both loop iterations, summed, which is ∑ig(x)iEi(x)\sum_i g(x)_i E_i(x) with all but kk terms zero.

Picture the dispatch over a short sequence. Each token connects to two of the eight experts, so most of the grid stays dark, and the dark is compute you are not spending:

The bars underneath are the per-expert load: how many tokens each expert handled. It is already uneven. Hold that thought; it is the central problem of MoE, and the measured section shows what it looks like in a production model.

The one line that changes

With experts and a router in hand, dropping MoE into a transformer block is an anticlimax. A standard block is attention → FFN, each wrapped in a layer norm and a residual. MoE swaps the FFN for the SparseMoE module:

class Block(nn.Module):
    def __init__(self, n_embed, n_head, num_experts, top_k, block_size):
        super().__init__()
        self.sa = MultiHeadAttention(n_head, n_embed, block_size)
        self.smoe = SparseMoE(n_embed, num_experts, top_k)   # was: FeedForward(n_embed)
        self.ln1 = nn.LayerNorm(n_embed)
        self.ln2 = nn.LayerNorm(n_embed)
 
    def forward(self, x):
        x = x + self.sa(self.ln1(x))      # attention, unchanged
        x = x + self.smoe(self.ln2(x))    # MoE replaces the feed-forward layer
        return x

That is the whole architectural delta. One FeedForward becomes one SparseMoE:

dense FFNtokensone MLPevery token100% of params, every tokensparse MoEtokensrouter8 experts stored · 2 run
Same slot in the block. Dense runs one MLP on every token; sparse runs a router plus the two chosen experts.

Stack eight of these blocks, add embeddings and an LM head, and you have the model from the top of the page. Train it exactly like a dense transformer, with cross-entropy on the next token. The router learns from the same gradient as everything else. Nobody tells it which expert should take which token.

Run it yourself

Here is everything above in one file: a character-level model that trains on tiny Shakespeare in about 200 lines, with no dependency past PyTorch. Expert, NoisyTopKRouter and SparseMoE are the pieces we just built; the rest is the smallest transformer that can hold them. Copy it, run python tinymoe.py, and watch the loss come down.

"""
tinymoe — a tiny Mixture-of-Experts language model in one file.
Char-level, trains on tiny Shakespeare. ~4.5M params, ~1.4M active per token.
Runs on CPU; much faster on a GPU.
 
    python tinymoe.py        # download data, train, then sample
 
It's a small decoder-only transformer where the feed-forward layer of every
block is replaced by a sparse mixture of experts with noisy top-k routing.
"""
import os
import urllib.request
 
import torch
import torch.nn as nn
from torch.nn import functional as F
 
# --------------------------------------------------------------------- config
batch_size = 32          # sequences per step
block_size = 128         # context length (chars)
n_embed = 128            # embedding / residual width
n_head = 4               # attention heads
n_layer = 4              # transformer blocks
num_experts = 8          # experts per MoE layer
top_k = 2                # experts actually run per token
dropout = 0.1
learning_rate = 3e-4
max_iters = 5000
eval_interval = 500
eval_iters = 100
device = "cuda" if torch.cuda.is_available() else "cpu"
torch.manual_seed(1337)
 
# ----------------------------------------------------------- data (shakespeare)
if not os.path.exists("input.txt"):
    url = ("https://raw.githubusercontent.com/karpathy/char-rnn/"
           "master/data/tinyshakespeare/input.txt")
    urllib.request.urlretrieve(url, "input.txt")
text = open("input.txt", encoding="utf-8").read()
 
chars = sorted(set(text))
vocab_size = len(chars)
stoi = {c: i for i, c in enumerate(chars)}
itos = {i: c for i, c in enumerate(chars)}
encode = lambda s: [stoi[c] for c in s]
decode = lambda t: "".join(itos[i] for i in t)
 
data = torch.tensor(encode(text), dtype=torch.long)
n = int(0.9 * len(data))
train_data, val_data = data[:n], data[n:]
 
 
def get_batch(split):
    d = train_data if split == "train" else val_data
    ix = torch.randint(len(d) - block_size, (batch_size,))
    x = torch.stack([d[i:i + block_size] for i in ix])
    y = torch.stack([d[i + 1:i + block_size + 1] for i in ix])
    return x.to(device), y.to(device)
 
 
# ------------------------------------------------------------------- attention
class Head(nn.Module):
    def __init__(self, head_size):
        super().__init__()
        self.key = nn.Linear(n_embed, head_size, bias=False)
        self.query = nn.Linear(n_embed, head_size, bias=False)
        self.value = nn.Linear(n_embed, head_size, bias=False)
        self.register_buffer("tril", torch.tril(torch.ones(block_size, block_size)))
        self.drop = nn.Dropout(dropout)
 
    def forward(self, x):
        B, T, C = x.shape
        k, q = self.key(x), self.query(x)
        wei = q @ k.transpose(-2, -1) * k.shape[-1] ** -0.5
        wei = wei.masked_fill(self.tril[:T, :T] == 0, float("-inf"))
        wei = self.drop(F.softmax(wei, dim=-1))
        return wei @ self.value(x)
 
 
class MultiHeadAttention(nn.Module):
    def __init__(self, n_head, head_size):
        super().__init__()
        self.heads = nn.ModuleList([Head(head_size) for _ in range(n_head)])
        self.proj = nn.Linear(n_embed, n_embed)
        self.drop = nn.Dropout(dropout)
 
    def forward(self, x):
        out = torch.cat([h(x) for h in self.heads], dim=-1)
        return self.drop(self.proj(out))
 
 
# --------------------------------------------------------- mixture of experts
class Expert(nn.Module):
    """One expert = one MLP. Same shape as a normal transformer FFN."""
 
    def __init__(self):
        super().__init__()
        self.net = nn.Sequential(
            nn.Linear(n_embed, 4 * n_embed), nn.ReLU(),
            nn.Linear(4 * n_embed, n_embed), nn.Dropout(dropout),
        )
 
    def forward(self, x):
        return self.net(x)
 
 
class NoisyTopKRouter(nn.Module):
    """Score experts per token, add learned noise, keep top-k, softmax."""
 
    def __init__(self):
        super().__init__()
        self.route = nn.Linear(n_embed, num_experts)
        self.noise = nn.Linear(n_embed, num_experts)
 
    def forward(self, x):
        logits = self.route(x)
        noisy = logits + torch.randn_like(logits) * F.softplus(self.noise(x))
        top_logits, idx = noisy.topk(top_k, dim=-1)
        sparse = torch.full_like(noisy, float("-inf")).scatter(-1, idx, top_logits)
        return F.softmax(sparse, dim=-1), idx
 
 
class SparseMoE(nn.Module):
    """Run only the top-k experts per token; combine them by gate weight."""
 
    def __init__(self):
        super().__init__()
        self.router = NoisyTopKRouter()
        self.experts = nn.ModuleList([Expert() for _ in range(num_experts)])
 
    def forward(self, x):
        gates, idx = self.router(x)                  # (B,T,E), (B,T,k)
        out = torch.zeros_like(x)
        flat_x = x.reshape(-1, x.size(-1))
        flat_gates = gates.reshape(-1, gates.size(-1))
        flat_out = out.reshape(-1, x.size(-1))
        for i, expert in enumerate(self.experts):
            mask = (idx == i).any(dim=-1).reshape(-1)  # tokens routed to expert i
            if mask.any():
                flat_out[mask] += flat_gates[mask, i:i + 1] * expert(flat_x[mask])
        return out
 
 
# ------------------------------------------------------------- block + model
class Block(nn.Module):
    def __init__(self):
        super().__init__()
        self.sa = MultiHeadAttention(n_head, n_embed // n_head)
        self.smoe = SparseMoE()                      # <- replaces the FFN
        self.ln1 = nn.LayerNorm(n_embed)
        self.ln2 = nn.LayerNorm(n_embed)
 
    def forward(self, x):
        x = x + self.sa(self.ln1(x))
        x = x + self.smoe(self.ln2(x))
        return x
 
 
class MoELanguageModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.tok_emb = nn.Embedding(vocab_size, n_embed)
        self.pos_emb = nn.Embedding(block_size, n_embed)
        self.blocks = nn.Sequential(*[Block() for _ in range(n_layer)])
        self.ln_f = nn.LayerNorm(n_embed)
        self.head = nn.Linear(n_embed, vocab_size)
 
    def forward(self, idx, targets=None):
        B, T = idx.shape
        x = self.tok_emb(idx) + self.pos_emb(torch.arange(T, device=idx.device))
        x = self.ln_f(self.blocks(x))
        logits = self.head(x)
        loss = None
        if targets is not None:
            loss = F.cross_entropy(logits.view(-1, vocab_size), targets.view(-1))
        return logits, loss
 
    @torch.no_grad()
    def generate(self, idx, max_new_tokens):
        for _ in range(max_new_tokens):
            logits, _ = self(idx[:, -block_size:])
            probs = F.softmax(logits[:, -1, :], dim=-1)
            idx = torch.cat([idx, torch.multinomial(probs, 1)], dim=1)
        return idx
 
 
# --------------------------------------------------------------------- train
@torch.no_grad()
def estimate_loss(model):
    out = {}
    model.eval()
    for split in ("train", "val"):
        losses = torch.zeros(eval_iters)
        for k in range(eval_iters):
            x, y = get_batch(split)
            _, losses[k] = model(x, y)
        out[split] = losses.mean().item()
    model.train()
    return out
 
 
model = MoELanguageModel().to(device)
total = sum(p.numel() for p in model.parameters())
print(f"{total / 1e6:.2f}M params on {device}")
opt = torch.optim.AdamW(model.parameters(), lr=learning_rate)
 
for it in range(max_iters):
    if it % eval_interval == 0:
        l = estimate_loss(model)
        print(f"step {it:5d} | train {l['train']:.3f} | val {l['val']:.3f}")
    x, y = get_batch("train")
    _, loss = model(x, y)
    opt.zero_grad(set_to_none=True)
    loss.backward()
    opt.step()
 
# -------------------------------------------------------------------- sample
ctx = torch.zeros((1, 1), dtype=torch.long, device=device)
print(decode(model.generate(ctx, 500)[0].tolist()))

At the default size it prints 4.52M params, and only about 1.4M of them run on any given token, because 6 of every 8 experts sit out. That is the parameter-versus-compute split in miniature. Raise num_experts and the total climbs while the active count barely moves; lower top_k to 1 and it gets sparser still. Mixtral 8×7B pulls the same lever, 8 experts and top-2, at 47B parameters with about 13B active per token.

This minimal version leans entirely on the routing noise to keep experts balanced. There is no auxiliary loss. At toy scale it trains fine. Scale it up and a few experts take over, which is the next problem and most of the rest of this guide.

Collapse, and the first fixes

MoE has one failure mode that dominates the rest, and the dispatch map already showed it forming: expert collapse. Routing is a positive feedback loop. An expert that wins a few tokens early gets gradient, improves, and so becomes the router's favourite for more tokens. The experts that lost early get no tokens, no gradient, and never improve. Left alone, a handful of experts do all the work and the rest are dead weight: you pay to store 8 experts and effectively run 2 or 3.

Shazeer's paper attacked it twice. Noise was the first defence. The second was a pair of auxiliary losses added to the training objective. The importance of an expert is the sum of its gate values over a batch, and the first loss is the squared coefficient of variation of the importances, times a hand-tuned weight wimportancew_\text{importance}:

Importance(X)=∑x∈XG(x),Limportance=wimportance⋅CV(Importance(X))2\mathrm{Importance}(X) = \sum_{x \in X} G(x), \qquad L_\text{importance} = w_\text{importance} \cdot \mathrm{CV}\big(\mathrm{Importance}(X)\big)^2

That is not enough on its own, because an expert can collect a few tokens with large weights while another collects many with small ones: equal importance, unequal load. So a second loss pushed a smooth estimate of each expert's token count toward even. The paper initialised WgW_g and WnoiseW_\text{noise} to zero, so training starts with no routing signal and some noise.

Every balancing scheme since is a variation on that trade. Push too little and experts collapse. Push too hard and the gradient fights the language-modelling loss for control of the router, and the router stops sending tokens where they would do the most good. A dense FFN has none of this: no routing, no balance to keep, no extra loss to tune. MoE buys cheap capacity and hands you a load-balancing problem.

GShard: top-2 inside the Transformer, and expert capacity

GShard (Lepikhin et al., 2020) moved the layer into the Transformer. It replaced every other feed-forward layer with an MoE layer of top-2 routing and trained a 600B-parameter translation model, 100 languages to English, on 2,048 TPU v3 cores in 4 days. Its figure is the first picture of the shape every MoE model has had since:

Three panels. Left, a standard Transformer encoder: multi-head attention and a feed-forward FFN with add-and-norm, repeated N times. Middle, the MoE Transformer encoder: every other block's FFN replaced by an MoE block holding FFN1 to FFNE and a Gating box, repeated N/2 times. Right, the MoE encoder with device placement: device 1 to device E each hold a copy of the attention and dense FFN layers, a shard of the input, and one expert FFN. Between the devices, ovals labelled All-to-All Dispatch and All-to-All Combine connect each device's gating to every expert.
GShard's three steps: a Transformer encoder, the same encoder with an MoE layer in every other block, and that MoE layer spread over E devices, one expert each, with an all-to-all dispatch before the experts and an all-to-all combine after them (Lepikhin et al. 2020, Figure 3).

The right-hand panel is the systems half of MoE in one drawing. Attention and the dense layers are replicated, data parallel; the experts are split, one per device. A token's hidden vector has to travel to the device that holds its expert and come back. That is the all-to-all, and it is why everything about routing after GShard is also about communication.

GShard's gating function added four mechanisms, each still in use in some form:

Capacity matters most for what follows: accelerators compile for fixed tensor shapes, so a dynamic routing decision is poured into fixed-size buffers, and the size decides who gets dropped.

Switch: one expert, a buffer, and the tokens that fall off

Switch Transformers (Fedus, Zoph and Shazeer, 2021) made one blunt change: route each token to exactly one expert. Shazeer's 2017 paper had argued that k≥2k \ge 2 was needed so the router could compare experts and learn. Switch keeps only the argmax and scales the chosen expert's output by its router probability, y=pi(x) Ei(x)y = p_i(x)\,E_i(x), so the router still gets a gradient through pip_i.

Switch Transformer encoder block. Left, a standard transformer block with a Switching FFN Layer replacing the dense feed-forward network. Right, the layer expanded: two tokens x1 and x2 each pass through self-attention, then a Router that selects a single FFN. Token x1 goes to FFN 2 with probability 0.65, token x2 goes to FFN 1 with probability 0.8, and the chosen expert's output is scaled by that gate probability before the add-and-normalize.
The Switch layer: the router sends x1 to FFN 2 with p = 0.65 and x2 to FFN 1 with p = 0.8, and each expert's output is scaled by that probability (Switch Transformers, Fedus et al. 2021, Figure 2).

Top-1 is not a small saving. Each routed copy of a token is an activation that has to be dispatched to another device and combined back, so one copy instead of two roughly halves both the router's work and the all-to-all volume. The paper's Table 1 compares the two head to head, both with 128 experts in every other layer on 32 TPUv3 cores: at a capacity factor of 1.0, Switch-Base trains at 1,000 examples a second and the top-2 MoE-Base at 860. Switch-Base also reaches the paper's quality threshold sooner, in 62.8 hours against 80.1.

The capacity factor

Switch writes GShard's buffer as a formula with one knob:

expert capacity=tokens per batchnumber of experts×capacity factor\text{expert capacity} = \frac{\text{tokens per batch}}{\text{number of experts}} \times \text{capacity factor}

and for top-kk routing the right-hand side is multiplied by kk. At a capacity factor of 1.0, each expert has room for exactly its fair share. Routing is never that even, so a factor above 1.0 buys slack. Any token past an expert's capacity is dropped: the expert skips it, and the token reaches the next layer through the residual connection. Raising the factor drops fewer tokens and pays for more empty slots, because every slot is computed and held in memory whether a token lands in it or not.

Three panels. Left, a terminology list defining experts (split across devices), expert capacity (tokens per batch divided by number of experts, times the capacity factor) and the capacity factor. Middle, capacity factor 1.0: six coloured tokens on device 0 are routed to three experts on devices 0, 1 and 2, each with two slots. Expert 1 receives three tokens, so one red dashed arrow marks a token that does not fit. Right, capacity factor 1.5: each expert has three slots, every token fits, and several slots stay empty. A brace on the right labels the arrows across-device communication.
Capacity factor 1.0 against 1.5. With two slots per expert, a third token routed to expert 1 overflows (the red dashed arrow) and is dropped; with three slots everything fits, and the empty white slots are compute paid for nothing (Switch Transformers, Fedus et al. 2021, Figure 3).

Try it. The toy mode uses 16 experts and an invented load profile; the second mode loads one layer of the real model measured below.

Switch reported drops "typically under 1%" with its balancing loss, and saw no dependence on the number of experts. It also tried rerouting overflow tokens to a second choice and found no benefit. The table above shows why the factor stayed low: at 1.0 Switch-Base was fastest per hour, at 2.0 it reached the threshold in 72.8 hours. Every slot costs.

The loss that every model copied

Switch's balancing loss is the one most MoE models used for the next four years:

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

fif_i is the fraction of the batch's tokens dispatched to expert ii, a count with no gradient, and PiP_i is the router's mean probability for expert ii over the batch, which has one. Under perfectly even routing both are 1/N1/N, the sum is N⋅1/N2=1/NN \cdot 1/N^2 = 1/N, and the loss equals α\alpha whatever NN is. The gradient flows only through PiP_i, scaled by fif_i: the experts that already receive the most tokens have their probability pushed down hardest. Switch swept α\alpha from 10−110^{-1} to 10−510^{-5} and used 10−210^{-2}, which balanced load quickly without disturbing the training loss.

Two smaller choices finished the recipe. Selective precision: the router's softmax runs in float32 inside an otherwise bfloat16 model, because the exponent is where rounding flips an argmax, and the float32 never leaves the device, so it costs no bandwidth. And a higher dropout inside experts during fine-tuning (0.4 against 0.1 elsewhere), because a model with that many parameters overfits small downstream sets.

A learning-curve chart with negative log perplexity on the y-axis and training time on the x-axis. Switch-Base curves with 128, 64 and 32 experts all rise well above the T5-Base curve. A horizontal arrow labelled 7x Speedup marks the training-time gap between Switch-Base and T5-Base at equal quality.
At equal FLOPs per token, the 64-expert Switch-Base reaches T5-Base's quality about 7× sooner. It is a sample-efficiency gain, bought with memory and communication for many more parameters (Switch Transformers, Fedus et al. 2021, Figure 5).

The 7× is steps to a quality target at matched FLOPs per token, not wall-clock. Switch-C stores 1.6 trillion parameters with 2,048 experts per layer, and each token still runs one expert's FFN. The Switch page keeps the short summary, including distillation back to dense.

Many small experts, and some that every token uses

By 2024 the experts had shrunk. DeepSeekMoE (Dai et al., 2024) changed how experts are cut, in two moves that are in nearly every large MoE released since.

Three panels, left to right. (a) Conventional top-2 routing: a router with K = 2 sends the input to 2 of N large experts. (b) Fine-grained expert segmentation: the same router now picks 4 of 2N experts, each half the size. (c) Shared expert isolation: expert 1 is coloured green as a shared expert that the input reaches directly without the router, and the router picks 3 of the remaining routed experts.
From conventional top-2 to DeepSeekMoE: split every expert into smaller ones and route to proportionally more (b), then take some experts out of routing and run them on every token (c). The compute per token is the same in all three panels (DeepSeekMoE, Dai et al. 2024, Figure 2).

Fine-grained segmentation. Split each of NN experts into mm smaller ones and route to mKmK of mNmN instead of KK of NN. The FLOPs per token do not change. What changes is how many different mixtures a token can be given: the paper's example is top-2 of 16 experts, 120 possible pairs, against top-8 of 64 at the same compute, 4,426,165,368 combinations. Qwen3-30B-A3B routes 8 of 128, which allows about 1.43 trillion sets per layer.

Shared experts. Set KsK_s experts aside that every token passes through without asking the router:

h=u+∑i=1KsFFNi(u)+∑i∈Tgi FFNi(u)h = u + \sum_{i=1}^{K_s} \mathrm{FFN}_i(u) + \sum_{i \in \mathcal{T}} g_i \, \mathrm{FFN}_i(u)

The argument is that common knowledge (syntax, frequent words) would otherwise be relearned inside many routed experts, and a shared expert holds it once. DeepSeekMoE 16B has 2 shared and 64 routed experts per layer, routes each token to 6 of the 64, and reports matching LLaMA2 7B with about 40% of the computation. DeepSeek-V2 and V3 and Kimi K3 kept shared experts. Qwen3 dropped them: its report says plainly that "unlike Qwen2.5-MoE, the Qwen3-MoE design excludes shared experts", which makes its routing easier to read, since every one of its eight choices is a real decision.

The parameter arithmetic is the same for every model. With LL MoE layers, EE routed experts of PeP_e weights, kk routed per token and N0N_0 for everything every token uses (attention, shared experts, routers, norms, embeddings):

Ntotal=N0+L E Pe,Nactive=N0+L k PeN_\text{total} = N_0 + L\,E\,P_e, \qquad N_\text{active} = N_0 + L\,k\,P_e

For Qwen3-30B-A3B, from its config.json: one SwiGLU expert is 3 × 2,048 × 768 = 4,718,592 weights, and 48 layers × 128 experts make 28,991,029,248 routed weights. Attention is 18,874,368 weights a layer and the router 262,144 (2,048 × 128, about a twentieth of one expert). With the untied embedding and output head, 311,164,928 each, the total is 30,532,122,624 and a token touches 3,353,032,704, of which 1,811,939,328 are its 384 expert calls. Qwen's card says 30.5B and 3.3B. The architecture page has the same count for Hunyuan-A13B and the ratio for Mixtral, DeepSeek-V2, V3 and Kimi K3; the ratio of stored to active has grown from 3.6 for Mixtral to 26.7 for K3.

Balancing without a loss

The auxiliary loss has a cost that took a few years to measure. Its gradient competes with the language-modelling loss for control of the router. Wang et al. (2024) put numbers on that dilemma with a metric I use below, the maximal violation:

MaxVio=max⁡iLoadi−Load‾Load‾\text{MaxVio} = \frac{\max_i \text{Load}_i - \overline{\text{Load}}}{\overline{\text{Load}}}

the busiest expert's excess over an even share. With a small loss coefficient, routing collapses and MaxVio is large; with a large one, balance is good and perplexity is worse. Their fix removes the loss and adds a per-expert bias bib_i that is used only for choosing:

gi={sisi+bi∈TopK({sj+bj},k)0otherwiseg_i = \begin{cases} s_i & s_i + b_i \in \mathrm{TopK}\big(\{s_j + b_j\}, k\big) \\ 0 & \text{otherwise} \end{cases}
Left panel, Model Training: a grid of gating scores for six tokens over four experts, an Expert Bias vector of 0.1, -0.2, -0.1, -0.1 added to the scores before a Top-K Selection box, and above it the resulting expert loads 5, 2, 1 and 4. Right panel, Bias Updating: the same loads drawn as bars against a dashed Mean Load line, a Feedback Updating funnel, and a new bias vector in which the overloaded experts' biases go down and the underloaded experts' go up.
Loss-free balancing: a per-expert bias shifts the scores used to pick the top-k, and after each step it is nudged down for experts above the mean load and up for those below. The bias never enters the output or the gradient (Wang et al. 2024, Figure 1).

The gate that weights the expert's output is the unbiased score, so the bias moves traffic without touching the gradient. After each step, the bias of every overloaded expert drops by a fixed amount and every underloaded one rises by the same amount. The update uses loads from past batches; using the current sequence's would leak information about future tokens into the routing of earlier ones. In the paper's Table 2 the result is better on both axes at once: at 1B parameters, validation perplexity 9.50 against 9.56 for the loss-controlled baseline, with MaxVio 0.04 against 0.72; at 3B, 7.92 against 7.97, with MaxVio 0.04 against 0.52.

DeepSeek-V3 trained this way at 671B parameters, with a bias update speed γ\gamma of 0.001 for the first 14.3T tokens and 0 for the last 500B, plus a sequence-wise balance loss at α=0.0001\alpha = 0.0001 "just to avoid extreme imbalance within any single sequence". It drops no tokens in training or in inference.

Where the balance is measured matters more than how

The V3 report contains a quieter result that changes how to read every balancing scheme. Its Figure 9 plots expert load per domain for a 16B model trained with a sequence-wise auxiliary loss and one trained loss-free:

Four heatmaps of relative expert load over 64 experts for three Pile domains, Wikipedia (en), Github and DM Mathematics, on a scale from 0 to 10. Aux-Loss-Based layers 9 and 18 are pale and uniform across all three domains. Aux-Loss-Free layers 9 and 18 have strong dark cells: some experts take several times their share of Github or DM Mathematics tokens and almost none of the others.
With a sequence-wise auxiliary loss every domain spreads evenly over the 64 experts (pale rows); trained loss-free, experts specialise by domain, and single cells reach many times an even share (DeepSeek-V3 report, Figure 9).

A sequence-wise loss forces every sequence to use every expert evenly, so a sequence of code cannot concentrate on the experts that are good at code. The same report then tested a batch-wise auxiliary loss, balanced over a whole batch instead of each sequence, and it matched the loss-free method: validation loss 2.253 for both at 1B, against 2.258 sequence-wise. So the bias was never the whole story. The scope of the balance was.

Qiu et al. (2025) made that their whole paper. Most training frameworks compute the Switch loss per micro-batch, and a micro-batch at billion scale holds only a few sequences, so the balance is in practice per sequence. Computing fif_i over the global batch with one extra all-reduce relaxes it to balance at the corpus level, and the paper reports better perplexity and much stronger domain specialisation. The Qwen3 report adopts exactly this: "we adopt the global-batch load balancing loss (Qiu et al., 2025) to encourage expert specialization." That is the claim the measured section tests.

Sixteen of 896: Kimi K3

Kimi K3 pushes sparsity to 16 routed experts of 896 per layer, plus 2 shared, for 2.78T total and 104.2B active. At that ratio, the bias nudge of loss-free balancing breaks down: a fixed step is either too slow to follow nearly a thousand loads or so fast that they oscillate. K3's quantile balancing replaces the step with a solve. The router runs top-(k+1)(k{+}1); the (k+1)(k{+}1)-th score is the cutoff a competing expert would have had to beat. Each expert's next bias is a quantile of its margins over the batch (score minus cutoff), the (1−k/n)(1 - k/n) quantile, which by construction hands every expert exactly its target load. At training scale the margins are scattered over ranks, so each rank bins its own into a histogram, one all-reduce sums the bins, and the quantile is read off the pooled histogram.

Equal loads make tensor shapes static, which removes the host synchronisation variable loads force on every layer; the Kimi K3 article has a widget for the quantile.

Latent experts

The newest change shrinks what an expert sees. In LatentMoE (Elango et al., 2026), each token is projected from the model width dd down to a latent width ℓ\ell by one shared matrix W↓W_\downarrow, routed and processed by experts that live entirely at width ℓ\ell, and projected back up by W↑W_\uparrow. The router and shared experts still read the full-width token.

Two block diagrams side by side. Left, standard MoE: after self-attention, a router and an all-to-all dispatch send the token to experts E1 to E4 (E2 and E3 selected) and a shared expert SE, then an all-to-all combine. Right, LatentMoE: a green Latent down-proj box sits before the all-to-all dispatch and a green Latent up-proj box after the combine; there are now eight experts E1 to E8, four of them selected, and the shared expert SE still takes the full-width path.
Standard MoE against LatentMoE. Dispatch, the experts and combine all happen at the latent width, which divides all-to-all traffic and expert weight reads by d/ℓ; the freed budget buys more experts and more of them per token (LatentMoE, Elango et al. 2026, Figure 1).

The paper's argument is about bottlenecks. In latency-bound serving, the cost is reading expert weights; in throughput-bound serving, it is the all-to-all. Both scale with the width of what an expert reads and sends. Shrinking that width by α=d/ℓ\alpha = d/\ell cuts both by α\alpha, and the paper spends the savings on α\alpha times as many experts (its ℓ\ell-MoEeff_\text{eff}) or α\alpha times as many experts and α\alpha times as many active ones (the default, ℓ\ell-MoEacc_\text{acc}), keeping communication and weight reads where a standard MoE has them. NVIDIA adopted it for Nemotron-3 Super and Ultra. Kimi K3's routed experts run at a 3,584-wide latent, half its 7,168 model width.

The price is that W↓W_\downarrow and W↑W_\uparrow are dense: every token pays for them. Edge0-145B, the site's latent-moe entry in the architecture gallery, makes the trade concrete. It squeezes Qwen's 2,560-wide experts through a 1,792-wide latent in 8 groups, so the projections are 2 × 2,560 × 1,792 × 8 = 73.4M weights a layer, read for every token, against 34.4M for the ten routed experts a token actually uses. Per layer, the dense part in front of and behind the experts is twice the size of the experts that fire. That is a good trade when the experts live on a slow tier (RAM or an SSD, as on Edge0) and the projections in VRAM. On a single GPU that holds everything, it is a lot of dense compute to save sparse bytes.

What 128 experts do with real text

The papers argue about specialisation from their own models. I wanted to see one router on my own inputs, so I logged every expert choice Qwen3-30B-A3B made. It is the right model for the question for three reasons: it fits on a 24 GB card at 4 bits, it has no shared expert to blur the picture, and its report says it was trained with the global-batch balancing loss "to encourage expert specialization". If specialisation shows up anywhere in an open model, it should show up here.

The setup. The official Qwen GGUF at Q4_K_M (18.56 GB), run by llama.cpp v1.0.0 on the RTX 3090 in my beast2 box. The router matrices, blk.*.ffn_gate_inp, are stored in F32 in that file; the experts are Q4_K and Q6_K, so the router sees slightly quantised hidden states, not bf16 ones. A 150-line C++ tool registers llama.cpp's eval callback and copies two tensors out of every MoE layer on every forward pass: ffn_moe_topk-<layer>, the 8 expert ids per token, and ffn_moe_weights-<layer>, their softmax probabilities before renormalisation. Four domains, each 8 windows of 1,024 tokens spread evenly over its source, every window a fresh context: Python standard-library code, Wikipedia prose (the wikitext-2 test split), GSM8K word problems with their worked answers, and MATH problems with LaTeX solutions. That is 32,768 tokens, 48 layers and 8 choices each, about 12.6 million routing decisions. The run checks its own reads: every id is below 128 and distinct within its token, and every token's 8 weights fall in order and sum to at most 1.

Here is all of it. Rows are layers, columns are experts sorted per layer by how busy they are across all four domains, and each cell is that expert's load divided by an even share (tokens × 8 / 128):

Five heatmaps, each 48 layers tall and 128 experts wide, with columns sorted per layer by load over all four domains pooled. The pooled panel at the bottom runs smoothly from orange on the left (busy experts) through white to blue on the right (quiet ones), with a small red block of never-chosen experts in the bottom-right corner, in the last layers. The four domain panels above it, Python code, Wikipedia prose, GSM8K word problems and MATH with LaTeX, are speckled: many cells far from their pooled colour, and red never-chosen cells scattered through each. Titles give never-chosen counts: code 324, prose 802, word problems 486, LaTeX 464, pooled 92, each out of 6,144.
Where Qwen3-30B-A3B sends 32,768 tokens, measured: each cell is an expert's load over an even share, columns sorted per layer by pooled load. Pooled, the load is a smooth slope; split by domain it breaks up, and each domain leaves hundreds of layer-expert cells untouched. Run on an RTX 3090 with llama.cpp v1.0.0, Q4_K_M GGUF.

The same data, live. Pick a domain, hover a cell for its count, and switch on the comparison against all domains to see which experts a domain owns:

Balanced over the corpus, lopsided everywhere else

Pooled over all four domains, the router is fairly even, as a corpus-level loss asks: on average the busiest expert in a layer takes 4.04× an even share (a MaxVio of about 3; the worst layer, 38, reaches 7.52×), and only 92 of the 6,144 layer-expert cells went unused by all 32,768 tokens. 53 of those 92 sit in the last eight layers.

Within one domain it falls apart. In an average layer, Python code never touches 6.75 of the 128 experts and Wikipedia prose never touches 16.7; word problems leave 10.1 unused and LaTeX 9.7. The busiest expert in a layer takes 9.2× to 9.9× an even share on average depending on the domain, and the single most overloaded cell, in prose, takes 15.09×. That MaxVio of 8 to 9 is more than ten times the 0.72 that Wang et al. measured for a loss-controlled model; the comparison is loose (their metric is over a validation set, mine over one domain at a time), but the direction is the point. A global-batch loss does not ask for balance inside a domain, and it does not get it.

Domains own their experts

To compare whole distributions I use the Jensen-Shannon divergence between two domains' load vectors, per layer, which is 0 for identical routing and 1 for disjoint routing. As a noise floor, I split each domain in half and compare the halves.

PairJS divergence, mean over 48 layersBusiest 16 experts in common (of 16)
code, prose0.5700.1
prose, LaTeX0.5330.6
code, word problems0.4860.5
code, LaTeX0.4281.5
prose, word problems0.3312.8
word problems, LaTeX0.2506.7
one domain against itself (halves)0.009 to 0.051

Code and prose share almost none of their busiest experts: on average, 0.1 of the 16 busiest experts for code are among the 16 busiest for prose. The two maths sets are closest, and the English word problems sit between prose and LaTeX. Every cross-domain mean is about five times or more the largest within-domain one, and code against prose is sixty times the steadiest domain's noise floor. Mixtral's authors looked for this and reported that "we do not observe obvious patterns in the assignment of experts based on the topic". Qwen3, trained to balance over the global batch, shows it on every layer. That is DeepSeek-V3's Figure 9 again, in a model I could run.

What a specialist takes is less romantic than "the Python expert". At layer 12, expert 82 receives 7.22% of all code assignments (an even share is 0.78%) and, to four decimal places, none of the other three domains'. Its most frequent tokens are commas, runs of indentation spaces, newlines, =, :\n and #. Layer 12's expert 34 takes 10.39% of prose assignments and 0.06% of everything else's, and its tokens are the, commas, full stops and of. At layer 0, expert 108 takes 5.37% of the LaTeX assignments, on \\, $, braces and =. Mixtral's observation that experts track syntax (indentation, punctuation) holds here too. The difference is that the syntax is domain-specific: prose's commas and code's commas do not go to the same expert.

Neighbours share experts

Two consecutive tokens share 3.58 of their 8 experts on average, against 1.69 for two random tokens from the same domain. Routing is sticky along a sequence, which is good for a cache of hot experts and bad for the load of whichever device holds them. Experts also travel in groups. In every layer, 12% to 15% of the expert pairs with enough data co-occur more than twice as often as independent choices would, and about half co-occur less than half as often; the tightest pair (layer 19) shows up together 33.86 times more than chance. The router has 1.43 trillion possible sets of 8 per layer, and the 32,768 tokens used between 13,526 and 29,482 distinct sets per layer, fewest at the first and the last layer.

Two smaller readings. The 8 chosen experts hold only a third of the router's probability before renormalisation (0.31 to 0.37 on average, by domain), rising with depth from about a quarter in the first layers to about a half in the last. The router's first choice gets 0.07 to 0.09 of the mass, against an even 0.0078.

What this does to capacity

Now put that routing through a Switch-style buffer. Treat each 1,024-token window as a batch, give every expert capacity factor × 1,024 × 8 / 128 slots, and fill them in token order:

Capacity factorAssignments dropped, one-domain batchesExpected drops, perfectly mixed batch
1.053.1%28.3%
1.2546.2%19.1%
2.032.2%6.1%
3.021.9%

A single sequence's batch would lose half its expert work at the capacity factor Switch used. To drop nothing, the median layer needs a capacity factor of 15.2. Even an ideally mixed batch, computed from the pooled average load, still drops 28.3% at 1.0 and needs 3.90 to drop nothing. (The mixed column uses expected loads, so real mixed batches, which fluctuate, would drop somewhat more.) The capacity toy above has this layer by layer in its "Qwen3 layer" mode.

This is why the modern recipe and dropless kernels arrived together. A model trained to specialise by domain cannot run inside a small fixed buffer, so it does not have one: inference engines run every routed token with grouped matrix multiplies sized at run time (llama.cpp's mul_mat_id is one), and DeepSeek-V3 states it drops no tokens anywhere. Specialisation and fixed capacity pull in opposite directions, and the field chose specialisation.

Expert parallelism and the two all-to-alls

A model with hundreds of experts per layer does not fit on one accelerator, so the experts are spread out. The Switch paper drew the options as grids of 16 cores:

Two rows of five 4-by-4 grids of cores. Top row, how the model weights are split: data parallelism puts a full copy on every core, model parallelism spreads one copy over all 16, model-and-data parallelism uses four blocks of four, expert-and-data parallelism puts a different coloured expert on each of the 16 cores, and expert-model-and-data parallelism puts four experts on four blocks of four cores. Bottom row, how the data is split: one block spanning all 16 cores under data parallelism and under expert-and-data parallelism, 16 small blocks under model parallelism, and four groups of four under the two mixed schemes.
Ways to split weights (top) and tokens (bottom) over 16 cores. In expert-and-data parallelism every core holds a different expert and its own slice of the batch, so tokens have to move to reach their expert (Switch Transformers, Fedus et al. 2021, Figure 9).

With expert parallelism, one MoE layer runs in four moves:

  1. Route. Each device scores its own tokens with the replicated router.
  2. Dispatch, the first all-to-all. Every device sends each token's hidden vector to the devices that host its chosen experts.
  3. Compute. Each device runs its experts on whatever arrived, one grouped matrix multiply per expert.
  4. Combine, the second all-to-all. Expert outputs travel back to each token's home device, where they are weighted by the gates and summed.

The backward pass repeats both exchanges. A token sends up to kk copies of a dd-wide vector each way, per MoE layer. For Qwen3-30B-A3B that is 8 × 2,048 = 16,384 numbers, 32,768 bytes in bfloat16, out and again back, in each of 48 layers: about 1.57 MB each way per token if every expert sat on a different device. Two experts on the same device need only one copy, which is where the real systems save.

DeepSeek-V3 is the most detailed public account. Each token sends 8 × 7,168 = 57,344 numbers out; it dispatches in FP8 and combines in BF16. Routing is node-limited: a token may pick experts on at most 4 nodes, so it crosses the slower InfiniBand link at most 4 times and is forwarded over NVLink inside each node. The report notes that each token can reach an average of 3.2 experts per node at no extra NVLink cost, so the same traffic could serve up to 13 experts instead of 8. In serving, the prefill unit is 4 nodes with 32 GPUs plus 32 redundant experts: the hottest experts, found from live statistics about every 10 minutes, get a second copy so every GPU sees about the same number of tokens. The decode unit is 40 nodes with 320 GPUs, one expert per GPU.

The busiest device sets the pace of every layer, so balance stops being a training nicety and becomes a latency term. With one expert per device, a layer whose busiest expert takes twice an even share takes twice as long as an evenly routed layer, while the other devices wait. Redundant experts, Kimi's MoonEP copies and its perfectly equal loads are all ways of paying for the gap between the busiest expert and the mean.

What serving actually pays for

MoE trades compute for memory. Only kk experts run, but every expert has to be resident, and which ones a step reads depends on the batch.

At batch 1, a decode step reads only the chosen experts. For Qwen3-30B-A3B at Q4_K_M, I count from the GGUF tensor types (gate and up projections in Q4_K, the down projection in Q4_K in half the layers and Q6_K in the other half) that one token reads about 1.10 GB of expert weights out of 17.55 GB stored. On a 3090's 936 GB/s that is a ceiling in the hundreds of tokens a second for the expert reads alone, which is why a 30B MoE decodes like a 3B dense model on one card.

A batch reads the union of what its tokens picked, and here the measurement matters more than the formula. If tokens chose uniformly at random, a batch of BB would touch 128 (1−(120/128)B)128\,(1 - (120/128)^B) experts per layer. What the router actually did:

Tokens in the batchUniform formulaMixed batch (random tokens, all domains)Same sequence (consecutive tokens)
18.08.08.0
851.646.828.4
64125.9108.464.8
512128.0123.293.2

Counts are distinct experts per layer, averaged over 48 layers and 20 random draws each. A decode batch of 8 users touches 46.8 experts a layer, close to the uniform guess: the step reads about 37% of every layer's experts for 8 tokens, not 8 × 6%. Sparsity saves FLOPs at any batch size; it saves memory bandwidth mostly at small ones. Consecutive tokens from one sequence are much cheaper, 28.4 experts for 8 tokens and only half the layer for 64, because neighbours share experts. A prefill chunk or a speculative-decoding verify window, both of which are consecutive tokens, reads far less than the formula says.

Shazeer's shrinking batch problem is the other face of this. Spread bb tokens over 128 experts at 8 each and an expert's matrix multiply sees b/16b/16 rows on average, and far fewer for the quiet ones. A serving engine has to batch hard enough that the hot experts' matrix multiplies are efficient while the cold ones' are cheap, and the skew measured above is what it is batching against.

When the experts do not fit, they go to RAM or an SSD and the GPU caches the hot ones (a 200 GB MoE on one RTX 3090 works through the bytes). The stickiness measured above, 3.58 of 8 experts carried from one token to the next, is what makes such caches hit.

Expert choice, and why decoders do not use it

Every router above is token-choice: each token picks its experts, and balance has to be coaxed. Zhou et al. (2022) flipped it. In expert choice, each expert picks its top tokens from the batch up to a fixed bucket size, so every expert is exactly full by construction, and a token can be taken by many experts or by none. The paper reports more than 2× faster training convergence than Switch's top-1 and GShard's top-2 at the same compute.

It has not spread to decoder language models, for a reason the loss-free paper spells out in its appendix: in a causal model, an expert choosing the best tokens of a sequence is looking at tokens that come later, so whether an early token is processed depends on the future. Training gets that information; generation, one token at a time, does not have it. The same problem shows up in Mixture-of-Depths, which routes tokens past whole blocks.

Where I land

Strip away the engineering and MoE is still small: an expert is the FFN you already had; keep many of them; a one-matrix router scores them per token; keep the top few, weight them, run only those. One line in the transformer block changes. Everything since 2017 has been about the two costs that one line creates.

The first is balance, and the lesson of the last two years is that the scope of the balance matters more than the mechanism. Shazeer's losses, GShard's capacity, Switch's fiPif_i P_i, DeepSeek's bias and Kimi's quantiles all trade balance against the freedom to route well, and the measurement says where Qwen3 landed: balanced over a corpus, sharply specialised by domain, and so lopsided inside any one sequence that a Switch-era capacity factor would throw away half its expert work. I think that is the right trade for a model meant to be good at many things, and it is why I would not build a new MoE with token dropping. Dropless kernels are the price, and they are worth it.

The second is memory and communication. Fine-grained experts, node-limited routing, redundant experts and latent experts are all ways of moving fewer bytes per token. Latent experts are the one I would watch: they attack the all-to-all and the weight reads at once, and the dense projections they add are cheap on a large cluster. On one GPU that already holds every expert, I would not pay for them.

If you are starting from zero, run tinymoe.py, then read the heatmap above with one domain selected. The gap between the pooled picture and the per-domain one is the whole subject.

Cite this article

For attribution, please use the following reference or BibTeX:

Satyajit Ghana, "Mixture of Experts, from scratch: the router, the balance and what 128 experts do with real text", ai.satyajit.si, June 2026.

bibtex
@misc{ghana2026mixtureofexpertsfromscratch,
  author = {Satyajit Ghana},
  title  = {Mixture of Experts, from scratch: the router, the balance and what 128 experts do with real text},
  url    = {https://ai.satyajit.si/articles/mixture-of-experts-from-scratch},
  year   = {2026}
}
share