REAL PYTORCH · CPU TRAINING AND AUTOGRAD

Route sparse top-two experts with an explicit capacity policy

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.

Run this Lab in Pythilo

Open Labs, choose its topic and tap Download entire topic, or Download entire category for all its Labs, including the required Python packages, then load the starter or worked answer and tap Trace. Progress, pause, resume and removal are in Downloads. Independent checks execute real CPU training and gradients.

No GPU, external model weights or API key is required. After downloading the topic and packages, this Lab runs offline.

PyTorch is unavailable in this browser runtime. The code and lessons are readable here; execution and checks run in the app.

Pythilo on the App Store →

Read lesson: Route sparse top-two experts with an explicit capacity policy →

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.

Starter

import torch

def sparse_mixture(x, router, experts, capacity):
    # TODO: implement sparse_mixture under the declared contract.
    return None
Inspect the worked answer
import torch

def sparse_mixture(x, router, experts, capacity):
    if x.ndim!=2 or min(x.shape)==0 or not x.is_floating_point() or not torch.isfinite(x).all() or type(capacity)!=int or capacity<=0:raise ValueError('Expected finite nonempty token matrix and positive integer capacity.')
    count=len(experts)
    if count<2 or not isinstance(router,torch.nn.Linear) or router.in_features!=x.shape[1] or router.out_features!=count:raise ValueError('Router and expert count must match.')
    if any(not isinstance(e,torch.nn.Linear) or e.in_features!=x.shape[1] or e.out_features!=experts[0].out_features for e in experts):raise ValueError('Experts must share input/output dimensions.')
    if any(not torch.isfinite(p).all() for m in [router,*experts] for p in m.parameters()):raise ValueError('Model parameters must be finite.')
    probabilities=router(x).softmax(-1)
    chosen=probabilities.argsort(dim=-1,descending=True,stable=True)[:,:2]
    requested=torch.bincount(chosen.flatten(),minlength=count).to(x.dtype)/(2*len(x))
    auxiliary=count*(probabilities.mean(0)*requested.detach()).sum()
    accepted=torch.zeros_like(probabilities,dtype=torch.bool)
    loads=[]
    for expert in range(count):
        tokens=(chosen==expert).any(-1).nonzero().flatten()[:capacity]
        accepted[tokens,expert]=True
        loads.append(len(tokens))
    retained=probabilities*accepted
    gates=retained/retained.sum(-1,keepdim=True).clamp_min(1e-12)
    zero=(x.sum()+probabilities.sum())*0
    output=x.new_zeros((len(x),experts[0].out_features))+zero
    for expert in range(count):
        tokens=accepted[:,expert].nonzero().flatten()
        if len(tokens):
            contribution=experts[expert](x.index_select(0,tokens))*gates[tokens,expert,None]
            output=output.index_add(0,tokens,contribution)
    dropped=2*len(x)-sum(loads)
    return output,auxiliary,loads,dropped

About this algorithm

How Route sparse top-two experts with an explicit capacity policy works

The idea

A sparse mixture-of-experts layer replaces one large feed-forward block with several smaller experts and a router. The router gives every token a probability for each expert, and only the two most probable experts process that token. Their outputs are blended by the router probabilities, renormalized over the experts kept.

The saving is real only if unselected experts never run. The code gathers the rows assigned to an expert with index_select, calls the expert on those rows alone, and writes the results back with index_add. A capacity limit caps how many rows one expert accepts, in input order, and assignments beyond it are dropped. The auxiliary term grows when the router's probability mass and its top-two requests pile onto the same experts, which pushes training toward a balanced load.

How it works

  1. Validate the token matrix, the router and expert shapes, finite parameters and a positive integer capacity.
  2. Compute probabilities with a softmax over the router output and take each token's top two experts with a stable descending argsort.
  3. Compute auxiliary as the expert count times the sum of mean router probability times the detached share of top-two requests per expert.
  4. For each expert, accept the first capacity tokens that chose it, in input order, and record the load.
  5. Zero the probabilities of rejected assignments and renormalize what remains per token to get gates.
  6. Run each expert only on its accepted rows, scale by the gate, add into output with index_add, and count the dropped assignments.

What it costs

Experts run
at most 2 per token
Router
scores all E experts
Per expert
up to capacity rows

The router is one small linear layer applied to every token, while each expert processes only its accepted rows, so expert compute stays near two calls per token however many experts exist.

Where it is used

  • Shazeer et al. (2017) introduced the sparsely gated mixture-of-experts layer with top-k routing and load-balancing losses.
  • Switch Transformer (Fedus et al., 2021) sets an expert capacity, lets overflowing tokens skip the expert layer, and uses an auxiliary load loss of this form.
  • Mixtral 8x7B routes each token to the top 2 of 8 experts in every layer.

Watch out for

  • Running every expert on every token and masking afterwards: nothing is saved, and the Lab's check fails as soon as an unselected expert is called.
  • Returning a constant zero tensor for a token whose two assignments both overflow: the zeros must stay connected to the graph so backward() works.
  • Keeping the original gate when one of a token's two assignments is dropped: the surviving expert's gate must be renormalized to 1.