Papers
Topics
Authors
Recent
Search
2000 character limit reached

A Fix for Softmax and Cross-Entropy

Published 22 Oct 2026 in cs.LG | (2610.31642v1)

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.

Summary

  • The paper identifies numerical pathologies in standard implementations of softmax and cross-entropy that can alter training dynamics, such as Softmax Collapse and Softmax Cancellation.
  • The proposed fixed implementations improve computational stability and precision, maintaining accurate gradients and preventing loss instabilities in lower-precision arithmetic by using operations like softplus, expm1, and log1p.
  • The solutions solve precision issues in grokking experiments, ensure reliable distillation, and meet margins dependant on the Adam optimizer's epsilon parameter, showing potential to improve handling of precision cliffs in various training scenarios.

The paper identifies two numerical pathologies in standard implementations of softmax, log-softmax, and cross-entropy and proposes algebraic fixes that preserve the exact gradient structure in low-precision arithmetic. The central claim is that these are not merely benign rounding effects: under adaptive optimization, they can qualitatively alter training dynamics, generate apparent loss instabilities, impair grokking, and induce parameter drift during distillation. The proposed implementations operate directly in log space and use softplus, expm1, and log1p to avoid numerically ill-conditioned additions and subtractions (2610.31642).

Numerical failure modes in standard cross-entropy

For logits z∈RKz \in \mathbb{R}^K, standard implementations subtract the maximum logit before evaluating softmax or log-softmax. This prevents exponent overflow, but it introduces a precision problem when the largest logit is substantially larger than the others. Let tt denote the target class and define the target margin

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

The exact target probability is

qt=11+e−m,q_t = \frac{1}{1+e^{-m}},

and the exact target gradient for hard-target cross-entropy is

gt=qt−1=−e−m1+e−m.g_t = q_t - 1 = -\frac{e^{-m}}{1+e^{-m}}.

The standard computation forms 1+e−m1+e^{-m} and then subtracts one from the resulting probability. Once e−me^{-m} becomes smaller than the spacing of floating-point numbers near one, the denominator rounds to exactly $1$. The target probability therefore becomes exactly one, and the target gradient becomes exactly zero. The non-target gradients, however, are computed from exponentials that remain representable near zero and therefore remain positive. The resulting gradient no longer satisfies the exact conservation law

∑kgk=0.\sum_k g_k = 0.

The paper calls this failure Softmax Collapse. Its precision thresholds are approximately m≈5.5m \approx 5.5 in bf16, tt0 in fp32, and tt1 in fp64. These thresholds are determined by the precision available near one, not by exponent underflow. Consequently, increasing the floating-point exponent range does not address the problem; the relevant issue is cancellation and rounding in the computation of a quantity close to one.

Figure 1

Figure 1

Figure 1

Figure 1: Softmax Collapse zeroes the target gradient beyond precision-dependent logit margins, while Softmax Cancellation produces a non-zero gradient floor when student and teacher logits coincide.

The proposed hard-target formulation excludes the target logit from the log-sum-exp calculation. It computes the margin from the non-target logits and evaluates the loss as

tt2

Because the target coordinate is represented by an exact zero rather than by a quantity obtained through subtraction and exponentiation, autodifferentiation produces the target gradient as the negative sum of the non-target gradients. This preserves the zero-sum property even when the denominator tt3 rounds to one. The target gradient remains accurate down to exponent underflow, which occurs much later than the precision cliff.

This distinction is practically important. For logits tt4 in fp32, standard JAX and Optax routines return a zero target log-probability, zero loss, and zero target gradient, while retaining positive non-target gradients of approximately tt5. The corrected implementation returns a target loss of approximately tt6 and a target gradient of tt7, exactly balancing the two non-target gradients. The forward loss and the backward gradient therefore remain mutually consistent.

Softmax Cancellation in soft-target objectives

The second pathology occurs when cross-entropy or KL-based distillation compares student logits tt8 with teacher logits tt9. The conventional implementation computes student and teacher probabilities independently,

m=zt−log⁡∑j≠tezj.m = z_t - \log \sum_{j \ne t} e^{z_j}.0

and forms the gradient as m=zt−log⁡∑j≠tezj.m = z_t - \log \sum_{j \ne t} e^{z_j}.1. When m=zt−log⁡∑j≠tezj.m = z_t - \log \sum_{j \ne t} e^{z_j}.2 is close to m=zt−log⁡∑j≠tezj.m = z_t - \log \sum_{j \ne t} e^{z_j}.3, both probabilities are nearly identical. Subtracting them after they have been rounded discards the information carried by the small logit difference. In addition, the forward softmax and backward log-softmax may use different operation sequences, so the two probability vectors can differ numerically even when the logits are identical.

This is Softmax Cancellation. Its most direct violation is at m=zt−log⁡∑j≠tezj.m = z_t - \log \sum_{j \ne t} e^{z_j}.4: the exact gradient is zero, but the standard implementation can produce a non-zero residual. Under Adam, a residual gradient larger than the optimizer’s m=zt−log⁡∑j≠tezj.m = z_t - \log \sum_{j \ne t} e^{z_j}.5 parameter can be normalized into a finite update, converting an arithmetic error into parameter motion.

The paper avoids probability-space subtraction by expressing the student-to-teacher ratio in log space. It centers the logit difference under the teacher distribution and evaluates the resulting probability differences with expm1 and log1p. These functions retain relative accuracy for small arguments. A final projection subtracts the residual mean gradient so that the computed gradient sums to zero exactly in floating-point arithmetic.

The numerical example is consequential rather than cosmetic. For teacher logits m=zt−log⁡∑j≠tezj.m = z_t - \log \sum_{j \ne t} e^{z_j}.6 and student logits differing by only m=zt−log⁡∑j≠tezj.m = z_t - \log \sum_{j \ne t} e^{z_j}.7, the standard fp32 gradient is

