Unit 7 of 11 · about 4 hours · derive, implement
Sparse MoE routing, expert capacity, dispatch and expert-parallel communication
A sparse layer separates parameters from compute, but it also makes each token's output depend on the other tokens in its batch, because capacity is shared. You need the dispatch rule before you can write an honest test for causality, determinism or an equal-compute comparison.
You'll be able to
- Derive router probabilities, top-k selection, expert capacity, dispatch counts and dropped tokens for a small example by hand, and reproduce them in code.
- Implement a sparse expert layer with dispatch, capacity, combine and dropped-token handling, and test it against a per-token loop.
- Derive the per-layer all-to-all payload of expert parallelism from the token count, , the capacity factor and the model width, without implementing the distributed runtime.
Covers
Read
In this order, only the parts listed
0 of 4 done
- CS336 Spring 2026, Lecture 4 slides (mixtures of experts)CS336 2026 - Architectures and Attention Alternatives
Slides 14 to 35 (what an MoE is, routing types, top-k routing in detail, shared and fine-grained experts, the expert-setup table) and slides 44 to 47 (systems side, MegaBlocks, communication, the stochasticity of token dropping)
Stop at slide 47. Slides 36 to 43 (training the router and balancing losses) belong to the next unit, and slides 54 to 59 are a DeepSeek case study.
- Switch Transformers (arXiv:2101.03961v3, JMLR version)Switch Transformers
Section 2.1 (Equations 1 and 2, why a gate value keeps the router differentiable), Section 2.2 (Equation 3, expert capacity, dropped tokens) and Figure 3 (capacity factors), Section 5.4 (expert and data parallelism); Appendix F as a pseudocode reference for dispatch and combine tensors
Appendix F is a reference to read once; do not port it.
- Build a Large Language Model (From Scratch), companion bonus codeBuild a Large Language Model (From Scratch), Chapters 3 and 4
ch04/07_moe: README andMoEFeedForwardingpt_with_kv_moe.pyIt groups tokens by expert but has no capacity limit, so nothing is ever dropped. It also has no balancing loss.
- Modern LLM Notebook: From Dense to MoE ArchitecturesModern LLM Notebook - Architecture Frontiers
Sections 1 to 3 and Section 5 (the parameter-versus-compute argument and the inference-memory consequence)
Its
MoELayerloops over tokens in Python and has no capacity; use it for the routing rule, not for dispatch. Section 4 (load balancing) is for the next unit.
Focus on
- Two router conventions. Switch and DeepSeek's first models take a softmax over all experts, then the top- probabilities as gate values. Mixtral-style routers take the top- logits, then a softmax over just those. They agree for only up to a renormalization, and they differ in an important way at : a softmax over one logit is the constant 1, so the router gets no gradient from the language-model loss.
- Capacity is a per-expert, per-batch limit: for tokens in the group that shares the buffer. Switch's Equation 3 is the case; with top- there are assignments to spread over experts. A token that arrives after an expert is full is not computed for that expert, and passes on through the residual connection. Which tokens lose a slot is a rule you must choose and test, for example token order within the group.
- A drop is silent. The loss still goes down, so track the dropped fraction per layer and per batch. Switch reports under 1% with its balancing loss. Because capacity is shared across the batch, a token's output can depend on its neighbors; Lecture 4 slide 47 points out that other requests can drop your token.
- Expert parallelism sends tokens to the device that holds their expert and brings the results back, so each MoE layer does two all-to-alls in the forward pass and two in the backward pass. With fixed-size capacity buffers the payload is set by the capacity, not by the actual routing, and only the fraction leaves the device.
Common mistakes · 3
- Using a softmax over the selected logits when . In a 6-token, 8-wide toy router (PyTorch 2.14.1), the gate values were exactly 1.0 and the summed absolute gradient of the router weights was 0.0, against 46.2 when the softmax was taken over all experts before the top-1. TensorTonic's router returns weight 1 for because it renormalizes over the selected experts, which is correct for its statement and has this consequence.
- Testing an MoE layer for causality or batch independence with capacity pressure on. A dropped token makes a layer's output depend on which other tokens share the buffer, and a priority by router score can let a later token take an earlier token's slot. Turn drops off (capacity at least ) for equivalence tests, and test the drop path separately with a fixed priority rule.
- Counting capacity from tokens rather than assignments for , or forgetting that two assignments of one token go to different experts. Check that a token's experts are distinct, and that the sum of the dispatched counts equals minus the drops.
Try it yourself
Closed-book, before checking anything
Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.A group has 4096 tokens, 64 experts, and a capacity factor of 1.25. What is the expert capacity?Answer
tokens per expert. The ideal load is 128 assignments per expert, and the factor adds a 25% buffer.
2.Eight tokens are assigned to experts with capacity 3 and token order as priority. Which tokens are dropped and what is the dropped fraction?Answer
Tokens 3 and 4, the fourth and fifth arrivals at expert 0, so the fraction is 2/8 = 0.25. The other tokens fit, since experts 1 to 3 hold one token each.
3.Why does a top-1 router with a softmax over the selected logit never learn from the language-model loss, and what fixes it?Answer
The gate value is of one number, which is always 1, so the output has no dependence on the router logits except through the discrete choice, which has no gradient. Take the softmax over all experts first and multiply the expert output by the selected probability, as Switch does, or use a balancing loss as the only router signal (which is not enough by itself).
4.Give the all-to-all payload per device for 4096 tokens, width 2048, bfloat16, , capacity factor 1.0 and 4 devices. Does a more balanced router change it with fixed buffers?Answer
bytes (12 MiB) per all-to-all. With fixed-size buffers, no: the payload is set by the capacity. Balance changes how many slots hold real tokens and how many are padding.
5.Why must a causal-prefix test of an MoE layer run with drops disabled?Answer
With drops, a token's output depends on the other tokens competing for the same expert buffer. Under a rule that lets a later token take a slot from an earlier one, a future token can change a past token's output, which breaks prefix invariance by design of the dispatch rule, not by a mask bug. With capacity at least the token count nothing is dropped, and the layer is a function of each token alone.
Practice
- TensorTonic: Top-k MoE Router with Load Statistics
Free problem
cs336-l04-topk-moe-router, functiontopk_moe_router(x, w_router, expert_outputs, shared_output, k)The three public cases check top-2 routing with a tie broken toward the lower expert index, a single selected expert, and a case where every expert ties, and they return the selected experts, their weights, the dispatched fraction and the mean router probability . Expert outputs are given in advance. There is no capacity, no dropping and no gradient check. Add your own tests for capacity and dropped tokens (the hand example above), distinct experts per token, and a gradient test of the router.
- Capacity and dispatch on top of your own router
Section 2.2 and Appendix F; build dispatch and combine with a fixed priority rule and a switch that turns drops off
Tests to write: equal to the per-token loop with no drops, the hand example above, the sum of dispatched counts equals minus the drops, dropped tokens leave only the residual, and the router weights receive a nonzero gradient. The section mini-project reuses this layer.
You're done when
Your dispatch matches the per-token loop with drops off, reproduces the 0.375, 0.25 and 0 dropped fractions of the hand example, and you can derive the all-to-all payload for a configuration you choose.
Only when you can do this without notes.
Leads to
- Load-balancing losses, router z-loss, dropped tokens and expert collapseAdd the balancing losses and measure when routing collapses.
- Weight transfer and differential tests between overlapping architecture variantsTurn the dense-equivalence special case into a differential test.
- Token packing, all-to-all dispatch and inverse combineTake the all-to-all derivation into a real expert-parallel runtime.
Notes
Resources · 4 for this unit, 14 more in the section
- CS336 2026 - Architectures and Attention AlternativesStanford University · primary
Study the Lecture 3 slides (
lecture_03.pdf, architectures and hyperparameters) and Lecture 4 slides (lecture_04.pdf, attention alternatives and mixture of experts) instanford-cs336/lectures, then implement the Assignment 1 Section 3.3 to 3.5 pieces (RMSNorm, SwiGLU, RoPE, causal attention, the pre-norm block) against its tests. Reconstruct every parameter and state equation before you change one mechanism. Keep GPUs, kernels and parallelism (Lectures 5 to 8) for their own tracks. - Build a Large Language Model (From Scratch), Chapters 3 and 4Sebastian Raschka / Manning · support
Use Chapter 3 (causal multi-head attention, pp. 50-91) and Chapter 4 (the GPT model, pp. 92-127) as the smallest runnable decoder, then the companion bonus folders
ch04/04_gqaandch04/07_moefor one bounded variant. The printed chapters use GPT-2 parts (LayerNorm, GELU, absolute positions); the modern pieces live only in the bonus folders. - Modern LLM Notebook - Architecture FrontiersWalking Labs · support
Use
notebooks-en/part2-training/08-gpt2-to-modern-models.ipynb,11-mla-kv-cache.ipynband13-moe.ipynb, andnotebooks-en/part4-frontiers/27-long-context.ipynband30-efficient-attention.ipynb. Implement only the one variant selected for the checkpoint. - Switch TransformersGoogle Research · depth
Use Equations 4 to 6 (the load-balancing loss), Figure 3 (capacity factors), Table 3 (smaller initialization for stability) and the Appendix F pseudocode as the deeper MoE reference. Reproduce only a tiny router experiment; full sparse pretraining belongs to later systems work.
Also in this section
- OLMo 2 Open Model and Training RecipeAllen Institute for AI · required
Read Section 2.1 (architecture), Section 3.2 (initialization) and Sections 3.3.1 to 3.3.3 (non-parametric norm to RMSNorm, reordered norm with QK-norm, z-loss) and Table 1, then find the same settings in a released configuration. The changes were adopted as a package, so the report cannot attribute stability to any single one.
- On Layer Normalization in the Transformer Architecture (Xiong et al., 2020)Microsoft Research Asia · support
Read Figure 1 and Sections 3 and 4: why Post-LN gradients near the output are large at initialization and need warmup, and why Pre-LN does not. The analysis holds at initialization only and assumes uniform attention weights and Gaussian inputs there.
- GLU Variants Improve Transformer (Shazeer, 2020)Google · support
Read Section 2 (the GLU family and SwiGLU) and Section 3.1 (hidden width cut from 3072 to 2048 so parameters match), then Table 1, where GEGLU edges out SwiGLU on the longest run. Check the matching arithmetic yourself.
- GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints (Ainslie et al., 2023) with Fast Transformer Decoding: One Write-Head is All You Need (Shazeer, 2019)Google Research · support
Read MQA Sections 2 and 3 (one shared key and value head to cut decoding memory traffic), then GQA Section 2 (grouped heads as the interpolation, mean-pooled uptraining with 5% of pretraining compute) and Table 1. Both report encoder-decoder results. MQA is at https://arxiv.org/abs/1911.02150.
- RoFormer: Enhanced Transformer with Rotary Position Embedding (Su et al., 2021)Zhuiyi Technology · required
Read Section 3: the rotation-matrix form of RoPE, why the attention score depends only on relative position, and the long-distance decay property. Base 10000 is the original choice; later models raise it.
- Extending Context Window of Large Language Models via Positional Interpolation (Chen et al., 2023) and YaRN (Peng et al., 2023)Meta AI; Nous Research · support
Read Position Interpolation Sections 2 and 3 (scale positions by the length ratio instead of extrapolating), then YaRN Section 3 (frequency-dependent interpolation and the attention temperature). Both still fine-tune. YaRN is at https://arxiv.org/abs/2309.00071.
- Small-Scale Proxies for Large-Scale Transformer Training Instabilities (Wortsman et al., 2023)Google DeepMind · support
Read Section 3.1: attention-logit growth and output-logit divergence reproduced in small models at high learning rates, and the QK-layernorm and z-loss fixes (Figures 1 to 4). It explains two of the OLMo 2 choices; transfer to a specific large run is argued, not proven.
- TensorTonic - Architecture and Attention AlternativesTensorTonic · support
Solve RMSNorm Forward Pass (
cs336-l03-rmsnorm-forward), Parameter-Matched SwiGLU Block (cs336-l03-parameter-matched-swiglu), Rotary Query and Key Embeddings (cs336-l03-rotary-query-key-embeddings), Causal Grouped-Query Attention (cs336-l03-causal-grouped-query-attention), Top-k MoE Router with Load Statistics (cs336-l04-topk-moe-router) and one ofcs336-l04-linear-attention-dualityorcs336-l04-mamba2-gated-state-scan. Add capacity and token-drop cases the router tests lack. Public test cases check the listed edge cases, not gradients or the hidden grader, so keep your own tests beside each solution. - Decoder-Only Transformer StackRoadmap-Final · support
Extend the already-tested decoder with the chosen mechanism. Preserve its slow oracle, causal and position tests, generation behavior and model arithmetic.
- ST-MoE: Designing Stable and Transferable Sparse Expert Models (Zoph et al., 2022)Google · depth
Read Section 3 and Appendix B: the router z-loss in Equation 5, its coefficient 0.001 and the load-balance weight in Equation 6, and why update clipping stabilizes runs at a quality cost. Its setting is encoder-decoder T5.
- DeepSeek-V2, Section 2.1 (Multi-head Latent Attention)DeepSeek-AI · optional
Read Sections 2.1.1 to 2.1.4: low-rank joint key-value compression, decoupled RoPE and the cache comparison. The 93.3% cache reduction is against their own 67B model, not a portable ratio.
- Transformers are SSMs: Generalized Models and Efficient Algorithms Through Structured State Space Duality (Dao and Gu, 2024)Princeton and CMU · optional
Read Section 1 and Sections 5 and 6, including Listing 1 (the
segsumreference), for a state-space alternative. Skip the full duality theory; compare against a linear-attention baseline in your own harness. - Modern LLM Notebook, Appendix B: From Parameters to MemoryWalking Labs · support
Appendix B Section 1 (parameters per block and per model, GQA and SwiGLU) and Section 2 (activation memory). Recount the activation tables with autograd hooks; the notebook lists produced tensors, not saved ones. Pin commit 979eecf.
- Deep Learning Tuning PlaybookGoogle Research · support
Read 'Identifying scientific, nuisance, and fixed hyperparameters' and 'Determining whether to adopt a training pipeline change or hyperparameter configuration' as the protocol for comparing architecture variants (per-arm learning rate, trial variance). Skip the batch-norm material. Last commit 2024; pin commit 7554a51.