Imports
run firstThe lab file's imports. Run this cell first (or press Run all).
Hands-on lab 08 of 10 · MoE routing
An MoE layer replaces the one FFN of a block with E expert FFNs and a router that sends each token to only k of them. You build the two router types used today (softmax top-k: Mixtral, Qwen-MoE; sigmoid top-k with a balancing bias: DeepSeek-V3), the auxiliary load-balancing loss, two ways to dispatch tokens to experts (a simple per-expert loop, and the sort-and-scatter layout that grouped-GEMM kernels use), and capacity-limited dispatch with token dropping.
T tokens (batch x sequence, flattened), d width, E experts, k experts per token.
s = x W_r^T [T, E]p = softmax(s) [T, E] idx = the k largest p per token (descending) [T, k] w = p[idx] / sum(p[idx]) [T, k] (renormalized)
g = sigmoid(s) [T, E] (independent scores) idx = top-k of (g + bias) bias [E] only steers the CHOICE w = g[idx] / sum(g[idx]) weights use g, not g + bias
f_e = (number of the T*k assignments that went to expert e) / (T*k) P_e = mean over tokens of p[:, e] L_aux = E * sum_e f_e * P_e
= 1.0 when routing is perfectly uniform, up to E when everything goes to one expert. f is a count (no gradient); the gradient flows through P. (The MoE guide writes alpha * E * sum f * P; this function returns the unweighted E * sum f * P, so its floor is 1. Multiply by alpha ~ 0.01 when adding it to the LM loss.)
y[t] = sum_j w[t, j] * Expert_{idx[t, j]}(x[t]) [T, d]loop: for each expert e, gather its tokens, run it once, scatter back.
sorted: flatten the T*k assignments, sort them by expert id, so each
expert's tokens are one contiguous slice; run every slice,
weight, and index_add the results back to their tokens.C = ceil(capacity_factor * T * k / E)
assignments. Served in order (token 0's choices, then token 1's, ...); assignments beyond C are dropped: they add nothing, and the token keeps only its residual for that expert.
dispatch_loop / dispatch_sortedEditor keys: Tab / Shift+Tab indent and dedent by 4 spaces, Enter keeps the indentation, Shift+Enter runs the cell and moves to the next one.
Cells on this page:
The lab file's imports. Run this cell first (or press Run all).
softmax_topk_router(logits, k)Mixtral-style router.
logits [T, E] → (weights [T, k], indices [T, k] int64, probs [T, E]) probs = softmax(logits); indices = the k most probable experts, in DESCENDING order of probability; weights = their probs renormalized to sum to 1.
sigmoid_topk_router(logits, k, bias=None)DeepSeek-V3-style router.
logits [T, E], bias [E] or None → (weights [T, k], indices [T, k] int64) scores = sigmoid(logits); choose the k experts with the largest scores + bias (descending); weights = the UNBIASED scores of the chosen experts, renormalized.
load_balancing_loss(probs, indices)L_aux = E * sum_e f_e * P_e (see the module docstring).
probs [T, E] (softmax router probabilities), indices [T, k] → scalar tensor.
class Expert(nn.Module)One expert: a small GELU MLP, d → d_ff → d.
make_experts(n_experts, d, d_ff)dispatch_loop(x, weights, indices, experts)y[t] = sum_j weights[t, j] * experts[indices[t, j]](x[t]), one expert at a time.
x [T, d], weights/indices [T, k] → y [T, d]. Call each expert at most once, on all of its tokens together (skip experts that got no tokens).
dispatch_sorted(x, weights, indices, experts)Same result as dispatch_loop, via sort → contiguous slices → scatter.
expert_of = indices.flatten() [T*k], token_of = the token each one belongs to, weight_of = weights.flatten()argsort(expert_of): now every expert's assignments are contiguousbincount(expert_of, minlength=E); run expert e on its slice of x[token_of[order]] (this layout is what grouped-GEMM kernels consume)index_add the rows back to their tokensexpert_capacity(n_tokens, n_experts, k, capacity_factor)C = ceil(capacity_factor * n_tokens * k / n_experts), as an int.
dispatch_with_capacity(x, weights, indices, experts, capacity)Like dispatch_loop, but every expert keeps at most capacity assignments.
Assignments are served in token-major order: (token 0, slot 0), (token 0, slot 1), (token 1, slot 0), ... An expert keeps the first capacity it receives and drops the rest. Returns (y [T, d], kept [T, k] bool).
Experiment here: print shapes, call your functions on small inputs. This cell runs in the same Python process as the cells above, is not part of Run all and is not saved to the lab file (your browser keeps it).