m=zt−log⁡∑j≠tezj.m = z_t - \log \sum_{j \ne t} e^{z_j}.8

whereas the corrected result is

m=zt−log⁡∑j≠tezj.m = z_t - \log \sum_{j \ne t} e^{z_j}.9

matching the exact fp64 gradient. The standard computation shrinks one component by roughly a factor of three, reverses the sign of another, and fails to maintain a zero sum. The corrected computation restores the local geometry of the distillation objective near its optimum (2610.31642).

Why Softmax Collapse produces Slingshot dynamics

The paper provides a mechanistic explanation for the Slingshot phenomenon observed in grokking experiments. After memorization, target margins continue increasing even though training loss is already close to zero. With standard cross-entropy, examples crossing the precision cliff lose their target gradients while retaining non-target gradients. Once most examples have crossed the cliff, parameter gradients become very small and Adam’s second-moment estimates decay.

Weight decay and residual updates can subsequently reduce some margins below the cliff. The target gradients then reappear abruptly, but Adam’s second moments have already decayed. The restored gradients are therefore divided by a small adaptive denominator, generating a large parameter update and a sudden loss spike. The spike resets the second moment, after which the process repeats.

The fixed implementation removes the discontinuity. Target gradients decay smoothly as qt=11+e−m,q_t = \frac{1}{1+e^{-m}},0, so Adam’s first- and second-moment estimates evolve continuously with the loss gradient. The result is the disappearance of recurrent Slingshot spikes.

The experiments distinguish two effects that are often conflated. With weight decay on qt=11+e−m,q_t = \frac{1}{1+e^{-m}},1, standard cross-entropy reaches the fp32 cliff and obtains qt=11+e−m,q_t = \frac{1}{1+e^{-m}},2 test accuracy, whereas fixed cross-entropy reaches qt=11+e−m,q_t = \frac{1}{1+e^{-m}},3. Without weight decay on qt=11+e−m,q_t = \frac{1}{1+e^{-m}},4, standard cross-entropy reaches approximately qt=11+e−m,q_t = \frac{1}{1+e^{-m}},5 test accuracy before a spike drops it to qt=11+e−m,q_t = \frac{1}{1+e^{-m}},6. Fixed cross-entropy continues smoothly to qt=11+e−m,q_t = \frac{1}{1+e^{-m}},7. On qt=11+e−m,q_t = \frac{1}{1+e^{-m}},8, the analogous drop is from approximately qt=11+e−m,q_t = \frac{1}{1+e^{-m}},9 to gt=qt−1=−e−m1+e−m.g_t = q_t - 1 = -\frac{e^{-m}}{1+e^{-m}}.0.

Figure 2

Figure 2

Figure 2

Figure 2: Standard cross-entropy exhibits margin-triggered loss spikes and accuracy drops, whereas fixed cross-entropy crosses the floating-point precision cliff smoothly.

The paper also argues that the apparent benefits of Slingshot events in some prior grokking settings are contingent on architectural and optimization details. When LayerNorm precedes the output layer and no weight decay is used, increases in pre-LayerNorm weight norms can reduce the effective learning rate without changing the logits. Under those conditions, a Slingshot event may act as an accidental learning-rate decay. When weight decay already controls the norm, however, the same events slow optimization. When neither mechanism controls the norm, an individual spike can be destructive. This interpretation makes the phenomenon optimizer- and architecture-dependent rather than an intrinsic property of grokking.

Margin equilibria under AdamW

Removing the precision cliff does not imply unlimited margin growth when weight decay is present. The paper derives a separate equilibrium determined by Adam’s gt=qt−1=−e−m1+e−m.g_t = q_t - 1 = -\frac{e^{-m}}{1+e^{-m}}.1 hyperparameter and the decay coefficient.

At a stationary point, the Adam moments satisfy approximately gt=qt−1=−e−m1+e−m.g_t = q_t - 1 = -\frac{e^{-m}}{1+e^{-m}}.2 and gt=qt−1=−e−m1+e−m.g_t = q_t - 1 = -\frac{e^{-m}}{1+e^{-m}}.3. The AdamW update then has the stationary condition

gt=qt−1=−e−m1+e−m.g_t = q_t - 1 = -\frac{e^{-m}}{1+e^{-m}}.4

where gt=qt−1=−e−m1+e−m.g_t = q_t - 1 = -\frac{e^{-m}}{1+e^{-m}}.5 is the weight-decay coefficient. The learning rate and Adam moment decay rates cancel from this local condition. The same stationary point therefore applies to RMSProp- and LaProp-like normalized updates under the assumptions used in the derivation.

For memorized examples, gradient magnitudes decrease approximately exponentially with margin. When gt=qt−1=−e−m1+e−m.g_t = q_t - 1 = -\frac{e^{-m}}{1+e^{-m}}.6, Adam normalizes the gradient to a nearly constant step. Once gt=qt−1=−e−m1+e−m.g_t = q_t - 1 = -\frac{e^{-m}}{1+e^{-m}}.7, the normalized step decreases proportionally to gt=qt−1=−e−m1+e−m.g_t = q_t - 1 = -\frac{e^{-m}}{1+e^{-m}}.8. Balancing that decaying update against weight decay yields the approximate margin law

gt=qt−1=−e−m1+e−m.g_t = q_t - 1 = -\frac{e^{-m}}{1+e^{-m}}.9

This law explains the observed plateau near 1+e−m1+e^{-m}0 for 1+e−m1+e^{-m}1, 1+e−m1+e^{-m}2 for 1+e−m1+e^{-m}3, and 1+e−m1+e^{-m}4 for 1+e−m1+e^{-m}5. The plateau is therefore not a floating-point artifact. It is an optimizer equilibrium whose location can nevertheless place training directly beyond the precision cliff of the selected datatype.

Figure 3

Figure 3

Figure 3: Fixed cross-entropy produces a smooth Adam-normalized step whose decay begins near 1+e−m1+e^{-m}6, while standard cross-entropy introduces abrupt precision-dependent discontinuities.

