betaFeedback

WorksComputer Science

A Fix for Softmax and Cross-Entropy

Abstract

Standard implementations of softmax, log-softmax, and cross-entropy have two numerical bugs. The first bug, Softmax Collapse, rounds the target logit's gradient to zero if that one logit is much larger than the others, resulting in gradients that no longer sum to zero. The second bug, Softmax Cancellation, occurs when student logits are close to teacher logits, and produces non-zero gradients even when the student and teacher logits are equal. We present simple implementations of log-softmax, softmax, and cross-entropy that fix both bugs. Our fix eliminates the previously observed "slingshot" phenomenon, speeds up grokking with weight decay, prevents accuracy collapse without weight decay, stops student networks from drifting away from the teacher during distillation, and shows that after memorization, logit growth is bounded by an equilibrium between weight decay and Adam's εε hyperparameter.

Introduction

Naively computing softmax or cross-entropy on logits z∈RK\mathbf{z} \in\mathbb{R}^{K} as ezk/∑jezje^{z_k} / \sum_j e^{z_j} overflows if any logit exceeds the floating-point exponent limit (≈88\approx88 in fp32), which is why standard implementations in all deep learning frameworks (JAX, PyTorch, TensorFlow, etc.) shift the input logits by subtracting their maximum value zmax⁡=max⁡jzjz_{\max} = \max_j z_j [4, 1]:

z~k=zk−zmax⁡,logsoftmax⁡(z)k=z~k−log⁡∑jez~j,qk=softmax⁡(z)k=ez~k∑jez~j(1)\tilde{z}_k = z_k - z_{\max}, \qquad\operatorname{logsoftmax}(\mathbf{z})_k = \tilde{z}_k - \log\sum_j e^{\tilde{z}_j}, \qquad q_k = \operatorname{softmax}(\mathbf{z})_k = \frac{e^{\tilde{z}_k}}{\sum_j e^{\tilde{z}_j}} \tag*{(1)}

For a target distribution p∈ΔK−1\mathbf{p} \in\Delta^{K-1}, cross-entropy (CE) is L(z,p)=−∑kpklogsoftmax⁡(z)k\mathcal{L}(\mathbf{z}, \mathbf{p}) = -\sum_k p_k \operatorname{logsoftmax}(\mathbf{z})_k, with exact gradient g=∇zL(z,p)=q−p\mathbf{g} = \nabla_{\mathbf{z}}\mathcal{L}(\mathbf{z}, \mathbf{p}) = \mathbf{q} - \mathbf{p}. Though subtracting zmax⁡z_{\max} prevents overflow, two numerical bugs remain.

The first bug, identified by Prieto et al. [15] as Softmax Collapse (Figure 1a), occurs when a model correctly predicts the target class t∈{1,…,K}t \in\{1,\ldots,K\} with high confidence, so that zt=zmax⁡z_t = z_{\max} is much larger than all non-target logits zjz_j (j≠tj \ne t). We measure this confidence by the logit margin, which is how much larger the target logit is than the log-sum-exp of all non-target logits:

Two bugs in standard softmax and cross-entropy

Figure 1. The two bugs in standard softmax and cross-entropy. (a) Softmax Collapse: As a model becomes more confident in the correct class (thereby increasing the logit margin mm), the true gradient on the target logit shrinks exponentially, but standard implementations incorrectly round that gradient to zero once mm crosses a precision cliff (≈5.5\approx5.5 in bf16, 16.6 in fp32, and 36.7 in fp64). (b) Softmax Cancellation: In soft-target distillation, as student logits zS\mathbf{z}_{S} approach teacher logits zT\mathbf{z}_{T}, the true gradient shrinks toward zero, but standard implementations lose precision and plateau at a non-zero noise floor. Our fix eliminates both bugs and yields accurate gradients across all precisions.

m=zt−log⁡∑j≠tezj.(2)m = z_t - \log\sum_{j \ne t} e^{z_j}. \tag*{(2)}

In Equation (1), subtracting zmax⁡=ztz_{\max} = z_t sets the shifted target logit to z~t=0\tilde{z}_t = 0 (so ez~t=1e^{\tilde{z}_t} = 1 in the denominator), while the K−1K-1 non-target exponentials sum to a small positive number e−m=∑j≠tezj−zt≪1e^{-m} = \sum_{j \ne t} e^{z_j-z_t} \ll1. Floating-point numbers have much finer precision near 0 than near 1: in fp32, values near 0 can be as small as ∼10−38\sim10^{-38}, whereas values added to 1.0 are lost to rounding below ∼10−7\sim10^{-7}. Because standard implementations form the denominator 1+e−m1+e^{-m} by adding e−me^{-m} to 1.0, the e−me^{-m} term is lost to rounding once the margin mm exceeds a threshold cdc_d that we will call the precision cliff (c16≈5.5c_{16} \approx5.5 in bf16, c32≈16.6c_{32} \approx16.6 in fp32, and c64≈36.7c_{64} \approx36.7 in fp64). When m>cdm > c_d, the denominator 1+e−m1+e^{-m} evaluates to exactly 1.0, which causes qt=1/(1+e−m)q_t = 1/(1+e^{-m}) to evaluate to 1.0 and zeroes out both the loss and the target gradient g~t=qt−1=0.0\tilde{g}_t = q_t-1 = 0.0. However, the non-target gradients g~j=qj=ezj−zt/(1+e−m)\tilde{g}_j = q_j = e^{z_j-z_t}/(1+e^{-m}) (j≠tj \ne t) are evaluated near 0 without adding 1.0 to their numerators, so they remain positive down to exponent underflow (m≈88m \approx88). Because the target gradient rounds to 0.0 while the non-target gradients do not, the gradients no longer sum to zero (∑kg~k>0\sum_k \tilde{g}_k > 0). When training with adaptive optimizers such as Adam and AdamW ([6, 9]), which normalize each gradient by a moving average of its magnitude, this asymmetry causes the recurring “slingshot” loss spikes ([19, 8]) and stalls grokking ([15]). While prior works used surrogate losses ([15]), gradient projection ([8]), or fp64 casting ([13, 21]) to ameliorate these issues, we instead fix log-softmax, softmax, and cross-entropy directly (§ 2).

