# The KL Divergence Is Never Negative, Except in PyTorch

Stable rewrites make PyTorch KL divergence accurate for nearly identical distributions

Zhen Yang, Wei Tang, Chu Chen, Rui Qian, Yixuan Chen, Fan Yang and 1 more · arXiv · 2026-11-23

- **Problem** PyTorch KL divergence formulas lose accuracy when two distributions are nearly identical. Rounding swamps their small terms, so values can come out negative, and higher precision does not fix it.
- **Method** The authors rewrite the closed-form KL formulas as sums of non-negative terms. They evaluate them with compensated arithmetic and derive gradients analytically.
- **Results** Strict repairs eliminate significant errors on 7.2 million scored closed-form samples. Promoting precision one step still leaves 7 to 51 percent of FP32 values significantly wrong.

![Figure 1: The problem and one consequence. The official PyTorch code is shown in red and ours in blue, with solid lines for FP32 and dashed lines for FP16.(a)R…](https://refivu.com/papers/a58a89ab-5b60-441f-9175-c03ffbd24fec/figures/figure-3c6e76a9f06439ed5b2fd34c6e4c819e.png?thumb=512)

**Figure 1** .The problem and one consequence. The official PyTorch code is shown in red and ours in blue, with solid lines for FP32 and dashed lines for FP16.(a)Relative error of the returned KL between two Exponential distributions as they approach each other (median over 3000 parameter pairs per point, with FP16 shown while the true value is a normal number). The official closed form is implemented correctly, yet its error reaches 100% once the true KL falls below about 4×10 −8 in FP32 (4×10 −4 in FP16), where it returns zero or a negative number. The repaired divergence stays at the accuracy of the format.(b)A student initialised as an exact copy of its teacher and trained with the KL loss alone (vocabulary 151,936, Adam, learning rate 10−2, median and range over 10 seeds, other settings in Appendix E). With the official loss the student’s top-1 predictions leave the teacher’s, whereas with our logits path they do not move.

[Original paper](https://arxiv.org/abs/2611.30835v1) · [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) · Zhen Yang, Wei Tang, Chu Chen, Rui Qian, Yixuan Chen, Fan Yang, Kangning Cui · The KL Divergence Is Never Negative, Except in PyTorch · Original paper figure · Extracted the figure area from page 2 of the original PDF.

## Why close distributions break the KL formulas

PyTorch exposes KL divergence through two interfaces, and the applications that use them often compare nearly identical distributions. When two distributions differ by a small relative amount δ, their KL is typically of order δ². Most closed forms, however, add up terms of order one or order δ that carry mixed signs. A divergence of that size or smaller is therefore buried in noise, and the computed value can be negative, zero or non-zero for identical distributions.

The cause is structural, because a second-order quantity is assembled from first-order or zeroth-order pieces.

## Which part of the error belongs to F.kl div

Interface B receives log-probabilities that are usually the output of a log softmax applied to model logits, so its inputs are already rounded. The authors compare the computed output with the exact operator result on those same stored inputs, and the gap is the operator error. A second gap compares that exact operator result with the exact result computed from the original logits, which the authors call the input-representation error.

Only the operator error can be attributed to F.kl div, so no change inside the function can remove the input-representation error.

Differentiating the forward KL with respect to the log-probability input gives a cancellation-free expression. The cancellation appears later, in the backward pass of log softmax, where two rounded probability vectors are subtracted.

## How the reference and the samples were built

For each family they draw P from an ordinary region and from stress regions, then build Q so that the true KL falls in a prescribed decade from 10−15 up to 1. The run yields 7,542,469 samples, of which 7,234,454 are scored, and some cells stay empty because the floating-point grid cannot fill them.

The exact KL and each gradient component are enclosed in Arb ball arithmetic until one correctly rounded value is fixed. For interface B the authors generate 942,200 batches over log target, two precisions, several class counts, batch sizes and reductions.

OFFICIAL is PyTorch 2.15.0 on CPU, and the evaluation was repeated on an NVIDIA A100 GPU. OFFICIAL+ promotes the parameters exactly to the next format and rounds once, which serves as the natural higher-precision baseline. A significant error is an output off by at least 8 ULP or one that is qualitatively wrong, such as a negative KL where the truth is positive.

## Where the official closed forms fail

In the control bin the official values are accurate, with 0.1% of FP32 values off by 1% or more. As the true KL approaches the unit roundoff, 86% of values are wrong at 10−7, and below that almost all are. Below 10−10 about three in ten values are negative.

Gradients fail differently, because they are first-order quantities and survive longer before they break down.

## Why higher precision is not the fix

The authors test OFFICIAL+, which keeps the official code unchanged but promotes the inputs exactly before a single rounding. It still leaves 7–51% of FP32 values significantly wrong across 22 of 23 configurations. More precision alone does not remove the cancellation, because the second-order quantity is still built from larger first-order pieces.

A smaller unit roundoff only moves the threshold at which the noise takes over.

## How the formulas are rewritten

Four ingredients do the work: decompositions into non-negative pieces, compensated sums, special functions evaluated directly, and gradients derived analytically. Two variants are evaluated, REWRITE computes in the target precision, while OURS evaluates in FP64 and rounds once as the strict repair.

For categorical probabilities the authors write the ratio ρk as qk divided by pk, minus one. Because the sum of pk times ρk is exactly zero, the linear term cancels, and the probability KL takes the form \\( \\mathrm{KL} = \\sum\_k p\_k\\,\\varphi(\\rho\_k) \\).

For nearby pairs a third-order remainder T3 replaces the direct three-term sum, which would otherwise cancel. The gradients come from identities that hold for any shift, instead of differences of large first-order terms.

For logits the authors avoid softmax and clamping entirely, and they centre the logit differences so that a common offset gives exactly zero. For ContinuousBernoulli the linear part of the log-partition function cancels exactly, and a power series in η evaluates the remainder. Three regions of (\|p\|, \|q\|) each use an exact identity, and the repair has no clamp and no window.

## How far the repairs reduce the errors

The strict repair also correctly rounds all 567 million scored F.kl div components.

For Dirichlet, the official KL is not correctly rounded in 98.76% of FP16 samples and 99.92% of FP32 samples. The repaired code is correctly rounded on every sample.

For the two 8-bit models, the repaired F.kl div cuts the share of tokens with operator error of at least 1% from 97.6 / 95.5% to 0.3 / 0.1%. Meanwhile 98.8 / 96.8% of tokens carry input-representation error of at least 1%, and F.kl div cannot remove that part.

## Identical-start distillation drifts under the official loss

The setup starts a student with the same weights as its teacher and trains it with the forward KL of the output distributions for 300 steps. Under the official loss the student's top-1 predictions move away from the teacher, with up to 97% top-1 disagreement. With the logits path the predictions do not move, as Figure 1b shows.

The median loss for V = 151,936 in FP32 is −1.7×10−8, a negative value from an identical start. Under Adam all 27 official curves rise with the learning rate, while the repaired version stays at zero in every cell.

## KL-based layer selection in a quantized LLM

The authors rank single-layer quantizations of Qwen2.5-1.5B-Instruct, using 16,384 selection tokens with the original model's perplexity at 11.66. The rankings are compared with an FP64 reference, using the reported mean KL under each method.

The official FP16 log-target loss, the official BF16 F.kl div and the BF16 logits path pick layer 25 rather than layer 5. The reference KL of layers 5, 23 and 25 is 5.787, 5.759 and 5.474 in units of 10−5. The resulting mixed model has 0.25% lower true KL on the disjoint evaluation set, so under the harmful-decision criterion this choice did not hurt, though it was +0.87% on the selection set.

Categorical BF16 selects four wrong layers, and its mixed model has 9.78% higher true KL on the evaluation set. The logits path has 0 strict inversions among 378 pairs at 8 bits, while the official FP16 batchmean has 19 inversions and a Kendall's τb of 0.898.

## When the error changes a result, and when it doesn't

In LLM distillation from a nearby start, the official losses end at an eval KL of about 0.10 with 13% top-1 disagreement. The logits path changes no weights in any seed, and from two quantized starts the three losses are indistinguishable. In LoRA runs from an identical start, the official losses reach a median eval KL of 0.025–0.037, while the logits path leaves the adapter at zero.

The authors attribute the difference to the spurious part of the gradient being absolute, and they single out the identical start as the only setting where that part is all there is. They also note that two BF16 executions differ by a KL of about 10−3 or more, a floor above the region where the official closed forms fail. The authors report no case where the error changed ordinary training from a start some distance away.

## Limitations

The logits path in BF16 is exploratory, since BF16 is not covered by the certified evaluation. The layer-ranking study uses one model and one dataset, round-to-nearest quantizers and two values of k. Its references are FP64 values that are not interval-certified and were spot-checked at 150 digits.

The Categorical logits repair is not itself certified by interval arithmetic. The Bernoulli-arm experiment exercises only the Beta closed form. Clamping removes negative outputs but leaves inaccurate positive values unchanged. In FP16 the grid leaves 325 of 1,568 scalar cells empty, which limits coverage there.

## Paper info

- **Authors**: Zhen Yang, Wei Tang, Chu Chen, Rui Qian, Yixuan Chen, Fan Yang, Kangning Cui
- **Venue**: arXiv · Preprint
- **First published**: 2026-11-23
- **Added**: 2026-11-25
- **Updated**: 2026-11-23
- **Version**: v1
- **arXiv**: 2611.30835
- **Category**: cs.LG
- **Original paper terms**: [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/)
- **What we show**: Paper info, commentary and permitted figures from the original paper

[Original paper ↗](https://arxiv.org/abs/2611.30835v1) · [PDF ↗](https://arxiv.org/pdf/2611.30835v1)

AI commentary is a separate explanation from the original paper and may contain errors. The original paper and figures follow each source's terms of use and any rights noted separately.

## 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

## Quote from the paper

Zhen Yang, Wei Tang, Chu Chen, Rui Qian, Yixuan Chen, Fan Yang, Kangning Cui (2026). The KL Divergence Is Never Negative, Except in PyTorch. arXiv:2611.30835v1. https://arxiv.org/abs/2611.30835v1

**BibTeX**

```
@misc{yang2026divergence,
  title = {{The KL Divergence Is Never Negative, Except in PyTorch}},
  author = {Zhen Yang and Wei Tang and Chu Chen and Rui Qian and Yixuan Chen and Fan Yang and Kangning Cui},
  year = {2026},
  eprint = {2611.30835},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/2611.30835v1}
}
```

## Other paper commentary

- [Per-Attack Blocking Hides Catalog Vulnerability: A Weakest-Link Analysis of Tool Manifests](https://refivu.com/en/papers/e81c6c5d-9783-464f-93c2-4b7a8263a787-per-attack-blocking-hides-catalog-vulnerability-a-weakest.md)
- [Beyond Single-Turn Privacy: Training-Data Leakage in Conversational RAG](https://refivu.com/en/papers/51c92831-e3a5-4575-943b-50961dd4fa10-beyond-single-turn-privacy-training-data-leakage-in.md)
- [Energy-preserving Bayesian model reduction: closed-form structured posteriors and probabilistic stability certificates for quadratic operator inference](https://refivu.com/en/papers/87bcab93-eba0-4ffc-89b9-8f653e413add-energy-preserving-bayesian-model-reduction-closed-form.md)
- [Directional Bias in Quantile SGD and Score-Inversion Inference under Dependence](https://refivu.com/en/papers/37e46fbd-2b06-425b-8b62-853f70137b7a-directional-bias-in-quantile-sgd-and-score-inversion.md)
- [Why Units Die in the Layer After a Frozen Random Encoder, and What the Number of Live Units Measures](https://refivu.com/en/papers/4baaa389-8ae5-4a25-8e3e-92a7440d07ac-why-units-die-in-the-layer-after-a.md)
- [Deterministic Proper Positive-Only Learning Is Independent of ZFC](https://refivu.com/en/papers/15836fd6-3e3a-45f8-9335-c46bfbb1d217-deterministic-proper-positive-only-learning-is-independent.md)
- [Benchmarking Protein Structure Tokenizers as Generation Targets for Language Models](https://refivu.com/en/papers/4d00bdf0-4a55-413c-828b-0d71373808b6-benchmarking-protein-structure-tokenizers-as-generation.md)
- [CO-GRAFT: Attributing Reinforcement Learning Gains in Search Agents via Role-Level Policy Grafting](https://refivu.com/en/papers/ca0608ae-9635-4dfa-aeee-67d5801fc208-co-graft-attributing-reinforcement-learning-gains-in-search.md)
- [(Be Cautious!) Bio-Foundation Models Are Not Yet Robust to Biologically Plausible Perturbations and ML Transformations](https://refivu.com/en/papers/6605e3c5-c4bf-40e9-9976-41c3b38c3353-be-cautious-bio-foundation-models-are-not-yet.md)
- [CLASP: Online learning algorithms for Convex Losses And Squared Penalties](https://refivu.com/en/papers/38b2c59e-54e2-4a8c-a89b-35340bffe40f-clasp-online-learning-algorithms-for-convex-losses-and.md)
- [$\\textit{Read-ME}$: Refactorizing LLMs as Router-Decoupled Mixture of Experts with System Co-Design](https://refivu.com/en/papers/a806bfd3-525b-49ad-a578-7f75e77b4d70-textit-read-me-refactorizing-llms-as-router-decoupled.md)
- [Embedding Dimension of Contrastive Learning and $k$-Nearest Neighbors](https://refivu.com/en/papers/9df2424e-149a-4953-912c-2bdfc9b778bc-embedding-dimension-of-contrastive-learning-and-k-nearest.md)

## Terms in this paper

- [KL divergence](https://refivu.com/en/terms/5f1dbea73907-kl-divergence)
- [relative error](https://refivu.com/en/terms/2688f874c6a8-relative-error)

---

AI-written text can contain mistakes. [Refivu](https://refivu.com/en/papers/a58a89ab-5b60-441f-9175-c03ffbd24fec-the-kl-divergence-is-never-negative-except-in)