Experiments with fixed cross-entropy and LaProp support the analytical prediction over several orders of magnitude in 1+e−m1+e^{-m}7. With weight decay, margins level off near the predicted 1+e−m1+e^{-m}8 values. Without weight decay, the normalized gradient remains approximately unit magnitude as the true gradient shrinks, and margins continue growing until the gradients themselves underflow. This result identifies 1+e−m1+e^{-m}9 as a direct control on post-memorization logit growth, rather than merely a numerical safeguard.

Results across precision formats and benchmarks

The principal controlled experiment uses a width-64, one-layer ReLU Transformer trained on e−me^{-m}0 with a 50% training split, full-batch AdamW, and weight decay e−me^{-m}1. The comparison varies datatype, loss implementation, and e−me^{-m}2.

At e−me^{-m}3, standard cross-entropy stalls near the bf16 cliff at e−me^{-m}4 and repeatedly spikes near the fp32 cliff at e−me^{-m}5. Fixed cross-entropy crosses both thresholds and reaches e−me^{-m}6 test accuracy in bf16, fp32, and fp64. At e−me^{-m}7, the predicted equilibrium is e−me^{-m}8, beyond the fp64 cliff at approximately e−me^{-m}9. Standard fp64 cross-entropy consequently fails even in double precision, while fixed cross-entropy remains stable.

Precision Loss $1$0 $1$1 $1$2
fp32 Fixed CE $1$3 $1$4 $1$5
fp32 Standard CE $1$6 $1$7 $1$8
bf16 Fixed CE $1$9 ∑kgk=0.\sum_k g_k = 0.0 ∑kgk=0.\sum_k g_k = 0.1
bf16 Standard CE ∑kgk=0.\sum_k g_k = 0.2 ∑kgk=0.\sum_k g_k = 0.3 ∑kgk=0.\sum_k g_k = 0.4
fp64 Fixed CE ∑kgk=0.\sum_k g_k = 0.5 ∑kgk=0.\sum_k g_k = 0.6 ∑kgk=0.\sum_k g_k = 0.7
fp64 Standard CE ∑kgk=0.\sum_k g_k = 0.8 ∑kgk=0.\sum_k g_k = 0.9 m≈5.5m \approx 5.50

The final margins further separate the methods. Fixed cross-entropy reaches approximately m≈5.5m \approx 5.51, m≈5.5m \approx 5.52, and m≈5.5m \approx 5.53 for the three m≈5.5m \approx 5.54 values, in agreement with the equilibrium law. Standard cross-entropy instead remains near the datatype-specific cliffs in bf16 and fp32, and shows degraded margins in fp64 at the smallest m≈5.5m \approx 5.55.

Figure 4

Figure 4: Across bf16, fp32, and fp64, fixed cross-entropy reaches the optimizer-predicted margins, while standard cross-entropy fails when those margins cross the datatype’s precision cliff.

Two alternative interventions perform less consistently. Mean-gradient projection restores a zero-sum gradient after the target gradient has already been lost, but it assigns only approximately m≈5.5m \approx 5.56 of the residual non-target gradient to the target coordinate. In the reported experiments, it stalls near margin m≈5.5m \approx 5.57 and falls below m≈5.5m \approx 5.58 test accuracy for m≈5.5m \approx 5.59. StableMax avoids exponential softmax behavior by replacing the exponential with a piecewise rational function, but produces margins between roughly tt00 and tt01 and lower test accuracy than fixed cross-entropy. The comparison supports the paper’s preference for correcting the numerically unstable evaluation of the original objective rather than changing the objective or projecting an already corrupted gradient.

The same pattern appears on four grokking benchmarks: two one-layer Transformer tasks, tt02 and tt03, and two two-layer MLP tasks, tt04 and tt05. At tt06, fp32 standard cross-entropy repeatedly breaks near the fp32 cliff, while fp32 fixed cross-entropy tracks fp64 standard cross-entropy and reaches tt07 test accuracy. This correspondence suggests that the mechanism is not specific to one architecture or modular task, although the experiments remain concentrated on small synthetic grokking benchmarks.

Distillation stability

The Softmax Cancellation experiments initialize a student with the weights of a teacher that achieves tt08 test accuracy on tt09. The student is trained for 2,000 Adam steps using temperature tt10, with no weight decay and tt11. The temperature keeps scaled margins below the Softmax Collapse regime, isolating cancellation near the teacher solution.

At initialization, student and teacher logits are identical, so the exact distillation gradient is zero. Under standard soft-target cross-entropy, the residual numerical gradient is approximately tt12 in fp64, tt13 in fp32, and tt14 in bf16. The resulting behavior follows the relationship between the residual and Adam’s tt15: fp64 remains effectively stationary, fp32 exhibits a brief KL spike, and bf16 drifts away from the teacher and loses accuracy. The corrected implementation returns exactly zero at equal logits, maintaining tt16 and tt17 test accuracy across all three precisions.

Figure 5

Figure 5

Figure 5

Figure 5

Figure 5: In distillation initialized at the teacher solution, standard soft-target cross-entropy amplifies precision-dependent residual gradients, whereas the corrected objective remains stationary.

This result is particularly relevant for self-distillation, teacher-student initialization, and KL regularization, where the desired optimum can involve extremely small student-teacher logit differences. The paper does not claim that cancellation dominates ordinary supervised training; rather, it isolates a regime in which the objective’s gradient is expected to vanish and demonstrates that standard implementations can prevent that invariance from being realized numerically.

Limitations and open questions

The empirical evaluation is concentrated on synthetic modular-arithmetic grokking tasks, small Transformers and MLPs, and carefully selected high-confidence or near-identical-logit regimes. These settings are appropriate for exposing the failure modes, but they do not establish the frequency or optimization impact of the bugs in large-scale language, vision, or multimodal training. The paper explicitly notes that the extreme margins and very small student-teacher gaps used in the experiments may be uncommon in standard training.

