# KL 散度不该为负，除非在 PyTorch 中

Original title: The KL Divergence Is Never Negative, Except in PyTorch

> Hacker News story 50629962 · language: zh · submitted 2026-11-24
> Web version: https://zeli.app/zh/story/50629962
> About this feed: https://zeli.app/llms.txt · Agent guide: https://zeli.app/skill.md

▲ 83 · by [Anon84](<https://news.ycombinator.com/user?id=Anon84>) · 💬 33
[original](<https://arxiv.org/abs/2611.30835>) · [HN discussion](<https://news.ycombinator.com/item?id=50629962>)

## Summary

理论上 Kullback-Leibler 散度永远非负，但 PyTorch 用户多年来却频繁遇到负值，标准做法只是简单截断。研究团队在 850 万个输入样本上验证了 18 类闭式 KL 公式及 F.kl_div 函数，发现 CPU 和 GPU 上普遍存在数值与梯度误差。在普通参数范围内，超过 85% 的 FP32 计算结果相对误差超 1%，部分甚至出现负值。单纯提升精度无法根治问题，而通过稳定的闭式分解、补偿算术及解析梯度，可消除 97% 以上的显著误差。这些错误已影响参数拟合、贝叶斯决策、模型蒸馏及 LLM 量化层排序等关键任务。修复后的代码让上述问题几乎消失，相关代码与数据已开源。

## Key quote

> 符号错误只是冰山一角，水面之下是无声的失败。

## HN discussion (33 comments)

### [derf_](<https://news.ycombinator.com/item?id=50632200>)

> 用浮点运算得到意想不到的负值，这其实出奇地容易。我记得有一次就是一个平方根运算，尽管参数已经被钳位（clamp）到零以上，却依然因为负数参数而失败。问题出在钳位操作使用了一些宏：
>
> \#define MIN(a, b) ((a) < (b) ? (a) : (b))
>
> \#define MAX(a, b) ((a) < (b) ? (b) : (a))
>
> 参数是用 MAX(x, 0) 来钳位的。问题是，如果 x 是负零（negative zero），它并不小于 0，所以宏会返回 x。随后平方根函数检查符号位，于是失败了。负零完全可能是一系列导致破坏性抵消的计算的结果。

### [newmana](<https://news.ycombinator.com/item?id=50636434>)

> 所以这是 2022 年的一个 bug？https://github.com/pytorch/pytorch/issues/80488

### [sva_](<https://news.ycombinator.com/item?id=50632706>)

> 现在把 bug 报告发到 arxiv 上，这选择挺有意思的？不过如果情况属实，这确实是个相当重大的发现。

### [divyekapoor](<https://news.ycombinator.com/item?id=50631371>)

> 这个问题找得很棒，修复方案也很全面。他们没留下任何可挑剔的地方。:D

### [carterschonwald](<https://news.ycombinator.com/item?id=50631516>)

> 哈哈，今年八月我发现并向上游提交了一个棘手的 PyTorch 误编译导致的读写损坏问题。如果你的张量维度不是 2 的大幂次的倍数，这会导致梯度出现 100 倍的相对误差。当然，大家通常都会选 2 的幂次。

---

## Cite

- Page: https://zeli.app/zh/story/50629962
- Date: 2026-11-24
- Source: arxiv.org (https://arxiv.org/abs/2611.30835)
- Hacker News: https://news.ycombinator.com/item?id=50629962

## Other languages

- en: https://zeli.app/story/50629962 · markdown: https://zeli.app/story/50629962.md
- ja: https://zeli.app/ja/story/50629962 · markdown: https://zeli.app/ja/story/50629962.md
- ko: https://zeli.app/ko/story/50629962 · markdown: https://zeli.app/ko/story/50629962.md
- de: https://zeli.app/de/story/50629962 · markdown: https://zeli.app/de/story/50629962.md
- es: https://zeli.app/es/story/50629962 · markdown: https://zeli.app/es/story/50629962.md
- ru: https://zeli.app/ru/story/50629962 · markdown: https://zeli.app/ru/story/50629962.md
