Create and explore imaginative 3D worlds with our new product Dreamfield (opens in a new tab)
Papers
Topics
Authors
Recent
Search
2000 character limit reached

The KL Divergence Is Never Negative, Except in PyTorch

Published 23 Nov 2026 in cs.LG | (2611.30835v1)

Abstract: A Kullback--Leibler (KL) divergence is never negative, yet PyTorch users have reported negative values for years, and the standard advice is to clamp them at zero. The sign is only the visible part of a silent failure. Many machine-learning applications compare nearby distributions, where conventional KL formulas lose accuracy. On 8.5 million inputs with certified references across 18 closed-form KL families and F.kl_div, we find widespread errors in values and gradients on CPU and GPU. Among scalar families in ordinary parameter ranges, over 85% of FP32 values have at least 1% relative error near KL 10-7 (FP16: 10-3), and about 30% become negative at smaller divergences. More precision is not the cure: evaluated one precision higher, the same formulas still leave 7--51% of FP32 values significantly wrong for 22 of 23 configurations. Stable closed-form decompositions, compensated arithmetic, and analytic gradients remove over 97% of significant errors in the working format. Strict repairs eliminate significant errors on 7.2 million scored closed-form samples and correctly round all 567 million scored F.kl_div components. The errors affect parameter fitting, Bayesian decisions, identical-start distillation (up to 97% top-1 disagreement), KL-based layer rankings in a quantized LLM, and 19--59% of GPT-2 circuit edge scores. With the repaired code they all but vanish. Code and data: https://github.com/xi-xiaoran/stablekl

Summary

  • The paper demonstrates that PyTorch KL implementations suffer structural cancellation, producing inaccurate values, negative outputs, and faulty gradients across 18 distribution families and `F.kl_div`.
  • The authors use certified interval-arithmetic references to show that stable algebraic reformulations eliminate significant errors, while simply clamping negatives or promoting calculations to higher precision does not reliably fix them.
  • The findings affect optimization, distillation, Bayesian design, quantization ranking, and model diagnostics, motivating KL computation from raw parameters or logits with compensated arithmetic and stable gradients.

Numerical failure is structural, not merely a sign error

The paper examines a basic but consequential discrepancy between the mathematical KL divergence and its implementation in PyTorch. Although DKL(P∥Q)≥0D_{\mathrm{KL}}(P\|Q)\ge 0, PyTorch’s torch.distributions.kl_divergence and torch.nn.functional.kl_div can return negative, zero, non-finite, or materially inaccurate values. The central claim is stronger than the familiar observation that floating-point arithmetic occasionally produces small negative numbers: clamping negative outputs does not repair the underlying computation, because positive outputs and gradients can remain substantially wrong.

The mechanism is cancellation near distributional equality. For nearby distributions, the true divergence is generally second order in the perturbation, while conventional closed forms subtract or combine terms of zeroth- or first-order magnitude. For two Exponential distributions with r=λq/λp=1+xr=\lambda_q/\lambda_p=1+x,

DKL(P∥Q)=r−1−log⁡r=x22+O(x3).D_{\mathrm{KL}}(P\|Q)=r-1-\log r =\frac{x^2}{2}+O(x^3).

The direct implementation evaluates quantities near one whose absolute rounding error is on the order of the unit roundoff uu. Consequently, the relative error scales approximately as 2u/x22u/x^2. In FP32, the returned divergence becomes unreliable when the true KL is around 10−810^{-8} or smaller; in FP16, the corresponding threshold moves into the range of ordinary machine-learning computations.

Figure 1

Figure 1: Direct evaluation of the Exponential KL suffers catastrophic relative error near equality, whereas the repaired computation maintains format-level accuracy and prevents identical-start distillation drift.

For λp=1\lambda_p=1 and λq\lambda_q equal to the FP32 representation of $1.0001$, the true KL is approximately 5.0013×10−95.0013\times10^{-9}, but the direct expression rounds to zero. The two distributions are distinct, yet the implementation reports equality. At still smaller divergences, the result can become negative. The same cancellation affects automatic differentiation: gradients derived from unstable expressions can vanish, acquire large relative errors, or point in an ascent direction.

This phenomenon is not confined to one distribution family or one kernel. The authors evaluate 18 same-family closed forms across 23 parameter and dimensional configurations, together with F.kl_div, using 7,542,469 closed-form inputs and 942,200 batches for the tensor interface. References are certified with Arb interval arithmetic, and the comparisons are performed against the exact correctly rounded result for the bit patterns received by the library. This protocol separates implementation error from error already present in the input representation.

Empirical scope of the PyTorch errors

The study stratifies samples by true KL, from 10−1510^{-15} to $1$, and includes ordinary and stress parameter regions, one-to-eight-ULP perturbations, and identity cases. The degradation is systematic as PP and QQ approach one another.

Among scalar families in ordinary FP32 parameter regions, 86.4% of values with true KL in the interval around 10−710^{-7} have relative error at least 1%, increasing to more than 96% around 10−810^{-8}. Approximately 29% of outputs are negative for sufficiently small KL. In FP16, 86.8% of values around KL 10−310^{-3} are wrong by at least 1%, and the negative-output rate reaches approximately 30% in smaller-divergence bins.

Gradients fail at a different scale. At true KL around 10−1310^{-13}, one fifth of FP32 gradient vectors have relative error exceeding 1%; at 10−1510^{-15}, 6.8% point into the opposite half-space. Thus, a non-negative loss value is not sufficient evidence that its optimization signal is usable.

The results are consistent across hardware. The aggregate significant-error rate for interface A is 87.7% for FP32 inputs and approximately 70–71% for FP16 inputs on CPU and an NVIDIA A100 GPU. Nevertheless, the official CPU and GPU implementations disagree bitwise for 27% of FP32 KL values. The repaired implementation has no significant errors in the evaluated interface-A samples on either device.