The implementation also introduces additional operations, masking, and in the soft-target case a custom backward expression. The paper reports no meaningful slowdown, but the evidence provided is not a broad systems benchmark across accelerator architectures, kernel fusions, batch shapes, and compiler stacks. The effects of nondeterministic reductions and mixed-precision accumulation are likewise not characterized.

The equilibrium law tt18 depends on assumptions about stationary Adam moments, exponential gradient decay, and a stable balance between normalized gradients and weight decay. It accurately describes the reported experiments, but its applicability to momentum transients, minibatch noise, parameter-wise heterogeneous gradients, or optimizers with materially different preconditioning remains open. Finally, the paper establishes that the corrected gradient is numerically faithful; it does not determine whether exact preservation of tiny gradients is always desirable when those gradients interact with stochastic regularization, gradient clipping, or noisy labels.

Conclusion

The paper shows that conventional numerically stable softmax implementations remain unstable in two distinct regimes. Softmax Collapse destroys the dominant-class gradient after a precision-dependent margin threshold, while Softmax Cancellation destroys information when student and teacher probabilities are nearly equal. Both failures violate exact gradient properties and can be amplified by adaptive optimizers.

The proposed log-space formulations preserve zero-sum gradients, maintain non-zero target gradients beyond the precision cliff, and compute student-teacher differences accurately near equality. Across grokking and distillation experiments, they eliminate Slingshot spikes, improve low-precision robustness, prevent teacher-student drift, and expose a margin equilibrium controlled by Adam’s tt19 and weight decay. The remaining question is how often these numerically extreme regimes occur in large-scale workloads and whether the same corrections produce measurable benefits outside the controlled settings studied here (2610.31642).

Whiteboard

Explain it Like I'm 14

1. What is this paper about?

This paper, “A Fix for Softmax and Cross-Entropy,” studies two common tools used when training neural networks:

  • Softmax, which turns a model’s scores into probabilities.
  • Cross-entropy, which measures how wrong the model’s prediction is.

For example, if a model is choosing between cats, dogs, and birds, softmax turns its raw scores into probabilities such as:

  • Cat: 95%
  • Dog: 3%
  • Bird: 2%

The paper argues that standard computer implementations of these tools can make small numerical mistakes. These mistakes usually do not matter, but they can cause problems when:

  • The model becomes extremely confident.
  • A student model is trying to copy a teacher model.
  • Training uses limited-precision numbers such as bf16 or fp32.
  • Special training behavior called grokking occurs.

The authors provide new implementations that avoid these problems.

2. What questions are the researchers asking?

The paper mainly asks:

  1. Why do standard softmax and cross-entropy sometimes give incorrect gradients? A gradient tells the neural network how it should change its weights to improve.
  2. Can these numerical errors be fixed without using much more computer memory or slower calculations?
  3. Do the errors explain strange training behaviors, such as sudden loss spikes during grokking?
  4. Can the new formulas improve knowledge distillation, where a smaller “student” model learns from a larger “teacher” model?

3. How did the researchers investigate the problem?

Understanding softmax

A neural network does not initially produce probabilities. It produces raw scores called logits. Softmax converts these scores into probabilities.

The usual formula involves exponentials, such as exe^x. Very large exponentials can overflow, like a calculator receiving a number too large to display. To avoid this, software usually subtracts the largest logit before calculating softmax.

This prevents overflow, but the authors found that it does not solve every problem.

Problem 1: Softmax Collapse

Imagine that a model is almost completely certain that the correct answer is “cat.” Its internal scores might look like this:

1
2
3
Cat:  9
Dog: -9
Bird: -9

The correct class is far ahead of the others. Mathematically, the model should still receive a tiny instruction saying:

“You are very close, but improve a little more.”

However, standard software may round that tiny instruction down to exactly zero. At the same time, it may still keep tiny instructions for the wrong classes.

This creates an impossible situation: the gradients no longer properly balance each other.

The authors call this Softmax Collapse.

A useful analogy is a very sensitive scale. If you add a tiny grain of sand to a heavy object, the scale may show no change. But if you measure the tiny grain by itself, it may still appear. Standard softmax makes a similar mistake by adding a very small number to 1.0.

Problem 2: Softmax Cancellation

The second problem appears in knowledge distillation.

In distillation:

  • A teacher model produces probabilities.
  • A student model tries to produce nearly the same probabilities.

If the teacher and student are already almost identical, the correct gradient should be nearly zero. If they are exactly identical, it should be exactly zero.

Standard software calculates the two probability lists separately and subtracts them:

1
student probabilities - teacher probabilities

When two numbers are almost equal, subtracting them can lose important digits. This is similar to subtracting:

1
1.0000001 - 1.0000000

A calculator with limited precision might produce an inaccurate answer. The paper calls this Softmax Cancellation.

The proposed solution

The researchers rewrite the calculations so that they work with tiny differences more safely. They use special mathematical functions:

  • softplus, which calculates expressions like log⁡(1+ex)\log(1+e^x) safely.
  • expm1, which calculates ex−1e^x-1 accurately when xx is very small.
  • log1p, which calculates log⁡(1+x)\log(1+x) accurately when xx is very small.

The key idea is to avoid calculating a number close to 1 and then subtracting or adding tiny values to it. Instead, the formulas calculate the small differences directly.

They also provide implementations in JAX, a software library commonly used for machine learning.

4. What did they find?

The new formulas preserve correct gradients

The fixed implementation keeps the tiny gradient for the correct class instead of rounding it to zero. It also makes sure that all the gradients add up to zero, as they should.

This is important because gradients are the instructions used to update a neural network. Incorrect instructions can cause unstable or inefficient learning.

Fewer “Slingshot” loss spikes

The authors studied grokking, a strange training behavior where a model first memorizes its training examples and only later suddenly learns to perform well on new examples.

