Switch Transformer replaces the Transformer's feedforward layers (FFN) with Switch FFN layers (left side of the figure above; Figure 2 in the paper). Many of the paper's models make every other FFN layer a Switch FFN layer. Each expert is a network with the same shape as an ordinary FFN, with separate weights.
A Switch FFN layer processes a single token x in the following order (right side of the figure above).
- Score: Multiply by the router weights Wr to obtain a score (logit) for each of the N experts, h(x)=Wr⋅x.
- Convert to probabilities: A softmax gives the probability (gate value) pi(x) of selecting expert i (formula below).
- Select just one: Select the single expert i with the highest probability.
- Compute only the selected expert: The output of expert i, Ei(x), is multiplied by the gate value pi(x) to give the output.
pi(x)=∑j=1Neh(x)jeh(x)i,y=pi(x)Ei(x)
This is the output of a top-k MoE, y=∑i∈Tpi(x)Ei(x) (T is the set of k selected experts), with k=1. Because the selected expert's output is multiplied by the gate value pi(x), gradients also flow to the router, so it can learn.
Expert capacity
On TPUs, tensor shapes must be fixed at compile time. So the number of tokens each expert receives (its capacity) is set by the following formula (Eq. (3) in the paper).
capacity=number of expertstokens per batch×capacity factor
A capacity factor greater than 1 provides slack when token assignment is unbalanced. Tokens sent beyond capacity (dropped tokens) skip that layer's computation and pass directly to the next layer through the residual connection.
Auxiliary load-balancing loss
To encourage experts to be used evenly, an auxiliary loss is added for each Switch layer (Eqs. (4)–(6) in the paper).
loss=α⋅N⋅i=1∑Nfi⋅Pi,fi=T1x∈B∑1{argmaxp(x)=i},Pi=T1x∈B∑pi(x)
B is a batch of T tokens, fi is the fraction of tokens dispatched to expert i, and Pi is the mean gate value of expert i. fi is not differentiable, but Pi is, so the model can learn in the direction that reduces the loss. Both are minimized when they equal 1/N (when balanced). Multiplying by N keeps the loss magnitude constant as the number of experts changes. The paper tried coefficients α from 10−1 to 10−5 and uses α=10−2.