Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 15

Router Z-Loss: Controlling Logit Scale, Not Expert Balance

Recommended resources

Hello. So far in this module, the router has had two distinct jobs: assign tokens to experts and produce weights for combining their outputs. The load-balancing loss you just studied addresses where tokens go. This lesson adds a different safeguard, router z-loss, which acts on the raw scores the router produces before softmax or top- selection.

By the end, you will be able to add z-loss to your small MoE implementation and explain a crucial distinction: keeping router computations numerically well behaved does not, by itself, distribute tokens evenly across experts. Allow about 40 minutes, including the short video, reading, and code walkthrough.


Why a functioning router can still become unstable

For one token, let be the router logit for expert . Softmax turns the logits into probabilities, and top- uses those probabilities to choose experts. A property of softmax is that adding the same constant to every logit leaves its probabilities unchanged. Thus the router can produce increasingly large raw values without necessarily changing a single routing decision.

Watch the following explanation for the distinction between that logit drift and the protection offered by a numerically stable softmax.

Mixture of Experts (MoE), Visually Explained

Watch “Mixture of Experts (MoE), Visually Explained” by Jia-Bin Huang for a visual account of softmax shift invariance and the motivation for router z-loss.

Watch logit drift for the common-shift argument and the limits of safe softmax. Then watch the z-loss idea for the proposed regularizer. Focus on adding a constant to all logits, not multiplying them: multiplication generally changes softmax probabilities.

Stable softmax remains essential: subtracting the largest logit before exponentiation prevents a common forward-pass overflow. It does not stop the model from producing large logits, nor does it repair probabilities that have become nearly zero or one because the differences between logits are extreme. These are related but distinct issues.

There is also a nuance in the video’s description of z-loss: its gradients do not generally leave routing probabilities unchanged. Z-loss can change relative logits during optimization. Its purpose is stability, not preservation of an exact probability distribution.



What z-loss measures

The ST-MoE paper introduces z-loss as a penalty on router logits and discusses why controlling their magnitude matters, particularly around lower-precision computation. Read its formulation and the short precision discussion before implementing it.

st-moe: designing stable and transferable sparse expert models - arXiv

Read the ST-MoE paper’s definition of router z-loss and its explanation of the numerical problem it targets.

On p. 7, in Section 3.3, “Stability and Quality Tradeoffs When Constraining Activations and Gradients,” begin at “Next, we study constraints on the logits going into the router.” Read the definition, including Equation 5. On p. 8, in Section 3.4, find the paragraph beginning “Sparse expert models introduce additional exponential functions” and read the precision rationale. Focus on why the loss is applied to logits entering the router, rather than to selected expert outputs.

Suppose a flattened batch contains tokens and experts. Let have shape , with the raw, unmasked router logit for token and expert . Define each token’s log-partition value and the batch z-loss as

The log-partition value is a smooth approximation to the largest logit:

Squaring makes the penalty nonnegative and pushes toward zero, whether it starts positive or negative. The coefficient used in training controls how much that pressure matters relative to the task loss.

The gradient makes the mechanism more precise. If is the full-softmax probability, then

Every expert logit can receive a z-loss gradient, including an expert excluded by hard top- selection. When is positive, a logit with higher probability receives a larger downward push from this term; when is negative, the direction reverses. Because those pushes differ across experts, z-loss can alter probability gaps. It is not merely a harmless post-processing shift.

The important limit: z-loss controls the log-partition value, not every individual logit’s absolute magnitude or the number of tokens assigned to each expert.



A router can have zero z-loss and terrible balance

Consider eight identical tokens, four experts, and top-1 routing. Give every token logits

Expert 0 receives every token. The log-partition value is approximately , so each token contributes about to z-loss.

Now subtract from all four logits for each token. Their softmax probabilities and top-1 selections remain exactly the same, but their new log-partition value is zero. All eight tokens still go to expert 0, while z-loss is zero. With a larger initial gap, the same construction produces even sharper routing and very negative losing logits while maintaining zero z-loss.

This is why the two auxiliary objectives have separate roles:

Objective Directly measures Failure it is designed to address
Load-balancing loss Assignment fractions and router probabilities across experts Skewed expert utilization
Router z-loss Squared log-partition values of raw router logits Uncontrolled router-logit scale

The objectives can interact during training, but neither guarantees the other’s result. In particular, z-loss does not enforce soft routing or prevent expert collapse. Conversely, evenly spread assignments do not establish that router logits are numerically well behaved.



Add z-loss to the small router

Keep the z-loss calculation on the full vector of raw expert logits, before softmax, top-, or any capacity-related masking. PyTorch’s logsumexp computes the expression stably; explicitly exponentiating and summing logits would reintroduce the overflow risk you are trying to manage.

import torch
import torch.nn.functional as F

def router_z_loss(router_logits: torch.Tensor) -> torch.Tensor:
    """Raw router_logits has shape [tokens, experts]."""
    if router_logits.ndim != 2 or router_logits.shape[0] == 0:
        raise ValueError("Expected a nonempty [tokens, experts] tensor")

    logits_for_loss = router_logits.float()
    log_partition = torch.logsumexp(logits_for_loss, dim=-1)
    return log_partition.square().mean()


# At the routing site of an existing sparse layer:
logits = router(flat_tokens)                  # [tokens, experts]
z_loss = router_z_loss(logits)                # scalar
probabilities = F.softmax(logits.float(), dim=-1)
gate_weights, expert_indices = probabilities.topk(k, dim=-1)

This snippet keeps the existing gate-weight convention: gate_weights are full-softmax probabilities of the selected experts. If your layer instead renormalizes selected weights to sum to one, do that after topk; it does not change where z-loss is computed.

Add the scalar to the training objective alongside the balancing term already present in your implementation:

In code, the addition is simply total_loss = task_loss + alpha_balance * balance_loss + alpha_z * z_loss. Do not detach z_loss: its gradient must reach the router. The z-loss term can still provide a router gradient under renormalized top-1 gating, where the selected gate becomes exactly one and the task loss may provide no gradient through that gate weight. That additional gradient is not a substitute for a load-balancing signal.

The .float() cast makes the loss calculation float32, but it cannot recover precision already lost if logits were produced in a lower-precision operation. Keep track of the precision at which your router projection and probability calculation actually run.

Here is a compact check of the central distinction. It verifies that a common shift removes z-loss without changing either probabilities or assignments:

row = torch.tensor([[4.0, 0.0, 0.0, 0.0]])
shifted = row - torch.logsumexp(row, dim=-1, keepdim=True)

torch.testing.assert_close(
    F.softmax(row, dim=-1),
    F.softmax(shifted, dim=-1),
)
assert row.argmax(dim=-1).item() == shifted.argmax(dim=-1).item()
assert torch.allclose(router_z_loss(shifted), torch.zeros(()), atol=1e-6)

print("Original z-loss:", router_z_loss(row).item())
print("Shifted z-loss:", router_z_loss(shifted).item())


Interpret the training traces carefully

Track z-loss and a logit-scale diagnostic alongside assignment counts. The provided plot illustrates why: its stronger z-loss settings have lower observed maximum absolute logits over this run.

Example training curves showing the maximum absolute router logit over 100 steps for no z-loss and two z-loss coefficients. They illustrate an observed scale reduction, not a guarantee of balanced routing or a bound on every logit.

The plot and the counterexample answer different questions. A lower maximum absolute logit is useful evidence about this run; the mathematical z-loss objective alone does not guarantee that metric will always fall. Neither metric reports expert utilization. To distinguish failures, inspect assignment fractions for imbalance, log-partition values and logits for drift, and the task loss for whether the intervention is helping training.



Takeaways

Router z-loss is the mean squared logsumexp of raw logits across all experts, computed before sparse selection and added to the task objective with its own coefficient. It supplies a differentiable stability pressure, but a router can achieve zero z-loss while sending every token to one expert. Keep the load-balancing loss and utilization measurements for that separate problem.

Next, you will put routing under a capacity limit: even with sensible auxiliary losses, a finite expert buffer needs an explicit policy for assignments that overflow it.