Unit 2 of 10 · about 4 hours · implement
Top-k selection with deterministic ties and output recombination
Selection and recombination are the only numerics every token passes through. An unstable tie rule or a wrong normalization silently changes which expert runs and how its output is weighted.
You'll be able to
- Select top- experts with a deterministic lower-index tie rule and keep them in descending score order.
- Renormalize weights over the selected experts and recombine expert outputs plus the shared expert without losing token contributions.
- Compute per-expert token fractions and mean probabilities for a small batch.
Covers
Read
In this order, only the parts listed
0 of 3 done
- Top-k routing contract with load statisticsTensorTonic - Top-k MoE Router with Load Statistics
Statement, function
topk_moe_router(x, w_router, expert_outputs, shared_output, k)and the three public cases; score equation, lower-index tie rule, weight renormalization and the and definitionsAttempt the public cases by hand before comparing with the worked examples.
- KeepTopK gatingMixture of Experts Explained
Noisy Top-k Gating: noise, KeepTopK with negative-infinity masking, then softmax
- Simplified top-1 routingSwitch Transformers
Section 2.1: routing to a single expert (), with the three stated effects on router compute, expert batch size and communication
Focus on
- Scores are ; selection sorts them descending with lower-index tie breaks. Keep that order in the outputs.
- Weights renormalize over the selected only. The full-vocabulary softmax is a separate statistic (), not the combine weight.
- The routed result is the shared output plus the weighted routed sum, with weights summing to 1 per token, so token contributions are conserved through combine.
- Switch shows preserves quality while cutting router compute, expert batch size and communication. The unit default is general ; is the special case.
Common mistakes · 3
torch.topktie order is implementation-defined andsorted=Falsedrops ordering. Use a stable descending sort when the contract needs ties and order.- Softmax over all experts () and softmax over the selected (combine weights) are different objects. Using as combine weights leaks unselected experts into the output.
- GShard dispatches the second expert randomly with probability proportional to its weight; Switch and TensorTonic are deterministic. Do not mix the two semantics in one oracle.
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.Scores , . Which experts and weights?Answer
Experts 0 and 1. Softmax over gives .
2.Scores , . What does the tie rule give?Answer
Experts 0 and 1 with weights ; lower index wins the tie and order stays descending.
3.Why is while in public case 1?Answer
Both tokens select expert 2, so its token fraction is 1. Its mean probability averages the full softmax rows, which spread mass over all experts.
4.A combine drops the shared expert term. Which public-case outputs change?Answer
All outputs shift by the shared output: case 1 becomes .
Practice
- TensorTonic: Top-k MoE Router with Load Statistics
Implement
topk_moe_router; the three public cases check tied top-two routing, single-expert selection and all-tied selection with exact outputs, indices, weights, token fractions and probability massesSolve on paper before running. Return
selected_expertsas int64 and everything else in the input dtype on the input device, as the statement requires.
You're done when
Your implementation matches all three public cases exactly, including order, dtype and device, and you can redo case 1 by hand.
Only when you can do this without notes.
Leads to
Notes
Resources · 3 for this unit, 9 more in the section
- Mixture of Experts ExplainedHugging Face · required
Study routing, capacity, token dropping, auxiliary loss and the expert-parallelism sections. Implement the small routing examples and verify conservation of token contributions through combine; group composition and FSDP interaction come from the papers and TorchTitan.
- TensorTonic - Top-k MoE Router with Load StatisticsTensorTonic · support
Solve Top-k MoE Router with Load Statistics, including its lower-index tie rule, before building dispatch.
- Switch TransformersGoogle Research · support
Read Section 2 for simplified routing, the capacity factor and the load-balancing loss, and Section 5 for combining data, model and expert parallelism. Reproduce its capacity arithmetic for one batch.
Also in this section
- Ultra-Scale Playbook - Expert ParallelismHugging Face · primary
Read Expert Parallelism and its interaction with DP in the 5D summary. Derive tokens, bytes and expected imbalance for one top-k routing example; use the linked MoE introduction only if the architecture is unfamiliar.
- How to Scale Your Model - Expert Parallelism on GPUsGoogle DeepMind · support
Read the expert-parallelism part of Rooflines for LLM Scaling on GPUs and work its quiz before the answer. Use it for the all-to-all cost half of your MoE accounting.
- TorchFeather - Expert ParallelismTorchFeather · required
Watch the video segments from 16:49:58 (MoE) through 18:36:24 (expert parallelism), 19:01:56 (all-to-all dispatch and combine) and 19:27:38 (expert tensor parallelism), then trace
model/moe/anddistributed/expert_parallel.py. Build a tiny router-dispatch-expert-combine oracle first, then map each group, placement andall_to_all_singlecall to it. - GShard: Scaling Giant Models with Conditional Computation and Automatic ShardingLepikhin et al. (ICLR 2021) · support
Read the mixture-of-experts layer: top-2 gating, expert capacity, the auxiliary loss and random routing. Compare its capacity rule with Switch.
- ST-MoE: Designing Stable and Transferable Sparse Expert ModelsZoph et al. (2022) · support
Read the stability section that introduces the router z-loss and compare it with the auxiliary balancing loss.
- DeepSeek-V3 Technical Report - MoE SectionsDeepSeek-AI (2024) · support
Read the DeepSeekMoE architecture (shared and fine-grained experts, auxiliary-loss-free balancing, node-limited routing) and the all-to-all communication design. Its throughput figures are its own cluster's results.
- Bumblebee - Router, Dispatcher and Expert PrimitivesBumblebee · depth
Only as a possible capstone target: read
primitive/modules/router.py,dispatcher.py,experts.pyandmoe.pyin a clean checkout. Its own todo lists no multi-GPU correctness test yet, so do not treat it as a reference implementation. - TorchTitan - MoE Model and ParallelismPyTorch · support
Read the MoE model files and their parallelization plan only after the tiny oracle passes, at a pinned commit. Record how a production PyTorch stack composes EP, expert FSDP and the other mesh dimensions.
- PyTorch Distributed - all-to-all collectivePyTorch · reference
Read
all_to_all_singleforinput_split_sizesandoutput_split_sizeson dim 0 and its uneven-split example. Use it for the dispatch and combine calls in the tiny oracle, and check zero splits yourself.