Complete the Switch Transformer auxiliary load-balancing loss formula.
Same topic, related formats. Practice these next.
Same topic, related formats. Practice these next.
L_aux = α × N × Σ f_i × p_i, hard dispatch fraction f_i times differentiable softmax probability p_i per expert.
Think of the aux loss like a coach comparing game plans to the final scoreboard. f_i counts how many tokens really went to expert i (hard fact). p_i is what the router said it wanted (soft intention). Multiplying them penalizes experts the router favors but underuses, or uses heavily but didn't prefer, pushing intentions and reality to align.
Everything you need to truly understand this topic: intuition, mechanics, step by step explanation, code, formulas, and worked example. Click to expand.
Everything you need to truly understand this topic: intuition, mechanics, step by step explanation, code, formulas, and worked example.
Everything important, quickly.
7 min: formula components + grad paths + design rationale + α role + alternatives.
import torch
import torch.nn.functional as F
def switch_aux_loss(router_logits, expert_indices, num_experts, alpha=0.01):
# router_logits: [batch, num_experts]
# expert_indices: [batch, top_k] hard dispatch from top-k
batch = router_logits.size(0)
p = F.softmax(router_logits, dim=-1).mean(dim=0) # p_i, differentiable
counts = torch.bincount(expert_indices.reshape(-1), minlength=num_experts).float()
f = counts / counts.sum() # f_i, detached hard dispatch fraction
aux = alpha * num_experts * (f.detach() * p).sum()
return aux # gradients flow through p only
Real products, models, and research that use this idea.
What an interviewer would ask next. Try answering before peeking at the approach.
Red flags and common mistakes that signal junior thinking. Click to expand.
Swapping f_i and p_i, or assuming both terms receive gradients through top-k.
The night-before-the-interview bullets. Scan these on the way to the call.
Primary sources. Skim if you want the original framing.