PyTorch's KL Divergence Turns Negative, and 85% of Small-Divergence Values Are Wrong

The KL Divergence Is Never Negative, Except in PyTorch

Zhen Yang, Wei Tang, Chu Chen, Rui Qian, Yixuan Chen, Fan Yang, Kangning Cui

cs.LG

2026-11-23

8.5M certified tests show both PyTorch KL interfaces fail on nearby distributions; rewritten non-negative formulas erase the errors and change downstream results.

What problem this solves

A KL divergence is non-negative by definition, and zero only when the two distributions coincide. Since 2019, PyTorch users have kept reporting negative values from both of its KL functions, and the standard reply has been to treat it as floating-point error and clamp the result at zero. This paper shows the clamp advice buries the failure: most inaccurate outputs are positive and finite, so nothing in a training log reveals them.

The failure lands exactly where machine learning uses KL. Policy optimization compares consecutive policies, distillation compares a student with its teacher, quantization work compares a model with its compressed copy. When two distributions differ by a relative amount δ, the true KL is O(δ²), yet the closed forms compute it as a sum of O(1) or O(δ) terms of mixed sign, each carrying a rounding error of roughly the unit roundoff u (about 6×10⁻⁸ in FP32, 5×10⁻⁴ in FP16). Once the true KL falls to that scale, the computed value is noise: negative, zero for distinct distributions, or paired with a gradient pointing the wrong way. Of 116 PyTorch-based packages the authors inspected, 39 call at least one of the two interfaces. The smallest example: two Exponential distributions with rates 1 and 1.0001 in FP32 have a true KL of 5.0013×10⁻⁹, and the official formula returns exactly 0.

Method

The measurement covers torch.distributions.kldivergence (closed forms between distribution objects) and F.kldiv, the operator behind nn.KLDivLoss. References are certified with Arb interval arithmetic, tight enough to fix the correctly rounded result for each of 8.5 million inputs across 18 closed-form families. The repair replaces the formulas rather than adding precision:

For distillation, the paper adds a logits path that computes KL straight from teacher and student logits. The attribution experiment is the telling part: swapping in a correctly rounded F.kldiv while keeping the softmax outputs reproduces the official drift bit for bit. The spurious gradient is born in the log softmax backward pass, where q − p is formed from two already-rounded probability vectors. Repairing the operator is not enough; the computation has to bypass the softmax step.

Results

Error rates climb steadily as the true KL approaches the unit roundoff, for every family, on CPU and on an A100 GPU (aggregate rates within 1.5 percentage points):

SettingOfficial PyTorchRepaired
FP32, true KL ≈ 10⁻⁷, ≥1% relative error86%0
Interface A significant-error rate (FP32, all bins)75–97%0
Interface B, 567M components correctly rounded52.5% fwd / 74.9% bwdall
Identical-start distillation, top-1 disagreement (FP16, vocab 151,936)97.4%0
GPT-2 circuit edge scores wrong (FP32)19–59%0

The same-format rewrite already removes more than 97% of significant errors (residual at most 0.7% in FP32, 2.5% in FP16); the strict mode clears them all. Promoting precision is rejected as a fix: the same formula one format higher still leaves 7–51% of FP32 values significantly wrong in 22 of 23 configurations, Uniform being the only exception. Gradients fail more quietly; at true KL 10⁻¹⁵, 6.8% of gradient vectors point into the opposite half-space.

The wrong numbers turn into wrong conclusions downstream. Distribution fitting in FP16 converges from 0 of 12 starts with the official loss and 12 of 12 with the repair. Sequential Bayesian design picks a wrong arm in 40–91% of rounds across 7 of 8 settings, and the official code turns a true KL of 2.5×10⁻⁶ into +0.31; the rewrite makes no wrong choice in 40 runs. In identical-start distillation, where the student starts as an exact copy and the true loss is zero, the official losses move the student in all 2,160 runs (a quarter report a negative loss at step 0), while the logits path leaves it unmoved in all 720. On a quantized Qwen2.5-1.5B, the official F.kldiv misreports mean KL by −19.0% and −4.4% for the two 8-bit models, with 30.2% and 12.3% of tokens negative, and the layer-sensitivity ranking inverts 19 of 378 pairs (up to 158 in the BF16 variants). In GPT-2 circuit analysis, 19–59% of edge scores are wrong in FP32, thousands of them negative.

The price is arithmetic: on a GPU the rewrite costs 2.4–5.9× the official call for five of seven timed families, and far more for Gamma, Beta and F.kldiv.

Why it matters

This is infrastructure work, not a new model. Anyone computing KL between nearby distributions in FP32 or FP16, for a VAE regularizer, a PPO trust region, a distillation loss, a quantization metric, or interpretability circuit scores, may be holding numbers that are wrong without looking wrong. The advice is directly actionable: compute divergences from parameters or logits rather than rounded probabilities, prefer sums of non-negative terms, and treat clamping as a way to bury the value and the gradient together.

Limitations

The authors' own list: the sampling design deliberately oversamples small divergences and stress regions, so headline error rates are conditional on that design; the repairs are unoptimised reference implementations; the first three experiments are synthetic or simulated; the training effect is shown only for an identical start; and in the layer-ranking experiment the most common official configuration still made the correct selection. BF16 results are exploratory, and CPU and GPU ran different PyTorch versions (2.15.0 and 2.4.0).

Two cautions when reading the numbers. The 97.4% distillation disagreement comes from the worst cell of the grid (FP16, largest vocabulary, Adam at a high learning rate); ordinary distillation starts from a random student whose initial KL sits far from the failing range, so typical drift will be smaller. The errors also concentrate where the true KL is tiny, and the paper itself notes the official KL is least reliable for the quantized models closest to the original. The accurate reading is that KL output fails exactly on nearby distributions, which happens to be its most common use, and stays usable further out.

Terms

Source

What people are saying

Related papers

All paper explainers