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

Sparse MoE routing, expert capacity, dispatch and token ownershipExpert-parallel communication implications without implementing the distributed runtime
1

Read

In this order, only the parts listed

0 of 4 done

  1. 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.

  2. 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.

  3. Build a Large Language Model (From Scratch), companion bonus codeBuild a Large Language Model (From Scratch), Chapters 3 and 4

    ch04/07_moe: README and MoEFeedForward in gpt_with_kv_moe.py

    It groups tokens by expert but has no capacity limit, so nothing is ever dropped. It also has no balancing loss.

  4. 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 MoELayer loops 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.

2

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.
3

Try it yourself

Closed-book, before checking anything

By hand, route 8 tokens to 4 experts with top-1 assignments , counts . With capacity factor 1.0 the capacity is 2, tokens 2, 3 and 4 are dropped, and the dropped fraction is 0.375. With 1.25 the capacity is and tokens 3 and 4 are dropped (0.25). With 2.5 the capacity is 5 and nothing is dropped. Then derive the payload for 8192 tokens per device, width 4096, bfloat16, , capacity factor 1.25 and 8 expert-parallel devices: bytes, exactly 140 MiB, per all-to-all per device. Finally implement dispatch (position in expert from a cumulative sum of the assignment mask), expert computation on the gathered tokens, and combine with gate weights, and check it against a per-token loop with the capacity set high enough that nothing drops. In float32 on random inputs the two should agree to about 1e-6.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 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. 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. 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. 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. 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.

5

Practice

  • TensorTonic: Top-k MoE Router with Load Statistics

    Free problem cs336-l04-topk-moe-router, function topk_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

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) in stanford-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_gqa and ch04/07_moe for 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.ipynb and 13-moe.ipynb, and notebooks-en/part4-frontiers/27-long-context.ipynb and 30-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