Figure 2

Figure 2: Promoting the unchanged PyTorch formulas to the next precision shifts the failure range but leaves substantial error, whereas cancellation-free reformulations address the source of the instability.

The paper’s precision experiment directly challenges the common prescription to “use more precision.” Evaluating the unchanged formula one format higher leaves 7–51% of FP32 values significantly wrong in 22 of 23 configurations. For FP32 inputs, promotion to FP64 moves the principal failure curve downward by roughly nine orders of magnitude, but does not eliminate it because the original FP32 inputs may differ by only one representable unit. In that case, the higher-precision computation cannot reconstruct information discarded during input formation.

Interface A: closed-form divergences and stable reformulation

The repair strategy is based on algebraic representations that preserve the non-negativity and local quadratic structure of the KL. The key building block is

φ(x)=x−log⁡(1+x)≥0,x>−1.\varphi(x)=x-\log(1+x)\ge 0,\qquad x>-1.

Direct evaluation of φ\varphi still suffers cancellation near zero, so the implementation uses exact identities involving log1p, atanh, compensated differences, and format-specific series expansions. The implementation also computes parameter differences directly, uses error-free transformations for differences of products, and supplies analytic gradients rather than differentiating the unstable original expression.

For example, the direct Normal KL combines variance and mean terms as

12(r2+w2−1−log⁡r2),\frac{1}{2}\left(r^2+w^2-1-\log r^2\right),

where r=σp/σqr=\sigma_p/\sigma_q and w=(μp−μq)/σqw=(\mu_p-\mu_q)/\sigma_q. When r≈1r\approx1, the w2w^2 contribution can be absorbed into a quantity near one before subtraction. The repaired form is

φ(e)+12e2+12w2,e=σp−σqσq,\varphi(e)+\frac{1}{2}e^2+\frac{1}{2}w^2, \qquad e=\frac{\sigma_p-\sigma_q}{\sigma_q},

which represents the divergence as a sum of non-negative components. Analogous decompositions are developed for Cauchy, Uniform, Exponential, Poisson, Laplace, Pareto, Bernoulli, Binomial, Geometric, Gumbel, Gamma, Beta, Dirichlet, Categorical, multivariate Normal, and low-rank multivariate Normal distributions.

The resulting difference between the official and repaired implementations is substantial:

Configuration Official significant-error rate Rewritten same-format rate Strict repaired rate
FP32, scalar families 75–97% in the reported families 0–0.7% 0%
FP16, scalar families 42–97% 0–2.5% 0%
FP32 multivariate Normal 88.6–93.4% 0% 0%
FP32/FP16 Categorical 46.6–90.5% at most 0.01% 0%

Across the 7,234,454 scored closed-form samples, the strict implementation produces no significant KL-value or gradient error, returns exact zero on identity cases, and never returns a negative or NaN KL. The same-format rewrite removes more than 97% of significant errors in every configuration, although residual errors remain near genuine gradient zero crossings and are most pronounced for Beta and Dirichlet.

The strict implementation evaluates the repaired formula in FP64 and rounds once to the target format. It also uses midpoint-aware rounding and interval recomputation when the result is close to a target-format boundary. This distinction matters because FP64 computation followed by FP32 and FP16 conversion can introduce double-rounding errors. The cost is nontrivial: the reference implementations are approximately 2.4–5.9 times slower than the official GPU calls for several common families, with substantially larger overhead for Gamma and Beta. The paper therefore demonstrates numerical correctness rather than a production-ready performance implementation.

Figure 3

Figure 3: In the ordinary FP32 parameter region, significant errors are widespread for PyTorch’s closed forms across small KL intervals, while the repaired implementation has no significant errors.

Interface B and the separation of two error sources

torch.nn.functional.kl_div has a different failure profile. With probability targets, the element-wise expression t(log⁡t−x)t(\log t-x) cancels when t≈ext\approx e^x. With log-probability targets, the expression et(t−x)e^t(t-x) is generally more stable in the forward pass, but reductions and backward formulas introduce additional problems.

For FP32 probability targets, 35–70% of sum outputs are wrong by at least 1% in the small-KL regime. In FP16 with reduction="mean" and K=256K=256, 95.4% of gradient rows contain a component with the wrong sign. A major source is the automatically differentiated expression (g t)/t(g\,t)/t: the exact derivative contains the upstream factor gg, but the implementation forms the product g tg\,t first, allowing subnormal underflow before division.

Across 83,899,496 scored forward components and 483,279,156 backward components, the official implementation is correctly rounded for only 52.5% and 74.9%, respectively. The repaired implementation correctly rounds all scored components, with no regressions in the benchmark.

Figure 4

Figure 4: The official F.kl_div exhibits substantial small-divergence error in forward reductions, whereas the repaired operator correctly rounds all scored components.

A particularly important contribution is the separation between operator error and input-representation error. Let TopT_{\mathrm{op}} denote the exact KL operator applied to the stored inputs, and Te2eT_{\mathrm{e2e}} the exact KL obtained from the original logits before their conversion into rounded probabilities or log-probabilities. Improving F.kl_div can eliminate the former but not the latter. The paper finds that TopT_{\mathrm{op}} differs from Te2eT_{\mathrm{e2e}} by at least 1% on 40–99% of batches, depending on the configuration, even when the operator is evaluated in higher precision.

This distinction invalidates a seemingly reasonable repair strategy for language-model applications: casting already-rounded softmax outputs to FP64 and then applying a more accurate KL kernel. The information needed to recover the original distribution is absent. The paper instead advocates computing the divergence directly from logits, using centered logit differences, expm1, compensated reductions, and a non-negative local decomposition. This logits path addresses both operator cancellation and the representation error caused by rounded probabilities.