The second bug, which we will call Softmax Cancellation (Figure 1b), occurs in knowledge distillation (Hinton et al. [5]) and KL regularization, where the target p=softmax⁡(zT)\mathbf{p} = \operatorname{softmax}(\mathbf{z}_T) comes from teacher logits zT\mathbf{z}_T. Standard implementations compute q=softmax⁡(zS)\mathbf{q} = \operatorname{softmax}(\mathbf{z}_S) and p=softmax⁡(zT)\mathbf{p} = \operatorname{softmax}(\mathbf{z}_T) separately and subtract them to get g~=q−p\tilde{\mathbf{g}} = \mathbf{q}-\mathbf{p}. When zS\mathbf{z}_S is close to zT\mathbf{z}_T, subtracting these nearly equal probabilities loses precision, and slight differences between the forward-pass softmax and backward-pass log-softmax formulas leave a non-zero gradient even when zS=zT\mathbf{z}_S = \mathbf{z}_T. We fix this by computing q−p\mathbf{q}-\mathbf{p} directly from zS−zT\mathbf{z}_S-\mathbf{z}_T in log space (§ 3).

Softmax Collapse

When the target logit zt=zmax⁡z_t = z_{\max} is the largest logit, shifting by zmax⁡z_{\max} in Equation (1) sets z~t=0\tilde{z}_t = 0 and z~j=zj−zt<0\tilde{z}_j = z_j-z_t < 0 for j≠tj \ne t, so the denominator is ∑iez~i=1+∑j≠tezj−zt=1+e−m\sum_i e^{\tilde{z}_i} = 1+\sum_{j \ne t}e^{z_j-z_t} = 1+e^{-m}. Mathematically, the hard-target loss is L(z,t)=−logsoftmax⁡(z)t=log⁡(1+e−m)\mathcal{L}(\mathbf{z},t)=-\operatorname{logsoftmax}(\mathbf{z})_t=\log(1+e^{-m}), with gradients

gt=11+e−m−1⏟Standard=−e−m1+e−m⏟Fixed,gj=ezj−zt1+e−mfor j≠t,(3)g_t = \underbrace{\frac{1}{1+e^{-m}}-1}_{\text{Standard}} = \underbrace{-\frac{e^{-m}}{1+e^{-m}}}_{\text{Fixed}}, \qquad g_j = \frac{e^{z_j-z_t}}{1+e^{-m}} \quad\text{for } j \ne t, \tag*{(3)}

which sum to zero (∑kgk=0\sum_k g_k = 0). In floating point, however, the two expressions for gtg_t in Equation (3) behave very differently once m>cdm > c_d, where e−me^{-m} is too small to change 1.0 when added to it (Figure 1a). Standard implementations form the denominator 1+e−m1+e^{-m}, which rounds to 1 when m>cdm > c_d ([15]). In the forward pass, log⁡(1+e−m)\log(1+e^{-m}) evaluates to log⁡(1)=0\log(1)=0, so both logsoftmax⁡(z)t\operatorname{logsoftmax}(\mathbf{z})_t and L(z,t)\mathcal{L}(\mathbf{z},t) round to zero. In the backward pass, standard implementations compute qt=1/(1+e−m)=1q_t=1/(1+e^{-m})=1 and subtract 1 to get g~t=qt−1=0\tilde{g}_t=q_t-1=0. In contrast, our fixed expression −e−m/(1+e−m)-e^{-m}/(1+e^{-m}) keeps e−me^{-m} in the numerator: even when the denominator 1+e−m1+e^{-m} rounds to 1.0, dividing −e−m-e^{-m} by 1.0 preserves gt≈−e−mg_t \approx-e^{-m} down to exponent underflow (m≈88m \approx88).

While g~t\tilde{g}_t rounds to zero when m>cdm > c_d, the non-target gradients do not. For each non-target class j≠tj \ne t, standard cross-entropy computes g~j=qj=ezj−zt/(1+e−m)\tilde{g}_j=q_j=e^{z_j-z_t}/(1+e^{-m}). Because the numerator ezj−zte^{z_j-z_t} is evaluated directly from zj−zt<0z_j-z_t<0 without adding 1, it remains accurate down to exponent underflow while the denominator rounds to 1. When m>cdm>c_d, standard cross-entropy zeroes out only the target entry tt while all K−1K-1 non-target gradients remain positive ([8]):

g~k=1[k≠t]gk,∑kg~k=−gt=e−m1+e−m>0for m>cd.(4)\tilde{g}_k = \mathbb{1}[k \ne t]g_k,\qquad\sum_k \tilde{g}_k = -g_t = \frac{e^{-m}}{1+e^{-m}} > 0 \quad\text{for } m > c_d. \tag*{(4)}

The same bug affects standalone softmax(z)(\mathbf{z}) ([16]): once m>cdm > c_d, its backward pass rounds qimax⁡q_{i_{\max}} (imax⁡=arg⁡max⁡izii_{\max} = \arg\max_i z_i) to 1 and zeroes g~imax⁡\tilde{g}_{i_{\max}} while the other gradients stay non-zero.

This bug can be fixed by never adding 1 to e−me^{-m} directly. In logsoftmax⁡(z)\operatorname{logsoftmax}(\mathbf{z}) and softmax⁡(z)\operatorname{softmax}(\mathbf{z}), only the largest logit zimax⁡z_{i_{\max}} is shifted to 0 (where e0=1e^0 = 1 in the denominator). Instead of including e0=1e^0 = 1 in the sum of exponentials, we set z~imax⁡=0\tilde{z}_{i_{\max}} = 0, compute the margin mm by excluding imax⁡i_{\max} from the log-sum-exp ([1]), and combine them with a numerically stable softplus⁡(x)=log⁡(1+ex)\operatorname{softplus}(x) = \log(1 + e^x) (with softmax⁡(z)k=exp⁡(logsoftmax⁡(z)k)\operatorname{softmax}(\mathbf{z})_k = \exp(\operatorname{logsoftmax}(\mathbf{z})_k)):

