Route each token to its top 2 experts in a mixture of experts

A mixture-of-experts (MoE) layer has many small feed-forward networks (experts) but runs only a few per token. A router scores every expert for every token, keeps the best k, and mixes their outputs with weights that sum to 1.

Write moe_route(logits, k=2) where logits has shape (tokens, experts). Return (idx, weights):

- idx: shape (tokens, k), the indices of the k highest logits per token, highest first. On a tie, the lower expert index wins.
- weights: shape (tokens, k), a softmax over only those k logits (subtract the max first).

Then write expert_load(idx, n_experts): a list with how many tokens were sent to each expert. Load balance matters: an expert that gets every token becomes the bottleneck.

Signaturedef moe_route(logits, k=2)

Understand the idea

A mixture-of-experts layer has many expert networks but runs only a few for each token. A router gives each expert a score, keeps the top k, and turns just those k scores into mixing weights that add up to 1. Like a hospital front desk sending each patient to the two most suitable doctors. Worked example, 4 experts, k = 2. Token 1 logits [1, 3, 2, 3]: the best two are experts 1 and 3 (tie at 3, lower index first), and softmax over [3, 3] gives [0.5, 0.5]. Token 2 logits [0, 2, 1, 0]: best are experts 1 and 2, softmax over [2, 1] gives [0.731, 0.269]. Expert load counts every chosen slot: expert 0 got 0, expert 1 got 2, expert 2 got 1, expert 3 got 1, so [0, 2, 1, 1]. Rule: stable sort on negated logits, take first k, softmax over only those k. Mixtral and other MoE LLMs route tokens this way, and uneven load slows training.

Part of the advanced LLM architecture track.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: top-2 indicesnp.asarray(moe_route(L)[0]).tolist()
  • Sample 2: weights are a softmax over the kept 2moe_route(L)[1][0]