Consequences for optimization and Bayesian decision-making

The downstream experiments establish that the numerical defects can affect both optimization and discrete decisions, although not every application is sensitive.

In a Geometric-distribution fitting experiment, the target distribution is represented exactly by the optimization problem. Nevertheless, in FP16, the official KL fails to reach a target with p⋆=0.001p^\star=0.001 from any of 12 starts. The median relative parameter deviation is 95%, and the true KL can reach 1.7. At the nominal optimum, the official implementation can report a loss of 0.098 and a gradient of −100-100, despite the exact loss and gradient being zero. The repaired implementation reaches the target bit pattern from all starts.

Figure 5

Figure 5: In FP16 Geometric fitting, the unstable official KL prevents convergence to the exact target, while the repaired computation reaches the target across the tested starts.

The Bayesian experimental-design experiment is more consequential because the numerical error enters a feedback loop. Ten Bernoulli arms are selected according to expected information gain, which is computed from Beta KL divergences. As posterior concentrations grow, the true information gain decreases into the regime in which the official Beta formula is unstable. For example, at concentration n=105n=10^5, the true divergence between Beta(n+1,n)\mathrm{Beta}(n+1,n) and Beta(n,n)\mathrm{Beta}(n,n) is approximately 2.5×10−62.5\times10^{-6}, whereas the official implementation returns approximately $0.31$.

In seven of eight settings, 40–91% of acquisition rounds select a suboptimal arm under the official implementation, and 35–60% of its computed information gains are zero or negative. With large committed batches, the consequence is amplified: from a warm start with batch size 10410^4, the total posterior variance is 1.2–5.2 times that of the exact policy, and the worst-arm variance is up to 11 times larger. The repaired implementation makes no wrong decision in any of the 40 runs. The implication is specific: numerical KL error can change an adaptive experimental policy when the policy itself drives divergences toward zero.

Identical-start distillation and the role of the backward pass

The distillation experiment isolates a case in which any parameter movement is necessarily numerical. A student MLP is initialized as an exact copy of its teacher and trained using only forward KL. Mathematically, the loss and gradient are exactly zero.

Under the official implementations, the student moves in all 2,160 runs. Under the logits path, it does not move in any of 720 runs. With Adam and a vocabulary of 151,936, FP16 top-1 disagreement reaches 97.4% at learning rate 10−210^{-2}; FP32 disagreement reaches 47.2%, and BF16 disagreement reaches 46.1%. The effect is much smaller under SGD because SGD scales the update directly with the small spurious gradient, whereas Adam normalizes it into a full-size update.

Figure 6

Figure 6: Identical-start distillation converts a small numerical gradient into large prediction disagreement under Adam, while the logits path preserves the exact stationary point.

The attribution analysis is important. Replacing only the KL operator produces bit-identical trajectories to the official runs, indicating that the dominant spurious parameter gradient arises during log_softmax backward, where rounded student and teacher probabilities are subtracted. Thus, fixing the forward F.kl_div expression alone is insufficient for this use case. The logits path avoids the problematic probability-space backward computation.

The experiment should not be interpreted as evidence that all distillation is unstable. Additional tests reported in the appendix find little or no effect when the student begins at a nontrivial distance from the teacher, because the true gradient then dominates the absolute numerical perturbation. The demonstrated failure is specifically strongest when the distributions are identical or nearly identical by construction.

Language-model evaluation, quantization, and circuit scores

The paper evaluates Qwen2.5-1.5B-Instruct on 16,384 WikiText-2 tokens, comparing original and quantized models. For near-lossless 8-bit quantization, official FP16 F.kl_div underestimates the mean KL by 19.0% for GPTQ and 4.4% for RTN; 30.2% and 12.3% of tokens, respectively, have negative KL values. With reduction="mean", the reported value can become exactly zero.

Repairing the operator on the same FP16 probability inputs eliminates operator error but does not recover the original-logit KL: 98.8% and 96.8% of tokens remain at least 1% from the end-to-end reference. The logits path has zero negative or infinite values and matches the rounded FP64 reference on every evaluated FP16 and FP32 token.

The same issue affects layer-sensitivity rankings for mixed-precision quantization. For 8-bit single-layer quantization, official FP16 F.kl_div inverts 19 of 378 layer pairs, while log_target=True inverts 35. BF16 Categorical KL is not rankable because of infinities. The logits path produces no inversions and Kendall’s τb=1\tau_b=1. In one BF16 configuration, the unstable ranking selects four wrong layers and increases the true KL of the resulting mixed model by 9.78% on a disjoint evaluation set. At 4-bit quantization, the divergences are larger and most methods become reliable, illustrating that the failure depends on the scale of the measured change rather than on quantization alone.

The paper also reports severe errors when measuring execution gaps between different evaluations of the same model. For cached decoding versus a full FP32 forward pass, the true KL is 8.1×10−118.1\times10^{-11}, while official F.kl_div has relative error −2304%-2304\%; in FP16 the true KL is 1.8×10−51.8\times10^{-5} and the error is −684%-684\%. The logits path has zero reported relative error in the listed cases. In FP16, the result from reduction="mean" depends on the number of rows processed together because individual terms underflow before reduction. This violates the expectation that a divergence should be invariant to batch partitioning.

For mechanistic-interpretability circuit scores, the impact is concentrated in tiny edge effects. In FP32, the official score is wrong for 19.3% of GPT-2-small IOI edges, 45.8% of Greater-than edges, and 58.8% of GPT-2-medium IOI edges; in FP16, the corresponding rates reach 81.4%, 6.8%, and 81.1%. GPT-2 medium recovers only 38% of the reference top-1,000 edges under the official FP16 score, compared with 99.9% for the logits path. The larger model is more affected in this experiment because its edge divergences are smaller, although the authors appropriately restrict this conclusion to the evaluated tasks and models.

