Mixture-of-Experts LLMs

Most frontier open LLMs are now sparse: hundreds of experts stored, a handful used per token. This guide covers the router, the MoE decoder block, the latent-attention KV cache that usually comes with it, and what all of this means for memory, bandwidth and GPU kernels at inference time.

Before you start

Prerequisites

What you'll learn

  • Total vs active parameters, and why an MoE decodes like a much smaller dense model.
  • How a top-k router works, and how load balancing keeps all experts busy.
  • How multi-head latent attention (MLA) shrinks the KV cache, compared with MHA, GQA and MQA.
  • The inference trade-offs: resident memory, expert parallelism, batch size, grouped GEMMs, offloading and FP8/FP4 experts.

Time

About 60–75 min to read and play with the widgets, plus 10 min to run and modify moe.py (CPU only, runs in seconds).

🎬 Learn it visually

Watch or read one of these first if a section feels abstract. Ordered: best intuition first, code last.

  1. 🎥 A Visual Guide to Mixture of Experts (MoE) in LLMs, Maarten Grootendorst (20 min). Best first watch: router, top-k, load balancing, capacity and parameter counting, all drawn.
  2. 📖 A Visual Guide to Mixture of Experts (MoE), Maarten Grootendorst. The written version with 50+ figures; good to keep open next to §2.
  3. 📖 Mixture of Experts Explained, Hugging Face blog. History (Shazeer → Switch → Mixtral), load balancing, capacity factor, fine-tuning and serving trade-offs.
  4. 🎥 Mistral / Mixtral Explained, Umar Jamil (1 h 26 min). Architecture and code walk-through of Mistral 7B / Mixtral 8x7B: the sparse MoE layer, sliding-window attention and the rolling-buffer KV cache.

Notation on this page

