Unit 8 of 10 · about 5 hours · implement

Masked-token, router-gradient and empty-expert tests

Routing bugs look like quality loss, not crashes. Only targeted tests separate a wrong router, a broken permutation and a true hotspot.

You'll be able to

  • Test masked and repeated tokens for exact dispatch identity and recombination.
  • Test router and dispatcher gradients, including empty experts and uneven tokens.
  • Name failure cases from empty experts, uneven splits and lost order.

Covers

Masked or repeated-token correctness testsRouter and dispatcher gradient testsFailure cases from empty experts and uneven tokens
1

Read

In this order, only the parts listed

0 of 2 done

  1. MoE correctness test patternsTorchTitan - MoE Model and Parallelism

    test_padding_is_excluded_from_counts_but_still_dispatched, test_eval_forward_does_not_accumulate_tokens_per_expert, test_explicit_moe_tp_transitions_with_ep_without_sp and test_routed_branch_rejects_tp_without_ep

    Read after the tiny oracle passes; copy the test patterns, not the framework.

  2. Combine and scoring-order codeTorchFeather - Expert Parallelism

    MoE.forward: score_before_experts scaling position, torch.gather routing, scatter_add combine, and tokens_per_expert accumulation under torch.no_grad

2

Focus on

  • Masked tokens are still dispatched but excluded from counts and the auxiliary loss. Dropping them from dispatch instead changes expert outputs.
  • Router gradients flow through selected scores only; selection indices carry none. The combine must use tensor weights, never Python floats.
  • Empty experts must run with zero rows and return zero grads. Uneven splits must be tested with at least one empty expert and one duplicated token.
  • Evaluation must not accumulate usage counters. TorchTitan fails a model that counts eval tokens toward balancing state.
Common mistakes · 3
  • Wrapping a routing weight in float() inside the combine loop. It detaches the router graph: in a measured example with 4 CPU processes on gloo and PyTorch 2.14.1, the tensor version keeps grad Wg while the float() version leaves it None.
  • Testing dispatch with balanced splits only. Real routing is uneven; without an empty expert and a duplicated token the tests miss the exact cases that break collectives.
  • Counting eval tokens in tokens_per_expert. The bias update then learns from inference-like passes; gate eval behind the training flag as the TorchTitan test demands.
3

Try it yourself

Closed-book, before checking anything

Closed-book, extend the oracle with three tests: repeated tokens produce identical outputs at both positions; converting combine weights with float() kills the router gradient while the tensor version keeps it; an expert with zero assigned tokens returns zeros with zero grads and matching empty splits.
4

Quiz yourself

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

0 got · 0 missed

  1. 1.Two identical tokens at positions 0 and 5 route differently. What is broken?Answer

    Dispatch or packing order: identical inputs must select the same experts with the same weights. Check the stable sort and the permutation inverse.

  2. 2.Router gradients are all None but expert gradients exist. What is the likely bug?Answer

    Weights were detached before combine, for example via float(). Keep them as tensors so the graph reaches the gate.

  3. 3.An empty expert raises a shape error in grouped matrix multiply. What should happen?Answer

    It should compute zero rows and return zeros with zero grads. Guard the zero-row case instead of skipping the expert.

  4. 4.Padding is excluded from counts. Must padded rows still reach experts?Answer

    Yes for compute layout in padded schemes, but they must not enter counts or the auxiliary loss. The TorchTitan padding test pins exactly this split.

5

Practice

  • Deep-ML 229: Sparse MoE Top-K Routing

    Implement moe_topk_routing(router_logits, expert_outputs, k); the tests check the combined output for weights and for the tied case

    Use it as the recombination oracle. Add your own masked-token, gradient and empty-expert tests around it.

You're done when

Your three oracle tests pass, Deep-ML 229 passes, and you can state the detach bug from the measured gradient run.

Only when you can do this without notes.

Leads to

Notes

Resources · 2 for this unit, 10 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/ and distributed/expert_parallel.py. Build a tiny router-dispatch-expert-combine oracle first, then map each group, placement and all_to_all_single call to it.

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

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.

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

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

  • 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.py and moe.py in a clean checkout. Its own todo lists no multi-GPU correctness test yet, so do not treat it as a reference implementation.

  • 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_single for input_split_sizes and output_split_sizes on dim 0 and its uneven-split example. Use it for the dispatch and combine calls in the tiny oracle, and check zero splits yourself.