Limitations and open questions

The numerical conclusions are conditional on a deliberately stratified sampling design that oversamples small divergences and stress regions. The benchmark uses PyTorch 2.15.0 on CPU and PyTorch 2.4.0 on an A100 GPU, so behavior in other versions, devices, kernels, and compiler paths remains open. The A100 comparison is also not a same-version CPU–GPU experiment in every interface.

The repaired implementations are reference implementations rather than optimized replacements. The strict F.kl_div repair can be 27–59 times slower on an A100 and up to 222 times slower on CPU for large inputs. Beta and Gamma repairs are particularly expensive because they use specialized quadrature and high-accuracy special-function evaluation. Whether comparable guarantees can be achieved with substantially lower overhead is not established.

The downstream experiments are heterogeneous and often narrow: parameter fitting uses one distribution family; Bayesian design uses simulated Bernoulli arms and one acquisition rule; distillation uses identical initialization; the language-model experiments use one Qwen model and one corpus; circuit experiments use one batch per setting, with GPT-2 medium only partially sampled. The paper also reports several settings with no measurable downstream effect, including ordinary PPO decisions, TRPO Fisher-vector products, some LoRA experiments, and distillation from already separated quantized models. These null results delimit the claim: the paper does not show that PyTorch KL errors routinely corrupt standard training.

A remaining technical question is how to expose these semantics in a practical API. The strict implementation distinguishes exact zeros, correctly rounded results, structural domain boundaries, and input-representation error. It remains open which subset of these guarantees should be incorporated into high-performance default kernels, and how the same design should be generalized to other probabilistic primitives whose values are formed by cancellation.

Conclusion

The paper establishes that negative KL values in PyTorch are only the most visible manifestation of a broader numerical instability. Across 18 closed-form families and F.kl_div, conventional formulas become unreliable when nearby distributions produce second-order divergences through cancellation of larger terms. Higher precision alone is insufficient for the closed forms; stable algebraic decomposition, compensated arithmetic, analytic differentiation, and, when necessary, strict final rounding are required.

The repaired implementations eliminate significant errors in the certified benchmark and prevent failures in parameter fitting, Bayesian allocation, identical-start distillation, quantization sensitivity ranking, execution-gap measurement, and circuit scoring. The practical prescription is correspondingly specific: compute KL from raw parameters or logits, preserve non-negative decompositions, avoid clamping as a substitute for repair, and distinguish operator accuracy from information already lost during low-precision probability formation (2611.30835).

Whiteboard

Explain it Like I'm 14

1. What is this paper about?

This paper investigates a surprising problem in PyTorch, a popular tool for building artificial intelligence systems.

The problem involves something called KL divergence. KL divergence measures how different one probability distribution is from another. For example, it could measure how different a student AI’s answers are from a teacher AI’s answers.

Mathematically, KL divergence can never be negative. It should be:

  • Zero when two distributions are exactly the same.
  • Positive when they are different.

However, PyTorch sometimes reports negative values, zero when the distributions are different, or other inaccurate answers.

The paper argues that negative values are only the most obvious symptom. Many incorrect results still look normal because they are positive and finite.

2. What questions did the researchers ask?

The researchers wanted to find out:

  1. How often does PyTorch calculate KL divergence incorrectly?
  2. Does the problem happen only for certain kinds of probability distributions?
  3. Does it happen on both computers and graphics cards?
  4. Can using a higher-precision number format solve the problem?
  5. Can the researchers design better formulas that are both accurate and stable?
  6. Do these errors actually affect machine-learning tasks?

The last question is especially important. A tiny numerical error might seem harmless, but in an AI system it can affect training, rankings, or important choices.

3. How did the researchers investigate the problem?

Testing many distributions

The researchers tested PyTorch’s KL-divergence calculations for 18 different families of probability distributions, including:

  • Normal distributions
  • Exponential distributions
  • Bernoulli distributions
  • Categorical distributions
  • Beta and Gamma distributions
  • Multivariate normal distributions

They created more than 7 million pairs of distributions for one PyTorch interface. They also tested nearly 1 million groups of inputs for another interface, called F.kl_div.

Some pairs were very different, while others were almost identical.

Creating a trustworthy answer

To know whether PyTorch was wrong, the researchers needed a highly accurate answer for comparison. They used interval arithmetic, a technique that calculates a safe range containing the true answer.

An everyday analogy is measuring the length of a pencil with a very precise ruler and saying, “The true length must be between 14.9999 and 15.0001 centimeters.” This gave the researchers a reliable reference.

Testing different number formats

Computers store numbers with limited precision. Common formats include:

  • FP16, which uses fewer bits and is faster but less accurate.
  • FP32, commonly used in machine learning.
  • FP64, which stores numbers more accurately but requires more memory and computation.

The researchers tested these formats on both CPUs and GPUs.

Testing improved formulas

The researchers did not only test the old PyTorch formulas. They designed improved versions using several ideas:

  • Rewriting formulas to avoid subtracting nearly equal numbers.
  • Breaking the answer into parts that cannot be negative.
  • Using more careful addition and multiplication.
  • Computing gradients directly instead of letting automatic differentiation work on unstable formulas.
  • Computing KL divergence directly from model logits, which are the raw scores produced before probabilities are calculated.

4. Why do the errors happen?

The main problem is called cancellation.

Imagine calculating:

1
1.00000001 - 1.00000000

The answer is very small. But if the computer rounds both numbers before subtracting them, it might store them as the same number and produce zero.

KL divergence often has the same problem. When two distributions are very similar, the true KL divergence is extremely small. But the formula may calculate it by subtracting or combining much larger numbers.

For example, the real answer might be:

1
0.000000005

But the computer may round the calculation to:

1
0

It might even produce a small negative number, despite the mathematical answer being positive.

This is similar to trying to hear a quiet whisper while standing next to a loud machine: the small signal gets hidden by the noise.

5. What did the researchers find?

PyTorch often gives wrong answers for very small KL values

When the true KL divergence was around 10−710^{-7} in FP32, about 86% of the tested values were wrong by at least 1%.

For even smaller values, roughly 30% became negative.

The problem appeared across all the tested distribution families. It was not limited to one special type of probability distribution.

The problem also appeared on both CPUs and GPUs.

More precision alone is not enough

The researchers tried calculating the existing formulas with one higher precision level. This helped somewhat, but it did not solve the problem.

For many settings, between 7% and 51% of FP32 results were still significantly wrong.

The reason is that the original input numbers may already have been rounded. Using more precision afterward cannot recover information that was lost earlier.

The gradients can also be wrong

A gradient tells a machine-learning system which direction to change its parameters to improve.

If the KL value is inaccurate, its gradient may also be inaccurate. In some extremely small cases, the gradient pointed in almost the opposite direction from the correct one.

This can cause an AI system to learn incorrectly.

The improved formulas worked much better

The researchers’ rewritten formulas removed more than 97% of significant errors in ordinary working precision.

Their strict version had:

  • No significant errors in more than 7.2 million tested closed-form examples.
  • Correctly rounded results for all tested components of F.kl_div.
  • No negative KL values.
  • Exact zero results when the two distributions were truly identical.

The improved methods were slower because they performed more careful calculations. On some GPU tests, they took about 2.4 to 5.9 times longer than the original code.

The errors changed real machine-learning results

The paper tested several applications.

Application What went wrong with the original calculations
Parameter fitting The system sometimes failed to learn a target distribution it was given exactly
Bayesian decision-making The system selected the wrong experiment or probability group in many rounds
Knowledge distillation A student model changed even when it started as an exact copy of its teacher
Quantized LLMs Incorrect KL values caused bad rankings of model layers
GPT-2 circuit analysis Many small importance scores were wrong or negative

One especially striking result came from knowledge distillation. A student model began as an exact copy of its teacher, so it should not have changed when trained only to match the teacher. With the original PyTorch calculations, it did change. In one large-vocabulary FP16 experiment, its final top prediction disagreed with the teacher on 97.4% of examples.

With the repaired calculation, the student did not move at all, as expected.

6. Why are these findings important?

KL divergence is used in many parts of modern AI, including:

  • Training generative models
  • Comparing a student model with a teacher model
  • Reinforcement learning
  • Bayesian statistics
  • Studying how much a model changes after compression or quantization
  • Analyzing which parts of a neural network are important

If KL divergence is wrong, an AI system may:

  • Stop learning too early.
  • Change when it should stay the same.
  • Choose the wrong option.
  • Rank model components incorrectly.
  • Report misleading scientific results.

Simply forcing negative answers to zero, called clamping, does not really solve the problem. It hides the visible symptom but leaves other inaccurate positive answers and incorrect gradients unchanged.

7. What should developers do?

The paper recommends several practical improvements:

  1. Do not assume that a negative KL value is the only problem. Positive values may also be inaccurate.
  2. Avoid calculating KL divergence from already-rounded probabilities when possible.
  3. Calculate it directly from logits or original distribution parameters.
  4. Use formulas designed to remain accurate when distributions are very close.
  5. Use higher precision when exact rounding is especially important.
  6. Test numerical software against highly accurate reference calculations.

Conclusion

The paper shows that KL divergence is mathematically safe, but computer programs can calculate it badly because computers use rounded numbers.

The problem is most serious when two distributions are nearly identical—the exact situation found in many AI applications. The old PyTorch formulas can return inaccurate, zero, or negative answers, and these errors can affect training and scientific decisions.

The researchers developed more careful formulas that greatly reduce or eliminate the errors. Their work suggests that reliable numerical code is not just a minor programming detail. It is an important part of making AI systems behave correctly and producing trustworthy research results.

Practical Applications

Immediate Applications

