PyTorch's KL Divergence Goes Negative, and Clamping It Isn't the Fix
The KL Divergence Is Never Negative, Except in PyTorch
KL divergence can never be negative, yet PyTorch users have reported negative values for years and been told to clamp them at zero. A study of 8.5 million inputs across 18 closed-form KL families and F.kl_div finds the sign is just the visible symptom: over 85% of FP32 values carry at least 1% relative error near KL 10⁻⁷, and about 30% turn negative at smaller divergences. Extra precision doesn't help, but stable decompositions and compensated arithmetic remove over 97% of significant errors.
The sign is only the visible part of a silent failure.
- derf_
It is surprisingly easy to get unexpected negative values with floating point operations. One I remember was a square root that was failing on a negative argument despite that argument being clamped against zero. The problem was that the clamp was using some macros
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#define MAX(a, b) ((a) < (b) ? (b) : (a))
and the arguments were being clamped with MAX(x, 0). Well, if x is negative zero, it is not less than 0, so the macro returns x. The square root then looks at the sign bit and fails. Negative zero is a perfectly possible result from a series of calculations that destructively cancel.
- sva_
Interesting choice to post bug reports to arxiv now? Pretty significant finding though if true.
- divyekapoor
The issue is a nice find and the fix is comprehensive. They left nothing to comment about. :D
- carterschonwald
lol , in august i found and upstreamed a gnarly pytorch miscompilatio read write corruption that would cause 100x relative error in gradients if your tensor dimensions arent a multiple of a large power of 2. granted everyone seems to pick powers of two usually
- bobmarleybiceps
it is sort of surprising how many parts of pytorch seem (sort of) buggy / numerically not great... I think they just have sooo many operations that some are (relatively) unused and don't receive as much attention. (though kl-divergence seems pretty important (??))
I wonder if it's also because ML stuff is just pretty insensitive to numerical issues, so users don't notice it.