PyTorch tutorial: mixture of experts from scratch
Build a sparse mixture-of-experts layer in PyTorch with top-k routing and a load-balancing loss, then inspect a number-doubling demo and its limits.
Player not loading? Watch on YouTube
NeuralNine explains mixture of experts (MoE), then implements a small sparse MoE layer in PyTorch. The tutorial assumes basic knowledge of neural networks and PyTorch. It uses synthetic data rather than a real dataset and does not build a transformer.
The conceptual explanation shows how a router selects expert networks for each token and assigns weights to their outputs. The presenter discusses activating a subset of weights to reduce computation, while keeping all expert weights in memory. These are architectural explanations rather than measured performance results.
In a local Python project, the presenter defines experts with two linear layers and a GELU activation. The implementation adds a linear router, softmax probabilities and top-k selection, then renormalizes the selected weights. It gathers each expert's assigned tokens, accumulates weighted outputs with index_add_ and restores the original tensor shape. An auxiliary load-balancing loss aims to discourage uneven routing.
The final example uses hidden dimension 128, expert dimension 512 and eight experts, with two selected per input. An Adam optimizer trains the model to double random numbers between -20 and 20. The presenter enters numbers and inspects predictions, selected experts and routing weights. Some predictions approximate the target, but some runs assign zero weight to the second expert. The presenter acknowledges this limitation. The script retrains each time it runs.
Source: NeuralNine, "Mixture of Experts: Explained & Implemented". https://www.youtube.com/watch?v=vHF7gGvAqu8