With standard cross-entropy, the model sometimes experienced sudden jumps in loss called Slingshot spikes. These occurred when the model became so confident that the numerical error appeared.

The fixed cross-entropy removed these spikes. In several experiments, it allowed the model to learn more smoothly and reach higher test accuracy.

For example, in one experiment without weight decay:

  • Standard cross-entropy caused test accuracy to fall from about 61% to 23% after a spike.
  • The fixed version continued learning and reached about 85% accuracy.

Better performance across number formats

Computers store numbers using different levels of precision:

  • bf16 uses relatively few digits and is faster.
  • fp32 is more precise and widely used.
  • fp64 is very precise but usually slower.

The standard implementation failed at different confidence levels depending on the format. The fixed version worked smoothly across all three formats.

In the modular addition experiments, the fixed method usually reached around 99–100% test accuracy, while standard cross-entropy sometimes stalled or became unstable.

Better knowledge distillation

When the student model started with exactly the same weights as the teacher, the correct behavior was for the student to stay unchanged.

Instead, standard soft-target cross-entropy sometimes produced small incorrect gradients. These errors caused the student to move away from the teacher, especially when using lower-precision bf16 numbers.

The fixed version gave exactly zero gradient when the student and teacher were identical. As a result, the student stayed close to the teacher and maintained high accuracy.

Explaining when model confidence stops increasing

The paper also explains why a model’s confidence may eventually stop growing when weight decay is used.

Weight decay gently pulls the model’s weights toward smaller values. The training gradient pushes the model toward greater confidence. Eventually, these two effects balance each other.

The authors predict that the model’s confidence, measured by the difference between the correct score and the other scores, settles near:

log⁡(1ϵ)\log\left(\frac{1}{\epsilon}\right)

Here, ϵ\epsilon is a small setting used by the Adam optimizer. This means that a detail of the optimizer, not just the model or data, can affect how large the model’s internal scores become.

5. Why is this important?

The paper shows that some surprising training behavior may not come from deep properties of neural networks. It may instead come from small mistakes in how computers calculate numbers.

The proposed fixes could:

  • Make training more stable.
  • Prevent sudden loss spikes.
  • Improve grokking experiments.
  • Help models train reliably with fast, lower-precision arithmetic.
  • Stop student models from drifting away from teacher models during distillation.
  • Avoid needing slower fp64 calculations.

The authors say these extreme situations are not present in every machine-learning task. Most models are not always confident enough to reach the problem’s numerical limits. Still, the fixes are simple enough to use as replacements for standard softmax and cross-entropy.

Simple conclusion

The main message is:

Standard softmax and cross-entropy can make tiny but important numerical mistakes when a model is extremely confident or when two models are almost identical.

The paper introduces safer formulas that preserve these tiny differences. In experiments, the new formulas made learning smoother, removed certain training spikes, improved some accuracy results, and prevented unwanted changes during teacher–student training.

In the future, these fixes could help machine-learning systems become more reliable, especially when they use fast low-precision arithmetic or train with very confident predictions.

Knowledge Gaps

The paper leaves the following knowledge gaps, limitations, and open questions unresolved:

  • Limited empirical scale: The fixes are evaluated mainly on small modular-arithmetic grokking tasks and toy distillation settings, leaving their behavior on large language, vision, speech, and multimodal models untested.
  • Unclear practical frequency: The paper does not measure how often Softmax Collapse or Softmax Cancellation occurs in contemporary large-scale training, inference, or production distillation workloads.
  • Incomplete hardware coverage: Experiments cover bf16, fp32, and fp64 but do not evaluate fp16, TF32, FP8, quantized inference formats, or hardware-specific implementations whose rounding and accumulation behavior may differ.
  • Framework and kernel compatibility: The implementations are provided in JAX, but their correctness and performance in PyTorch, TensorFlow, XLA, CUDA kernels, fused attention kernels, and distributed training systems are not established.
  • Unquantified computational overhead: The claim of no meaningful slowdown is not supported by systematic benchmarks of runtime, memory use, kernel fusion, compilation cost, or throughput across vocabulary sizes and batch dimensions.
  • Numerical behavior under mixed precision: It remains unclear whether intermediate quantities such as logsumexp, expm1, log1p, and softplus are evaluated in sufficiently high precision in common mixed-precision pipelines.
  • Handling of tied maxima: The fixed log_softmax implementation uses an argmax and treats only one maximum as special. The numerical accuracy, gradient behavior, and invariance properties when multiple logits are exactly or nearly tied are not analyzed.
  • Stability for very large class counts: The paper does not characterize error accumulation in the margin and centered-logit computations when KK is extremely large, as in language-model vocabularies.
  • Behavior with non-finite or extreme inputs: The implementations’ behavior for NaN, +\infty, -\infty, masked logits, empty non-target sets, or logits near representational limits is not specified or tested.
  • General soft-target coverage: The proposed cancellation fix is derived for teacher distributions generated by softmax logits, but its behavior for externally supplied probabilities, sparse targets, label smoothing, mixtures of teachers, or distributions containing exact zeros is unresolved.
  • Temperature-scaling analysis: Distillation experiments use a single temperature, T=4T=4. The numerical and optimization behavior across very low and very high temperatures, including the usual temperature-dependent loss rescaling, is not studied.
  • Distillation beyond identical initialization: The experiments primarily initialize the student with the teacher’s weights. It remains unclear whether the fix materially improves ordinary distillation when the student has a different architecture, initialization, capacity, or substantially different logits.
  • Effect on other objectives: The paper does not examine softmax cancellation in KL regularization, preference optimization, policy distillation, ensemble distillation, calibration losses, or other objectives involving nearly matching distributions.
  • No systematic optimizer comparison: The Slingshot and margin-equilibrium claims are mostly examined with Adam, AdamW, and LaProp. Their validity under SGD, momentum SGD, Adagrad, Lion, Adafactor, second-order methods, and optimizer variants with different epsilon placement is not established.
  • Idealized margin-equilibrium assumptions: The derivation of m(ϵ)≈log⁡(1/ϵ)m^{(\epsilon)} \approx \log(1/\epsilon) assumes stationary parameters, converged moment estimates, exponentially shrinking gradients, and a simple relation between parameter gradients and logit margins. These assumptions are not formally validated for deep, nonlinear networks.
  • Incomplete treatment of Adam dynamics: Transient effects from bias correction, mini-batch noise, nonstationary gradients, parameter-wise sign differences, gradient clipping, learning-rate schedules, and decoupled versus coupled weight decay are not incorporated into the equilibrium analysis.
  • Unresolved role of model parameterization: The extent to which the proposed margin law depends on LayerNorm, scale invariance, residual connections, output-layer parameterization, or normalization placement remains unexplored.
  • Generalization conclusions are task-dependent: The claim that eliminating Slingshot improves grokking is supported by a small set of synthetic benchmarks, but it is unclear whether the same mechanism improves or harms generalization in natural-data tasks.
  • Interaction with regularization and training techniques: Effects involving label smoothing, dropout, data augmentation, gradient clipping, sharpness-aware optimization, learning-rate warmup, stochastic sampling, and early stopping are not investigated.
  • No formal error bounds: The paper demonstrates numerical improvements empirically but does not provide rigorous forward-error or backward-error bounds for the proposed formulas across floating-point formats and class counts.
  • Accuracy of the zero-sum correction: The final correction g←u−q∑iuig \leftarrow u-q\sum_i u_i enforces a zero-sum gradient numerically, but its effect on the accuracy of individual gradient components and on higher-order derivatives is not analyzed.
  • Higher-order autodifferentiation is untested: The custom-gradient construction using stop_gradient may produce incorrect Hessians, Jacobian-vector products, or meta-learning gradients; these cases are not evaluated.
  • Inference-time implications are unclear: The paper focuses on training gradients and losses, leaving unresolved whether the revised softmax changes probabilities, calibration, log-likelihood evaluation, ranking, or reproducibility during inference.
  • Reproducibility details are incomplete: Exact hardware, compiler versions, kernel implementations, initialization procedures, data-ordering choices, and complete hyperparameter configurations are not sufficiently documented to determine how robust the reported results are.
  • Comparison with production implementations is incomplete: The paper compares against selected standard and proposed alternatives but does not evaluate numerically stable fused cross-entropy kernels, higher-precision accumulators, loss scaling, or vendor-specific implementations.
  • Long-term training effects remain unknown: Although the fix prevents certain spikes, its consequences for optimization trajectories, margin growth, calibration, representation learning, and eventual generalization over substantially longer training horizons are not established.