The paper’s central practical recommendation is to replace cancellation-prone KL implementations with stable decompositions, compensated arithmetic, analytic gradients, or a logits-based computation path. These applications can be implemented now, although production deployment should include validation against high-precision references and performance testing.

  • Numerically stable PyTorch KL operators — software infrastructure and ML tooling
    • Replace calls to torch.distributions.kl_divergence and torch.nn.functional.kl_div with the paper’s repaired implementations or equivalent stable formulas.
    • Package the methods as a drop-in library, for example:
    • stablekl.distributions.kl_divergence
    • stablekl.functional.kl_div
    • a fused categorical loss accepting teacher and student logits directly.
    • This would prevent negative, zero-for-distinct, non-finite, or materially inaccurate KL values in FP16, BF16, and FP32 workflows.
    • Dependencies: The implementation must cover the relevant distribution families, preserve PyTorch autograd semantics, support CPU and GPU kernels, and be benchmarked because the reference repairs cost approximately 2.4–5.9× more than standard calls for several families.
  • A numerical audit for existing machine-learning pipelines — industry and academia
    • Search codebases for KL-dependent components, including VAEs, Bayesian neural networks, policy optimization, distillation, model compression, circuit analysis, and probabilistic programming.
    • Add tests covering:
    • identical distributions,
    • distributions differing by one or a few ULPs,
    • very small positive KL values,
    • FP16/BF16 and FP32 execution,
    • forward and backward gradients,
    • CPU/GPU consistency.
    • Treat negative KL as a diagnostic failure rather than simply applying torch.clamp(kl, min=0).
    • Dependencies: Teams need access to original logits or distribution parameters and must distinguish operator error from errors already introduced when probabilities or log-probabilities were rounded.
  • Stable knowledge distillation — education technology, foundation models, and model serving
    • Compute teacher–student divergence directly from teacher and student logits rather than from separately rounded softmax probabilities or log-probabilities.
    • Use the logits path in:
    • language-model distillation,
    • speech-recognition distillation,
    • vision-model compression,
    • student–teacher anomaly detection,
    • deployment of smaller models on edge devices.
    • This can eliminate spurious parameter updates when the student is initialized as a copy of the teacher. The paper reports up to 97% top-1 disagreement under some unstable FP16 settings, compared with no observed drift using the repaired path.
    • Dependencies: Teacher and student logits must be available, and the fused implementation must handle masking, temperature scaling, large vocabularies, distributed training, and mixed precision.
  • Reliable KL-based model quantization and mixed-precision selection — hardware and AI deployment
    • Use the logits-based KL to rank the sensitivity of layers to quantization and to select which layers should remain in FP16 or FP32.
    • Integrate the computation into workflows for RTN, GPTQ, AWQ, pruning, and mixed-precision deployment.
    • The result can prevent incorrect layer rankings caused by negative or tied KL values and avoid selecting a mixed-precision configuration that increases the true divergence.
    • Dependencies: Quantization evaluation must compare the same stored logits or model outputs, and the ranking should be validated on held-out inputs rather than assumed to generalize from a single calibration set.
  • More reliable reinforcement-learning and policy-optimization diagnostics — robotics and autonomous systems
    • Replace unstable KL calculations in PPO-style trust-region constraints, policy-monitoring dashboards, policy rollback systems, and RL fine-tuning pipelines.
    • Compute policy divergence from policy logits, especially when consecutive policies are close and low precision is used.
    • This can prevent inaccurate trust-region penalties, incorrect early stopping, or acceptance of policy updates that actually exceed a divergence threshold.
    • Dependencies: The repair must be integrated consistently into both the forward loss and gradient computation; action masking, variable-length trajectories, distributed reductions, and policy parameterization must be handled correctly.
  • Improved Bayesian experimental design and adaptive sampling — healthcare, science, and finance
    • In sequential Bayesian design, use stable Beta, Bernoulli, Dirichlet, or categorical KL implementations when selecting the next experiment, patient subgroup, financial scenario, or sensor measurement.
    • An immediate workflow is:
    • 1. compute the expected information gain for each candidate action;
    • 2. evaluate it with a stable KL routine;
    • 3. validate close decisions with higher precision or interval arithmetic;
    • 4. choose the action only when the ranking is numerically reliable.
    • This is particularly relevant when posterior updates become large and incremental information gains become very small.
    • Dependencies: The chosen action may still be sensitive to modeling assumptions, prior specification, Monte Carlo error, and ties between nearly equal information gains. Stable arithmetic does not correct a misspecified Bayesian model.
  • Correct probabilistic parameter fitting — statistics and scientific computing
    • Use stable KL values and analytic gradients when fitting one distribution to another, calibrating probabilistic forecasts, or optimizing variational parameters.
    • Applicable families include Normal, Gamma, Beta, Dirichlet, categorical, geometric, Poisson, and related distributions supported by the repair.
    • This is useful for variational inference, calibration, synthetic-data fitting, and likelihood-free optimization where the optimum requires both the loss and gradient to approach exact zero.
    • Dependencies: Stable arithmetic cannot resolve errors from poorly scaled parameters, invalid supports, inaccurate special functions outside the tested range, or an unsuitable optimizer.
  • Trustworthy interpretability and circuit-discovery scores — research tooling
    • Replace standard KL calls in activation patching, edge ablation, causal tracing, and circuit-discovery libraries.
    • Compute the divergence between clean and ablated outputs from logits and use stable scores for thresholding and ranking.
    • This can reduce false negative scores, negative edge importances, and incorrect top-edge selections, especially in FP16/BF16 or for large models where most effects are tiny.
    • Dependencies: The score definition must be compatible with a logits-based divergence, and researchers should report numerical precision, score stability, and sensitivity to thresholds.
  • Numerical-regression tests for ML frameworks and hardware backends — academia and industry
    • Add certified tests based on interval or arbitrary-precision arithmetic to continuous integration for PyTorch-like frameworks, GPU kernels, compilers, and accelerator libraries.
    • Test both value and gradient correctness, including correct rounding, exact identity behavior, and CPU/GPU consistency.
    • Such tests could detect regressions when kernels are rewritten, fused, or lowered to specialized hardware.
    • Dependencies: Reference generation is computationally expensive, and “correctly rounded” behavior may require architecture-specific handling of reductions, fused operations, and transcendental functions.
  • Better user-facing diagnostics and monitoring
    • Implement warnings when:
    • KL is negative,
    • KL is exactly zero despite materially different inputs,
    • a distribution comparison is below the estimated precision floor,
    • probabilities were computed in a lower precision than the divergence requires,
    • CPU and GPU results disagree materially.
    • A practical diagnostic tool could report whether the dominant problem is operator cancellation or input-representation error.
    • Dependencies: Diagnostics need thresholds adapted to dtype, dimension, reduction mode, and distribution family; warnings should not be interpreted as proof that the underlying model is incorrect.

Long-Term Applications

