35% of my KL divergences came back negative
35% of my KL divergences came back negative I ran 2,000 random near-identical distributions through PyTorch's F.kl_div in float32. At a true KL of 1e-8, 25.7% of the answers came back negative — and 100% were off by more than 1%. KL divergence is mathematically never negative. The function disagrees. The paper that sent me here Yang et al. posted "The KL Divergence Is Never Negative, Except in…
A report reveals that 35% of KL divergence calculations performed using PyTorch's F.kl_div function in float32 returned negative values, even though mathematically this should not be possible. The issue was investigated by running 2,000 random near-identical distributions through the function, comparing the results against certified references from a paper titled "The KL Divergence Is Never Negative, Except in PyTorch" by Yang et al.
The paper tested 8.5 million inputs across 18 different KL families, finding that at a true KL of 1e-7, over 85% of FP32 values carried at least 1% relative error, and about 30% went negative at smaller divergences. The problem arises due to catastrophic cancellation, where subtracting two nearly equal numbers results in a tiny difference that is prone to floating-point precision errors.
The paper's authors claim that even using higher precision does not fix the problem, as 7-51% of values remain significantly wrong when evaluated in higher precision. The issue is particularly significant in training scenarios where KL divergence is used as a loss function, as it can lead to misleading results and incorrect conclusions.
The authors provide a repaired code implementation that removes over 97% of significant errors, but the problem appears to be widespread and affects various distribution families and training stages.
Rewritten by urgent.news; may contain errors — check the original.
Source: dev.to