Unit 1 of 10 · about 5 hours · explain, implement
Sparse MoE layers, router scores and shared and fine-grained experts
Every MoE layer replaces a dense feed-forward block with routed experts plus a router. The router decides which parameters run for each token, so sparse parameter count and active compute diverge from here on.
You'll be able to
- Explain router logits, token-to-expert scores and top- selection, and compute active expert FLOPs per token versus total expert parameters.
- Implement a router that maps token vectors to scores, selects experts and combines their outputs with a shared expert.
- Contrast shared experts with routed experts, and fine-grained experts with few large experts.
Covers
Read
In this order, only the parts listed
0 of 3 done
- MoE layers, routers and sparsityMixture of Experts Explained
What is a Mixture of Experts (MoE)? and What is Sparsity?, including Noisy Top-k Gating with the KeepTopK and softmax equations
- DeepSeekMoE with shared and fine-grained expertsDeepSeek-V3 Technical Report - MoE Sections
Section 2.1.2, Basic Architecture of DeepSeekMoE, Equations 12 to 15 (arXiv:2412.19437v2): shared experts, routed experts, sigmoid affinities and top-k normalization
- Router and MoE layer codeTorchFeather - Expert Parallelism
MoEArgsdefaults,TokenChoiceTopKRouter.forwardandMoE.forward, includingscore_func,route_norm,route_scale,expert_bias,score_before_expertsand the shared expertRead the code. On CPU its forward stops at
torch.histcon int64 expert indices (histogram_cpu not implemented for Long), so a CPU oracle counts withtorch.bincountinstead.
Focus on
- Router logits are ; scores are or . The gate value that multiplies an expert output comes from the scores, not from the ranking.
- With top- routing each token activates of experts. Active expert FLOPs scale with ; total expert parameters scale with .
- A shared expert runs for every token and is added outside the top- weighting. Fine-grained experts split the same capacity into more, smaller experts with larger .
- On a CUDA device TorchFeather computes the gate in float32 under autocast, then optionally normalizes (
route_norm) and scales (route_scale) the selected scores. On CPU that autocast is disabled with a warning, so keep oracle inputs in float32. The bias term changes selection only, as in DeepSeek-V3.
Common mistakes · 3
torch.topkwithsorted=False, as TorchFeather uses it, does not promise lower-index tie order or descending output. A contract that needs ties and order needs an explicit stable sort.- Sigmoid scores are independent affinities between 0 and 1; they sum to 1 across experts only after
route_norm. Do not treat raw sigmoid outputs as a distribution. - The shared expert is not one of the routed choices. Counting it inside top- undercounts routed compute and breaks the load statistics.
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.For scores and with lower-index ties, which experts are selected and with what weights?Answer
Experts 0 and 2 in that order. Selected scores give softmax weights .
2.A layer has experts with active per token. How do parameters and active compute scale?Answer
Parameters scale with 8 experts; active expert compute scales with 2. Doubling at fixed adds parameters without adding per-token FLOPs.
3.What changes in the routed result if the shared expert output is zero?Answer
The result is only the weighted routed sum. In the example above it would be instead of .
4.TorchFeather adds
expert_biasto scores beforetorch.topkbut gathers gate values from the original scores. Why?AnswerThe bias steers selection toward underloaded experts without changing the multiplies. It implements auxiliary-loss-free balancing; gate values still derive from the unaugmented affinities.
Practice
- Deep-ML 125: Implement a Sparse Mixture of Experts Layer
Implement
moe(x, We, Wg, n_experts, top_k); the tests check the seed-42 forward values with , 4 experts and top-, and the all-zero expert-weight edge caseDo the closed-book reproduce first. The tests check forward values only, not routing gradients or dispatch.
You're done when
Your router reproduces the example by hand, and your MoE layer passes both Deep-ML 125 tests.
Only when you can do this without notes.
Leads to
Notes
Resources · 3 for this unit, 9 more in the section
- 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. - 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.
- 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.
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.
- 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.
- 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.
- 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.
- 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.
- 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.