The following applications require further engineering, broader validation, or changes to numerical libraries and hardware ecosystems before they can become standardized.

  • Upstream integration into PyTorch and other numerical libraries
    • Incorporate stable closed forms, compensated reductions, analytic gradients, and logits-based categorical KL directly into PyTorch, TensorFlow Probability, JAX, Stan, Pyro, and related libraries.
    • A mature API could offer:
    • a fast approximate mode,
    • a stable mode,
    • a strict correctly rounded mode,
    • automatic fallback based on the estimated divergence scale.
    • Dependencies: Upstream adoption requires backward compatibility, kernel optimization, API agreement, support for all relevant distribution families, and evidence that the runtime cost is acceptable for large-scale training.
  • Adaptive-precision KL computation
    • Develop algorithms that estimate cancellation risk and dynamically select FP16, BF16, FP32, FP64, compensated arithmetic, or interval arithmetic.
    • For example, a library could use a fast low-precision path for large KL values and automatically invoke a stable or strict path when the divergence approaches the unit-roundoff scale.
    • Dependencies: Reliable error estimators must be developed for high-dimensional distributions, GPU reductions, sparse probabilities, and batched workloads. Adaptive switching must not introduce unacceptable latency or nondeterminism.
  • Hardware-supported accurate divergence primitives
    • Design GPU, TPU, and edge-AI instructions for:
    • correctly rounded log1p and expm1,
    • compensated summation,
    • error-free transformations,
    • accurate log-sum-exp and softmax,
    • fused logits-to-KL operations.
    • Such primitives could make stable KL affordable in real-time robotics, autonomous control, and large-scale model training.
    • Dependencies: Hardware support must balance silicon area, power consumption, throughput, reproducibility, and compatibility with IEEE-754 behavior.
  • Certified numerical guarantees for safety-critical AI
    • Extend the paper’s interval-arithmetic approach into certification frameworks for medical decision systems, autonomous vehicles, industrial control, and financial risk models.
    • A system could certify that:
    • a divergence is positive,
    • a policy update remains within a trust region,
    • a Bayesian action ranking is not changed by rounding,
    • a quantization decision preserves a specified output tolerance.
    • Dependencies: Numerical certification addresses arithmetic uncertainty, not data uncertainty, distribution shift, model misspecification, or software defects elsewhere in the pipeline. End-to-end certification will require compositional error bounds.
  • Reliable information-theoretic control for robotics
    • Use certified KL estimates in active sensing, belief-space planning, multi-robot coordination, and adaptive exploration.
    • Robots could select observations or actions based on expected information gain without being misled by vanishing or negative numerical estimates.
    • Dependencies: Real-time constraints, non-Gaussian beliefs, online updates, sensor noise, and high-dimensional state spaces may require new stable approximations beyond the closed forms evaluated in the paper.
  • Numerically robust privacy and distribution-shift monitoring
    • Deploy stable KL or related divergence estimators for monitoring whether production data, model outputs, or user populations differ from reference distributions.
    • Potential uses include:
    • detecting demographic or geographic drift,
    • monitoring privacy-preserving synthetic data,
    • auditing federated-learning updates,
    • comparing data distributions across hospitals or financial institutions.
    • Dependencies: Practical monitoring often uses histograms, samples, smoothing, or estimated probabilities, so input-representation error may dominate even after the KL operator is repaired. Privacy constraints may also limit access to logits or raw distribution parameters.
  • Standardized benchmarking for low-precision probabilistic computation
    • Create community benchmarks spanning FP16, BF16, FP32, FP64, quantized probabilities, logits, GPU architectures, batch sizes, reduction modes, and distribution families.
    • Benchmarks could become part of procurement and deployment requirements for AI accelerators and scientific libraries.
    • Dependencies: The sampling design must reflect real workloads rather than oversampling extreme small-KL cases, while still testing the failure modes that are difficult to observe in ordinary benchmarks.
  • Compiler-assisted numerical rewriting
    • Extend compiler and graph-optimization systems so that they automatically recognize cancellation-prone KL expressions and replace them with stable decompositions while preserving gradients.
    • This could be integrated into TorchInductor, XLA, MLIR, or domain-specific probabilistic-programming compilers.
    • Dependencies: Automatic rewriting requires formal equivalence proofs, differentiation-aware transformations, support for control flow and batching, and cost models that decide when stability justifies extra arithmetic.
  • Stable divergence layers for compressed and edge-deployed models
    • Develop standardized divergence-monitoring layers that operate directly on logits during quantization-aware training, federated aggregation, continual learning, and on-device adaptation.
    • These layers could trigger recalibration, preserve selected layers at higher precision, or detect unintended model drift.
    • Dependencies: On-device memory and energy budgets may prohibit FP64 or interval arithmetic; efficient fixed-point or compensated implementations will be needed.
  • Improved reproducibility standards for ML experiments
    • Require papers and production reports using KL to specify:
    • the KL direction,
    • the input representation,
    • dtype and accumulation precision,
    • reduction mode,
    • CPU/GPU backend,
    • whether logits or rounded probabilities were used,
    • numerical validation procedures.
    • This would make results in distillation, RL, Bayesian inference, compression, and interpretability more reproducible.
    • Dependencies: Community standards must distinguish meaningful numerical discrepancies from harmless last-bit variation and must be adopted by frameworks, reviewers, and benchmark maintainers.

Overall, the most immediately actionable intervention is to stop computing close-distribution KL values from rounded probabilities when original logits or parameters are available, and to replace cancellation-prone formulas rather than merely clamping negative outputs. The main long-term challenge is making these stable methods fast, standardized, and automatically available across numerical libraries and hardware platforms.