Practical Applications

Immediate Applications

The paper’s fixes are drop-in numerical improvements to softmax, log_softmax, and cross-entropy, particularly valuable in low-precision training, high-confidence classification, and knowledge distillation.

  • Deep-learning framework and library updates — Software/ML infrastructure
    • Replace standard implementations in JAX, PyTorch, TensorFlow, Optax, and custom CUDA kernels with numerically stable versions based on softplus, expm1, log1p, and log-space differences.
    • Preserve the mathematically required zero-sum property of cross-entropy gradients and avoid target-gradient underflow.
    • Assumptions/dependencies: Implementations must correctly handle masking, arbitrary batch dimensions, ties in the maximum logit, sparse labels, automatic differentiation, and accelerator-specific precision behavior. Performance should be benchmarked for large class counts.
  • More reliable mixed-precision model training — AI infrastructure and cloud computing
    • Use the fixed losses in bf16 and fp16 training to reduce numerical failures without routinely casting the entire loss computation to fp64.
    • This may be useful for LLMs, vision models, recommendation systems, and speech classifiers whose training depends on low-precision accelerators.
    • Assumptions/dependencies: The paper directly evaluates bf16, fp32, and fp64, not every fp16 or quantized implementation. End-to-end benefits depend on the rest of the training pipeline, including gradient scaling, fused kernels, and optimizer state precision.
  • Stabilized knowledge distillation — Education technology, healthcare AI, robotics, and model compression
    • Replace standard soft-target cross-entropy or KL-divergence implementations when training a student model from teacher logits.
    • The corrected gradient should prevent a student initialized near the teacher from drifting solely because of rounding differences, especially in bf16.
    • Potential products include a safer distillation loss in model-compression libraries, edge-model training pipelines, and teacher–student deployment workflows.
    • Assumptions/dependencies: Teacher and student outputs must use compatible class vocabularies and temperature scaling. The method addresses numerical drift, not teacher bias, poor calibration, label mismatch, or genuinely informative differences between the two models.
  • Improved fine-tuning of high-confidence classifiers — Healthcare, finance, security, and industrial inspection
    • Apply the fixed hard-target cross-entropy when models produce very large logit margins, such as medical-image classifiers, fraud detectors, defect inspection systems, or malware classifiers.
    • The method can maintain small but correct gradients after the standard implementation’s precision cliff, reducing the risk that optimizer updates become asymmetric.
    • Assumptions/dependencies: The paper does not establish improved real-world accuracy or safety on these domains. Validation is required under domain shift, class imbalance, calibration requirements, and operational decision thresholds.
  • More stable Adam/AdamW training — General model development
    • Use the corrected loss with Adam, AdamW, RMSProp, or related adaptive optimizers to avoid artificial loss spikes caused by Softmax Collapse.
    • Training dashboards can monitor logit margins, gradient-sum error, loss discontinuities, and optimizer second moments to identify whether observed instability is numerical rather than architectural.
    • Assumptions/dependencies: The reported Slingshot mechanism is demonstrated mainly on grokking-style benchmarks. Effects in ordinary large-scale training may be smaller and should be confirmed through controlled ablations.
  • Reproducible research on grokking and implicit regularization — Academia
    • Use the fixed loss as the default baseline in studies of grokking, modular arithmetic tasks, optimizer dynamics, and generalization after memorization.
    • Researchers can avoid confusing floating-point artifacts with genuine learning phenomena and compare experiments across bf16, fp32, and fp64 more fairly.
    • The analytical relation between weight decay, Adam’s ϵ\epsilon, and equilibrium margin can also guide hyperparameter sweeps.
    • Assumptions/dependencies: The approximate law m≈log⁡(1/ϵ)m \approx \log(1/\epsilon) depends on optimizer behavior, weight decay, model parameterization, and the relationship between gradients and margins. It should not be treated as universal.
  • Numerical-quality tests for ML systems — Software engineering and model governance
    • Add unit tests that verify:
    • gradients sum to approximately zero;
    • the target gradient remains nonzero below the floating-point precision cliff;
    • the loss remains positive for extremely confident but imperfect predictions;
    • soft-target gradients become exactly or nearly zero when student and teacher logits coincide;
    • results remain stable across supported floating-point formats.
    • These tests can be integrated into CI/CD pipelines for training libraries and safety-critical ML systems.
    • Assumptions/dependencies: Tolerances must be adapted to datatype, hardware, class count, and reduction strategy. Correct loss derivatives alone do not guarantee overall numerical stability.
  • More dependable everyday AI behavior through retraining — Consumer software
    • Applications such as keyboard prediction, image classification, content moderation, and voice recognition may benefit indirectly when their underlying models are retrained with the fixed losses.
    • Users would not interact with the loss directly, but could experience fewer training instabilities, more reproducible model updates, and potentially better behavior in high-confidence cases.
    • Assumptions/dependencies: The paper does not show direct improvements in user-facing metrics, calibration, fairness, or robustness. Any deployment claim requires task-specific evaluation.
  • Training and deployment guidance for practitioners — Industry and policy
    • ML teams can document the use of numerically stable softmax and cross-entropy as part of model cards, reproducibility checklists, and low-precision deployment standards.
    • Organizations can require numerical stress tests before approving models trained with aggressive mixed precision or adaptive optimizers.
    • Assumptions/dependencies: Such guidance should be treated as a software-quality recommendation rather than a regulatory control; it does not replace validation, monitoring, or risk assessment.

