Build an MoE layer with naive and grouped dispatch on CPU
CPU · your Macnotebook150 minrequiredGoal · A PyTorch MoE layer with top-2-of-8 routing implemented two ways, proven equivalent, with a timing comparison and a per-expert load histogram.
- 1Define MoE(d_model=512, d_ff=1024, E=8, k=2) with a router nn.Linear(d_model, E) and eight expert MLPs; initialise with a fixed seed.
- 2Implement forward_naive that loops over tokens, picks top-k experts with softmax-renormalised weights, and sums the weighted expert outputs.
- 3Implement forward_grouped that sorts token indices by expert id, computes group offsets, runs each expert once on its contiguous slice (or torch.bmm on padded groups), and scatters results back with index_add_.
- 4Assert torch.allclose(forward_naive(x), forward_grouped(x), atol=1e-5) on random x of 4,096 tokens.
- 5Time both on 4,096 tokens with 10 repeats and report the speedup; count the FLOPs of the MoE versus a dense MLP with the same total parameters.
- 6Record tokens routed per expert, plot the histogram, and compute the imbalance ratio max/mean; then add a capacity factor of 1.25 and count how many tokens would be dropped.
- 7Skew the router by adding a bias to one expert and repeat the imbalance and drop measurements.
- Deliverable
- A notebook with both implementations, the allclose assertion, the timing table, the histograms and the drop counts.
- Check
- allclose passes; forward_grouped is at least 2x faster than forward_naive at 4,096 tokens; the MoE uses about k/E of the dense-equivalent FLOPs per token (within 10 percent, ignoring the router).