PyTorch's KL functions go negative for nearly equal distributions; a new paper measures when that matters
PyTorch's KL divergence functions return negative values, zeros and wrong gradients when the two distributions are close, and a preprint posted on November 23 measures how far that goes. In "The KL Divergence Is Never Negative, Except in PyTorch" (arXiv:2611.30835), Zhen Yang, Wei Tang, Chu Chen, Rui Qian, Yixuan Chen, Fan Yang and Kangning Cui checked torch.distributions.kl_divergence (18 same-family closed forms) and torch.nn.functional.kl_div on 8.5 million inputs against certified reference values. Below a true KL of about 1e-7 in float32 (1e-3 in float16), more than 85% of the values from the scalar families are off by at least 1%, and about 30% come out negative at smaller divergences. The authors released a drop-in fix, stablekl. On November 24 the account that hosts it, xi-xiaoran, opened pytorch/pytorch#206487, offering to upstream the fix one distribution family at a time.
People have been running into this for years. The repository lists PyTorch forum threads from 2019, 2022 and 2023 and issues #32520 and #80488. The usual answer was that it is floating-point error and the result should be clamped at zero. The paper's point is that clamping removes the minus sign and keeps the error. Positive values stay wrong, and where a value was negative the clamp also zeroes its gradient.
Why the formulas break
The textbook closed forms add up terms of ordinary size that almost cancel. For two Normals PyTorch computes something like log(s2/s1) + (s1² + (m1-m2)²)/(2 s2²) - 1/2. When the distributions are close, the true KL is many orders of magnitude smaller than those terms, and float32 rounding in the terms is larger than the answer. In F.kl_div the per-element term t * (log t - x) cancels the same way when t is close to exp(x). Computing in a wider type doesn't fix it: the paper evaluated the same formulas one precision higher and still found 7–51% of float32 values significantly wrong in 22 of 23 configurations.
The repair rewrites each divergence as a sum of non-negative terms built from differences that are computed exactly, adds analytic gradients, and computes the categorical KL directly from logits instead of from separately rounded probabilities. On the benchmark, the default mode of the repaired code left no significant errors on 7.2 million closed-form inputs and gave correctly rounded results for all 567 million scored F.kl_div components.
What we reproduced
We ran the authors' examples and a small sweep of our own on PyTorch 2.15.0 (CPU build), with float64 or 50-digit mpmath as the reference:
| Call | PyTorch result | Exact |
|---|---|---|
kl_divergence(Normal(0, 1), Normal(1e-4, 1)), float32 |
0.0 | 5.0e-9 |
kl_divergence(Beta(5, 5), Beta(5.001, 5)), float32 |
−1.27e-6 | 5.81e-8 |
kl_divergence(Exponential(1), Exponential(1.001)), float32 |
4.77e-7 | 5.00e-7 |
| same, rate 1.0003 or closer | 0.0 | 4.5e-8 and below |
Categorical(logits=…) KL, 32,000 float16 logits 1e-2 apart |
−0.0001 | 4.93e-5 |
F.kl_div(log_softmax(s), softmax(t), reduction="batchmean"), float32, logits 1e-3 apart |
3.14e-7 | 4.91e-7 |
Then we took 1,000 pairs of 1,000-way logit vectors per noise level, computed F.kl_div on float32 log_softmax outputs with log_target=True, and compared with the KL of the same logits in float64. At a typical KL of 5e-5 eight results in 1,000 were off by 1% or more. At 5e-7, 988 were, and at 5e-9, 999 were, with 496 of them negative. Our sweep measures the whole usual pipeline, softmax included, not kl_div alone.
Where it matters
One experiment starts a student network as an exact copy of its teacher and trains it on the KL between them. The true loss and gradient are exactly zero, so the student should never move. With the official losses it moved in all 2,160 runs. Adam rescales the tiny spurious gradient into a full-size step, and the drift grows with the learning rate. In float32 the student ended up disagreeing with the teacher's top-1 prediction on 31–47% of inputs at the higher rates; in float16 the worst case reached 97.4%. With the logits-based repair it did not move in any of the 720 runs. The same thing happened at LLM scale: with the loss of TRL's GKD distillation trainer, a Qwen2.5-1.5B student started as an exact copy of the model drifted to 13% top-1 disagreement, while the logits path left its weights unchanged.
The paper also lists the cases where the KL itself is the thing being measured:
- For 8-bit quantized Qwen2.5-1.5B-Instruct, float16
F.kl_divmisreports the mean KL against the original by −19.0% and −4.4% for the two near-lossless models, with 30.2% and 12.3% of tokens negative. Withreduction="mean"it reports exactly 0, and theCategorical(logits)version returns infinity for almost every token because about 38% of the float16 probabilities underflow. - Ranking the 28 layers by how much quantizing each one alone changes the output, a common way to choose which layers stay in float16: the official float16 KL is negative for 24 of the 28 layers and swaps 19 of the 378 layer pairs.
- Comparing cached decoding with a full forward pass, the official
F.kl_divis off by more than 600% in float32 and float16. - In GPT-2 circuit discovery with the
auto-circuitlibrary, float32 edge scores are wrong for 19%, 46% and 59% of edges in three settings. The errors sit in scores below about 1e-6, so the largest edges mostly keep their order.
Where it doesn't
The authors also report the settings where they saw no effect, and that list covers most everyday training. Distilling Qwen2.5-1.5B with that GKD loss from an 8-bit or 4-bit quantized copy, LoRA runs with a KL anchor, PPO and TRPO KL checks, and the sampled KL estimators that RL fine-tuning frameworks log all came out within run-to-run noise. Their explanation is that once two models actually differ, the true gradient dwarfs the spurious part, and loops like PPO hold the KL around 1e-2, far above where the closed forms fail. Two bf16 executions of the same model that are not bitwise identical already differ by a KL of about 1e-3 or more.
So the bug matters when the distributions are identical or nearly identical by construction, or when a small KL is the number you report: evaluating a near-lossless quantization, checking that two inference paths agree, ranking layers, thresholding circuit edges. For those uses, a negative KL is the obvious symptom, and a mean that is 19% low with a plausible sign is the less obvious one.
The fix is not free. stablekl is pure Python on top of PyTorch with no fused kernels. On a GPU the repaired kl_div is 27–59× slower than the official kernel, the closed forms 3.4–12× slower for common families, and Beta about 320×. The logits path, which the README recommends for comparing two models, costs 3–22×.
Comments
No comments yet. Be the first.