KL divergence is supposed to be non-negative—it's a basic property. Yet, PyTorch users have spent years seeing negative values pop up, often told to just clamp them to zero. A new study shows that this is a symptom of a much deeper problem: PyTorch’s implementations of KL divergence can be inaccurate across a huge range of scenarios, and the errors are not limited to rare edge cases.
Researchers evaluated both PyTorch’s F.kl_div and closed-form KL formulas against 8.5 million inputs, covering 18 different KL families, on both CPUs and GPUs. The findings: significant numerical errors are the rule, not the exception, especially when comparing distributions that are nearly identical—a common case in machine learning workflows.
Where PyTorch's KL Divergence Goes Wrong
The audit found that for scalar distributions in typical parameter ranges, over 85% of FP32 KL values have at least 1% relative error close to KL 10^(-7), while FP16 hits that error rate at 10^(-3). At even smaller divergences, around 30% of results from these formulas go negative. Trying to fix this by increasing floating-point precision helps, but not enough: in 22 of 23 tested configurations, between 7% and 51% of FP32 values are still significantly off, even at higher precision.
The problem is not just the negative sign—it’s that the numerical instability in the standard KL formulas means you can’t trust the value near zero, which is exactly where many applications care most. These silent inaccuracies can slip into any workflow relying on KL for loss, evaluation, or decision-making.
Real-World Impact: Distillation, Quantization, and Model Scoring
These errors aren’t just theoretical. The authors show that parameter fitting and Bayesian inference can be affected, and identical-start distillation experiments (where two models begin with the same weights) can see up to 97% disagreement in top-1 predictions. KL-based layer rankings in quantized LLMs, and 19–59% of circuit edge scores in GPT-2, are also hit by these inaccuracies.