z~k=1[k≠imax⁡](zk−zimax⁡),m=−LSE⁡j≠imax⁡z~j,logsoftmax⁡(z)k=z~k−softplus⁡(−m).(5)\tilde{z}_k = \mathbf{1}[k \ne i_{\max}](z_k - z_{i_{\max}}), \quad m = -\operatorname{LSE}_{j \ne i_{\max}} \tilde{z}_j, \quad\operatorname{logsoftmax}(\mathbf{z})_k = \tilde{z}_k - \operatorname{softplus}(-m). \tag*{(5)}

For hard-target cross-entropy with target tt, we can use tt directly in place of imax⁡i_{\max} without an arg max:

m=−LSE⁡j≠t(zj−zt),L(z,t)=log⁡(1+e−m)=softplus⁡(−m).(6)m = -\operatorname{LSE}_{j \ne t}(z_j - z_t), \quad\mathcal{L}(\mathbf{z}, t) = \log(1 + e^{-m}) = \operatorname{softplus}(-m). \tag*{(6)}

Because the tt-th slot is replaced with the constant 0 rather than zt−ztz_t - z_t, ztz_t only appears in L\mathcal{L} through the K−1K - 1 differences zj−ztz_j - z_t (j≠tj \ne t), so autodiff correctly computes the target gradient as the negated sum of the non-target gradients:

gj=ezj−zt−L=ezj−zt1+e−mfor j≠t,gt=−∑j≠tgj=−e−m1+e−m.(7)g_j = e^{z_j-z_t-\mathcal{L}} = \frac{e^{z_j-z_t}}{1 + e^{-m}} \quad\text{for } j \ne t, \qquad g_t = -\sum_{j \ne t} g_j = -\frac{e^{-m}}{1 + e^{-m}}. \tag*{(7)}

Here is a JAX implementation of log-softmax, softmax, and hard-target cross-entropy, which evaluates log⁡(1+e−m)\log(1 + e^{-m}) via log1p, remains accurate down to exponent underflow, and satisfies ∑kgk=0\sum_k g_k = 0:

import jax, jax.numpy as jnp, optax

def log_softmax(z):
    i_max = jnp.argmax(z, axis=-1)
    z_max = jnp.take_along_axis(z, i_max[..., None], axis=-1) # Max logit.
    is_max = jax.nn.one_hot(i_max, z.shape[-1], dtype=bool) # Max mask.
    shifted = jnp.where(is_max, 0.0, z - z_max) # Exact 0 at argmax.
    exp_others = jnp.where(is_max, 0.0, jnp.exp(shifted)) # Non-max exp.
    s = jnp.sum(exp_others, axis=-1, keepdims=True) # Sum non-max exp.
    return shifted - jnp.log1p(s) # log_softmax(z).

softmax = lambda z: jnp.exp(log_softmax(z))

def cross_entropy(z, t):
    z_t = jnp.take_along_axis(z, t[..., None], axis=-1) # Target logit.
    is_t = jax.nn.one_hot(t, z.shape[-1], dtype=bool) # Target mask.
    shifted = jnp.where(is_t, 0.0, z - z_t) # Exact 0 at target.
    b = jnp.max(shifted, axis=-1, keepdims=True) # Max shift >= 0.
    s = jnp.sum(jnp.where(is_t, 0.0, jnp.exp(shifted - b)), axis=-1)
    return b[..., 0] + jnp.log1p(s + jnp.expm1(-b[..., 0])) # -log_softmax(z)_t.

As an example, consider z=[9.0,−9.0,−9.0]\mathbf{z} = [9.0, -9.0, -9.0] and t=0t = 0. The standard jax.nn and optax implementations return zero for the target log-probability, loss, and target gradient, while our functions return accurate values whose gradients sum to zero:

z, t = jnp.array([9.0, -9.0, -9.0], dtype=jnp.float32), jnp.array(0)
std_ce = optax.softmax_cross_entropy_with_integer_labels
jax.nn.log_softmax(z)                       # ->       [ 0.0,     -18.0,     -18.0       ]
jax.grad(lambda z: jax.nn.softmax(z)[0])(z) # ->       [ 0.0,      1.523e-8,  -1.523e-8]
jax.value_and_grad(std_ce)(z, t)            # -> 0.0,   [ 0.0,      1.523e-8,   1.523e-8]
log_softmax(z)                              # ->      [-3.046e-8, -18.0,     -18.0       ]
jax.grad(lambda z: softmax(z)[0])(z)        # -> [ 3.046e-8, -1.523e-8,  -1.523e-8]
jax.value_and_grad(cross_entropy)(z, t)     # -> 3.046e-8, [-3.046e-8,  1.523e-8,  1.523e-8]

Softmax Cancellation

Given student logits zS∈RK\mathbf{z}_{\mathrm{S}} \in\mathbb{R}^{K} and teacher logits zT∈RK\mathbf{z}_{\mathrm{T}} \in\mathbb{R}^{K}, standard soft-target cross-entropy computes p=softmax⁡(zT)\mathbf{p} = \operatorname{softmax}(\mathbf{z}_{\mathrm{T}}) and evaluates

L(zS,zT)=−∑kpklogsoftmax⁡(zS)k,q=softmax⁡(zS),g~k=∂L∂zS,k=qk−pk.(8)\mathcal{L}(\mathbf{z}_{\mathrm{S}}, \mathbf{z}_{\mathrm{T}}) = -\sum_k p_k \operatorname{logsoftmax}(\mathbf{z}_{\mathrm{S}})_k, \quad\mathbf{q} = \operatorname{softmax}(\mathbf{z}_{\mathrm{S}}), \quad\tilde{g}_k = \frac{\partial\mathcal{L}}{\partial z_{\mathrm{S},k}} = q_k - p_k. \tag*{(8)}

