Skip to content
Skip to lesson
Back to Topics
LearnTransformer & Multimodal ArchitecturesMixture of Experts Architecture
HardTransformer Architecture13 min read

Mixture of Experts Architecture

Eight experts can mean two feed-forward calls per token and a full expert pool still sitting in memory.

On this page

An eight-expert layer routes every token to just two feed-forward networks. On paper that looks like a 4x smaller model, until you try to load the checkpoint onto a GPU and discover all eight experts still need memory. How can per-token arithmetic stay sparse while weight residency stays huge?

In a standard Transformer, a single transforms every after attention. replaces that single FFN with NN parallel expert FFNs and a lightweight router (gating network) that chooses a subset for each token at every layer.[1] Attention, , and norms usually remain shared.[2][3]

That design decouples total parameter capacity (all NN experts stored in memory) from active compute per token (only the kk selected experts). The trade-off shifts from raw FLOPs to weight memory, load balance, token overflow, and cross-GPU dispatch.

From one FFN to many experts

Given a token hidden state xx, a linear router WgW_g produces NN logits, converts them to probabilities g(x)=softmax(Wgx)g(x) = \text{softmax}(W_g x), picks the top kk experts, and blends their outputs:

MoE(x)=∑i∈TopK(g(x))g~i(x)⋅Ei(x)\text{MoE}(x) = \sum_{i \in \text{TopK}(g(x))} \tilde{g}_i(x) \cdot E_i(x)

Follow one 4-dimensional token through a 4-expert top-2 Mixtral-style router with logits [-0.65, -1.77, -1.35, -3.00]:

  1. Softmax probabilities: [0.521, 0.170, 0.259, 0.050].
  2. Top-2 selection: Expert 1 (0.521) and Expert 3 (0.259).
  3. Renormalize: 0.521/(0.521+0.259)≈0.6680.521 / (0.521 + 0.259) \approx 0.668 and 0.259/0.780≈0.3320.259 / 0.780 \approx 0.332.
  4. Compute & blend: Run only E1(x)E_1(x) and E3(x)E_3(x) and compute 0.668⋅E1(x)+0.332⋅E3(x)0.668 \cdot E_1(x) + 0.332 \cdot E_3(x).
Exact router probabilities (0.521 and 0.259 for E1 and E3) renormalize to 0.668 and 0.332, blending E1 and E3 into [1.336, 0.995, 0, 0] while E2 and E4 stay idle in memory.

Let's run the exact top-2 router in PyTorch:

topk-router.py
import torch

gate = torch.tensor([[-0.65, 0., 0., 0.], [-1.77, 0., 0., 0.],
                     [-1.35, 0., 0., 0.], [-3.00, 0., 0., 0.]])
x = torch.tensor([1.0, 0.0, 0.0, 0.0])

probs = torch.softmax(gate @ x, dim=0)
top_probs, selected = torch.topk(probs, k=2)
weights = top_probs / top_probs.sum()

# Four simple diagonal-like expert projections mapping R^4 -> R^4
experts = torch.zeros(4, 4, 4)
experts[0, 0, 0], experts[1, 2, 0], experts[2, 1, 0], experts[3, 3, 0] = 2.0, 4.0, 3.0, 5.0

blended = weights @ (experts[selected] @ x)
print("selected experts:", (selected + 1).tolist())
print("renormalized weights:", [round(w, 3) for w in weights.tolist()])
print("blended output:", [round(v, 3) for v in blended.tolist()])
Output
selected experts: [1, 3]
renormalized weights: [0.668, 0.332]
blended output: [1.336, 0.995, 0.0, 0.0]

Why sparse activation separates compute from memory

Because only FFN blocks are replicated while attention and embeddings stay shared, Mixtral 8x7B totals 46.7B parameters (not 8×7=568 \times 7 = 56B) and activates 12.9B parameters per token under top-2 routing.[2]