Long-Term Applications

The paper also suggests broader applications that require larger-scale validation, optimized implementations, or further theoretical work before they can be considered generally reliable.

  • Fused accelerator kernels for stable cross-entropy — Hardware/software systems
    • Develop GPU, TPU, and inference-accelerator kernels that compute the corrected formulas without sacrificing the speed and memory efficiency of fused softmax-cross-entropy operations.
    • A production kernel could combine stable margin computation, logsumexp, softplus, and custom backward rules while supporting distributed and sharded class dimensions.
    • Assumptions/dependencies: The paper provides JAX-level code, not optimized kernels. Benefits depend on compiler fusion, memory bandwidth, reduction accuracy, and whether the additional masking and special-function operations create measurable overhead.
  • Numerically stable large-vocabulary language-model training — Generative AI
    • Adapt the method to sampled softmax, adaptive softmax, vocabulary parallelism, mixture-of-experts routing, and other large-output-space objectives.
    • Stable gradients could be useful when token probabilities become extremely concentrated or when teacher and student LLMs have nearly identical logits.
    • Assumptions/dependencies: The paper studies conventional finite-class softmax. Large-vocabulary systems introduce distributed reductions, approximation error, label smoothing, tied embeddings, and specialized losses that require separate analysis.
  • Robust distillation and continual model transfer — Edge AI and autonomous systems
    • Build distillation workflows in which a deployed model is compressed, personalized, quantized, or transferred to new hardware without numerical drift away from its teacher.
    • Applications could include mobile vision, autonomous robotics, speech systems, and privacy-preserving on-device adaptation.
    • Assumptions/dependencies: Stable gradients do not solve quantization error, catastrophic forgetting, domain mismatch, or teacher uncertainty. Experiments should test whether the benefit persists across architectures, temperatures, calibration methods, and distributed training.
  • Calibration and confidence-management tools — Healthcare, finance, and safety-critical AI
    • Combine stable loss computation with margin monitoring to distinguish genuine confidence from numerical saturation.
    • Future tools could provide alerts when logit margins approach datatype-specific precision cliffs or when optimizer dynamics indicate artificial spikes.
    • Assumptions/dependencies: A large margin is not equivalent to a well-calibrated probability. Additional calibration methods, uncertainty estimation, out-of-distribution testing, and human oversight remain necessary.
  • Optimizer and regularization design based on margin equilibria — Academia and ML engineering
    • Use the relationship between ϵ\epsilon, weight decay, and equilibrium margin to design optimizer settings that control post-memorization logit growth rather than allowing margins to drift until underflow.
    • This could lead to automated hyperparameter selection or optimizer variants that maintain stable normalized updates without relying on accidental precision cliffs.
    • Assumptions/dependencies: The reported equilibrium analysis assumes stationary optimizer statistics and simplified gradient behavior. Momentum transients, minibatch noise, LayerNorm, parameter sharing, and adaptive schedules may change the predicted equilibrium.
  • Formal numerical guarantees for differentiable ML primitives — Scientific computing
    • Extend the analysis to attention normalization, sigmoid losses, sparse probability transformations, contrastive objectives, and other operations where subtracting nearly equal quantities or adding a tiny value to one causes cancellation.
    • Libraries could eventually expose documented error bounds and precision-aware gradient guarantees for common neural-network primitives.
    • Assumptions/dependencies: Each primitive has distinct stability issues. The techniques in this paper cannot automatically be generalized without mathematical error analysis and extensive cross-hardware testing.
  • Standardized benchmarks for floating-point robustness — Academia, industry, and policy
    • Establish benchmark suites that evaluate model training across bf16, fp16, fp32, and fp64 while reporting loss continuity, gradient conservation, optimizer-state behavior, convergence, calibration, and downstream accuracy.
    • Such benchmarks could support procurement requirements, reproducibility standards, and comparisons among ML frameworks.
    • Assumptions/dependencies: Benchmarks must include ordinary commercial tasks, not only grokking problems, and should separate numerical improvements from changes caused by hyperparameter retuning or additional compute.
  • Safety-critical and regulated deployment workflows — Healthcare, transportation, energy, and finance
    • If large-scale validation confirms the method’s benefits, regulated ML pipelines could require stable probability-loss implementations as part of numerical verification and software validation.
    • This could reduce one class of silent training defects in systems used for diagnosis, predictive maintenance, autonomous control, grid monitoring, or risk scoring.
    • Assumptions/dependencies: The paper does not demonstrate safety improvements or reduced real-world error rates. Regulatory adoption would require evidence of material impact, traceable implementations, reproducible audits, and testing under realistic operational conditions.

