Aux loss and balancing¶
MoE training collapses when a handful of experts eat all the tokens and the rest starve — those starved experts are dead parameters. KempnerForge has three mechanisms to prevent that, composable depending on the router:
Mechanism |
Router it applies to |
On by default? |
Config |
|---|---|---|---|
Switch-style auxiliary loss |
|
always |
|
Bias-based EMA balancing |
|
always |
|
Sequence-level aux loss |
|
opt-in |
|
Per-expert gradient scaling |
both |
opt-in |
|
Training-loop integration¶
Regardless of which router is active, the aux loss flows the same way:
# training/loop.py step body
main_loss = cross_entropy(logits, labels)
aux_loss = model.get_moe_aux_loss()
total = main_loss + mc.moe_aux_loss_weight * aux_loss
Transformer.get_moe_aux_loss() sums aux_loss over every MoE
router: one per MoE layer, and on a Mixture-of-Transformers (MoT) VLM
one per modality on each MoE layer, since every modality’s FFN holds
its own MoEMLP. The coefficient moe_aux_loss_weight
(default 0.01) is the knob that scales the balance pressure.
Every router gets the same pressure per unit of the coefficient, but
the logged moe/aux_loss is the sum. A balanced softmax router’s
term is about 1.0, so the sum is about the number of routers, and an
image + text MoT model logs about twice what a text model with the
same MoE layers logs. Compare a MoT run’s value with other MoT runs, or
divide it by the number of routers. MoMa’s expert-choice groups carry
no aux loss and add nothing.
For sigmoid_topk with no sequence aux loss, each layer’s
aux_loss is the scalar 0.0 — so total = main_loss and the
coefficient has no effect. For softmax_topk, every step contributes
a non-zero Switch-style penalty.
Softmax router — Switch-Transformer aux loss¶
# kempnerforge/model/router.py — SoftmaxTopKRouter.forward (trimmed)
one_hot = F.one_hot(indices, num_classes=self.num_experts).float()
tokens_per_exp = one_hot.sum(dim=(0, 1)) # (E,)
f = tokens_per_exp / (num_tokens * self.top_k) # hard counts
p = probs.mean(dim=0) # soft probs
self.aux_loss = self.num_experts * (f * p).sum()
The quantity num_experts · Σ_i f_i · p_i is minimized when every
expert gets 1/num_experts of the tokens. f_i is detached (hard
assignment) so no gradient flows through it; gradient flows only
through p_i, lowering the gate logits for over-utilized experts.
Typical coefficient: moe_aux_loss_weight = 0.01. Higher values
(0.1) over-regularize — router gets uniform but can’t specialize.
Lower (0.001) under-regularizes — collapse risk on long runs.
Sigmoid router — bias-based balancing¶
The sigmoid_topk router holds an expert_bias parameter that is
added to logits before sigmoid, a buffer expert_ema holding running
utilization, and a buffer pending_counts that each training forward
adds its expert counts to:
# kempnerforge/model/router.py: SigmoidTopKRouter.__init__
self.expert_bias = nn.Parameter(torch.zeros(num_experts), requires_grad=False)
self.register_buffer("expert_ema", torch.ones(num_experts) / num_experts)
self.register_buffer(
"pending_counts", torch.zeros(num_experts, dtype=torch.long), persistent=False
)
The optimizer never trains expert_bias: requires_grad=False keeps it
out of every optimizer group, and freeze_params never unfreezes it. It
is a parameter so that it is checkpointed with the model and sharded with
its module under FSDP2.
Right after each optimizer step, the training loop calls
Transformer.balance_routers(). One all-reduce sums every router’s
pending counts over the step’s micro-batches and all ranks, and each
router balances from its share:
# kempnerforge/model/router.py: SigmoidTopKRouter.balance (trimmed)
ema.lerp_(counts / counts.sum(), 1.0 - self.ema_decay) # ema_decay = 0.99
bias.add_(self._effective_bias_rate() * (1.0 / self.num_experts - ema))
Two moving parts:
expert_ema: exponential moving average of each expert’s share of the step’s routed tokens.ema_decay = 0.99means each optimizer step contributes 1% of its utilization to the smoothed estimate; with gradient accumulation, one step’s counts cover all its micro-batches.expert_bias: incremented byeffective_rate · (target − ema). Under-utilized experts (ema < target) get a positive nudge, so higher logits and more tokens next step; over-utilized experts get a negative nudge.
The update runs on FP32 masters of the EMA and the bias, so that bf16
storage does not round the small moves away, and expert_ema and
expert_bias are rounded from them. The masters are buffers that hold
the FP32 values as int32 bit patterns (fp32_ema_bits and
fp32_bias_bits), so casting the model to bf16 leaves them exact and a
resumed run continues from them; a checkpoint written before they
existed starts them from its expert_ema and expert_bias. Under FSDP2
the update lands on each rank’s shard of the bias. Utilization is each
expert’s share of
the summed counts, so tensor-parallel ranks, which route the same
tokens, cancel out. A step skipped for a NaN loss drops its counts, and
an eval forward counts nothing.
A checkpoint from a version that trained expert_bias still loads, and
its optimizer moments for the bias are left out. The exception is a run
whose optimizer.lr_multipliers gave the routers’ biases an optimizer
group of their own: the load refuses that group layout. To continue
from its weights with a fresh optimizer, set checkpoint.load_path to
it and checkpoint.exclude_from_loading = ["optimizer"], with a
checkpoint.dir that holds no checkpoint yet (auto-resume from a
checkpoint.dir loads everything).
Three of these are KempnerForge’s choices rather than the published
defaults. DeepSeek-V3 (section 2.1.2) and the auxiliary-loss-free
balancing paper (Algorithm 1) move each bias by a fixed step toward the
mean load, b += u · sign(e), where KempnerForge moves it in proportion
to the EMA’s shortfall. Both papers add the bias to the affinity scores
after the sigmoid, where KempnerForge adds it to the logits before the
sigmoid. And in both papers the bias only picks the experts, while the
gating weights come from the scores without it; KempnerForge weights
the selected experts by the biased scores.
Bias adjustment¶
Default bias_update_rate = 0.001. Not exposed in config — hardcoded
in SigmoidTopKRouter.__init__. The effective rate used per step is
modulated by the schedule:
# kempnerforge/model/router.py — _effective_bias_rate
if self.bias_schedule == "constant":
return rate
progress = self._step / self._max_steps
if self.bias_schedule == "cosine_decay":
return rate * 0.5 * (1 + cos(pi * progress))
if self.bias_schedule == "linear_warmup":
return rate * min(1.0, progress * 10.0) # ramp over first 10% of training
|
Effective-rate curve |
Typical use |
|---|---|---|
|
flat at |
standard DeepSeek-V3 |
|
decays |
late-training stability after balance is achieved |
|
|
cold-start stabilization when bias would otherwise overshoot |
The schedule needs the current training step, which is pushed in each
step via model.set_moe_step(step, max_steps) in
the step body. Transformer.set_moe_step walks only sigmoid
routers, each MoT modality’s included. _moe_mlps() yields every
MoEMLP: the one a flat MoE layer holds, and on a MoT layer the one
each modality holds.
# kempnerforge/model/transformer.py — set_moe_step
for _, _, mlp in self._moe_mlps():
if isinstance(mlp.router, SigmoidTopKRouter):
mlp.router.set_step(step, max_steps)
Sequence-level aux loss (sigmoid only)¶
Opt-in. When moe_sequence_aux_loss_weight > 0, the sigmoid router
adds a Switch-style penalty on top of the bias mechanism:
# kempnerforge/model/router.py — SigmoidTopKRouter.forward (trimmed)
if self.sequence_aux_loss_weight > 0:
f = tokens_per_expert.detach() / (num_tokens * self.top_k + 1e-8)
p = scores.mean(dim=0) # differentiable through sigmoid
balance_loss = self.num_experts * (f * p).sum()
self.aux_loss = self.sequence_aux_loss_weight * balance_loss
Same formula as the softmax router’s Switch-style loss, but with p
as mean sigmoid scores rather than softmax probabilities. Gradient
flows through p only.
When to use: long runs (100k+ steps) where bias balancing alone
sometimes drifts into degenerate modes. Recommended weight is much
smaller than the softmax router’s moe_aux_loss_weight — typical
0.001 (one tenth of 0.01) or lower, because the bias mechanism is
already doing most of the balancing work.
Leave moe_aux_loss_weight at its default 0.01 — it’s the
multiplier on aux_loss downstream, so the effective weight on the
balance loss is moe_aux_loss_weight × sequence_aux_loss_weight.
Router z-loss (logit-growth stability)¶
Opt-in via moe_router_z_loss_weight > 0 (default 0.0 = off). The
ST-MoE z-loss penalizes the router’s pre-softmax logits so they don’t
grow without bound. It is orthogonal to the balancing losses above — it
targets logit-growth stability, not load balance:
# kempnerforge/model/router.py — both routers, after computing logits
self.z_loss = (torch.logsumexp(logits, dim=-1) ** 2).mean()
Both SoftmaxTopKRouter and SigmoidTopKRouter set it. MoEMLP.z_loss
surfaces the per-layer value, and Transformer.get_moe_router_z_loss()
sums it across MoE routers, one per modality on a MoT layer, mirroring
aux_loss / get_moe_aux_loss().
The training loop adds it only when the weight is positive:
# training/loop.py::_add_moe_losses
if mc.moe_router_z_loss_weight > 0:
z = inner_transformer(model).get_moe_router_z_loss()
loss = loss + mc.moe_router_z_loss_weight * z
Logged as moe/router_z_loss. z_loss is a plain attribute (like
aux_loss), not a buffer or parameter, so it never enters state_dict
(checkpoint-safe); with the default 0.0 the term is never added, so
training, outputs, and gradients are unchanged.
When to use: long runs where router logits drift upward. A small
weight such as 1e-3 keeps the summed router z-loss bounded (~2–3, vs.
~14→24 when off) at identical LM loss — stabilizing the router at
negligible cost. Distinct from the output-logit z_loss_weight
(a cross-entropy regularizer); this one acts on the router logits.
Per-expert gradient scaling¶
Opt-in via moe_gradient_scale = true. Normalizes each expert’s
output by its utilization so high-traffic experts don’t dominate
training:
# kempnerforge/model/moe.py — MoEMLP._local_forward (grouped path, trimmed)
if self.gradient_scale and self.training:
avg_tokens = total_assignments / max(self.num_experts, 1)
offset = 0
for count in tokens_per_expert:
if count > 0:
scale = avg_tokens / count
expert_out[offset:offset + count] *= scale
offset += count
An expert that receives count tokens has its output multiplied by
avg_tokens / count. Hot experts get scale < 1 (gradients shrunk);
cold experts get scale > 1 (gradients amplified). The scale passes
through the expert_out * sorted_weights scatter-add, so the
routing weights still apply on top of it.
The same logic runs on the EP path (ep_dispatch_and_compute), which
scales each local expert by its receive count against the same average
over all experts, so EP leaves the scale unchanged; see
EP § Gradient scaling.
Reference: DeepSeek-V3 §3.2. Empirically small effect on short runs, visible on long runs where the router has converged to a specific usage distribution.
When to use: long MoE training where expert utilization is known-imbalanced and you want gradient-magnitude parity across experts. Disabled by default because it changes gradient magnitudes and should be validated against a baseline.
Diagnosis¶
Transformer.get_expert_counts() returns
dict[layer_idx → tensor(num_experts,)] with the per-expert token
count from the most recent forward. It is empty for a MoT model:
Transformer.get_mot_expert_counts() returns
dict[layer_idx → dict[modality → tensor(num_experts,)]] instead, one
router per modality, each counting only its own modality’s tokens.
Interpretation rule-of-thumb:
Balanced: counts within ~20% of
num_tokens · top_k / num_experts, withnum_tokensthe tokens that router saw.Hot/cold: one expert ≥ 2× the mean → router is specializing. Fine if intentional, bad if unintentional.
Dead expert: count = 0 for many consecutive steps → that expert isn’t learning. Root cause is usually a too-small aux-loss coefficient or a cold-start bias issue.
See also¶
Routers — where
aux_lossis computed per router.Capacity and dispatch — what happens when
capacity_factordrops a token (the router still sees it, but its weight becomes 0).Expert parallelism § Gradient scaling — per-expert gradient scaling on the EP path.
MoE experiments — recommended aux loss weights per training scale.
Validation rules § MoE + PP — cross-section config checks (MoE + PP is unsupported).