As the student logits approach the teacher logits (zS→zTz_S \to z_T), the true gradient g=q−p\mathbf{g} = \mathbf{q} - \mathbf{p} shrinks toward 00 and equals 00 when zS=zTz_S = z_T. In floating point, however, computing q\mathbf{q} and p\mathbf{p} separately and subtracting them (Equation 8) loses precision when zSz_S is close to zTz_T, because the small logit difference δ=zS−zT\delta= z_S - z_T is lost when q\mathbf{q} and p\mathbf{p} are rounded to probabilities before being subtracted (Figure 1b). Furthermore, because p=softmax⁡(zT)\mathbf{p} = \operatorname{softmax}(z_T) in the forward pass and q=exp⁡(logsoftmax⁡(zS))\mathbf{q} = \exp(\operatorname{logsoftmax}(z_S)) in the backward pass are evaluated using slightly different sequences of operations, q\mathbf{q} and p\mathbf{p} do not match to machine precision even when zS=zTz_S = z_T, leaving a non-zero gradient g~=q−p≠0\tilde{\mathbf{g}} = \mathbf{q} - \mathbf{p} \ne0.

To avoid subtracting nearly equal probabilities, we pass zTz_T directly to our loss function and compute q−p\mathbf{q} - \mathbf{p} in log space using expm1⁡(x)=ex−1\operatorname{expm1}(x) = e^x - 1 and log1p⁡(x)=log⁡(1+x)\operatorname{log1p}(x) = \log(1 + x). Given δ=zS−zT\delta= z_S - z_T, we center δ\delta under p\mathbf{p} and write the log-ratio sk=log⁡(qk/pk)s_k = \log(q_k/p_k) and difference uk=qk−pku_k = q_k - p_k as:

dk=δk−∑ipiδi,sk=dk−log⁡1p(∑ipiexpm1⁡(di)),uk=pkexpm1⁡(sk).(9)d_k = \delta_k - \sum_i p_i\delta_i,\qquad s_k = d_k - \log1p\left(\sum_i p_i\operatorname{expm1}(d_i)\right),\qquad u_k = p_k\operatorname{expm1}(s_k). \tag*{(9)}

Because ∑ipidi=0\sum_i p_i d_i = 0 and expm1⁡(x)≥x\operatorname{expm1}(x) \ge x, the input to log1p⁡\operatorname{log1p} is always non-negative. When ∣sk∣≥1\lvert s_k\rvert\ge1, we fall back to uk=qk−pku_k = q_k - p_k to avoid 0.0×∞0.0 \times\infty if pkp_k rounds to 0.00.0 while expm1⁡\operatorname{expm1} overflows, and we set gk=uk−qk∑iuig_k = u_k - q_k\sum_i u_i so that ∑kgk=0\sum_k g_k = 0. Because (9) avoids adding or subtracting 1, g\mathbf{g} remains accurate as zS→zTz_S \to z_T and is 0 when zS=zTz_S = z_T. Here is a JAX implementation of soft-target cross-entropy (using log_softmax and softmax from § 2), which uses jax.lax.stop_gradient (sg) to return the forward loss while substituting g\mathbf{g} in the backward pass:

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                                      # Logit difference.
    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)) # log(q / p).
    u = jnp.where(jnp.abs(s) < 1, p * jnp.expm1(s), q - p) # Difference q - p.
    g = u - q * jnp.sum(u, axis=-1, keepdims=True)         # Ensure sum(g) = 0.
    sg = jax.lax.stop_gradient
    loss = -jnp.sum(p * sg(log_q), axis=-1)                 # Forward loss.
    return loss + jnp.sum(sg(g) * (z_S - sg(z_S)), axis=-1) # Custom gradient g.

As an example, let zSz_S be a small fp32 perturbation of zTz_T. Standard soft-target cross-entropy shrinks the second gradient entry by nearly 3×3\times, flips the sign of the third, and fails to sum to zero, while our implementation matches the exact fp64 gradient:

z_T = jnp.array([2.0, 1.0, 0.0], dtype=jnp.float32)
z_S = z_T + jnp.array([-1e-7, 1e-7, 0.0], dtype=jnp.float32)
std_soft_ce = lambda z_S, z_T: -jnp.sum(jax.nn.softmax(z_T) * jax.nn.log_softmax(z_S))
jax.grad(std_soft_ce)(z_S, z_T)                 # -> [-5.960e-8, 1.452e-8, 1.123e-9]
jax.grad(soft_target_cross_entropy)(z_S, z_T)   # -> [-4.596e-8, 4.144e-8, 4.513e-9]
# Exact (float64) gradient:                         [-4.596e-8, 4.144e-8, 4.513e-9]

The Slingshot Mechanism

In grokking (Power et al. [14]), a network quickly memorizes the training set (qt→1q_t \to1) and generalizes much later. While studying grokking on modular addition with Adam (Kingma & Ba [6]; Loshchilov & Hutter [9]), Thilak et al. [19] observed the slingshot mechanism, where training after memorization alternates between flat loss plateaus near zero and sudden loss spikes that coincide with jumps in test accuracy.

These slingshot spikes are a direct consequence of Softmax Collapse (§ 2, Prieto et al. [15]; Liu et al. [8]). Recall that AdamW updates parameters θ\theta by subtracting η(m^/(v^+ϵ)+λθ)\eta(\hat{\mathbf{m}}/(\sqrt{\hat{\mathbf{v}}} + \epsilon) + \lambda\theta), where m^\hat{\mathbf{m}} and v^\hat{\mathbf{v}} are bias-corrected moving averages of the parameter gradient g=∇θL(θ^)\mathbf{g} = \nabla_\theta\mathcal{L}(\hat{\theta}) and its square (with decay rates β1,β2\beta_1, \beta_2). After memorization, the logit margins mm grow as the network pushes its target probabilities toward 1. Once an example’s margin exceeds the precision cliff cdc_d, standard cross-entropy rounds its target gradient g~t\tilde{g}_t to zero while its non-target gradients g~j>0\tilde{g}_j > 0 (j≠tj \ne t) remain positive. When all examples in a batch sit above cdc_d, the parameter gradients nearly vanish and Adam’s second moment v^i\hat{v}_i decays exponentially toward zero while weight decay slowly shrinks the parameters. Eventually, weight decay or the residual non-target updates pull a few examples back below cdc_d, where their target gradients g~t≈−e−m\widetilde{g}_t\approx-e^{-m} abruptly turn back on. Because v^i\sqrt{\hat{v}_i} decayed while those examples were above cdc_d, Adam divides the restored gradients by a very small denominator v^i+ϵ\sqrt{\hat{v}_i}+\epsilon, producing a large parameter step that spikes the training loss, resets v^i\hat{v}_i, and repeats the cycle. With our fixed cross-entropy, the target-logit gradient gt=−e−m/(1+e−m)g_t=-e^{-m}/(1+e^{-m}) does not round to zero at cdc_d, so m^i\hat{m}_i and v^i\sqrt{\hat{v}_i} decay smoothly together and slingshot spikes disappear (Figure 2).

