PyTorch's KL Divergence Goes Negative: Stable Formulas Fix 97% of Precision Errors

CSProfKGD · x · 2026-11-25

A new arXiv paper shows KL divergence, which is mathematically never negative, frequently comes out negative or inaccurate in PyTorch due to floating-point precision loss when comparing nearby distributions.

Key findings from 8.5M verified inputs: 85% of FP32 scalar configurations carry relative errors of at least 1e-7, and 30% of divergences go negative. Higher precision doesn't fix it — the same formulas remain 7-51% significantly wrong in FP32 across 22 of 23 configurations. Stable closed-form decompositions with compensated arithmetic remove over 97% of significant errors.

The implications touch knowledge distillation, PPO/DPO KL penalties, and variational inference, especially in FP16/BF16: of 116 PyTorch-based packages inspected, 39 call at least one affected KL implementation. With the fix, identical-seed distillation reaches up to 97% top-1 agreement. Code: github.com/xi-xiaoran/stablekl

Original post →

More from Research

Research channel →