TL;DR
In the world of mathematics, the Kullback–Leibler (KL) divergence is a fundamental law: it is never negative. In the world of PyTorch, however, it frequently dips below zero due to the messy reality of floating-point math. This paper reveals that these negative values are just the tip of a "silent failure" iceberg that corrupts gradients and ruins model training, and provides a suite of numerically stable "repairs" to make your code match the math.
What Problem Does This Paper Address?
Imagine you’re trying to measure the thickness of a single human hair. Instead of using a micrometer, you decide to measure the distance from the Earth to the Moon, then measure the distance from the Earth to the Moon plus the hair, and subtract the two.
In a perfect world, that works. In a world of finite-precision computers (floating-point arithmetic), you’re in trouble. The computer can't hold enough digits to distinguish those two massive distances, so the subtraction results in zero, or worse, a random negative number.
This is called catastrophic cancellation, and it’s exactly what happens in PyTorch’s KL divergence functions. KL divergence measures how one probability distribution differs from another. In many modern AI tasks—like training a "student" model to mimic a "teacher" (distillation) or fine-tuning a robot's policy—we compare distributions that are nearly identical.
When distributions are close, the standard "textbook" formulas used in libraries like PyTorch involve subtracting large, nearly equal terms. The result is numerical noise. For years, the standard advice has been "just clamp it at zero." The authors argue that clamping is like putting a piece of tape over a "Check Engine" light: the symptom is gone, but the engine (your model's gradients) is still broken.
Methods
The authors don't just point out the flaw; they provide a surgical fix. Their approach, which they call Stable KL, relies on four key ingredients:
- Stable Decompositions: Instead of the textbook formulas, they use mathematically equivalent identities that are numerically robust. For example, they use a building-block function $\phi(x) = x - \log(1+x)$. When $x$ is tiny, the standard formula fails, but $\phi(x)$ can be calculated accurately using a power series.
- Accurate Differences: They ensure that the inputs to these formulas (like the difference between two means) are computed exactly using techniques like "error-free transformations."
- Analytic Gradients: Automatic differentiation (Autograd) often inherits the instability of the underlying formula. The authors implement the derivatives of their stable formulas directly to ensure the "downhill" direction actually points downhill.
- Strict Rounding: For the highest level of precision, they compute the result in high precision (FP64) and round it once to the target format (like FP16), avoiding the "double rounding" errors that often plague deep learning.
Datasets
To prove their point, the authors created a massive "certified" benchmark:
- 8.5 million inputs across 18 different "closed-form" distribution families (like Normal, Exponential, and Categorical).
- They used interval arithmetic (via the Arb library) to generate "ground truth" values that are guaranteed to be correct to the last bit.
- They also tested their fixes on real-world scenarios: training GPT-2 circuits, performing Bayesian experimental design, and knowledge distillation with large language models.
Key Insights and Ideas
- The "100% Error" Cliff: As distributions get closer, the relative error of the official PyTorch implementation doesn't just grow—it hits a wall. Once the true KL falls below a certain threshold (around $10^{-7}$ for FP32), the returned value is essentially pure noise.
- Precision is Not a Panacea: You might think, "I'll just use FP32 instead of FP16." The authors show that while this moves the failure point, it doesn't fix the underlying structural problem. Even in higher precision, the textbook formulas still fail when distributions are sufficiently close.
- Silent Failures are the Deadliest: If PyTorch crashed, you'd fix it. But it doesn't. It returns a "plausible" but wrong number. This leads to "distillation drift," where a student model mysteriously wanders away from its teacher even when it should be perfectly aligned.
Key Results
- 97% Error Reduction: Their "REWRITE" method removes over 97% of significant errors in the standard working formats.
- Bit-Perfect Accuracy: Their "OURS" (strict) method eliminated all significant errors across 7.2 million scored samples.
- Fixing Distillation: In an "identical-start" distillation test (where the student starts as a perfect copy of the teacher), the official PyTorch loss caused a 97% top-1 disagreement after training. With the authors' fix, the disagreement dropped to zero.
- Circuit Analysis: When analyzing the "circuits" inside GPT-2, the official code gave wrong scores for up to 59% of the edges. The stable version corrected these, revealing the true internal logic of the model.
Limitations and Future Work
The primary trade-off for this stability is speed. The authors' unoptimized Python implementations are currently 2.4x to 5.9x slower than the official PyTorch calls on a GPU. While this is a significant overhead for some applications, the authors argue it's a price worth paying for correctness, especially in sensitive tasks like model compression or RL.
The authors suggest that the next logical step is for these stable formulas to be integrated directly into the core C++/CUDA kernels of deep learning libraries like PyTorch and JAX, where they can be optimized for speed without sacrificing the mathematical truth.
Summary updated