Glossary

  • Ablation: Removal or disabling of a model component to measure its effect. “Circuit discovery scores each edge of a model by the KL between the clean output and the output with that edge ablated”
  • Adaptive precision: A numerical method that increases arithmetic precision when the current precision cannot guarantee a reliable result. “If the FP64 value is closer to a rounding boundary than its a-priori error bound, the sum is re-evaluated with interval arithmetic at increasing precision”
  • Analytic gradient: A gradient derived symbolically rather than computed through automatic differentiation. “We implement the derivative of the rewritten form directly”
  • Arb ball arithmetic: Arbitrary-precision interval arithmetic representing values with a midpoint and an error radius. “The exact KL and every gradient component are then enclosed with Arb ball arithmetic”
  • Automatic differentiation: Algorithmic computation of derivatives by applying the chain rule to a computational graph. “Gradients come from automatic differentiation”
  • Bfloat16 (BF16): A 16-bit floating-point format with a wider exponent range and fewer significand bits than IEEE FP16. “for binary16 (FP16), binary32 (FP32), binary64 (FP64) and bfloat16 (BF16)”
  • Bregman divergence: A discrepancy measure generated from a differentiable convex function and its first-order approximation. “sums of φ\varphi terms and Bregman divergences of convex functions for Gamma, Beta and Dirichlet”
  • Cancellation: Loss of significant numerical information when nearly equal quantities are subtracted. “Subtracting two nearby floating-point numbers is exact ..., but exposes the rounding errors already present in them (cancellation)”
  • Compensated arithmetic: Numerical techniques that track and correct rounding errors during arithmetic operations. “Stable closed-form decompositions, compensated arithmetic, and analytic gradients remove over 97% of significant errors”
  • Compensated difference: A carefully computed subtraction designed to preserve accuracy when operands are close. “form the compensated, centred differences”
  • Correct rounding: Producing the representable floating-point number nearest to the exact mathematical result. “A result is correctly rounded if it equals the exact value rounded to nearest in the output format”
  • Cross-entropy: A loss measuring the discrepancy between a target probability distribution and a predicted distribution. “Numerical failures of softmax and cross-entropy explain stalled grokking”
  • Distillation drift: Unintended divergence of a student model from an identical teacher caused by numerical errors during knowledge distillation. “The official losses are F.kl on softmax/log_softmax outputs”
  • Double rounding: Error introduced when a value is rounded successively to two intermediate formats instead of directly to the final format. “FP64→\toFP32→\toFP16 is a double rounding”
  • Error-free transformation: An arithmetic procedure that represents an operation’s exact result as a leading term plus a correction term. “from error-free transformations”
  • Expected information gain (EIG): The expected reduction in uncertainty from obtaining a new observation. “Bayesian experimental design chooses the next observation by its expected information gain (EIG)”
  • Floating-point underflow: A condition in which a nonzero value is too small to be represented normally in a floating-point format. “about 38% of the FP16 softmax probabilities underflow to zero”
  • Fused implementation: An implementation that combines multiple computational operations to reduce intermediate rounding and representation errors. “show that a fused implementation stops distillation drift”
  • Gradient component: One coordinate of a vector of partial derivatives with respect to model parameters. “correctly round all 567 million scored F.kl_div components”
  • Interval arithmetic: Arithmetic that represents each quantity as an interval guaranteed to contain the exact value. “the sum is re-evaluated with interval arithmetic at increasing precision”
  • Input-representation error: Error caused by finite-precision representations of inputs before an operator is applied. “the input-representation error already present in rounded (log-)probabilities”
  • Kendall’s τb\tau_b: A rank-correlation statistic that accounts for ties between two orderings. “Kendall's τb\tau_b (1 indicates perfect agreement)”
  • Low-rank factor: A compact matrix representation using factors whose rank is smaller than the original matrix dimension. “different low-rank factors of one covariance”
  • Logits: Unnormalized real-valued scores that become probabilities after applying softmax. “This logits path, a row-vectorised form of the Categorical(logits) repair”
  • Log-sum-exp: A numerically stabilized method for computing the logarithm of a sum of exponentials. “Accurately Computing the log⁡\log-Sum-Exp and Softmax Functions”
  • Mixed precision: Use of multiple numerical precisions within one computation or training process. “Low-precision training and inference”
  • Operator error: Error introduced by an operation acting on already stored, possibly rounded inputs. “We call the difference between the computed output and $T_{\mathrm{op}$ the operator error”
  • Quantization: Mapping numerical values to a representation with fewer bits or discrete levels. “a standard metric for how far a compressed model has moved”
  • Relative error: The magnitude of an error divided by the magnitude of the reference value. “The relative error is therefore about 2u/x22u/x^2”
  • Softmax cancellation: Numerical cancellation occurring when probability vectors are subtracted during the backward pass of log-softmax. “A related backward error is Softmax Cancellation”
  • Softmax collapse: A numerical failure in which softmax computations lose distinctions between probabilities, often because of extreme exponentials or rounding. “Softmax Collapse (first diagnosed by \citet{prieto2025})”
  • Special-function evaluation: Numerically computing functions such as logarithms or inverse hyperbolic functions with accuracy guarantees. “non-negative decompositions, compensated arithmetic, special-function evaluation, and analytic gradients”
  • Stratified sampling: Sampling designed to ensure representation across predefined ranges or categories. “from logits stratified in the same way”
  • Trust-region constraint: A restriction requiring an optimization update to remain close to a reference policy or parameter state. “the trust-region constraint of policy optimisation”
  • Unit roundoff: A bound characterizing the maximum relative rounding error in a floating-point format. “The rounding error of those terms is of the order of the unit roundoff uu”
  • ULP (unit in the last place): The spacing between adjacent representable floating-point values near a specified number. “errors in ULP are in units of the spacing of the format at the exact value”
  • Variational autoencoder: A generative model that learns a probabilistic latent representation using variational inference. “The KL divergence is the regulariser of variational autoencoders”
  • Vectorized computation: Applying an operation simultaneously to many vector or matrix elements rather than iterating individually. “a row-vectorised form of the Categorical(logits) repair”
  • Zero crossing: A point where a function or derivative changes sign by passing through zero. “Where a gradient has a genuine zero crossing”

Open Problems

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

Tweets

Sign up for free to view the 11 tweets with 5 likes about this paper.

HackerNews