The KL Divergence Is Never Negative, Except in PyTorch
A new research paper demonstrates that PyTorch's KL divergence implementations produce widespread numerical errors and negative values when evaluating nearby distributions.
summary is enough The abstract and core findings clearly outline the numerical instability bug, making the full paper unnecessary unless implementing the specific fixes.
summary
Mathematically, the Kullback-Leibler divergence can never be negative, yet PyTorch's standard implementations frequently yield negative values and large relative errors when comparing nearby distributions. Testing across 8.5 million inputs, researchers found that over 85% of scalar family values have significant relative errors and about 30% become negative. These numerical inaccuracies stem from conventional formula limitations near zero rather than precision constraints alone. The paper shows that these bugs affect downstream tasks like distillation and quantization, but stable closed-form decompositions effectively resolve them.
key points
- Over 85% of FP32 values in tested scalar families exhibit at least 1% relative error near 10^-7, and roughly 30% produce invalid negative values.
- The numerical bugs originate from conventional KL formulas breaking down when comparing nearby distributions, which higher precision alone fails to fix.
- Proposed fixes using stable closed-form decompositions and compensated arithmetic eliminate significant errors across millions of tested samples.
who should read it
Machine learning engineers and researchers dealing with probabilistic models, quantization, or knowledge distillation.
discussion mixed
consensus
Commenters note that while the numerical finding is mathematically interesting, machine learning models are typically resilient to these subtle floating-point inaccuracies in practice.
pushback
Some commenters question the unorthodox approach of publishing an arXiv preprint instead of simply opening a GitHub pull request, while others debate whether the tested scenarios reflect real training conditions.
So this is a bug from 2022? https://github.com/pytorch/pytorch/issues/80488
They didn't really show any real world impacts - maybe in distillation? And what impact using logits throughout would have?
This seems like an engineering tradeoff decision and each of their changes they haven't quantified it - how much slower does each change give you for an effect in the simulated/real world?
Could you just cast things to float64 and call it a day?
It connects the paper to a long-standing GitHub issue and questions the practical engineering trade-offs of the proposed fixes.
Generated by an LLM from the article and thread. Check the sources before relying on it.