The slingshot mechanism: mean logit margin, training loss, and test accuracy

Figure 2. The slingshot mechanism ([19]) with and without weight decay (5 random seeds, fp32). Top row (a+ba+b mod 31, λ=1\lambda=1, ϵ=10−8\epsilon=10^{-8}, Varma et al. [21]): Standard cross-entropy hits the fp32 cliff (m=c32≈16.6m=c_{32}\approx16.6, where loss rounds to 0) and repeatedly drops and rebounds, slowing and degrading grokking; fixed cross-entropy crosses c32c_{32} smoothly, groks faster on all 5 seeds, and saturates just above c32c_{32} near log⁡(1/ϵ)≈18.4\log(1/\epsilon)\approx18.4 (§ 5). Bottom row (a2+b2a^{2}+b^{2} mod 97, λ=0\lambda=0, ϵ=10−16\epsilon=10^{-16}, Doshi et al. [2]): Without weight decay, hitting c32c_{32} around step 1250 triggers a spike that drops standard cross-entropy test accuracy from 61% to 23%, whereas fixed cross-entropy continues smoothly to 85%.

Whether slingshot spikes appear to help or hurt generalization depends on how the network’s weight norm is controlled (Figure 2). When a network uses LayerNorm before the output layer and no weight decay ([19, 15]), growing the pre-LayerNorm weights does not change the logits, but it does shrink the effective step size η/∥θ∥2\eta/\lVert\theta\rVert_2; each slingshot spike inflates ∥θ∥2\lVert\theta\rVert_2 and acts as an accidental learning-rate decay. When weight norms are already controlled by weight decay ([21]), slingshot spikes at c32c_{32} only slow down and hurt grokking (94 ±\pm 5% vs. 100 ±\pm 0% test accuracy on a+ba+b mod 31; Figure 2, top). And when neither LayerNorm nor weight decay is used ([2]), a single slingshot spike at c32c_{32} is destructive: on a2+b2a^{2}+b^{2} mod 97 (λ=0\lambda=0, ϵ=10−16\epsilon=10^{-16}), standard cross-entropy tracks fixed cross-entropy up to 61% test accuracy until mm hits c32c_{32} around step 1250, where a spike drops test accuracy to 23% (and from 60% to 21% on a3+ba^{3}+b mod 97), while fixed cross-entropy continues smoothly to 85% (Figure 2, bottom).

Margin Equilibria

In Figure 2a, our fixed cross-entropy eliminates the precision cliff at c32≈16.6c_{32}\approx16.6, yet with weight decay (λ=1\lambda=1, top) its margin still saturates just above c32c_{32} near 18, whereas without weight decay (λ=0\lambda=0, bottom) its margin continues to climb. This plateau is the equilibrium where weight decay balances AdamW’s normalized gradient step. At a stationary point where the parameters stop changing, the moving averages converge to m^i=gi\hat{m}_i=g_i and v^i=gi2\hat{v}_i=g_i^2 (so v^i=∣gi∣\sqrt{\hat{v}_i}=|g_i|), and setting the update to zero gives:

m^iv^i+ϵ+λθi=0⟹gi∣gi∣+ϵ+λθi=0∀i.(10)\frac{\hat{m}_i}{\sqrt{\hat{v}_i}+\epsilon}+\lambda\theta_i=0 \quad\Longrightarrow\quad \frac{g_i}{|g_i|+\epsilon}+\lambda\theta_i=0\quad\forall i. \tag*{(10)}

Here η\eta, β1\beta_1, and β2\beta_2 cancel out, so RMSProp [20] and LaProp [23] share the same stationary point. After memorization, the gradients shrink exponentially with the margin (∣gi∣∝e−m|g_i|\propto e^{-m}). If ϵ=0\epsilon=0, the normalized gradient gi/∣gi∣=sign⁡(gi)g_i/|g_i|=\operatorname{sign}(g_i) has a magnitude of 1 no matter how small ∣gi∣|g_i| becomes, which causes the margin to grow until the gradients underflow.

When ϵ>0\epsilon> 0, however, the normalized gradient has magnitude ≈1\approx1 while ∣gi∣≫ϵ|g_i| \gg\epsilon, and shrinks as gi/ϵ∝e−mg_i/\epsilon\propto e^{-m} once ∣gi∣≪ϵ|g_i| \ll\epsilon (Figure 3). Balancing this shrinking step against weight decay λθi\lambda\theta_i requires ∣gi∣≈ϵλ∣θi∣|g_i| \approx\epsilon\lambda|\theta_i| [22, 12, 3, 7], which acts like an L2L_2 regularizer with weight ϵλ\epsilon\lambda [17, 18]. Since ∣gi∣∝e−m|g_i| \propto e^{-m}, the margin stops growing at:

m⋆(ϵ)≈log⁡(1/ϵ).(11)m^\star(\epsilon) \approx\log(1/\epsilon). \tag*{(11)}

Equation 11 explains why the default ϵ=10−8\epsilon= 10^{-8} causes slingshot spikes in fp32: its equilibrium log⁡(1/ϵ)≈18.4\log(1/\epsilon) \approx18.4 sits just above c32≈16.6c_{32} \approx16.6 (Figure 3), so standard cross-entropy hits the cliff before equilibrium (whereas for ϵ≥10−7\epsilon\ge10^{-7}, log⁡(1/ϵ)≤16.1<c32\log(1/\epsilon) \le16.1 < c_{32} and standard cross-entropy settles without spiking). To test Equation 11 across many orders of magnitude down to ϵ=0\epsilon= 0 in fp32 (Figure 4), we train with our fixed cross-entropy and LaProp on a+ba+b mod 31, updating v^\sqrt{\hat{v}} directly without squaring gig_i (which underflows in fp32 once ∣gi∣<2−63|g_i| < 2^{-63}, or m≈38m \approx38). With weight decay (λ=1\lambda= 1, Figure 4a), the margin for each ϵ>0\epsilon> 0 climbs along the ϵ=0\epsilon= 0 trajectory and levels off at m⋆(ϵ)=log⁡(1/ϵ)m^\star(\epsilon) = \log(1/\epsilon), while ϵ=0\epsilon= 0 grows until the fp32 gradients underflow at m≈81.2m \approx81.2. Without weight decay (λ=0\lambda= 0, Figure 4b), nothing balances the gi/ϵg_i/\epsilon step, so margins keep rising past log⁡(1/ϵ)\log(1/\epsilon).