E, k
routed experts per MoE layer, experts chosen per token (top-k)
T
tokens: the flattened batch in the router code, the sequence length in the attention code (Module 1's N)
d, d_ff
model width and FFN width, as in Module 1 (d_expert or f = one expert's FFN width in code)
n_h, d_h
query heads and head dimension in DeepSeek's notation: n_h = h, d_h = d_k of Module 1
n_kv; d_c, d_R
K/V heads (GQA); MLA's cached latent width and RoPE-key width
B
batch size (sequences decoded together)

The Core Idea: Conditional Compute

Intuition first. An MoE layer is a team of specialists with a dispatcher. The dispatcher (the router) reads each token and sends it to the two or eight specialists best suited to it; everyone else on the team sits idle for that token. You pay to keep the whole team on staff (memory), but each token only pays for the few it talks to (compute and bandwidth).

In a dense transformer, every token goes through every weight. In a sparse Mixture-of-Experts (MoE) model, the feed-forward network (FFN) of each layer is replaced by E smaller FFNs, the experts, plus a tiny router that picks k of them for each token. The other E − k experts are skipped for that token.

# Dense FFN: every token uses all the weights
y = FFN(x)

# Sparse MoE FFN: the router picks k of E experts for THIS token
scores = router(x)                       # [E]   one score per expert
top    = topk(scores, k)                 # e.g. k = 8 of E = 256
y = Σ_shared FFN_s(x) + Σ_{i ∈ top} g_i · FFN_i(x)    # g_i = normalised score

That gives MoE two parameter counts, and they matter for different things:

Why this is a big deal for inference. Decode is bound by memory bandwidth: each new token has to stream its weights from HBM/DRAM. A dense model reads all of its weights per token. An MoE reads only its active weights. DeepSeek-V3 stores 671B parameters but activates 37B per token, so at batch 1 its weight traffic per token is about that of a 37B dense model. The catch: all 671B must still be resident somewhere.

Representative open MoE models (as of Oct 2026)

All numbers below come from the official paper, model card or config.json (links in References). "Active share" is active ÷ total; "weights out" is the month the open weights appeared.

ModelWeights outTotalActiveActive shareRouted experts (+ shared)Top-kAttention
Mixtral 8x7BDec 202347B13B28%82GQA (32 Q / 8 KV heads)
DeepSeek-V3Dec 2024671B37B5.5%256 + 18MLA (latent dc = 512)
Qwen3-235B-A22BApr 2025235B22B9.4%128 (no shared)8GQA (64 Q / 4 KV)
Qwen3-30B-A3BApr 202530.5B3.3B11%128 (no shared)8GQA (32 Q / 4 KV)
Kimi K2Jul 20251T32B3.2%384 + 18MLA
gpt-oss-120bAug 2025116.8B5.1B4.4%1284GQA (64 Q / 8 KV), alternating 128-token window and full layers
gpt-oss-20bAug 202520.9B3.6B17%324same as 120b
Qwen3.5-397B-A17BFeb 2026397B17B4.3%512 + 110Hybrid: 3 Gated DeltaNet layers per 1 gated-attention layer (32 Q / 2 KV)
DeepSeek-V4-FlashApr 2026284B13B4.6%256 + 16Hybrid compressed attention (CSA + HCA), 1M context
DeepSeek-V4-ProApr 20261.6T49B3.1%384 + 16same as V4-Flash

The trend is clear: more and smaller experts, and a smaller active share. Mixtral used 2 of 8 large experts, about 28% of its weights per token. The large 2025–2026 models use 4–10 of 128–512 small experts and activate 3–5% of their weights; smaller siblings such as Qwen3-30B-A3B and gpt-oss-20b sit at 11–17%. Other 2026 open families follow the same DeepSeek-V3 recipe: GLM-5 and Kimi K2.6 both ship 256 or 384 fine-grained experts with 1 shared expert, MLA, and a sigmoid router with a balancing bias, according to their config.json.

1. Dense FFN vs MoE FFN

Intuition. Same job, different staffing: a dense model has one generalist that every token must visit; an MoE has many narrower specialists and each token visits only k of them.

Only the FFN changes. Attention, norms, residuals and the LM head stay the same as in the transformer guide. Each expert is an ordinary SwiGLU FFN with its own weights, just narrower than a dense FFN would be.

One FFN for everyone vs k experts per token Dense token x FFN (all weights) y MoE token x router: top-2 1 E1 · 0.7E5 · 0.3 2 shared expert (always on) 3 y = Σ g·E(x)

What to notice: the router is just a d × E matrix and a top-k. All experts sit in memory, but each token runs only k of them (plus any shared expert), so FLOPs follow active parameters while memory follows total parameters.

  1. 1The router is a d × E matrix plus a top-k. Here E = 8 routed experts and top-k = 2, and the two winners get gates g = 0.7 and 0.3.
  2. 2The 6 idle experts are stored in memory but not run for this token: 8 + 1 experts stored, 2 + 1 run. A dense SwiGLU FFN (d → d_ff → d, 3·d·d_ff weights) is read in full by every token, so for it total = active.
  3. 3The shared expert has no routing and runs for every token. DeepSeek-V3, Kimi K2 and Qwen3.5 have one; Mixtral, Qwen3 and gpt-oss have none. Here y = shared(x) + 0.7·E1(x) + 0.3·E5(x).

Two practical facts follow from the shape of the network:

2. The Router

Intuition. The router is a scoring desk: one dot product per expert, keep the top k, turn their scores into weights that sum to 1.

The router is a linear layer W_r ∈ ℝ^{E×d} followed by a scoring function and a top-k. Three common variants:

Router: from hidden state to k gate weights x[d] u = W_r x[E] logits s = score(u)softmax or sigmoid top-k of s + bbias: choice only g = renormalised s[k] gates 12

What to notice: with softmax, renormalising over the chosen k gives exactly the same gates as a softmax over just those k logits, so the two orderings in different codebases are equivalent.

  1. 1The bias b only steers which experts are picked (auxiliary-loss-free balancing, §2.1). It never enters the gate values.
  2. 2Gates use the original scores s, renormalised over the k picked experts. DeepSeek-V3 then multiplies them by a routed scaling factor of 2.5.
RecipeUsed byNote
Softmax → top-k → renormaliseQwen3, Mixtral (HF code)Identical to "top-k on logits, then softmax over those k", which gpt-oss uses
Sigmoid → (+ bias) top-k → normaliseDeepSeek-V3, Kimi K2, GLM-5Each expert is scored independently, so adding experts does not shrink scores
√softplus → (+ bias) top-kDeepSeek-V4Changes the affinity function to Sqrt(Softplus(·)); the rest of the recipe is kept

Top-k gating, step by step

Intuition. Score every expert, keep the k best, and mix their outputs in proportion to their scores.

g = softmax(top-k(Wr x))y = Σi ∈ top-k gi · Ei(x)
Read it aloud
"g is the softmax of the top-k router logits; y is the sum over the chosen experts of g-i times expert-i of x." x is one token's hidden vector [d]; Wr is the router matrix [E × d], so Wrx is E logits; top-k keeps the k largest; g holds k gates that sum to 1; each Ei is a SwiGLU FFN mapping [d] → [d], so y is [d].
Why it exists
Running every expert would cost E times the FLOPs. Top-k gives each token a few specialists and leaves the rest idle, so compute follows k, not E. The gates matter for learning too: the expert choice itself is discrete, so the router learns only through the gate values that scale each expert's output.
Tiny example

E = 4, k = 2, logits u = (2.0, 1.0, 0.5, −1.0):

softmax over all 4 = (0.609, 0.224, 0.136, 0.030) → top-2 = E0, E1

renormalise: g = (0.609, 0.224) / 0.833 = (0.731, 0.269) = softmax(2.0, 1.0)

E0(x) = (1, 0), E1(x) = (0, 2) → y = 0.731·(1, 0) + 0.269·(0, 2) = (0.731, 0.538)

A sigmoid router (DeepSeek-V3) scores σ(u) = (0.881, 0.731, 0.622, 0.269): same top-2, gates (0.546, 0.454).

Code
scores = (x @ W_r.T).softmax(-1)              # [T, E]
w, idx = scores.topk(k, dim=-1)                # [T, k]
w = w / w.sum(-1, keepdim=True)                # gates

2.1 Load balancing: why it is needed

Intuition. Without rules, everyone queues at the most popular desk. Balancing adds a small push toward spreading tokens evenly.

Left alone, a router collapses: a few experts win early, get more gradient, get better, win more. That wastes capacity in training and, at inference, overloads the GPUs that host the popular experts. Three fixes are in use:

MethodHow it worksUsed by
Auxiliary lossAdd α · E · Σᵢ fᵢ · Pᵢ to the loss. fᵢ is the fraction of tokens routed to expert i, Pᵢ is its mean router probability. It is minimised by a uniform spread. Switch Transformer used α = 10⁻².Switch Transformer; Qwen3 (computed over the global batch rather than per micro-batch)
Auxiliary-loss-free biasKeep a per-expert bias bᵢ that is added to the scores only for the top-k choice. After each step: overloaded expert → bᵢ −= γ, underloaded → bᵢ += γ. No extra gradient interferes with the language-model loss.DeepSeek-V3 (γ = 0.001, plus a tiny sequence-wise loss with α = 0.0001); DeepSeek-V4; Kimi K2 and GLM-5 configs use the same noaux_tc router
Capacity limitEach expert accepts at most C = ⌈capacity_factor · tokens · k / E⌉ tokens per batch; overflow is dropped (the residual carries the token through). Bounds the worst case but loses information.Switch Transformer (training). DeepSeek-V3 drops no tokens in training or inference.

The load-balancing loss, step by step

Intuition. Penalise the router when the experts that receive the most tokens are also the ones it is most confident about.

Laux = α · E · Σi fi · Pi
Read it aloud
"L-aux equals alpha times E times the sum over experts of f-i times P-i." fi is the fraction of routed slots that went to expert i (a count, no gradient); Pi is expert i's mean router probability over the batch (has a gradient); E is the number of experts; α is a small weight (Switch Transformer: 0.01).
Why it exists
Routers collapse: a popular expert gets more gradient, gets better, wins more tokens. fi·Pi is large when load and confidence pile up on the same experts: Laux = α when both are uniform and grows toward E·α as everything moves to one expert. The gradient flows through P, nudging probability away from overloaded experts. The aux-loss-free alternative skips the loss and adjusts a per-expert bias instead.
Tiny example

E = 2 experts:

collapsed: f = (1, 0), P = (0.9, 0.1) → 2·(1·0.9 + 0·0.1) = 1.8 → L = 1.8α

balanced: f = P = (0.5, 0.5) → 2·(0.25 + 0.25) = 1.0 → L = α (the minimum)

Aux-loss-free bias instead, E = 4, loads (6, 2, 4, 4), mean 4, γ = 0.001:

b += γ·sign(mean − load) = (−0.001, +0.001, 0, 0)

Code
f = load.float() / (T * k)                          # [E], no grad
P = (scores / scores.sum(-1, keepdim=True)).mean(0)  # [E]
aux = alpha * E * (f * P).sum()

2.2 Interactive: route a batch of tokens

Router playground: 24 tokens, 16 experts

Click a token to see which experts it picks and with what gate weight. The histogram shows how many tokens each expert received. The router logits are synthetic: each token type (words, code, numbers, names, punctuation) prefers a few experts, and experts E0–E2 are "generalists" that every token likes a bit. That is how collapse starts.

Aux-loss-free rule: bi += γ · sign(mean load − loadi), γ = 0.05
picked by selected token load within capacity dropped (over capacity) shared expert

What to notice: with the bias at zero, the generalists E0 and E1 are overloaded and late tokens get dropped (red underline). Press "Bias update" a few times: the bias pushes the busy experts down the ranking and the histogram flattens, while each token's gate weights are still computed from the unbiased scores.

2.3 Shared + fine-grained experts (DeepSeekMoE)

Intuition. More, smaller specialists give vastly more possible teams for the same cost; one always-present generalist handles the common stuff.

DeepSeekMoE made two changes to the Mixtral-style "few big experts" design, and nearly every large open MoE since has adopted at least the first:

Same active compute, far more combinations Mixtral: 8 experts, top-2 28 possible pairs 176M params each DeepSeek-V3: 256 + 1 shared, top-8 shared 4.1 × 10¹⁴ possible sets 44M params each

What to notice: the fine-grained layout lights up more, smaller boxes. Mixtral picks 2 of 8 experts, C(8, 2) = 28 pairs, each expert 3 × 4096 × 14336 ≈ 176M parameters; DeepSeek-V3 picks 8 of 256, C(256, 8) ≈ 4.1 × 10¹⁴ sets, each expert 3 × 7168 × 2048 ≈ 44M parameters, and its always-on shared expert is the same size. For inference this means more, smaller GEMMs per layer, which is why grouped-GEMM kernels matter (Section 5.5). Qwen3 dropped the shared expert again, and Qwen3.5 brought one back, so the shared expert is a design choice rather than a rule.

3. The Full MoE Decoder Block

Intuition. Take the transformer from Module 1 and swap exactly one part: the FFN. Everything else stays.

Putting it together, an MoE LLM is the decoder-only transformer from Module 1 with two swaps: the FFN becomes an MoE FFN, and (in the DeepSeek lineage) attention becomes MLA. Some models keep their first layers dense (DeepSeek-V3 and GLM-5: 3, Kimi K2: 1); DeepSeek-V4 instead turns them into MoE layers that pick experts with a fixed hash of the token ID.

An MoE LLM: a normal decoder with an MoE FFN Token IDs Embedding dense layers 1 MoE decoder layer × 58 RMSNorm attention (MLA) 2 RMSNorm MoE FFN 3 LM head Logits 4

What to notice: nothing about attention changes when you add experts. MoE fixes the FFN half of the cost; the attention half (KV cache and context-length scaling) needs its own fix, which is where MLA comes in.

  1. 1Some models keep their first layers dense: DeepSeek-V3 has 3 dense layers with d_ff = 18,432 (GLM-5: 3, Kimi K2: 1). The embedding is 129,280 × 7168 in DeepSeek-V3.
  2. 2Attention is dense per token: every head, every layer, and it reads and writes the KV cache. Its cost grows with context, not with the number of experts. MLA in DeepSeek-V3 is 187M parameters per layer (§4). Each sub-block is pre-norm with a residual add (the ⊕ nodes).
  3. 3The MoE FFN: router → top-8 of 256 routed experts + 1 shared, each a SwiGLU 7168 → 2048 → 7168 (44M parameters). Routed experts hold 97.4% of all weights, but only 8 of 256 run per token.
  4. 4Where the bytes go at decode: at B = 1 about 36.6 GB of FP8 weights per token; at B = 128 almost every expert is touched, but the cost is shared by 128 tokens. The MTP head (training and speculative decoding) adds 14B parameters not counted in the 671B.

4. Multi-head Latent Attention: shrinking the KV cache

Intuition. Instead of storing every head's keys and values, store one compressed note per token and unzip it into per-head keys and values when needed.

MoE reduces the bytes of weights read per token. At long context or large batch, the other big byte stream is the KV cache: every decode step reads all cached keys and values of its sequence. The transformer guide covers the plain KV cache. Here are the four ways to size it, from biggest to smallest per token per layer (DeepSeek's notation: n_h = h query heads, d_h = d_k of Module 1):

AttentionCached per token per layerIdeaUsed by
MHA2 · n_h · d_hevery query head has its own K and V headoriginal transformer
GQA2 · n_kv · d_hgroups of query heads share one K/V headMixtral (8 KV), Qwen3 (4 KV), gpt-oss (8 KV)
MQA2 · d_hall heads share a single K/V headShazeer (2019); fastest, but can cost quality (GQA paper)
MLAd_c + d_Rcache one low-rank latent c_KV plus one small RoPE key; rebuild per-head K, V from the latentDeepSeek-V2/V3/V3.2, Kimi K2, GLM-5
MLA: cache a small latent, rebuild K and V per head h_t down-project KV cache c_KV [512] k_R [64] 12 up-project 3 K, V × 128 heads attention query path

What to notice: the cache holds only the red box. RoPE cannot be applied inside the compressed path (it would block folding W_UK into the query), so DeepSeek adds a small separate RoPE key k_R that is shared by all heads.

  1. 1Per token per layer the cache holds 512 + 64 = 576 values (DeepSeek-V3), instead of 2 × 128 heads × 128 dims = 32,768 for MHA. ht is 7168-wide; WDKV maps 7168 → 512 + 64.
  2. 2kR is a small RoPE key shared by all heads (the "decoupled RoPE"). It joins the scores directly: score = qC·kC + qR·kR, and out = softmax(score / √192)·v, then WO maps back to [7168].
  3. 3WUK and WUV rebuild per-head keys kC (128 heads × 128) and values v (128 × 128). At decode, qC·(WUKcKV) = (WUKᵀqC)·cKV, so WUK folds into the query and WUV into WO (the "absorbed" form): attention runs straight on the cache, 128 query heads sharing one 576-dim key, an MQA over the latent. The query path is compressed too: WDQ to cQ [1536], then WUQ to qC (128 × 128) and qR (128 × 64, RoPE).

The DeepSeek-V2 paper sizes this as (d_c + d_R) ≈ 4.5 · d_h per token per layer, "equal to GQA with only 2.25 groups", while reporting quality better than MHA. Computed for DeepSeek-V3's shape (61 layers, 128 heads, d_h = 128, BF16):

Attention at DeepSeek-V3 shapeKV per token (all layers)4K context32K context128K contextvs MHA
MHA (128 KV heads)3,904 KiB15.25 GiB122.0 GiB488.0 GiB1×
GQA (8 KV heads)244 KiB0.95 GiB7.62 GiB30.5 GiB16× smaller
MQA (1 KV head)30.5 KiB0.12 GiB0.95 GiB3.81 GiB128× smaller
MLA (d_c = 512, d_R = 64)68.6 KiB0.27 GiB2.14 GiB8.58 GiB56.9× smaller
Interactive: KV cache for one batch at the DeepSeek-V3 shape

What to notice: the dashed line is the 80 GB of one H100. With MHA, a single 32K-token sequence would not fit; with MLA, dozens do. MQA is smaller still, but MLA keeps per-head expressiveness that MQA gives up.

4.1 The catch: MLA trades bytes for FLOPs

In absorbed form, every one of the 128 query heads does a 576-dim dot product with every cached latent, then a 512-dim weighted sum. Counted with moe.py at 32K context, that is about 557 GFLOP per decoded token for DeepSeek-V3's attention, far more than the 73 GFLOP of all its active matmuls. Per byte of BF16 cache read, MLA does about 242 FLOPs; Qwen3-235B's GQA does 16, gpt-oss's 8 and Mixtral's 4. An H100 SXM (about 990 dense BF16 TFLOPS, 3.35 TB/s) breaks even at about 295 FLOP/byte, so MLA decode attention is close to compute-bound while GQA decode attention is firmly bandwidth-bound.

Where this went next (as of Oct 2026). DeepSeek-V3.2 keeps MLA but adds DeepSeek Sparse Attention: a cheap "lightning indexer" picks 2,048 cached tokens per query, and DSA runs on the MQA mode of MLA, so attention cost stops growing with context. DeepSeek-V4 (Apr 2026) goes further and compresses along the sequence axis: its CSA and HCA layers merge every m tokens into one shared key/value entry, reporting 10% of V3.2's KV cache at 1M tokens. Qwen3.5 instead makes 3 of every 4 layers Gated DeltaNet, a linear-attention recurrence with a fixed-size state, the same idea as Mamba. Three different routes to the same goal: fewer bytes per cached token.

5. Inference: why MoE decodes cheaply, and why it is still hard

Intuition. You pay rent for the whole team (all experts must sit in memory), but each token only pays wages to the k experts it uses (bytes read per token).

The general techniques used below (roofline estimates, batching, quantization, offloading, speculative decoding) are collected in the Memory & inference efficiency cookbook; this section applies them to MoE.

5.1 Decode reads active weights, but stores all of them

At batch 1, decoding one token is a chain of matrix-vector products: every weight is read once and used for 2 FLOPs. Arithmetic intensity is about 1 FLOP per byte at BF16, hundreds of times below the GPU's break-even point, so time per token ≈ bytes read ÷ memory bandwidth. For an MoE, bytes read ≈ active parameters × bytes per parameter. That gives an upper bound on tokens per second, independent of FLOPs:

tokens/s (batch 1)  ≤  memory bandwidth / (active params × bytes per param)
resident memory     ≥  total params × bytes per param   (+ KV cache + activations)
Model, weight formatResident weightsRead per token (B = 1)Jetson AGX Orin 64GB
204.8 GB/s
Jetson AGX Thor T5000
273 GB/s
H100 SXM 80GB
3.35 TB/s
Qwen3-30B-A3B, 4-bit14.2 GiB1.52 GB≤ 135 tok/s≤ 179 tok/s≤ 2,203 tok/s
a dense 30B, 4-bit (same total)14.2 GiB15.1 GB≤ 13.6 tok/s≤ 18.1 tok/s≤ 222 tok/s
gpt-oss-20b, MXFP4 experts + BF1612.8 GiB3.71 GB≤ 55 tok/s≤ 74 tok/s≤ 904 tok/s
gpt-oss-120b, MXFP4 experts + BF1660.7 GiB5.00 GBtoo tight in 64 GB≤ 55 tok/s≤ 670 tok/s
DeepSeek-V3, FP8625 GiB36.6 GBdoes not fitdoes not fitneeds a multi-GPU node

4-bit here means 0.5 B per parameter, group scales ignored. With g = 128 scales (4.25 bits, the INT4 format of the efficiency cookbook), Qwen3-30B-A3B needs 15.1 GiB resident and reads 1.62 GB per token: ≤ 127 tok/s on AGX Orin, ≤ 169 on Thor.

These are roofline ceilings from moe.py (weights only; KV reads, activations and kernel efficiency make real numbers lower). The point is the ratio: at the same total size, the MoE has a 10× higher ceiling than the dense model, because it reads 10× fewer bytes per token. The resident-memory column is the price. The gpt-oss resident sizes match the model card's checkpoints (60.7 vs 60.8 GiB, and 12.8 GiB).

5.2 Batch size vs expert utilisation

The "read only active weights" argument holds for one token. A batch of B tokens in the same decode step each pick their own k experts. Under uniform routing, the expected number of distinct experts hit in a layer is

distinct(B) = E · (1 − (1 − k/E)^B)        # each expert is missed by one token with prob. 1 − k/E
# DeepSeek-V3 (E=256, k=8):  B=1 → 8,  B=8 → 57.4,  B=32 → 163.3,  B=128 → 251.6,  B=512 → 256.0

So by batch ~100 nearly every expert is read every step, and the step reads almost all 671B parameters. That is fine: the cost is now shared by B tokens. What matters for efficiency is tokens per expert = B·k/E. Each expert's weights are reused only that many times per read, so an MoE needs E/k times the batch of a dense model to reach the same arithmetic intensity. To get ~295 tokens per expert (the H100 break-even for BF16 and for FP8 alike), DeepSeek-V3 needs a global batch of about 295 × 256 / 8 ≈ 9,440 tokens per step. That is why large deployments spread experts over many GPUs and pool many users' requests (Section 5.3).

Interactive: how many experts does one decode step touch?
distinct experts hit per layer (left) bytes read per token, log scale (right) current batch

What to notice: the left curve saturates at E while the right curve keeps falling: bigger batches amortise the expert reads. At large B with long context, the KV-cache share of the bytes grows until attention, not experts, dominates. Weights use the format shown in the stats (FP8 for DeepSeek and Kimi, MXFP4 experts for gpt-oss, BF16 otherwise); the uniform-routing assumption overestimates distinct experts slightly, because real routing is skewed.

5.3 Expert parallelism and the all-to-all

Intuition. Each GPU hosts a subset of the specialists, so tokens have to travel to whichever GPU holds their expert, and the answers travel back.

A 671B model does not fit on one GPU, and slicing every small expert across GPUs (tensor parallelism) makes each GEMM tinier still. The standard answer is expert parallelism (EP): whole experts live on different GPUs, attention runs data-parallel, and two all-to-all exchanges per MoE layer move tokens to their experts and back.

Expert parallelism: tokens travel to their experts and back dispatch: all-to-all combine: all-to-all GPU 0E0–63GPU 1E64–127GPU 2E128–191GPU 3E192–255 1234

What to notice: every token crosses the interconnect twice per MoE layer. Limiting how many devices a token may use bounds that traffic, and overlapping the all-to-all with compute hides it.

  1. 1Attention runs data-parallel: each GPU serves its own requests and computes the router for its own tokens (blue squares).
  2. 2Dispatch: each token is sent to the GPUs that own its k experts, one all-to-all exchange.
  3. 3Each GPU runs its 64 experts (EP = 4, 256 experts) as a grouped GEMM over the tokens it received from everyone (light squares).
  4. 4Combine: results go back to each token's home GPU (a second all-to-all), which forms y = Σ gi·Ei(x), adds the shared expert and moves on to the next layer (bottom row).

What production systems do about it:

5.4 Capacity factor and token dropping at inference

A capacity limit makes every expert's buffer a fixed size, which is convenient for static shapes. The cost is subtle: whether your token is dropped depends on which other tokens share the batch. moe.py shows it directly: with capacity factor 1.0, 12 of 60 tokens get a different output inside the batch than when run alone; dropless dispatch changes none. DeepSeek-V3 drops no tokens in training or inference, and dropless kernels (MegaBlocks) exist precisely so that nobody has to choose between dropping tokens and padding every expert to the worst case.

5.5 Grouped GEMM: from E tiny matmuls to one kernel

Intuition. Line the tokens up by expert so each expert works through one contiguous queue, then process all queues in one go.

The naive implementation loops over experts and launches E small GEMMs per layer, most of them nearly empty at decode. The fix is to permute tokens so that each expert's tokens are contiguous, then run one grouped GEMM that walks the segments:

Sort by expert, one grouped GEMM, unsort 1. route2. sort by expert3. grouped GEMM4. unsort + sum t0: E1, E3t1: E0, E2t2: E1, E2t3: E3, E1E0 ← t1E1 ← t0, t2, t3E2 ← t1, t2E3 ← t0, t3× W_e per segmenty₀ … y₃

Worked example (4 tokens, top-2 of 4 experts): the gates are t0: E1·0.6, E3·0.4; t1: E0·0.7, E2·0.3; t2: E1·0.5, E2·0.5; t3: E3·0.8, E1·0.2. Step 2 is argsort(expert_id) plus a gather of rows; segment offsets tell the kernel where each expert starts (1, 3, 2 and 2 rows). Step 4 scatters the rows back and sums: y0 = 0.6·E1 + 0.4·E3, y1 = 0.7·E0 + 0.3·E2, y2 = 0.5·E1 + 0.5·E2, y3 = 0.8·E3 + 0.2·E1.

What to notice: the permutation is cheap (an argsort and a gather); the win is that the expert math becomes one launch over contiguous memory. Prefill uses a contiguous layout; decode under CUDA graphs uses a masked layout with a fixed maximum per expert, because the CPU does not know the per-expert counts in advance (DeepGEMM documents both). moe.py's dispatch_sorted is the padded/masked flavour written with torch.bmm.

5.6 Quantizing the experts

Since routed experts are 91–99% of the weights in the models above, expert precision sets both the resident memory and the decode bytes. The common pattern is to quantize experts hardest and keep the small, sensitive parts in higher precision:

5.7 Edge: offloading and unified memory

On a single edge device the problem flips: batch is 1, so bandwidth per token is great (only k experts per layer), but total parameters must fit. When they do not, expert offloading keeps hot experts in fast memory and fetches the rest on demand. Eliseev & Mazur ran Mixtral-8x7B on consumer GPUs and free Colab this way, at about 2–3 tokens/s, using an LRU cache of experts per layer, speculative prefetch (apply the next layer's router to the current hidden state to guess its experts), and 2–3-bit expert quantization.

Jetson is different. On Jetson (Tegra) the CPU and the integrated GPU share the same SoC DRAM: "device memory, host memory, and unified memory are allocated on the same physical SoC DRAM" (CUDA for Tegra app note). "Offloading experts to CPU RAM" frees nothing there, and the next tier down is NVMe storage. On Orin and Thor the practical recipe is to choose an MoE whose quantized total fits in DRAM (Qwen3-30B-A3B at 4-bit is about 14 GiB, gpt-oss-120b is 60.7 GiB, which fits on a 128 GB Thor) and enjoy the small active set.

5.8 Multi-token prediction and speculative decoding (briefly)

DeepSeek-V3 trains one extra multi-token-prediction (MTP) module that predicts the token after next; at inference it can serve as a draft for speculative decoding. The paper reports an 85–90% acceptance rate for that second token and 1.8× tokens per second. DeepSeek-V4 keeps the same MTP setup, and Qwen3.5 also ships an MTP layer. One MoE-specific caveat follows from the formula in 5.2: verifying 2 tokens in one step is a batch of 2, so DeepSeek-V3 reads about 15.75 experts per layer instead of 8. Speculation saves fewer bytes on an MoE at batch 1 than on a dense model, where the second token's weights are free.

6. Code Walkthrough

The core pieces of moe.py. Run python moe.py to execute every test below on CPU in a few seconds.

7. MoE Memory and Bandwidth Calculator

Pick a preset (values from each model's config.json) or edit any field. The formulas are those of moe.py; the presets reproduce its printout. Capacities are in GiB, traffic in GB (10⁹ bytes), because bandwidth is quoted in GB/s.

Small terms (attention biases, QK-norm, attention sinks, expert and router biases) come from the selected preset. Distinct experts assume uniform routing. Tokens/s is a memory-bandwidth ceiling for one decode step, ignoring compute, communication and kernel efficiency.

8. Dense vs MoE vs Mamba

AspectDense transformerSparse MoE transformerMamba / hybrid
Weights touched per tokenallattention + k of E experts (3–28% in the table above)all
Memory to hold weightstotaltotal, roughly 4–33× the active settotal
Decode bytes per token, batch 1all weights + KVactive weights + KVall weights + fixed-size state
Long-context memoryKV grows with contextsame; MLA/GQA/compression shrink itconstant state per sequence
Weight reuse per step at batch BBB·k/E per expertB
Multi-GPU patterntensor / pipeline parallelexpert parallel + two all-to-alls per layertensor / pipeline parallel
Kernel shapelarge GEMMsmany small grouped GEMMs + permutesscan + GEMMs
Edge sweet spotsmall modelsbatch 1, if the quantized total fitslong sequences on small memory

9. Connection to the Rest of the Roadmap

Key Takeaways

Self-Check

1. At batch 1, why can DeepSeek-V3 (671B total) decode faster than a 70B dense model on the same hardware, assuming both fit?

Answer

Batch-1 decode is memory-bandwidth-bound, so time per token ≈ bytes of weights read ÷ bandwidth. DeepSeek-V3 reads only its ~37B active parameters per token; the dense model reads all 70B. Same precision means roughly half the bytes, so roughly twice the token rate ceiling. Total parameters only set how much memory you need.

2. DeepSeek-V3 has 61 layers, d_c = 512 and d_R = 64. How big is its MLA KV cache per token at BF16, and for one 128K-token sequence?

Answer

61 × (512 + 64) × 2 B = 70,272 B ≈ 68.6 KiB per token. × 131,072 tokens ≈ 8.58 GiB. With full MHA (128 heads × 128 dims for K and V) it would be 3,904 KiB per token and 488 GiB, 56.9× more.

3. Qwen3-235B-A22B uses GQA with 4 KV heads of dim 128 in 94 layers. What is its BF16 KV cache for one 32K-token sequence?

Answer

Per token: 94 × 2 × 4 × 128 × 2 B = 192,512 B (188 KiB). × 32,768 = 6,308,233,216 B ≈ 5.88 GiB, about 2.7× DeepSeek-V3's MLA cache at the same length (2.14 GiB), despite having only 4 KV heads.

4. With uniform routing, how many of DeepSeek-V3's 256 experts per layer does a decode batch of 32 tokens touch?

Answer

256 × (1 − (1 − 8/256)32) ≈ 163.3. A batch of 32 already reads about 64% of the expert weights each step, which is why batching erodes the "read only active weights" advantage per step while still lowering bytes per token.

5. In auxiliary-loss-free balancing, the bias is added to the scores only for the top-k choice, not to the gate weights. Why?

Answer

The bias is a control signal for load, not a statement about how useful an expert is for this token. If it entered the gate values, it would change the model's output in a way the language-model loss never asked for and would leak load-balancing pressure into the function being learned, which is exactly the interference an auxiliary loss causes. Keeping it in the selection only changes which experts get the token.

6. A training batch has 4,096 tokens, 64 experts, top-8 and capacity factor 1.25. What is the per-expert capacity, and what happens if one expert receives 700 assignments?

Answer

C = ⌈1.25 × 4096 × 8 / 64⌉ = 640 slots. The 60 assignments over capacity are dropped: those tokens get no contribution from that expert and pass through on the residual path. Under dropless routing the expert would instead process all 700.

7. Roughly what global decode batch does DeepSeek-V3 need before its experts become compute-bound on an H100, and why is it so much larger than for a dense model?

Answer

An H100 SXM breaks even at about 990 TFLOPS ÷ 3.35 TB/s ≈ 295 FLOP/byte, i.e. about 295 tokens per weight read at BF16 (or FP8 weights with FP8 math). Each expert sees only B·k/E of the batch, so B ≈ 295 × 256 / 8 ≈ 9,440 tokens. A dense model reaches that intensity at B ≈ 295. Hence large expert-parallel deployments that pool many users per step.

8. Qwen3-30B-A3B is quantized to 4 bits and run on a Jetson AGX Orin 64GB (204.8 GB/s). What is the batch-1 token-rate ceiling, and how does it compare with a dense 30B at 4 bits?

Answer

Active weights excluding the embedding lookup are ≈ 3.04B → 1.52 GB per token at 0.5 B/param → ≤ 135 tok/s (≤ 127 with g = 128 scales, 4.25 bits). A dense 30B reads ≈ 15.1 GB per token → ≤ 13.6 tok/s. Both need ≈ 14.2 GiB resident, which fits in 64 GB of shared DRAM.

9. Why is MLA's decode attention much closer to compute-bound than GQA's?

Answer

In absorbed form all 128 query heads attend to the same 576-value latent per cached token, so each byte of cache read feeds many heads: ≈ 242 FLOPs per BF16 byte for DeepSeek-V3. In Qwen3-235B's GQA each KV head serves only 16 query heads (≈ 16 FLOP/byte). MLA reads fewer bytes but does more math per byte.

10. Speculative decoding verifies 2 tokens per step. Why does that save less on DeepSeek-V3 at batch 1 than on a dense model?

Answer

A dense model reads the same weights whether it verifies 1 or 2 tokens, so the second token is nearly free. In an MoE the two tokens usually pick different experts: expected distinct experts per layer go from 8 to 256 × (1 − (31/32)²) ≈ 15.75, almost doubling the expert bytes for that step.

Hands-on Exercises

Build it yourself. Start with the guided lab labs/lab08.html: implement the softmax and sigmoid top-k routers, the load-balancing loss, per-expert-loop and sort-and-scatter dispatch, and capacity-limited dispatch with token dropping. Check each step with python labs/check.py 8, then do the exercises below.

All exercises use moe.py. Import it with from moe import * from the moe/ directory.

1. A Mixtral-shaped toy easy

Build MoEConfig(n_routed_experts=8, top_k=2, n_shared_experts=0, scoring="softmax", balance="aux_loss") and a TinyMoEDecoder from it. Print total and active parameters. Verify: assert count_parameters(model) == analyze(spec_from_config(cfg))["total"], and run test_dispatch_equivalence-style loop vs sorted outputs for this config.

2. The aux loss floor easy

Create a TopKRouter with balance="aux_loss", zero its weight, put it in training mode and route 100 random tokens. Verify: abs(aux.item() - cfg.aux_loss_coef) < 1e-6. Then explain why the result does not depend on which experts the ties sent tokens to (hint: look at Pi).

3. Capacity factor sweep medium

For capacity factors 0.75, 1.0, 1.25, 1.5 and 2.0, route 512 random tokens through an MoEFFN and record moe.last_dropped / (512 * k). Verify: the dropped fraction is non-increasing in the capacity factor, and with capacity_factor=None, moe.last_dropped == 0.

4. Group-limited routing medium

Add DeepSeek-V3-style group-limited routing to TopKRouter: split E experts into G groups, score each group by the sum of its top-2 scores, keep the best M groups, then take top-k inside them (the HF config calls these n_group and topk_group). Verify: assert all(len(set((row // (E // G)).tolist())) <= M for row in idx), and that with M = G the routing equals the original.

5. INT8 experts hard

Quantize w_gate, w_up and w_down to symmetric INT8 with one scale per output channel per expert, dequantize, and rerun the MoE FFN. Verify: relative error (y_q - y).norm() / y.norm() < 2e-2, and report how many bytes the routed experts take before and after. Then quantize the router weight the same way and count how many tokens change their top-k set.

6. Simulate expert offloading hard

Decode 200 tokens with the tiny model and record each MoE layer's chosen experts per step. Simulate a per-layer LRU cache holding C experts and count misses for C = 1, 2, 4, 8, 16. Verify: with C = E the only misses are first uses (misses == number of distinct experts ever used), and the miss rate is non-increasing in C. Bonus: add "speculative prefetch" by running layer l+1's router on layer l's output and measure the hit rate of that guess.

References

Papers

Model cards and configs

Kernels, serving and hardware