Router Z-Loss › Worked Example: Z-Loss Step by Step
Language AI HandbookAll chapters Router Z-Loss › Worked Example: Z-Loss Step by StepOne section · Sections in this chapter4 / 12 ↓
Reading tools Definitions & inline links
Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.
Article links
Make inline references clickable
To make the mathematics concrete, let's trace through a single z-loss computation with specific numbers. Suppose we have a batch of tokens and experts. The router produces the following logit matrix:
where row contains the logits for token across all four experts. Notice that token 1 has moderate, nearly uniform logits, while token 3 has a very large logit for expert 1.
Step 1: Compute LSE for each token.
For token 1, with logits :
For token 2, with logits :
For token 3, with logits :
Notice that token 3's LSE is almost exactly equal to its maximum logit (8.0), confirming the approximation is tight when one logit dominates strongly. Token 2's LSE is 2.55, compared to its maximum logit of 1.5, a gap of 1.05, close to since the logits are nearly equal.
Step 2: Square each LSE value.
Step 3: Average across the batch.
Step 4: Understand what this tells us.
Token 3 contributes 64.00 to the sum, while tokens 1 and 2 together contribute only 16.87. Token 3's extreme logit of 8.0 for expert 1 is responsible for nearly 80% of the total z-loss, even though it is only one of three tokens. This is the quadratic amplification working as intended: logit values that are dangerously large receive a disproportionate share of the penalty, creating strong corrective pressure exactly where it is most needed.
Step 5: Compute the gradient for the dominant logit.
For token 3, the softmax probability for expert 1 is approximately:
The z-loss gradient for this logit is:
This is a substantial gradient that will push downward in the next parameter update, counteracting the logit drift that produced this large value. The other logits for token 3 receive much smaller gradients, proportional to their much smaller softmax probabilities. This numerical trace confirms the theoretical properties we derived: the corrective pressure is both scale-proportional and routing-probability-weighted.