PythiloLesson 4 of 8 · progress kept in this browser

Practice in Lab: Route sparse top-two experts with an explicit capacity policy →

Route sparse top-two experts with an explicit capacity policy

A sparse router introduces a discrete ownership decision between differentiable computations. The selected gate probabilities remain trainable, but selection indices and capacity decisions do not. Overflow policy changes which examples reach which expert; this exercise makes input-order admission and renormalization explicit. Load balancing uses pre-capacity assignments so dropping work cannot masquerade as balanced demand. CPU execution demonstrates correctness and gradients, not expert-parallel communication, a distributed all-to-all operation or an inference speedup.

Your task

For finite floating [tokens,dim] x, a Linear router with E>=2 outputs and E Linear experts of one common output width, choose the two largest router softmax probabilities per token (ties by expert index). Process tokens in input order; accept an assignment while that expert has capacity. Renormalize the retained gates per token. A token whose two assignments overflow returns graph-connected zeros. Return (output, auxiliary, accepted_loads, dropped_assignments). Auxiliary is E*sum(mean_full_router_probability*detached_pre_capacity_top2_fraction), fractions normalized by 2*tokens. Execute only accepted expert rows; do not evaluate every expert densely. Reject invalid shapes, nonfinite inputs/parameters and nonpositive integer capacity.

This lesson uses torch, which Python in this browser does not include. Read it here, and run and check it in the Pythilo app on iPhone or iPad.