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.
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).
Watch or read one of these first if a section feels abstract. Ordered: best intuition first, code last.
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:
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.
| Model | Weights out | Total | Active | Active share | Routed experts (+ shared) | Top-k | Attention |
|---|---|---|---|---|---|---|---|
| Mixtral 8x7B | Dec 2023 | 47B | 13B | 28% | 8 | 2 | GQA (32 Q / 8 KV heads) |
| DeepSeek-V3 | Dec 2024 | 671B | 37B | 5.5% | 256 + 1 | 8 | MLA (latent dc = 512) |
| Qwen3-235B-A22B | Apr 2025 | 235B | 22B | 9.4% | 128 (no shared) | 8 | GQA (64 Q / 4 KV) |
| Qwen3-30B-A3B | Apr 2025 | 30.5B | 3.3B | 11% | 128 (no shared) | 8 | GQA (32 Q / 4 KV) |
| Kimi K2 | Jul 2025 | 1T | 32B | 3.2% | 384 + 1 | 8 | MLA |
| gpt-oss-120b | Aug 2025 | 116.8B | 5.1B | 4.4% | 128 | 4 | GQA (64 Q / 8 KV), alternating 128-token window and full layers |
| gpt-oss-20b | Aug 2025 | 20.9B | 3.6B | 17% | 32 | 4 | same as 120b |
| Qwen3.5-397B-A17B | Feb 2026 | 397B | 17B | 4.3% | 512 + 1 | 10 | Hybrid: 3 Gated DeltaNet layers per 1 gated-attention layer (32 Q / 2 KV) |
| DeepSeek-V4-Flash | Apr 2026 | 284B | 13B | 4.6% | 256 + 1 | 6 | Hybrid compressed attention (CSA + HCA), 1M context |
| DeepSeek-V4-Pro | Apr 2026 | 1.6T | 49B | 3.1% | 384 + 1 | 6 | same 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.
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.
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.
Two practical facts follow from the shape of the network:
config.json with moe.py, routed experts hold 97.4% of DeepSeek-V3's parameters, 96.6% of Qwen3-235B-A22B's and 98.2% of gpt-oss-120b's. Whatever you do to the experts (quantize, offload, shard) is what moves the memory needle.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:
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.
| Recipe | Used by | Note |
|---|---|---|
| Softmax → top-k → renormalise | Qwen3, Mixtral (HF code) | Identical to "top-k on logits, then softmax over those k", which gpt-oss uses |
| Sigmoid → (+ bias) top-k → normalise | DeepSeek-V3, Kimi K2, GLM-5 | Each expert is scored independently, so adding experts does not shrink scores |
| √softplus → (+ bias) top-k | DeepSeek-V4 | Changes the affinity function to Sqrt(Softplus(·)); the rest of the recipe is kept |
Intuition. Score every expert, keep the k best, and mix their outputs in proportion to their scores.
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).
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
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:
| Method | How it works | Used by |
|---|---|---|
| Auxiliary loss | Add α · 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 bias | Keep 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 limit | Each 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. |
Intuition. Penalise the router when the experts that receive the most tokens are also the ones it is most confident about.
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)
f = load.float() / (T * k) # [E], no grad P = (scores / scores.sum(-1, keepdim=True)).mean(0) # [E] aux = alpha * E * (f * P).sum()
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.
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.
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:
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.
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.
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.
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):
| Attention | Cached per token per layer | Idea | Used by |
|---|---|---|---|
| MHA | 2 · n_h · d_h | every query head has its own K and V head | original transformer |
| GQA | 2 · n_kv · d_h | groups of query heads share one K/V head | Mixtral (8 KV), Qwen3 (4 KV), gpt-oss (8 KV) |
| MQA | 2 · d_h | all heads share a single K/V head | Shazeer (2019); fastest, but can cost quality (GQA paper) |
| MLA | d_c + d_R | cache one low-rank latent c_KV plus one small RoPE key; rebuild per-head K, V from the latent | DeepSeek-V2/V3/V3.2, Kimi K2, GLM-5 |
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.
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 shape | KV per token (all layers) | 4K context | 32K context | 128K context | vs MHA |
|---|---|---|---|---|---|
| MHA (128 KV heads) | 3,904 KiB | 15.25 GiB | 122.0 GiB | 488.0 GiB | 1× |
| GQA (8 KV heads) | 244 KiB | 0.95 GiB | 7.62 GiB | 30.5 GiB | 16× smaller |
| MQA (1 KV head) | 30.5 KiB | 0.12 GiB | 0.95 GiB | 3.81 GiB | 128× smaller |
| MLA (d_c = 512, d_R = 64) | 68.6 KiB | 0.27 GiB | 2.14 GiB | 8.58 GiB | 56.9× smaller |
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.
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.
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.
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 format | Resident weights | Read 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-bit | 14.2 GiB | 1.52 GB | ≤ 135 tok/s | ≤ 179 tok/s | ≤ 2,203 tok/s |
| a dense 30B, 4-bit (same total) | 14.2 GiB | 15.1 GB | ≤ 13.6 tok/s | ≤ 18.1 tok/s | ≤ 222 tok/s |
| gpt-oss-20b, MXFP4 experts + BF16 | 12.8 GiB | 3.71 GB | ≤ 55 tok/s | ≤ 74 tok/s | ≤ 904 tok/s |
| gpt-oss-120b, MXFP4 experts + BF16 | 60.7 GiB | 5.00 GB | too tight in 64 GB | ≤ 55 tok/s | ≤ 670 tok/s |
| DeepSeek-V3, FP8 | 625 GiB | 36.6 GB | does not fit | does not fit | needs 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).
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).
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.
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.
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.
What production systems do about it:
moe_tp_size × moe_ep_size = tp_size).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.
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:
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.
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:
modules_to_not_convert in its config). That is how 117B parameters fit in 60.8 GiB.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.
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.
The core pieces of moe.py. Run python moe.py to execute every test below on CPU in a few seconds.
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.
| Aspect | Dense transformer | Sparse MoE transformer | Mamba / hybrid |
|---|---|---|---|
| Weights touched per token | all | attention + k of E experts (3–28% in the table above) | all |
| Memory to hold weights | total | total, roughly 4–33× the active set | total |
| Decode bytes per token, batch 1 | all weights + KV | active weights + KV | all weights + fixed-size state |
| Long-context memory | KV grows with context | same; MLA/GQA/compression shrink it | constant state per sequence |
| Weight reuse per step at batch B | B | B·k/E per expert | B |
| Multi-GPU pattern | tensor / pipeline parallel | expert parallel + two all-to-alls per layer | tensor / pipeline parallel |
| Kernel shape | large GEMMs | many small grouped GEMMs + permutes | scan + GEMMs |
| Edge sweet spot | small models | batch 1, if the quantized total fits | long sequences on small memory |
1. At batch 1, why can DeepSeek-V3 (671B total) decode faster than a 70B dense model on the same hardware, assuming both fit?
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?
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?
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?
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?
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?
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?
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?
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?
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?
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.
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.
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.
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).
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.
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.
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.
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.