研究:PyTorch 的 KL 散度在邻近分布场景存在系统性数值误差
The KL Divergence Is Never Negative, Except in PyTorch
做蒸馏、贝叶斯推断或模型可解释性的人该看看这篇:PyTorch 的 kl_div 在分布很接近时数值和梯度都会错,GPT-2 电路分析里近六成边评分受影响。论文给了稳定实现,换上就能修。
arXiv 论文指出 KL 散度理论上非负,但 PyTorch 的 F.kl_div 多年来会输出负值,常规做法是直接截断为零,而这只是深层数值错误的表象。作者在 18 个闭式 KL 分布族和 F.kl_div 上,用认证参考值测试 850 万个输入,发现 CPU 和 GPU 上的数值与梯度普遍出错:普通参数范围内超过 85% 的 FP32 标量结果在 KL 约 10^(-7) 处有至少 1% 相对误差(FP16 在 10^(-3)),约 30% 在更小散度处变成负值。
误差根源在于常规 KL 公式在比较相近分布时发生灾难性抵消,精度不够:单纯提高一档精度后,23 个配置中仍有 22 个留下 7–51% 的 FP32 结果明显错误。修复方案采用稳定闭式分解、补偿算术和解析梯度,可消除工作精度下超过 97% 的显著误差,严格版本在 720 万个闭式样本和 5.67 亿个 F.kl_div 分量上做到无显著错误。
实际影响包括参数拟合、贝叶斯决策、同起点蒸馏中高达 97% 的 top-1 分歧、量化 LLM 的 KL 层级排序,以及 GPT-2 电路边评分中 19–59% 的结果,修复代码后这些误差基本消失。代码和数据在 GitHub(xi-xiaoran/stablekl)开源。
The KL Divergence Is Never Negative, Except in PyTorch
A Kullback--Leibler (KL) divergence is never negative, yet PyTorch users have reported negative values for years, and the standard advice is to clamp them at zero. The sign is only the visible part of a silent failure. Many machine-learning applications compare nearby distributions, where conventional KL formulas lose accuracy. On 8.5 million inputs with certified references across 18 closed-form KL families and F.kl_div, we find widespread errors in values and gradients on CPU and GPU. Among scalar families in ordinary parameter ranges, over 85% of FP32 values have at least 1% relative error near KL 10^(-7) (FP16: 10^(-3)), and about 30% become negative at smaller divergences. More precision is not the cure: evaluated one precision higher, the same formulas still leave 7--51% of FP32 values significantly wrong for 22 of 23 configurations. Stable closed-form decompositions, compensated arithmetic, and analytic gradients remove over 97% of significant errors in the working format. Strict repairs eliminate significant errors on 7.2 million scored closed-form samples and correctly round all 567 million scored F.kl_div components. The errors affect parameter fitting, Bayesian decisions, identical-start distillation (up to 97% top-1 disagreement), KL-based layer rankings in a quantized LLM, and 19--59% of GPT-2 circuit edge scores. With the repaired code they all but vanish. Code and data: https://github.com/xi-xiaoran/stablekl
本条情报归属 AITOP「论文」核心栏目,重点聚焦北美前沿实验室与硅谷科技巨头。在跨区域产业观察坐标中,该动态直接关联「AI 开发者工具链、Coding Agent 与工程化实践」研究主线,反映出当前技术演进与商业落地的最新风向。涉及核心实体与技术议题包括:PyTorch、KL散度、数值稳定性、GPT-2,读者可通过下方标签进入对应专题页查阅历史脉络与关联对比。
信源核验说明:本文原始线索采编自「arXiv cs.LG」(@Zhen Yang, Wei Tang, Chu Chen, Rui Qian, Yixuan Chen, Fan Yang, Kangning Cui),经 AITOP 多维评分管线结构化提炼。