Add the z-loss auxiliary term to cross-entropy

Why it matters z-loss is a cheap stabiliser used in large training runs and in mixture-of-experts routers.

Large-scale training can drift into huge logits even when the loss looks fine. The z-loss used in PaLM adds a small penalty on log Z, the log of the softmax normaliser, to keep it near 0.

Write ce_with_z_loss(logits, targets, z_coef=1e-4). logits is (n, V), targets is length n. Compute log Z per row with a stable logsumexp. ce = mean(log Z - logits[row, target]), z = z_coef * mean(log Z ** 2). Return the tuple (ce, z, ce + z) as floats.

Signaturedef ce_with_z_loss(logits, targets, z_coef=1e-4)

Example

ce_with_z_loss([[0, 0]], [0]) is about (0.693147, 4.8045e-05, 0.693195).

Understand the idea

Softmax does not care if you add the same number to every logit, so logits can drift upward together with no change in the loss. Very large logits then cause numerical trouble in low precision. The z-loss gently pulls log Z, the log of the softmax denominator, toward zero, like a spring tied to the origin.

Example: logits [0, 0] and target 0. Z = e^0 + e^0 = 2, log Z = 0.693. Cross-entropy = 0.693 - 0 = 0.693. z-loss = 1e-4 * 0.693^2 = 0.000048. The total barely changes, but over long training the gradient keeps log Z small.

Rule: log Z_i = logsumexp(logits_i); CE = mean(log Z_i - logit_i[target]); z = c * mean((log Z_i)^2).

PaLM used a coefficient of 1e-4. The same idea is applied to mixture-of-experts router logits to stop them from exploding.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: examplece_with_z_loss([[0.0, 0.0]], [0])
  • Sample 2: two rowsce_with_z_loss([[2.0, 0.0, -1.0], [-3.0, -3.0, -3.0]], [0, 2], 0.01)
  • Test 3: huge logitsce_with_z_loss([[1000.0, 0.0]], [1], 1e-4)