Normalized Adam step versus logit margin

Figure 3. Normalized Adam step ∣gt∣/(∣gt∣+ϵ)|g_t|/(|g_t|+\epsilon) vs. logit margin mm at ϵ=10−8\epsilon= 10^{-8}. With our fixed cross-entropy, the step stays near 1 and decays smoothly around log⁡(1/ϵ)≈18.4\log(1/\epsilon) \approx18.4, whereas standard cross-entropy zeroes out g~t\tilde{g}_t at c16≈5.5c_{16} \approx5.5 and c32≈16.6c_{32} \approx16.6.

Logit margins with weight decay and without weight decay

Figure 4. Logit margins with our fixed cross-entropy and LaProp on a+ba+b mod 31 in fp32 (β1=0.9\beta_1 = 0.9, β2=0.98\beta_2 = 0.98; 3 seeds per setting as solid lines, analytical predictions m⋆(ϵ)=log⁡(1/ϵ)m^\star(\epsilon) = \log(1/\epsilon) as dashed lines). (a) With weight decay (λ=1\lambda= 1), margins level off at log⁡(1/ϵ)\log(1/\epsilon). (b) Without weight decay (λ=0\lambda= 0), margins overshoot log⁡(1/ϵ)\log(1/\epsilon).

Grokking Across Precisions and Benchmarks

To see how the precision cliff behaves across floating-point formats, we follow Varma et al. [21] and Lyle et al. [10] and train a 1-layer, 4-head, width-64 ReLU Transformer without LayerNorm on a+ba+b mod 31 (50% training split) for 10,000 epochs of full-batch AdamW (η=10−3\eta= 10^{-3}, β1=0.9\beta_1 = 0.9, β2=0.98\beta_2 = 0.98, λ=1\lambda= 1), varying the loss (standard vs. fixed cross-entropy), logit precision at the loss (bf16, fp32, fp64), and ϵ∈{10−8,10−12,10−16}\epsilon\in\{10^{-8}, 10^{-12}, 10^{-16}\} (Figure 5, Table 1). At ϵ=10−8\epsilon= 10^{-8} (Figure 5, top), standard cross-entropy stalls at c16≈5.5c_{16} \approx5.5 in bf16 and repeatedly spikes at c32≈16.6c_{32} \approx16.6 in fp32, whereas fixed cross-entropy crosses both cliffs smoothly to log⁡(1/ϵ)≈18.4\log(1/\epsilon) \approx18.4 and reaches 100% test accuracy in all three precisions. Reducing ϵ\epsilon to 10−1610^{-16} (Figure 5, bottom) raises the equilibrium to log⁡(1/ϵ)≈36.8>c64\log(1/\epsilon) \approx36.8 > c_{64}, breaking even fp64 standard cross-entropy at c64≈36.7c_{64} \approx36.7 while fixed cross-entropy converges smoothly across all precisions.

Table 1 summarizes these results and compares against two recent methods that modify the gradients or loss to mitigate Softmax Collapse. Liu et al. [8] subtract the mean logit gradient from each entry so the gradients sum to zero (“Zero-sum Proj.”), which eliminates slingshot spikes. However, once m>c32m > c_{32} and g~t=0\tilde{g}_t = 0, subtracting the mean only gives the target logit −1/k-1/k of the total non-target gradient, stalling mm near 18 and dropping test accuracy below 50% for ϵ≤10−12\epsilon\le10^{-12}. Prieto et al. [15] propose “StableMax,” which replaces exp⁡(x)\exp(x) in softmax with a piecewise rational function $(x+1 for x≥0x \ge0 and 1/(1−x)1/(1-x) for x<0x < 0). Because this function grows linearly instead of exponentially, logit margins blow up to ∼104\sim10^{4} and test accuracy lags our fixed cross-entropy across all ϵ\epsilon.

We observe the same behavior across four grokking benchmarks at ϵ=10−12\epsilon= 10^{-12} (Figure 6): 1-layer Transformers on a+ba+b mod 113 [13] and a+ba+b mod 31 [21] with λ=1\lambda= 1, and 2-layer MLPs on a2+b2a^{2}+b^{2} mod 97 and a3+ba^{3}+b mod 97 [2] with λ=0.2\lambda= 0.2. On all four tasks, fp32 standard cross-entropy spikes once it hits c32c_{32}, whereas fp32 fixed cross-entropy matches fp64 standard cross-entropy and reaches 100% test accuracy.

Results across four grokking tasks: (a) $a+b$ mod 113, Nanda et al. (2023); (b) $a+b$ mod 31, Varma et al. (2023); (c) $a^2+b^2$ mod 97, Doshi et al. (2024); (d) $a^3+b$ mod 97, Doshi et al. (2024)

Figure 6. Results across four grokking tasks at ϵ=10−12\epsilon= 10^{-12} (2 of 3–5 seeds shown): 1-layer Transformers (a, b) and 2-layer MLPs (c, d). Fixed cross-entropy in fp32 (blue) matches fp64 standard cross-entropy (red), while standard cross-entropy in fp32 (orange) breaks at c32c_{32}.

Plots of mean logit margin, training loss, and test accuracy across precisions

Figure 5. Standard cross-entropy fails at the precision cliff cdc_d; fixed cross-entropy removes the cliff across all precisions (a+ba+b mod 31, λ=1\lambda= 1; 2 of 5 seeds shown). Top: ϵ=10−8\epsilon= 10^{-8}. Bottom: ϵ=10−16\epsilon= 10^{-16}, where even fp64 standard cross-entropy fails at c64c_{64} while fixed cross-entropy converges smoothly.

