Why “numerically stable” softmax is not enough
For logits , the textbook definition divides one exponential by the sum of all exponentials. If any logit exceeds roughly 88 in fp32, the numerator overflows before the division can rescue it. Frameworks therefore subtract the largest logit first:
The shift protects the exponent range. It does not protect the other end of floating point. Suppose the model is correct and confident, so the target logit is the largest one. Define the logit margin as how far the target sits above the log-sum-exp of every other class:
After shifting by , the target slot is exactly 0 and every other slot is negative. The denominator becomes a sum of one large term and a collection of tiny ones:
Floating-point precision is relative. Near 0, fp32 can represent values as small as about ; near 1, the spacing between adjacent values is about . Once is smaller than half that spacing, adding it to 1.0 changes nothing. The denominator rounds to exactly 1.0, and the information that the target was only *almost* certain disappears.
Bug 1: Softmax Collapse
For hard-target cross-entropy, the loss is and the gradient is , where is the softmax vector. The target entry has two algebraically equal forms that behave completely differently in floating point:
The standard code computes . Past the cliff, that division returns exactly 1.0. Subtracting the one-hot target gives exactly 0.0. The non-target gradients are computed from directly, so they never pass through the “add 1” step and remain positive all the way down to exponent underflow near . The result is an asymmetric gradient:
This is not a hypothetical edge case. The paper’s fp32 example uses with target 0, which gives a margin of about 17.3, just past the fp32 cliff. The standard JAX/Optax path returns a loss of 0.0 and gradients . The fixed path returns a loss of and gradients .
| Quantity | Standard | Fixed |
|---|---|---|
| Loss | 0.0 | 3.046 × 10⁻⁸ |
| log q_t | 0.0 | −3.046 × 10⁻⁸ |
| g_t | 0.0 | −3.046 × 10⁻⁸ |
| g₁ = g₂ | 1.523 × 10⁻⁸ | 1.523 × 10⁻⁸ |
| Σ g | 3.046 × 10⁻⁸ | 0.0 |
The same collapse affects standalone and . The maximum entry is shifted to 0, so its exponential is 1; once the denominator rounds to 1, the backward pass treats the maximum probability as exactly 1 and zeroes its gradient while every other entry keeps a positive gradient. A model can therefore look perfectly confident and still receive a non-zero, non-conservative update.
Why optimizers care: the Slingshot mechanism
A zero target gradient is not harmless, because Adam and AdamW do not use the raw gradient directly. They divide by a running estimate of its magnitude. In AdamW, the update is
After a network memorizes its training set, the target margins keep growing. Once every example in a batch crosses the cliff, the target gradients vanish and the parameter gradients nearly vanish with them. The second-moment estimate decays toward zero. Weight decay, or the leftover non-target gradients, eventually pulls a few examples back below the cliff. Their target gradients switch on again and are divided by , which is now tiny. The optimizer takes a huge step, the loss spikes, resets, and the cycle repeats. This is the Slingshot Mechanism described by Thilak et al. in 2022.
With the fixed gradient, shrinks smoothly instead of snapping to zero. The first and second moments decay together, so there is no cliff for the optimizer to fall off. The paper reports that fixed cross-entropy removes the spikes, groks faster with weight decay, and prevents accuracy collapse without it. On with weight decay, standard fp32 cross-entropy reached test accuracy while the fixed version reached . On without weight decay, a single fp32 spike dropped standard accuracy from 61% to 23%; the fixed version continued to 85%.
The paper also explains where the margin settles once the cliff is gone. At a stationary point of AdamW, the normalized gradient balances weight decay. After memorization, the gradient magnitude shrinks like . While the normalized step has magnitude about 1; once it shrinks like . Setting the update to zero gives:
That coincidence is the cleanest explanation of why default fp32 training is vulnerable. The optimizer is trying to settle about 1.8 nats past the point where the loss function stops reporting the target gradient. Raise ε to and the equilibrium drops to 16.1, below the cliff, so the standard implementation settles quietly. Lower ε to and the equilibrium rises to 36.8, past the fp64 cliff at 36.7, so even fp64 breaks.
Bug 2: Softmax Cancellation
Distillation replaces the one-hot target with a teacher distribution . The loss and its exact gradient are still simple:
Standard implementations compute and separately and subtract them in probability space. That is the problem. As the student approaches the teacher, the information about their difference lives in the logit difference , not in the probabilities. Both and round to nearly the same vector, and subtracting two nearly equal vectors destroys the significant digits that encoded the difference.
There is a second, quieter mismatch. The forward pass computes the teacher probabilities with . The backward pass computes the student probabilities as . Those are slightly different sequences of operations, so even when exactly, and do not match to machine precision. The computed gradient at an exact tie is not zero. Adam sees any residual larger than ε as a real direction and normalizes it into a full-size step.
The paper’s fp32 example starts from teacher logits and perturbs the student by . The standard gradient shrinks one entry by about 3×, flips the sign of another, and fails to sum to zero. The fixed gradient matches the fp64 reference to every printed digit:
| Entry | Standard | Fixed | fp64 reference |
|---|---|---|---|
| g[0] | −5.960464 × 10⁻⁸ | −4.595504 × 10⁻⁸ | −4.595504 × 10⁻⁸ |
| g[1] | 1.451589 × 10⁻⁸ | 4.144190 × 10⁻⁸ | 4.144190 × 10⁻⁸ |
| g[2] | −1.123343 × 10⁻⁹ | 4.513142 × 10⁻⁹ | 4.513142 × 10⁻⁹ |
| Σ g | −4.621 × 10⁻⁸ | 0.0 | 0.0 |
The fix: keep the small term in the numerator
The fix is structural rather than a higher-precision cast. For and , only the largest logit is shifted to zero. Instead of including its in the denominator, exclude the argmax from the log-sum-exp, compute the margin from the remaining logits, and combine the two pieces with a stable softplus:
For hard-target cross-entropy, the target index replaces the argmax. There is no need to compute a maximum at all:
That last sentence is the whole trick. Because appears only inside differences, autodiff computes the target gradient as the negative sum of the non-target gradients:
Here is the paper’s JAX implementation. The same structure translates directly to PyTorch with torch.logsumexp, torch.nn.functional.softplus, torch.expm1 and torch.log1p.
import jax
import jax.numpy as jnp
def log_softmax(z):
i_max = jnp.argmax(z, axis=-1)
z_max = jnp.take_along_axis(z, i_max[..., None], axis=-1)
is_max = jax.nn.one_hot(i_max, z.shape[-1], dtype=bool)
shifted = jnp.where(is_max, 0.0, z - z_max) # exact 0 at the argmax
others = jnp.where(is_max, -jnp.inf, shifted) # exclude it from the sum
margin = -jax.nn.logsumexp(others, axis=-1, keepdims=True)
return shifted - jax.nn.softplus(-margin)
softmax = lambda z: jnp.exp(log_softmax(z))
def cross_entropy(z, target):
z_t = jnp.take_along_axis(z, target[..., None], axis=-1)
is_t = jax.nn.one_hot(target, z.shape[-1], dtype=bool)
others = jnp.where(is_t, -jnp.inf, z - z_t) # exclude the target
margin = -jax.nn.logsumexp(others, axis=-1)
return jax.nn.softplus(-margin) # log(1 + exp(-margin))Soft targets need log-space subtraction
For distillation, pass the raw teacher logits instead of precomputed probabilities. Let , center it under the teacher distribution, and compute the log-ratio and the difference without ever forming directly:
At , every term is zero: , , and . As the student approaches the teacher, the formula keeps working in the region where the logit difference is still representable, instead of rounding both probabilities to the same vector and subtracting them.
def soft_target_cross_entropy(z_s, z_t):
log_q = log_softmax(z_s)
q, p = jnp.exp(log_q), softmax(z_t)
delta = z_s - z_t
d = delta - jnp.sum(p * delta, axis=-1, keepdims=True) # center under p
s = d - jnp.log1p(jnp.sum(p * jnp.expm1(d), axis=-1, keepdims=True))
u = p * jnp.expm1(s) # q - p in log space
g = u - q * jnp.sum(u, axis=-1, keepdims=True) # force sum(g) = 0
sg = jax.lax.stop_gradient
loss = -jnp.sum(p * sg(log_q), axis=-1)
return loss + jnp.sum(sg(g) * (z_s - sg(z_s)), axis=-1) # custom backward passThe forward loss is still the ordinary cross-entropy. The stop_gradient trick supplies the accurate gradient in the backward pass without changing the value the model reports. The cost is a handful of extra elementwise operations, no fp64 cast, and no change to the forward semantics.
Experiment: watch the cliff appear
The panel below reproduces both failures in your browser. Every arithmetic operation is rounded to the selected format, including the exponentials, the sums and the divisions. Switch between hard targets and distillation, then move the slider. The fp64 reference uses the same rounded logits, so the comparison isolates the algorithm rather than the input quantization.
Watch the precision cliff appear
All arithmetic below is rounded after every operation to the selected format. The fp64 reference uses the same logits, so the only difference is the algorithm.
| Quantity | Standard | Fixed | fp64 reference |
|---|---|---|---|
| Loss | 0 | 1.021e-8 | 1.021e-8 |
| qt | 1 | 1 | 1 |
| gt | 0 | -1.021e-8 | -1.021e-8 |
| gother | 5.104e-9 | 5.104e-9 | 5.104e-9 |
| Σ g | +1.021e-8 | 0 | 0 |
The standard curve falls off a vertical cliff at the format's precision limit. The fixed curve keeps shrinking smoothly until exponent underflow near m ≈ 88. The y-axis is logarithmic, so one grid step is a factor of 10.
Four runs are worth doing in order. First, set fp32 and move the margin from 16.0 to 17.0: the standard target gradient drops from about to exactly zero in one step, while the fixed form continues smoothly. Second, switch to bf16 at the same margin and note that the cliff moved all the way down to 5.5. Third, open the distillation tab, set ε to and compare the standard, fixed and reference gradients entry by entry. Fourth, drag ε toward and watch the standard curve flatten at a noise floor while the fixed curve follows the reference to zero.
Audit your own stack
You do not need to replace every softmax call. Start where confidence is high or where two distributions start equal, and check the gradient rather than only the loss.
- Print the sum of the cross-entropy gradient over the class dimension. It should be zero to within a few ulps. A persistent positive sum is the signature of a collapsed target gradient.
- Run a synthetic batch with logits [30, 0, 0] and target 0 in bf16 and fp32. Compare the target gradient with an fp64 reference. If the low-precision run returns exactly zero while the reference is non-zero, you have found the cliff.
- For distillation, initialize the student from the teacher and check that the gradient is exactly zero before the first step. If it is not, the implementation is subtracting probabilities instead of logits.
- For KL-regularized RL, check the policy gradient at the first step, where the policy and reference model are identical. The same cancellation applies.
- Log the mean target margin during training. If it approaches 5.5 in bf16 or 16.6 in fp32, the loss is close to the cliff even if the loss curve looks flat.
- Prefer logits over probabilities at module boundaries. A function that accepts p = softmax(z_T) has already thrown away the information the fixed gradient needs.
- Use torch.logsumexp, jax.nn.logsumexp, tf.math.reduce_logsumexp and the corresponding softplus, expm1 and log1p primitives. Do not hand-roll log(1 + x) when log1p exists.
| Setting | What to check | Why it matters |
|---|---|---|
| Hard-label classification | Gradient sum and target margin in the loss dtype | The target gradient can be zero while non-target gradients remain |
| Knowledge distillation | Gradient at an exact student–teacher tie | Cancellation produces a noise floor instead of zero |
| KL / RLHF regularization | First-step gradient against the reference model | Policy and reference start identical |
| Low-precision training | Whether the loss is computed in bf16 or upcast to fp32 | Upcasting moves the cliff from 5.5 to 16.6; it does not remove it |
| AdamW with weight decay | The relationship between ε and the observed margin | The equilibrium is m* ≈ log(1/ε) |
A final caution: a numerically correct gradient is not a substitute for a well-designed objective. The fix removes a silent asymmetry, but it does not make an unstable learning rate, a bad initialization or a mismatched distillation temperature disappear. Treat the gradient-sum check as a diagnostic, not as a guarantee that the training run is healthy.
Frequently asked questions
- What is Softmax Collapse?
- Softmax Collapse is the failure mode in which the target logit is so much larger than the others that the shifted denominator 1 + e^(−m) rounds to exactly 1.0. The target probability rounds to 1.0, the target gradient q_t − 1 rounds to 0.0, and the non-target gradients remain non-zero. The gradient therefore no longer sums to zero.
- What is the softmax precision cliff?
- It is the margin at which e^(−m) becomes too small to change 1.0 in a given floating-point format. It is about 5.5 in bf16, 16.6 in fp32 and 36.7 in fp64. The cliff comes from the spacing of representable numbers near 1.0, not from the exponent range.
- Is the standard max-shift softmax implementation wrong?
- It is correct in real arithmetic and still the right way to prevent overflow. The bug is in how the shifted expression is evaluated in floating point: adding a tiny e^(−m) to 1.0 loses the term, and computing q_t − 1 loses the target gradient. The fix keeps the same forward value but changes the operation order.
- Does this affect ordinary training or only grokking experiments?
- The most extreme margins in the paper come from small grokking tasks, and the authors are explicit that this is not a hidden cause of frontier-scale instability. But the bf16 cliff is at a probability of about 0.996, which confident classifiers, reward models and token predictors do reach, and distillation or KL regularization starts at an exact tie where cancellation is immediate.
- How is this different from StableMax or zero-sum gradient projection?
- StableMax replaces exp with a different function, which changes the loss and lets margins grow into the thousands. Zero-sum projection fixes the symptom after the target gradient has already collapsed. The Barron et al. fix keeps the same cross-entropy value and changes the computation so the target gradient is derived from pairwise logit differences and the zero-sum property holds by construction.
- What does the fix cost?
- A handful of extra elementwise operations and one extra log-sum-exp, with no fp64 cast and no change to the forward loss. The paper reports no meaningful slowdown and argues the fixed functions are reasonable defaults for frameworks to adopt.
Further reading
Start with primary reports and documentation. Community discussions are discovery leads, not evidence on their own.
- Barron, Gnanapragasam & Tschannen — A Fix for Softmax and Cross-Entropy (arXiv:2610.31642)
- Paper HTML with full equations and JAX implementations
- Project page for A Fix for Softmax and Cross-Entropy
- PyTorch documentation: CrossEntropyLoss
- JAX documentation: jax.nn.softmax and log_softmax
- Thilak et al. — The Slingshot Mechanism (arXiv:2206.04817)
- Prieto et al. — Grokking at the Edge of Numerical Stability (ICLR 2025)
- Hinton, Vinyals & Dean — Distilling the Knowledge in a Neural Network (arXiv:1503.02531)