Skip to content
Hard Research

Mixture of Experts Routing

A mixture-of-experts layer chooses a few expert functions for an input, then combines their outputs using routing weights. Implement moe_forward for one token and simple linear experts.

Inputs and output

  • x has shape (d,): one token vector, with d positive.
  • gate_weights has shape (d, E), where E is the number of experts.
  • expert_weights is a list of E matrices, each with shape (d, d). List index i identifies expert i.
  • top_k is an integer with 1 <= top_k <= E.

Inputs are floating-point tensors with a shared dtype and device. Assume the computed gate logits are finite. Return one vector of shape (d,), preserving dtype and device and leaving all inputs unchanged.

Route, evaluate and combine

  1. Compute logits = x @ gate_weights, giving one score per expert.
  2. Select the top_k largest scores. Break ties by choosing lower expert indices first.
  3. Apply a stable softmax over those selected scores only. The selected weights sum to one; unselected experts contribute nothing.
  4. For each selected expert i, compute expert_output = x @ expert_weights[i]. x is a row vector here. Do not transpose the expert matrix.
  5. Add each expert output multiplied by its routing weight.

For example, if two selected experts have equal scores, each gets weight 0.5. If their outputs are [2, -1] and [4, 3], return [3, 1].

With top_k=1, the selected expert has routing weight one, regardless of its score. With top_k=E, combine all experts. Do not return the routing weights or concatenate expert outputs.

This exercise uses deterministic routing and linear experts, with no bias, activation, routing noise or auxiliary loss. It is a simplified version of the sparse expert combination described by Shazeer et al. in The Sparsely-Gated Mixture-of-Experts Layer.