Variant\multicolumn{3}{c}{Test Accuracy (%)}\multicolumn{3}{c}{Final Margin mm}
fp32 Fixed CE100.0±0.0100.0 \pm0.099.6±0.799.6 \pm0.799.0±2.399.0 \pm2.317.917.927.427.436.836.8
fp32 Standard CE94.3±5.494.3 \pm5.496.4±5.196.4 \pm5.196.5±4.396.5 \pm4.313.013.015.115.112.712.7
bf16 Fixed CE100.0±0.1100.0 \pm0.199.8±0.299.8 \pm0.298.9±2.498.9 \pm2.417.917.927.427.436.836.8
bf16 Standard CE93.3±7.493.3 \pm7.494.9±4.994.9 \pm4.994.2±8.394.2 \pm8.35.15.15.65.65.85.8
fp64 Fixed CE100.0±0.0100.0 \pm0.099.5±1.199.5 \pm1.199.0±2.099.0 \pm2.017.917.927.427.436.836.8
fp64 Standard CE100.0±0.0100.0 \pm0.0100.0±0.1100.0 \pm0.197.2±3.297.2 \pm3.217.917.927.427.430.130.1
fp32 Zero-sum Proj. [8]97.9±3.297.9 \pm3.248.9±2.648.9 \pm2.649.3±2.549.3 \pm2.517.017.018.918.918.918.9
fp32 StableMax [15]97.3±4.797.3 \pm4.795.6±2.095.6 \pm2.097.3±4.397.3 \pm4.3320032005661566163136313
fp64 StableMax [15]97.4±4.297.4 \pm4.296.7±5.396.7 \pm5.395.6±2.795.6 \pm2.731703170212522125223222322

Table 1. Comparison of loss functions on modular addition (a+ba+b mod 31, λ=1\lambda= 1, 3–5 seeds) across ϵ∈{10−8,10−12,10−16}\epsilon\in\{10^{-8}, 10^{-12}, 10^{-16}\}. Fixed CE reaches the predicted equilibrium margin (log⁡(1/ϵ)≈18.4,27.6,36.8\log(1/\epsilon) \approx18.4, 27.6, 36.8) and ≥98.9%\ge98.9\% test accuracy across all precisions, whereas Standard CE stalls once m⋆(ϵ)m^{\star}(\epsilon) exceeds the cliff cdc_d (c16≈5.5c_{16} \approx5.5 in bf16, c32≈16.6c_{32} \approx16.6 in fp32, and c64≈36.7c_{64} \approx36.7 in fp64).

Soft-Target Distillation

To see how Softmax Cancellation (§ 3) affects optimization, we initialize a 2-layer ReLU MLP student with the fp32 weights of a teacher trained to 100% accuracy on a+ba+b mod 53 (θS(0)=θT\theta_{S}^{(0)} = \theta_{T}), and run 2,000 full-batch steps of Adam (η=2×10−3\eta= 2 \times10^{-3}, β1=0.9\beta_{1} = 0.9, β2=0.98\beta_{2} = 0.98, λ=0\lambda= 0, ϵ=10−8\epsilon= 10^{-8}) on the 50% training split at temperature T=4T = 4 [5] (which keeps m/T<c16m/T < c_{16} so pp does not round to one-hot), computing the forward pass and loss in bf16, fp32, or fp64. Because zS=zTz_{S} = z_{T} initially, the true gradient is zero and the student should not move. However, standard soft-target cross-entropy has a non-zero residual gradient at zS=zTz_{S} = z_{T} due to the mismatch between its forward softmax and backward log-softmax (Figure 1b). Because Adam divides by v^+ϵ\sqrt{\hat{v}}+\epsilon, it amplifies even tiny residual gradients (Figure 7): in bf16 (∼10−3\sim10^{-3}) it drives the student away from the teacher and degrades test accuracy, in fp32 (∼10−8\sim10^{-8}) it causes an initial KL spike and a ∼10−6\sim10^{-6} floor, and in fp64 (∼10−17\sim10^{-17}) the update is too small to change the fp32 weights. Our fixed soft-target cross-entropy returns g=0\mathbf{g} = \mathbf{0} at zS=zTz_{S} = z_{T}, so the student stays at KL =0= 0 and 100% accuracy across all precisions.

Figure 7. Soft-target distillation when the student is initialized with the teacher’s weights (θS(0)=θT\theta_{\mathrm{S}}^{(0)} = \theta_{\mathrm{T}}, T=4T = 4, ϵ=10−8\epsilon= 10^{-8}, 2 of 3 seeds shown). Fixed soft-target cross-entropy stays at KL = 0 and 100% accuracy across all precisions; standard soft-target cross-entropy amplifies rounding error into parameter drift in bf16 and an initial KL spike and ∼10−6\sim10^{-6} floor in fp32.

Conclusion

We have presented simple fixes for two numerical bugs in standard implementations of softmax, log-softmax, and cross-entropy: Softmax Collapse, which zeroes out the dominant logit’s gradient at high confidence while leaving non-dominant gradients non-zero, and Softmax Cancellation, which loses precision when student logits approach teacher logits in soft-target distillation. Rewriting these functions in log space using softplus, expm1, and log1p restores accurate, zero-sum gradients across bf16, fp32, and fp64 without internally casting to higher precision. Fixing these bugs eliminates slingshot loss spikes during grokking, prevents student networks from drifting away from the teacher during distillation, and reveals that logit margins under AdamW and weight decay naturally converge to log⁡(1/ϵ)\log(1/\epsilon). Though the extreme margins and near-zero student–teacher gaps probed by our experiments are uncommon in standard large-scale training, our fixed functions are easy drop-in replacements that can be implemented without meaningful slowdown, and may prove useful whenever models make high-confidence predictions or distill from close teachers.

Acknowledgments: We thank Jean-Baptiste Alayrac, Forrester Cole, Roy Frostig, Mark Hamilton, Muhammad Maaz, Miki Rubinstein, Keith Rush, and Brandon Zhao for their helpful advice.

