A fast MoE layer does not loop over experts token by token. It permutes: makes one row per (token, selected expert) assignment, sorts the rows so each expert's rows are contiguous, runs every expert on its own segment with one grouped matrix multiply, and then unpermutes, scattering each result back to its token with the routing weight. Implement the three stages and the full layer.
Inputs: x is (T, d), idx and w are (T, k) (the selected experts and their routing weights). Assignment (t, j) has flat id .
permute(x, idx, num_experts, align=1) returns a dict:
"counts": list of real assignments per expert (length num_experts)."padded_counts": each count rounded up to a multiple of align (a count of 0 stays 0)."offsets": list of length num_experts + 1, the cumulative sum of the padded counts starting at 0; expert owns rows offsets[e]:offsets[e+1]."order": list of length offsets[-1]. Inside expert 's segment, the first counts[e] entries are the flat ids of its assignments in increasing flat id (a stable sort by expert), followed by -1 for each padding row."rows": the (offsets[-1], d) array whose row is x[order[r] // k], or zeros for a padding row."padding_share": padding rows over all rows (0.0 if there are no rows), rounded to 4 decimals.grouped_ffn(rows, offsets, W1, W2): W1 is (E, d, h), W2 is (E, h, d); rows of expert 's segment become . Return the (R, d) array.
unpermute(y_rows, order, w, num_tokens): return the (T, d) array , skipping padding rows.
moe_grouped(x, idx, w, W1, W2, align=1): permute, grouped FFN, unpermute; return the (T, d) output.