PropertyDense peer (~13B)Mixtral 8x7B (top-2 of 8)
Total parameters (memory)~13B~46.7B
Active parameters (FLOPs)~13B~12.9B
Extra runtime workNoneRouting, token grouping, all-to-all dispatch

Active parameters govern per-token FLOPs; total parameters govern weight residency. A model with 3B shared weights and eight 2B expert partitions activates only 7B weights (14 GB BF16) per token, yet still requires 38 GB BF16 to hold all 19B weights in memory.

Aligned BF16 memory comparison against a 14 GB GPU VRAM cap: the stored resident pool totals 38 GB (6 GB shared + 8 GB for 2 active experts + 24 GB for 6 idle experts), exceeding the 14 GB cap by 24 GB even though each token computes with only 14 GB of active weights (7B of 19B parameters).
One token computes with 7B active parameters (14 GB BF16), while all 19B parameters (38 GB) must remain resident in memory.

Expert choice vs. token choice routing

Standard token-choice routing lets each token pick its top kk experts, guaranteeing every token gets kk experts at the risk of overloading popular experts. Expert-choice routing flips the direction: each expert selects its top-scoring fixed bucket of tokens from the batch.[5]

That guarantees balanced expert buckets, but introduces two subtle catches:

  1. Uncovered tokens: Some tokens can land in zero expert buckets (passing through the residual stream alone) while others land in multiple buckets.
  2. Causality leak in decoders: Because an expert ranks tokens across the batch, a future token with a higher score (0.9) can knock an earlier token (0.6) out of the bucket despite causal attention masking. Autoregressive decoders therefore need prefix-consistent routing.
expert-choice-tradeoffs.py
import numpy as np

# 3 experts (rows) each pick top-2 tokens from 5 tokens t0..t4 (columns)
scores = np.array([
    [0.90, 0.80, 0.10, 0.05, 0.01],
    [0.85, 0.20, 0.75, 0.10, 0.02],
    [0.15, 0.25, 0.80, 0.70, 0.03],
])
buckets = np.argsort(-scores, axis=1, kind="stable")[:, :2]
counts = np.bincount(buckets.ravel(), minlength=5)
print("assignments per token:", counts.tolist(), "-> uncovered:", [f"t{i}" for i in np.flatnonzero(counts == 0)])

# Future token (0.9) displaces earlier token (0.6) in a 1-slot bucket
print("prefix winner:", ["earlier"][int(np.argmax([0.6]))])
print("with future token:", ["earlier", "future"][int(np.argmax([0.6, 0.9]))])
Output
assignments per token: [2, 1, 2, 1, 0] -> uncovered: ['t4']
prefix winner: earlier
with future token: future

Why routers collapse without load balancing

Left to pure task loss, routers suffer from rich-get-richer collapse: an expert that wins slightly more tokens early gets more gradient updates, improves faster, attracts still more tokens, and starves its peers. You end up paying VRAM for every expert while only training a few.

The auxiliary load-balancing loss

Switch Transformer counters collapse with a differentiable penalty combining each expert's actual assignment fraction fif_i and its mean router probability pip_i across the batch:[4]

Lbalance=α⋅N∑i=1Nfi⋅pi\mathcal{L}_{\text{balance}} = \alpha \cdot N \sum_{i=1}^N f_i \cdot p_i

Hard counts fif_i stop gradients, so updates flow through pip_i to push down probabilities on heavily loaded experts. Under uniform routing (fi=pi=1/Nf_i = p_i = 1/N), the unscaled factor N∑fipi=1.0N \sum f_i p_i = 1.0. On a skewed batch [0.60, 0.20, 0.15, 0.05] with mean probabilities [0.55, 0.22, 0.15, 0.08], it jumps to 4×0.4005=1.6024 \times 0.4005 = 1.602.