Errata: In an earlier version of this paper, the code in Section 2 produced NaN gradients when all but one logit was effectively −∞-\infty, as happens with masking in causal attention or with extreme logits. This bug was not present in our internal codebase, which produced all results in this paper. It appears to have been introduced by an over-eager agent that simplified our code for this paper, likely in an attempt to match Equations 5 and 6 (with s=∑j≠imax⁡ezjs = \sum_{j \ne i_{\max}} e^{z_j}, softplus⁡(−m)\operatorname{softplus}(-m) can be written as log⁡1p(s)\log1p(s) or equivalently as softplus⁡(log⁡s)\operatorname{softplus}(\log s), but the latter makes autodiff differentiate through log⁡0\log0 when s=0s = 0). We thank Maaz [11] for identifying this issue.

References

  1. [1]Pierre Blanchard, Desmond J. Higham, and Nicholas J. Higham. Accurately computing the log-sum-exp and softmax functions. IMA Journal of Numerical Analysis, 2021.DOI
  2. [2]Darshil Doshi, Tianyu He, Aritra Das, and Andrey Gromov. Grokking modular polynomials. arXiv:2406.03495, 2024.arxiv.org/abs/2406.03495
  3. [3]Katie Everett, Lechao Xiao, Mitchell Wortsman, Alexander A. Alemi, Roman Novak, Peter J. Liu, Izzeddin Gur, Jascha Sohl-Dickstein, Leslie Pack Kaelbling, Jaehoon Lee, and Jeffrey Pennington. Scaling exponents across parameterizations and optimizers. ICML, 2024.arxiv.org/abs/2407.05872
  4. [4]Nicholas J. Higham. Accuracy and stability of numerical algorithms. SIAM, 2nd edition, 2002.DOI
  5. [5]Geoffrey Hinton, Oriol Vinyals, and Jeff Dean. Distilling the knowledge in a neural network. arXiv:1503.02531, 2015.arxiv.org/abs/1503.02531
  6. [6]Diederik P. Kingma and Jimmy Ba. Adam: A method for stochastic optimization. ICLR, 2015.arxiv.org/abs/1412.6980
  7. [7]Atli Kosson, Bettina Messmer, and Martin Jaggi. Rotational equilibrium: How weight decay balances learning across neural networks. ICML, 2024.arxiv.org/abs/2305.17212
  8. [8]Hanqin Liu, Jianjun Cao, Yuanze Li, and Zijian Zhou. Grokking or glitching? How low-precision drives Slingshot loss spikes. arXiv:2605.06152, 2026.arxiv.org/abs/2605.06152
  9. [9]Ilya Loshchilov and Frank Hutter. Decoupled weight decay regularization. ICLR, 2019.
  10. [10]Clare Lyle, Ghada Sokar, András György, and Razvan Pascanu. What can grokking teach us about learning under non-stationarity? Conference on Lifelong Learning Agents, 2025.
  11. [11]Muhammad Maaz. Property-based testing for robust softmax and cross-entropy. arXiv:2610.36427, 2026.arxiv.org/abs/2610.36427
  12. [12]Igor Molybog, Peter Albert, Moya Chen, Zachary DeVito, David Esiobu, Naman Goyal, Punit Singh Koura, Sharan Narang, Andrew Poulton, Ruan Silva, et al. A theory on Adam instability in large-scale machine learning. arXiv:2304.09871, 2023.arxiv.org/abs/2304.09871
  13. [13]Neel Nanda, Lawrence Chan, Tom Lieberum, Jess Smith, and Jacob Steinhardt. Progress measures for grokking via mechanistic interpretability. ICLR, 2023.arxiv.org/abs/2301.05217
  14. [14]Alethea Power, Yuri Burda, Harri Edwards, Igor Babuschkin, and Vedant Misra. Grokking: Generalization beyond overfitting on small algorithmic datasets. arXiv:2201.02177, 2022.arxiv.org/abs/2201.02177
  15. [15]Lucas Prieto, Melih Barsbey, Pedro A. M. Mediano, and Tolga Birdal. Grokking at the edge of numerical stability. ICLR, 2025.arxiv.org/abs/2501.04697
  16. [16]Haiquan Qiu and Quanming Yao. Why low-precision Transformer training fails: An analysis on Flash Attention. ICLR, 2026.arxiv.org/abs/2510.04212
  17. [17]Saharon Rosset, Ji Zhu, and Trevor Hastie. Margin maximizing loss functions. NeurIPS, 2004.
  18. [18]Daniel Soudry, Elad Hoffer, Mor Shpigel Nacson, Suriya Gunasekar, and Nathan Srebro. The implicit bias of gradient descent on separable data. JMLR, 2018.arxiv.org/abs/1710.10345
  19. [19]Vimal Thilak, Etai Littwin, Shuangfei Zhai, Omid Saremi, Roni Paiss, and Joshua Susskind. The Slingshot mechanism: An empirical study of adaptive optimizers and the grokking phenomenon. arXiv:2206.04817, 2022.arxiv.org/abs/2206.04817
  20. [20]Tijmen Tieleman and Geoffrey Hinton. Lecture 6.5—RMSProp: Divide the gradient by a running average of its recent magnitude. COURSERA: Neural Networks for Machine Learning, 2012.
  21. [21]Vikrant Varma, Rohin Shah, Zachary Kenton, János Kramár, and Ramana Kumar. Explaining grokking through circuit efficiency. arXiv:2309.02390, 2023.arxiv.org/abs/2309.02390
  22. [22]Mitchell Wortsman, Peter J. Liu, Lechao Xiao, Katie Everett, Alexander Alemi, Ben Adlam, John D. Co-Reyes, Izzeddin Gur, Abhishek Kumar, Roman Novak, et al. Small-scale proxies for large-scale Transformer training instabilities. ICLR, 2024.arxiv.org/abs/2309.14322
  23. [23]Liu Ziyin, Zhikang T. Wang, and Masahito Ueda. LaProp: Separating momentum and adaptivity in Adam. arXiv:2002.04839, 2020.arxiv.org/abs/2002.04839

Paper details

vlnc:W_mre43xeb
Published
Added
License
CC BY 4.0
Usage

views · 27

downloads · 0

A view counts once per browser per day, a download each time the PDF is requested.

  • Computer Science

Not recorded for this paper

View statement
Looking for related papers…
Contents