With thousands of experts, one gate choosing among all of them has a huge branching factor. The Sparsely-Gated MoE paper uses a two-level hierarchy instead: a primary gate picks a few of groups, and each chosen group's own secondary gate picks a few of its experts. Implement the forward pass.
top_k_softmax(logits, k)
logits has shape (rows, m). For each row keep the k largest logits (ties: the lower index wins), apply a softmax over just those, and set every other entry to 0. Return an array of the same shape.hierarchical_moe(x, W_primary, W_secondary, W_experts, k1, k2)
x: (batch, d). W_primary: (d, a). W_secondary: (a, d, b), one gate per group. W_experts: (a, b, d, d_out); expert .top_k_softmax(x @ W_primary, k1). Group 's gate: top_k_softmax(x @ W_secondary[i], k2).(y, importance, evaluated):
y: (batch, d_out), the output above.importance: (a, b), .evaluated: integer array (batch,), how many experts actually ran for each example.np.argsort(-row, kind="stable")[:k] gives the top-k indices with ties going to the lower index.k1 * k2 experts.