load-balancing-and-counterexample.py
# 1. Skewed 4-expert batch: 4 * sum(f * p) = 1.602 vs uniform 1.0
f = torch.tensor([0.60, 0.20, 0.15, 0.05])
p = torch.tensor([0.55, 0.22, 0.15, 0.08])
print("skewed 4-expert score:", round((4 * torch.dot(f, p)).item(), 3))

# 2. Counterexample: Expert 2 gets 0 tokens yet score = 0.90 < 1.0!
probs = torch.tensor([[0.51, 0.09, 0.40], [0.09, 0.51, 0.40]])
winners = probs.argmax(dim=1)
fracs = torch.bincount(winners, minlength=3).float() / probs.shape[0]
score = 3 * torch.dot(fracs, probs.mean(dim=0))
print("dead-expert fractions:", fracs.tolist(), "score:", round(score.item(), 2))
Output
skewed 4-expert score: 1.602
dead-expert fractions: [0.5, 0.5, 0.0] score: 0.9
Left: Switch auxiliary balance terms f_i * p_i for four experts on a skewed batch are 0.330, 0.044, 0.0225, and 0.004, yielding N * sum(f_i * p_i) = 4 * 0.4005 = 1.602 versus uniform 1.00. Right: two-token, three-expert counterexample routing probabilities [[0.51, 0.09, 0.40], [0.09, 0.51, 0.40]] produce fractions [0.5, 0.5, 0.0] and score 3 * 0.30 = 0.90 < 1.0 even though E2 receives zero tokens.
Left: Skewed 4-expert batch scores 1.602. Right: A 3-expert batch scores 0.90 (below 1.0) while leaving Expert 2 unused, showing why histograms must accompany the scalar loss.

Router z-loss for numerical stability

Even when load is balanced, drifting router logits can destabilize mixed-precision training. Router z-loss penalizes the squared log-partition function (log⁡∑iezi)2(\log \sum_i e^{z_i})^2 averaged over tokens.[6] Shifting logits [\log 0.75, \log 0.25] upward by +3 leaves softmax probabilities untouched at [0.75, 0.25] while raising log-sum-exp from 0 to 3 and z-loss from 0 to 9, keeping logit magnitudes bounded without distorting expert selection.

Capacity factor and token overflow

Fixed-shape GPU kernels pre-allocate a static token buffer per expert scaled by a capacity factor cc:

Expert Capacity=⌈TkN×c⌉\text{Expert Capacity} = \left\lceil \frac{T k}{N} \times c \right\rceil

For T=4,096T = 4{,}096 tokens, top-k=2k = 2, and N=32N = 32 experts, the uniform share is 256 slots per expert (308 at c=1.2c = 1.2). When a hot expert receives 400 assignments at c=1.0c = 1.0, 144 overflow. Runtimes either drop overflowing assignments (leaving the residual pass-through),[4] reroute them to spare experts, or run dropless variable-length grouped GEMMs over all 400 assignments.[7]

For 4,096 tokens with top-2 routing across 32 experts (mean 256 per expert), a hot expert receives 400 assignments. Capacity factor c = 1.0 fits 256 slots and leaves 144 overflow tokens; c = 1.2 raises capacity to 308 slots and cuts overflow to 92. Three overflow paths at c = 1.0 handle the 144 excess tokens: drop (skip expert, keep residual), reroute to a spare expert, or dropless variable-size execution running all 400.
A hot expert receiving 400 assignments for 256 slots overflows 144 assignments at c=1.0c=1.0 (92 at c=1.2c=1.2). Dropping skips those expert updates, rerouting redirects them, and dropless kernels run all 400.

How modern architectures scale the idea

Modern frontier MoEs shifted from coarse 8-expert pools to fine-grained pools of 160 to 256 experts paired with always-on shared experts and auxiliary-loss-free balancing:

ModelTotal / ActiveExperts per MoE layerKey routing innovation
Mixtral 8x7B[2]46.7B / 12.9B8 routed (top-2), SwiGLU[8]Clean coarse-grained softmax top-2
DeepSeek-V2[3]236B / 21B160 routed (top-6) + 2 sharedFine-grained experts, shared experts, device-limited routing, MLA
DeepSeek-V3[9]671B / 37B256 routed (top-8) + 1 sharedSigmoid affinity + bias-adjusted auxiliary-loss-free balancing
DeepSeek V4 Flash 0731[10][11]284B / 13B256 routed (top-6) + 1 sharedsoftplus(⋅)\sqrt{\text{softplus}(\cdot)} affinity, hash routing in first 3 blocks
GLM-5.3[12][13][14][15]744B / ~40B256 routed (top-8) + 1 shared3 dense + 75 MoE layers, routed scaling factor 2.5
Qwen3.6-35B-A3B[16]35B / 3B256 routed (top-8) + 1 sharedInterleaved Gated DeltaNet + gated attention
Exact per-layer expert pools comparing Mixtral 8x7B and DeepSeek-V2. Mixtral 8x7B stores 8 coarse routed experts and activates 2 per token (~46.7B total, ~12.9B active, 27.6% active). DeepSeek-V2 stores 160 fine-grained routed experts (6 active) plus 2 always-on shared experts (236B total, 21B active, 8.9% active).
Per-MoE-layer pools: Mixtral selects 2 of 8 coarse experts; DeepSeek-V2 selects 6 of 160 fine-grained experts alongside 2 always-on shared experts.

DeepSeek-V3's auxiliary-loss-free balancing computes sigmoid affinities sis_i, adds a dynamically updated bias bib_i only when picking top-8 expert IDs, and weights expert outputs using the original unbiased affinities sis_i (backed by a tiny sequence-wise balance guard), balancing load without fighting the language-modeling gradient.[9]

Note also that FFN sparsity and sequence mixing are independent choices: Qwen3.6-35B-A3B interleaves Gated DeltaNet layers with gated attention so both the feed-forward and memory paths stay lean.

Serving an MoE on real hardware

Sparse FLOPs do not automatically translate to lower latency: experts span GPUs, hidden states cross NVLink or InfiniBand, and small decode batches shrink expert matmuls.

Expert parallelism, wire traffic, and grouped GEMMs

While shards each expert's matrices across GPUs, places whole experts on different GPUs and runs all-to-all dispatch and all-to-all combine.[7][17] Large serving clusters mix both (for example, DeepSeek-V3 pairs TP4 attention with EP320 decode and hot-expert replication via EPLB).[9][17]

If a fraction rr of TkT k assignments target remote GPUs, transferring an HH-element vector at bb bytes round-trip costs Qremote=2rTkHbQ_{\text{remote}} = 2 r T k H b. When one token picks two experts on the same remote GPU, per-destination coalescing sends the input once, runs both experts remotely, and returns one already-weighted combined output, halving wire bytes (16 KiB vs. 32 KiB for a 4,096-wide BF16 vector) with identical expert math (though actual latency still depends on overlap and fixed overheads).

Expert parallelism across two GPUs: GPU 0 holds experts E0 and E1, while GPU 1 holds E2 and E3. Two assignments stay local (t0 to E0 on GPU 0, t2 to E2 on GPU 1) with 0 KiB network traffic. Three remote assignments (t1 and t4 from GPU 0 to GPU 1, and t3 from GPU 1 to GPU 0) cross the interconnect, each transferring 8 KiB on dispatch and 8 KiB on combine for 48 KiB total.
G0 owns E0–E1 and G1 owns E2–E3. Three remote routes move 8 KiB out and 8 KiB back (48 KiB total) while expert weights stay resident.

Inside each GPU, batched expert execution sorts assignments by expert ID for dense grouped GEMMs, applies each gate weight once, and scatter-adds weighted outputs back to each token's row so no route overwrites another:

dispatch-and-weighted-combine.py
inputs = torch.tensor([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])
token_ids = torch.tensor([0, 1, 2, 0, 2])
expert_ids = torch.tensor([2, 0, 2, 1, 0])
gate_weights = torch.tensor([0.25, 1.0, 0.6, 0.75, 0.4])
scales = torch.tensor([2.0, -1.0, 0.5])  # Simple per-expert transforms

# Sort by expert for contiguous grouped GEMM, then weighted scatter-add by token ID
order = torch.argsort(expert_ids, stable=True)
p_tok, p_exp, p_w = token_ids[order], expert_ids[order], gate_weights[order]
p_out = inputs[p_tok] * scales[p_exp].unsqueeze(1)

combined = torch.zeros_like(inputs).index_add(0, p_tok, p_out * p_w.unsqueeze(1))
print("packed token order:", p_tok.tolist())
print("restored weighted rows:", [[round(v, 3) for v in row] for row in combined.tolist()])
Output
packed token order: [1, 2, 0, 0, 2]
restored weighted rows: [[-0.625, -1.25], [6.0, 8.0], [5.5, 6.6]]

On consumer GPUs where the full expert pool exceeds VRAM, combining weight quantization with CPU/SSD expert offloading keeps shared layers on GPU and streams selected experts on demand.

When MoE is worth the complexity

Large and high-concurrency decode batches amortize routing and all-to-all dispatch across many tokens per expert; single-request decode (batch = 1) exposes fixed launch and interconnect overhead every step. Evaluate MoE against a matched dense baseline across quality, , and throughput together:

Decision signalDense is usually simplerMoE shines
Traffic shapeLow batch size, strict interactive p95 latencyHigh batch concurrency or offline throughput
Memory budgetTight fixed VRAM ceilingEnough memory/sharding for the full expert pool
InterconnectSlow cross-node linksHigh-bandwidth NVLink / InfiniBand
Serving stackStandard dense kernelsGrouped GEMMs, EP dispatch, load telemetry
Consistent color-coded comparison of Dense (blue) vs MoE (green) across three serving criteria. Quality: Dense 0.82 and MoE 0.83 both pass the 0.82 floor. Throughput: MoE reaches 1,100 tokens/s (+34.1%), passing the 1,000 tokens/s floor while Dense fails at 820. Tail latency p95: Dense is 48 ms and MoE is 55 ms (+7 ms), so MoE passes a 60 ms cap but fails a stricter 50 ms cap.
MoE lifts throughput 34.1% (1,100 vs. 820 tok/s) at +7 ms p95 latency: it wins under a 60 ms latency budget but misses if the cap tightens to 50 ms.

Diagnosing common MoE surprises

  • 7B-active model OOMs on a 16 GB GPU: Always size VRAM from total parameters (plus KV cache and workspace), never active parameters.
  • Uniform long-run histogram, degraded accuracy: Check per-step bursty overflow, dropped top-2 branches, and z-loss logit blowup separately.
  • "Math expert" myths: Mixtral's routing analysis found experts specializing strongly in syntax and formatting (like indentation and Python self) rather than neat high-level domains like "math" vs. "history."[2]
Check your understanding

Mastery Check

Check each question as you go, or answer all of them and check together. Score 75% or higher to complete this lesson.

