Mixtral's Sparse Mixture-of-Experts Block
In Mixtral 8x7B every feed-forward block of the Transformer is replaced by a layer of n=8 experts. For each token a linear router scores the experts, the two best are kept, and the token's output is the weighted sum of those two experts' outputs:
y=∑i=0n−1Softmax(Top2(xWg))i⋅SwiGLUi(x),
where TopK(ℓ)i=ℓi if ℓi is among the K largest logits and −∞ otherwise. Implement the layer for a batch of tokens and any K, evaluating each expert only on the tokens routed to it.
mixtral_moe(x, W_g, W1, W2, W3, k=2)
x has shape (T,d), one row per token. W_g has shape (d,n).
W1 and W3 have shape (n,d,h) and W2 has shape (n,h,d). Expert i is
SwiGLUi(x)=(SiLU(xW1i)⊙xW3i)W2i,SiLU(z)=zσ(z).
- Return a tuple
(y, chosen, counts):
y: float array of shape (T,d);
chosen: a list of T lists, each holding the k selected expert indices in order of decreasing logit;
counts: a list of n ints, the number of tokens each expert processed.
Notes
- Ties among logits: the lower expert index ranks first.
- An expert that no token selects must not be evaluated at all. Some tests give such experts weights that are not finite numbers.
- Raise
ValueError unless 1≤k≤n.
- Inputs are not modified.