Glossary

  • Adaptive optimizer: An optimization algorithm that adjusts parameter updates using statistics of past gradients. “adaptive optimizers such as Adam and AdamW”
  • Adam: An adaptive gradient-based optimizer that combines momentum with a moving estimate of squared gradients. “training after memorization alternates between flat loss plateaus near zero and sudden loss spikes”
  • AdamW: A variant of Adam that applies weight decay separately from the gradient update. “When training with adaptive optimizers such as Adam and AdamW”
  • Autodiff: Automatic differentiation, which computes derivatives of programs by systematically applying the chain rule. “so autodiff correctly computes the target gradient”
  • bf16: Brain floating-point format, a 16-bit floating-point representation commonly used in machine learning. “in bf16, values near”
  • Cross-entropy: A loss function measuring the discrepancy between a target probability distribution and a model’s predicted distribution. “For a target distribution p∈ΔK−1p \in \Delta^{K-1}, cross-entropy is then computed”
  • Distillation temperature: A scaling parameter in knowledge distillation that softens model probability distributions. “run 2,0002{,}000 steps of Adam (=2×10−3= 2\times 10^{-3}, =0= 0, =10−8= 10^{-8}) at distillation temperature T=4T = 4”
  • Exponent underflow: The numerical condition in which an exponentiated value becomes too small to be represented and rounds to zero. “it remains accurate down to exponent underflow”
  • Floating-point precision: The finite numerical accuracy determined by a floating-point representation’s significand and exponent range. “The two bugs in standard softmax and cross-entropy.”
  • Grokking: A delayed-generalization phenomenon in which a neural network memorizes its training data before abruptly generalizing. “a network quickly memorizes the training set”
  • Gradient projection: A transformation that modifies a gradient to satisfy a constraint, such as having components that sum to zero. “While prior works used surrogate losses”
  • KL divergence: Kullback–Leibler divergence, a measure of how one probability distribution differs from another. “Held-out KL(p∥q)\mathrm{KL}(p \parallel q).”
  • Knowledge distillation: Training a student model to reproduce the outputs or behavior of a teacher model. “The second bug, Softmax Cancellation”
  • LaProp: An adaptive optimization method that uses a normalized gradient estimate related to RMSProp. “RMSProp and LaProp share the same stationary point.”
  • LayerNorm: Layer normalization, which normalizes activations within each layer or token representation. “When a network uses LayerNorm before the output layer”
  • Logit: An unnormalized real-valued score produced by a model before conversion into probabilities. “Naively computing softmax or cross-entropy on logits”
  • Log-sum-exp: A numerically stabilized computation of the logarithm of a sum of exponentials. “we call the precision cliff”
  • Margin equilibrium: A stable value of the logit margin at which competing optimization effects balance. “This plateau has nothing to do with fp32 precision; rather, it is the equilibrium where weight decay balances AdamW's normalized gradient step.”
  • Moving average: A running statistic of recent values, used by optimizers to estimate gradient moments. “which normalize each gradient by a moving average of its magnitude”
  • Numerical cancellation: Loss of significant digits when subtracting nearly equal finite-precision numbers. “To avoid subtracting nearly equal probabilities”
  • Precision cliff: A threshold beyond which finite-precision rounding causes a small numerical quantity to disappear. “the e−je^{-j } term is lost to rounding once the margin”
  • ReLU Transformer: A Transformer architecture using rectified linear units as its activation function. “train a 1-layer width-$64$ ReLU Transformer”
  • RMSProp: An adaptive optimizer that scales gradients using a moving average of their squared values. “Here ,,, and cancelout,soRMSProp”</li><li><strong>Softmax</strong>:Afunctionthatconvertsavectoroflogitsintonormalizedprobabilitiesusingexponentials.“Standardimplementationsofsoftmax,log−softmax,and”</li><li><strong>Softplus</strong>:Anumericallystablesmoothapproximationtotherectifiedlinearunit,definedas cancel out, so RMSProp”</li> <li><strong>Softmax</strong>: A function that converts a vector of logits into normalized probabilities using exponentials. “Standard implementations of softmax, log-softmax, and”</li> <li><strong>Softplus</strong>: A numerically stable smooth approximation to the rectified linear unit, defined as \log(1+e^x).“weset. “we set z_{} = 0$, compute the margin”
  • Surrogate loss: An alternative loss function introduced to approximate or replace the original objective for numerical or optimization purposes. “While prior works used surrogate losses”
  • Underflow: Numerical rounding of a value below the smallest representable magnitude to zero. “which would otherwise underflow in fp32”
  • Weight decay: A regularization method that shrinks model parameters during optimization to discourage large weights. “the equilibrium where weight decay balances AdamW's normalized gradient step”

Open Problems

We haven't generated a list of open problems mentioned in this paper yet.

Tweets

Sign up for free to view the 15 tweets with 710 likes about this paper.

HackerNews

  1. A Fix for Softmax and Cross-Entropy (3 points, 0 comments)