Expert Choice MoE layers replace the feedforward layer in every other Transformer layer (left side of the figure above; Section 3.4 of the paper). Each expert is a network with the same shape as an ordinary feedforward layer.
First, the number of tokens k each expert selects (the bucket size) is determined by the following formula (Eq. (1) in the paper).
k=enΓcβ
n is the number of tokens in the batch (batch size Γ sequence length), e is the number of experts, and c is the capacity factor. c represents how many experts a token is used by on average. With c=2, the total computation is the same as GShard, which selects the top 2.
The MoE layer processes the batch of tokens XβRnΓd in the following order (Eqs. (2)β(4) in the paper).
- Measure affinities: Multiply by the expert embeddings Wgβ and take a softmax for each token to obtain the tokenβexpert affinities S.
- Experts select tokens: For each expert, select the top k tokens with the highest affinity. Let I be the indices of the selected tokens, G the corresponding affinities (gate values), and P the one-hot version of I.
- Compute only the selected tokens: Each expert i computes only the k tokens it selected, Xinβ[i].
- Sum per token: For each token, the outputs of the experts that selected it are multiplied by the gate values and summed.
S=Softmax(Xβ
Wgβ),G,I=TopK(Sβ€,k),P=Onehot(I)
Xinβ=Pβ
X,Xeβ[i]=GeLU(Xinβ[i]β
W1β[i])β
W2β[i]β€
Xoutβ[l,d]=i,jββP[i,j,l]G[i,j]Xeβ[i,j,d]
The softmax of SβRnΓe is taken per token (per row), but TopK is taken per row of the transposed Sβ€, that is, per expert, along the token dimension. This is the difference from conventional methods, which select the top experts per token. The GeLU activation function is GELU.
The right side of the figure above shows an example with 6 tokens, 3 experts, and c=1 (k=6Γ1/3=2). E1β selects t1β and t4β, which have high affinity, E2β selects t2β and t4β, and E3β selects t3β and t6β. As a result, t4β is used by 2 experts and t5β is selected by no expert. Every expert processes exactly 2 tokens, so the load is balanced.
A variant that caps the number of experts per token
The paper also tries a variant that caps at b the number of experts that can select a single token (Section 3.3 of the paper). For the matrix AβReΓn representing the selection, it solves an entropy-regularized linear program.
AmaxβΒ β¨Sβ€,Aβ©+Ξ»H(A)s.t.βi:jβ²ββA[i,jβ²]=k,βj:iβ²ββA[iβ²,j]β€b,βi,j:0β€A[i,j]β€1
H(A) is the sum of element-wise entropies. The paper solves this with Dykstra's algorithm (Ξ»=0.001, up to 100 iterations) and selects the top k from the resulting A.