0 of 10 answered
1.A toy top-2 router selects probabilities 0.39 and 0.21. The selected experts return [3, 0] and [0, 5], respectively. After selected-weight normalization, what are the two weights and the blended output?
2.A top-1 gate keeps probability 0.8 for an expert returning scalar 5. An engineer normalizes the selected gate to 1 while holding the selected expert and its output fixed. What changes?
3.Four tokens a, b, c and d enter two expert-choice buckets. Expert 0 selects [a, b] and expert 1 selects [a, c]. Which diagnosis follows from the assignments?
4.An expert chooses its two highest-scoring tokens. A prefix contains a=0.8 and b=0.6. The extended sequence adds future tokens c=0.9 and d=0.7, with both earlier scores and attention inputs fixed. Which selected sets and diagnosis follow?
5.A batch has 120 tokens, top-3 routing and 12 experts. Each expert has a fixed buffer with a capacity factor of 1.25 and no extra padding. One expert receives 41 assignments. How many slots does its buffer have, and how many assignments overflow?
6.An MoE model has 2B shared parameters and ten 1B expert partitions. Each token uses two partitions. All raw weights use two bytes, with decimal GB. What is the complete raw weight residency before cache and workspace?
7.A token selects two experts on one remote device. Its input and each returned hidden vector use 4 KiB. Under the stated per-destination protocol, the remote device receives one input and returns one already weighted combined output. What follows?
8.A token vector [2, 4] visits expert A, which doubles it, with gate 0.25, and expert B, which negates it, with gate 0.75. Which weighted scatter-add result is correct?
9.Two logits equal log(0.6) and log(0.4). Add 2 to both. For z-loss defined as the square of log-sum-exp, which pair of observations is correct?
10.A serving candidate measures quality 0.86, p95 latency 64 ms and throughput 1300 tokens/s. Requirements are quality at least 0.85, latency at most 60 ms and throughput at least 1200 tokens/s. Which decision follows?

10 questions remaining.

References

Outrageously Large Neural Networks: The Sparsely-Gated Mixture-of-Experts Layer.

Shazeer, N., et al. · 2017 · ICLR 2017

https://arxiv.org/abs/1701.06538

Mixtral of Experts.

Jiang, A. Q., et al. · 2024

https://arxiv.org/abs/2401.04088

DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Model

DeepSeek-AI · 2024

https://arxiv.org/abs/2405.04434

Switch Transformers: Scaling to Trillion Parameter Models with Simple and Efficient Sparsity.

Fedus, W., Zoph, B., & Shazeer, N. · 2022

https://arxiv.org/abs/2101.03961

Mixture-of-Experts with Expert Choice Routing

Zhou, Y., et al. · 2022

https://arxiv.org/abs/2202.09368

ST-MoE: Designing Stable and Transferable Sparse Expert Models

Zoph, B., et al. · 2022

https://arxiv.org/abs/2202.08906

Mixture of Experts

NVIDIA · 2026

https://docs.nvidia.com/megatron-core/developer-guide/latest/user-guide/features/moe.html

GLU Variants Improve Transformer

Shazeer, N. · 2020

https://arxiv.org/abs/2002.05202

DeepSeek-V3 Technical Report.

DeepSeek-AI · 2024 · arXiv preprint

https://arxiv.org/abs/2412.19437

DeepSeek-V4: Towards Highly Efficient Million-Token Context Intelligence

DeepSeek-AI · 2026

https://arxiv.org/abs/2606.19348

DeepSeek-V4-Flash-0731 Model Card

DeepSeek-AI · 2026

https://huggingface.co/deepseek-ai/DeepSeek-V4-Flash-0731

GLM-5 Repository

Z.AI · 2026

https://github.com/zai-org/GLM-5

GLM-5.3 Model Card (187fb9f)

Z.AI · 2026

https://huggingface.co/zai-org/GLM-5.3/blob/187fb9fff6319062325ff825627ef6db084d9bc6/README.md

GLM-5.3 BF16 Configuration (304b805)

Z.AI · 2026

https://huggingface.co/zai-org/GLM-5.3-BF16/blob/304b8051cfb2b260b61ce0cbe330e02a98e73639/config.json

GLM-5.3-Flash Model Card and Architecture

Z.AI · 2026

https://huggingface.co/zai-org/GLM-5.3-Flash

Qwen3.6-35B-A3B

Qwen Team · 2026

https://huggingface.co/Qwen/Qwen3.6-35B-A3B

Expert Parallel Deployment

vLLM Contributors · 2026

https://docs.vllm.ai/en/latest/serving/expert_parallel_deployment/

Discussion

Questions and insights from fellow learners.

Discussion loads when you reach this section.