論文解説
The KL Divergence Is Never Negative, Except in PyTorch
KLの式を非負の項の和に組み直し、近い分布でも正しく計算する
- 課題 PyTorchのKL計算は、分布が近いと従来の式が丸め誤差に弱く、負の値や誤った勾配を返していました。0にclampする対策では、誤った正の値は残ったままでした。
- 手法 本研究は、KLを非負の項の和に組み直します。近い値の差を最後に取る代わりに、式全体を非負の項だけで書き、丸め誤差で符号が崩れないようにします。
- 結果 修正版は、公式実装で有意な誤りの97%超を取り除き、採点対象の閉形式サンプルでは有意な誤りを残しませんでした。
clampでは隠れる誤差
PyTorchでは2019年以降、KLの負の値が報告されるたびに、丸め誤差なので0にclampすればよいという答えが繰り返されてきました。しかしclampは値を隠すだけで、負の推定値とその勾配をゼロにし、正で有限だが誤っている推定値はそのまま残ります。KLは、VAEの正則化や方策最適化の信頼領域、知識蒸留、量子化モデルとの比較など、近い分布同士を比べる場面で使われるため、この問題が効きやすくなります。調べた116のPyTorchベースのパッケージのうち39が、どちらかのKLインターフェースを呼んでいました。
近い分布では、従来の閉形式が丸め誤差に弱くなるのが根本の原因です。分布の相対的なずれがδのとき、真のKLは\(O(\delta^2)\)と小さい一方、閉形式は符号の異なるO(1)やO(δ)の項の和として計算します。そのため、負になることも、異なる分布でゼロになることも、同一の分布で非ゼロになることもあり、勾配も下り方向を指すとは限りません。
式自体は正しく実装されているのに精度の限界で壊れる点が、この問題の厄介なところです。同じ誤差は学習にも及び、図1の(b)では、教師と同じ重みで始めた生徒の上位1位予測が公式損失の下で教師から離れていきます。

Figure 1 .The problem and one consequence. The official PyTorch code is shown in red and ours in blue, with solid lines for FP32 and dashed lines for FP16.(a)Relative error of the returned KL between two Exponential distributions as they approach each other (median over 3000 parameter pairs per point, with FP16 shown while the true value is a normal number). The official closed form is implemented correctly, yet its error reaches 100% once the true KL falls below about 4×10 −8 in FP32 (4×10 −4 in FP16), where it returns zero or a negative number. The repaired divergence stays at the accuracy of the format.(b)A student initialised as an exact copy of its teacher and trained with the KL loss alone (vocabulary 151,936, Adam, learning rate 10−2, median and range over 10 seeds, other settings in Appendix E). With the official loss the student’s top-1 predictions leave the teacher’s, whereas with our logits path they do not move.
出典 · CC BY 4.0 · Zhen Yang, Wei Tang, Chu Chen, Rui Qian, Yixuan Chen, Fan Yang, Kangning Cui · The KL Divergence Is Never Negative, Except in PyTorch · 論文の図を引用 · 元のPDFの2ページ目から図の部分を抽出しています。非負の項への分解
修正版の鍵は、近い値同士の差を最後に取るのではなく、式全体を常に非負の項の和として組み直すことです。インターフェースAのtorch.distributions.kl_divergenceは分布オブジェクトの型で閉形式を選び、インターフェースBのtorch.nn.functional.kl_divは対数確率xと目標tから要素ごとに計算して縮約します。一つは、F.kl divが受け取った入力に対する演算誤差で、実装の責任になります。もう一つは、丸めた対数確率に最初から含まれる入力表現誤差で、ロジットから直接発散を計算すると取り除けます。
カテゴリ分布の確率パラメータ版では、比\(\rho_k=q_k/p_k-1\)を使い、KLを\(KL=\sum_k p_k\,\varphi(\rho_k)\)の形に書き換えます。φは論文で定義される関数で、各項が非負になるため、KL全体も非負の項の和になります。pkρkの総和はゼロなので線形項が厳密に消え、残りは2次の量だけになります。ρkの分子Nkは、4K個のDekker積から正確に計算するため、近い分布でも相対誤差が保たれます。
Beta族では、公式の対数ベータ関数の差の代わりに、凸関数VのBregman divergenceであるBVを残し、これを非負の項として扱います。近い対では3つのBvを直接引くと打ち消し合うため、第3次の剰余T3を使った式に切り替えます。Dirichletでも同じ構造を各成分の和に広げて使い、K=2の場合はBetaの式に帰着します。
勾配も解析的に書き直し、TwoProductとTwoSumで差を正確に作ってから割るため、等しい平均を持つ対ではz=0が厳密に得られます。作業精度で書き換えたREWRITEと、FP64で計算して一度だけ丸める厳密版のOURSは、同じ書き換えの計算精度を変えたものです。精度を上げることと式を変えることは別の操作なので、後の比較はこの違いを確かめるためのものです。
真のKLに対する誤差の出方
評価では格納された入力に対する厳密なKLを基準にし、数値を区間で囲んで誤差を押さえるArb ball arithmeticで、正しく丸めた参照値を決めます。インターフェースAでは18の閉形式族を23の構成で試し、7,542,469個のサンプルのうち7,234,454個を採点しました。公式実装はPyTorch 2.15.0のCPUで評価し、NVIDIA A100のGPUでも繰り返しています。
制御区間では公式の値はほぼ正確で、FP32値のうち1%以上ずれるのは0.1%です。
1段階上の精度で同じ式を評価しても、23の構成のうち22では、FP32値の7–51%が依然として有意に誤ります。ここから著者らは、精度不足ではなく、式が差の打ち消しを含むことが原因だと読んでいます。作業精度で書き換えた版は有意な誤りの97%超を取り除き、厳密版は採点対象の7.2 million個の閉形式サンプルで有意な誤りを残しませんでした。
蒸留とLLMの層選択での影響
同一初期化の蒸留では、教師と同じ重みで初期化したMLPを、KL損失だけで300ステップ学習させ、最後のtop-1不一致を測ります。語彙サイズ、精度、学習率、シードを組み合わせた2,880回の実行で、公式損失は最大97%の不一致を生みました。Adamではすべての公式の曲線が学習率とともに厳密に増え、step 0で負の損失を出した公式実行は24.4%ありました。修正版はどの格子点でも不一致が0のままでした。

Figure 8 .Identical-start distillation. Top-1 disagreement between student and teacher after 300 steps as a function of the learning rate (median over 10 seeds). The official F.kl div is shown in red, with line style and marker indicating the precision, and ours in blue (identically zero in every cell).
出典 · CC BY 4.0 · Zhen Yang, Wei Tang, Chu Chen, Rui Qian, Yixuan Chen, Fan Yang, Kangning Cui · The KL Divergence Is Never Negative, Except in PyTorch · 論文の図を引用 · 元のPDFの31ページ目から図の部分を抽出しています。Qwen2.5-1.5B-Instructの量子化モデルで層を選ぶ実験では、公式のlog target FP16 F.kl divが層5の代わりに層25を選びました。選ばれた混合モデルは評価集合で真のKLが0.25%低く、判断の誤りが害にはならなかったことになります。一方、Categorical BF16は8層のうち4層を誤って選び、評価集合での真のKLは+9.78%になりました。
同一初期化のLoRAでは、公式損失の学習で評価KLが中央値0.025–0.037に動く一方、ロジットパスはアダプタをゼロのまま残しました。LLMの同一初期化の蒸留でも、公式損失では評価KLが約0.10、top-1不一致が13%に達し、ロジットパスでは重みが動きませんでした。一方、8ビットと4ビットの量子化コピーを出発点にした近い場合では、ロジットパスとBF16損失の最終評価KLの差は中央値+1.4%で、シード間の差2.8%と区別がつかないと著者らは読んでいます。
FP64厳密版と入力表現誤差の限界
厳密版のOURSはFP64で計算して一度だけ丸めるもので、FP32やFP16で動くREWRITEとは結果の扱いが異なります。BF16のロジットパスは探索的な扱いで、認証された評価の対象ではありません。LLMの実験は1つのモデル、1つのデータセット、round-to-nearestの量子化、kの2つの値に限られ、参照KLはFP64で計算され区間演算で認証されていません。
入力表現誤差はF.kl divの修正では取り除けず、ロジットから直接KLを計算する経路が必要になります。clampは負の値を消すだけで、真のKLや勾配を回復しません。さらに、不正確な正の値もそのまま残ります。同一初期化や近い出発点での比較は示しましたが、すでに一定の距離がある出発点から通常の学習をしたときに、誤差が結果を変えた例は見つかりませんでした。
誤差が効くのは、KLの値そのものが成果物になる場面、たとえば近い変化の評価、監視、閾値や順位付けです。閾値や順位のように小さなKLを直接使う場面では修正が必要ですが、通常の学習の結果だけを見ると差が見えにくいと考えられます。
論文情報
- 著者
- Zhen Yang, Wei Tang, Chu Chen, Rui Qian, Yixuan Chen, Fan Yang, Kangning Cui
- 学会・ジャーナル
- arXiv · プレプリント
- 公開日
- 2026年11月23日
- 登録日
- 2026年11月25日
- 更新日
- 2026年11月23日
- バージョン
- v1
- arXiv
- 2611.30835
- カテゴリ
- cs.LG
- ライセンス
- CC BY 4.0
- 掲載内容
- 論文情報・解説・論文の図
この解説は、Refivuの韓国語解説をAIで翻訳したものです。不正確な翻訳や誤りが含まれる可能性があります。論文と図の利用条件は各出典に従います。
アブストラクト
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
論文の図

Figure 2 . Errors of the official interface-A implementation (red) and of the same formula evaluated in the next higher precision (green) versus the true KL, for the 16 scalar-family configurations in the ordinary parameter region R0. Solid lines are FP32 inputs and dashed lines FP16 inputs. The inset enlarges the lower right corner of the last panel. FP16 relative error is shown only while the true KL is a normal number (above about 6 × 10−5 ).
出典 · CC BY 4.0 · Zhen Yang, Wei Tang, Chu Chen, Rui Qian, Yixuan Chen, Fan Yang, Kangning Cui · The KL Divergence Is Never Negative, Except in PyTorch · 論文の図を引用 · 元のPDFの4ページ目から図の部分を抽出しています。
Table 1 . Significant KL error rates (%) for interface A, across all KL bins and parameter regions. Entries are percentages of scored inputs with ≥ 8 ULP error or a qualitative failure. N counts scored inputs across supported formats. OFFICIAL is PyTorch, OFF.+ the promoted official formula, REWRITE our same-format formula and OURS the strict repair. Ranges span dimension settings. The two multivariate families lack official FP16 support. Gradient results are in Appendix B.
出典 · CC BY 4.0 · Zhen Yang, Wei Tang, Chu Chen, Rui Qian, Yixuan Chen, Fan Yang, Kangning Cui · The KL Divergence Is Never Negative, Except in PyTorch · 論文の図を引用 · 元のPDFの5ページ目から図の部分を抽出しています。
Table 2 .Top-1 disagreement (%) between student and teacher after 300 steps from an identical initialisation (median over 10 seeds). Each cell gives official F.kl div /ours. The other two official variants agree with the first within 2.1 points in every cell. “0” means that no weight changed in any seed.
出典 · CC BY 4.0 · Zhen Yang, Wei Tang, Chu Chen, Rui Qian, Yixuan Chen, Fan Yang, Kangning Cui · The KL Divergence Is Never Negative, Except in PyTorch · 論文の図を引用 · 元のPDFの7ページ目から図の部分を抽出しています。
Table 3 .KL errors and layer rankings at 8-bit quantization (FP16). Part A reports signed relative error (%) in mean KL and the per- centage of tokens with negative or infinite KL (GPTQ / RTN). Part B reports inverted layer pairs out of 378 and Kendall’sτb (1 indicates perfect agreement). “B fix” repairs F.kl div on the same rounded probability inputs.
出典 · CC BY 4.0 · Zhen Yang, Wei Tang, Chu Chen, Rui Qian, Yixuan Chen, Fan Yang, Kangning Cui · The KL Divergence Is Never Negative, Except in PyTorch · 論文の図を引用 · 元のPDFの7ページ目から図の部分を抽出しています。
Figure 3 .Interface A, FP32 inputs, region R0. Share of samples whose KL has relative error ≥1% , per configuration and KL interval. The left panel shows the official implementation on CPU (PyTorch 2.15.0), the middle panel the official implementation on an A100 GPU (PyTorch 2.4.0), and the right panel OURS, whose CPU and GPU results are identical (all zero). Blank cells have fewer than 100 samples (not constructible on the FP32 grid).
出典 · CC BY 4.0 · Zhen Yang, Wei Tang, Chu Chen, Rui Qian, Yixuan Chen, Fan Yang, Kangning Cui · The KL Divergence Is Never Negative, Except in PyTorch · 論文の図を引用 · 元のPDFの14ページ目から図の部分を抽出しています。
Table 7 .Closed forms: running time relative to the official FP32 call, for 65,536 / 1,048,576 pairs of FP32 parameters. “FP64”: the official formula evaluated in FP64.
出典 · CC BY 4.0 · Zhen Yang, Wei Tang, Chu Chen, Rui Qian, Yixuan Chen, Fan Yang, Kangning Cui · The KL Divergence Is Never Negative, Except in PyTorch · 論文の図を引用 · 元のPDFの26ページ目から図の部分を抽出しています。
Table 8 . F.kl div: running time relative to the official call in the input precision ( batchmean). “no check”: the repair with the boundary check of the final rounding skipped.
出典 · CC BY 4.0 · Zhen Yang, Wei Tang, Chu Chen, Rui Qian, Yixuan Chen, Fan Yang, Kangning Cui · The KL Divergence Is Never Negative, Except in PyTorch · 論文の図を引用 · 元のPDFの26ページ目から図の部分を抽出しています。
Table 10 .Official implementation and OURSon CPU (PyTorch 2.15.0) and on an A100 GPU (PyTorch 2.4.0), all KL intervals and parameter regions. Interface A: significant-error rate of the KL value (%). Interface B: share of components that are not correctly rounded (%); the backward rate of the official implementation excludes the boundary-gradient components.
出典 · CC BY 4.0 · Zhen Yang, Wei Tang, Chu Chen, Rui Qian, Yixuan Chen, Fan Yang, Kangning Cui · The KL Divergence Is Never Negative, Except in PyTorch · 論文の図を引用 · 元のPDFの27ページ目から図の部分を抽出しています。
Figure 5 .Interface B, FP32 inputs, region R0, batches of one row, reduction="sum". Share of samples whose output has relative error ≥1% , per configuration and KL interval. The left and middle panels show the official F.kl div on CPU and on GPU, and the right panel OURS, whose CPU and GPU results are identical (all zero).
出典 · CC BY 4.0 · Zhen Yang, Wei Tang, Chu Chen, Rui Qian, Yixuan Chen, Fan Yang, Kangning Cui · The KL Divergence Is Never Negative, Except in PyTorch · 論文の図を引用 · 元のPDFの28ページ目から図の部分を抽出しています。
Figure 6 .Interface B, FP16 inputs, as Figure 5. Blank cells have fewer than 100 samples.
出典 · CC BY 4.0 · Zhen Yang, Wei Tang, Chu Chen, Rui Qian, Yixuan Chen, Fan Yang, Kangning Cui · The KL Divergence Is Never Negative, Except in PyTorch · 論文の図を引用 · 元のPDFの28ページ目から図の部分を抽出しています。
Table 12 .Sequential Bayesian design, all settings; 100,000 observations, K= 10, ranges over 5 seeds. “Lost”: mean over the rounds of 1−EIG chosen/EIGmax, with exact values at the policy’s own posterior. “Zero or negative”: share of the EIG values computed by the official code. “Worst arm”: largest posterior variance of an arm, relative to the largest of the exact policy. “Fewest”: smallest number of observations of an arm at the end over the seeds, official code (exact policy). The rewrite has no wrong round and variance ratios of 1.0000 in all 40 runs; its allocation of the observations is identical to that of the exact policy in 39 runs and differs by one observation in one (cold start,m= 1).
出典 · CC BY 4.0 · Zhen Yang, Wei Tang, Chu Chen, Rui Qian, Yixuan Chen, Fan Yang, Kangning Cui · The KL Divergence Is Never Negative, Except in PyTorch · 論文の図を引用 · 元のPDFの30ページ目から図の部分を抽出しています。
Table 13 .Language models, Part A. Reported mean KL ( batchmean) and its deviation from the FP64 reference. “inf”: the reported value is infinite.
出典 · CC BY 4.0 · Zhen Yang, Wei Tang, Chu Chen, Rui Qian, Yixuan Chen, Fan Yang, Kangning Cui · The KL Divergence Is Never Negative, Except in PyTorch · 論文の図を引用 · 元のPDFの31ページ目から図の部分を抽出しています。
Table 14 .Language models, Part A. Per-token errors on 16,384 tokens for the two 8-bit models (GPTQ / RTN). “Total” error is relative to the exact KL of the FP16 model logits; “operator” error is relative to the exact value on the inputs the call received. For the logits path the last column is agreement with the rounded FP64 reference.
出典 · CC BY 4.0 · Zhen Yang, Wei Tang, Chu Chen, Rui Qian, Yixuan Chen, Fan Yang, Kangning Cui · The KL Divergence Is Never Negative, Except in PyTorch · 論文の図を引用 · 元のPDFの32ページ目から図の部分を抽出しています。
Table 15 .Language models, Part B. Ranking of 28 single-layer quantizations: strict inversions among 378 pairs / reported ties, and Kendall’sτ b against the reference.
出典 · CC BY 4.0 · Zhen Yang, Wei Tang, Chu Chen, Rui Qian, Yixuan Chen, Fan Yang, Kangning Cui · The KL Divergence Is Never Negative, Except in PyTorch · 論文の図を引用 · 元のPDFの32ページ目から図の部分を抽出しています。
Table 20 .Settings without a measurable effect of the KL implementation. “Official” is the KL as the cited library computes it; “ours” is the logits path. LLM runs use Qwen2.5-1.5B-Instruct with a BF16 forward pass on WikiText-2; “eval KL” is the exact (FP64) KL between teacher and student on held-out text.
出典 · CC BY 4.0 · Zhen Yang, Wei Tang, Chu Chen, Rui Qian, Yixuan Chen, Fan Yang, Kangning Cui · The KL Divergence Is Never Negative, Except in PyTorch · 論文の図を引用 · 元のPDFの36ページ目から図の部分を抽出しています。この論文を引用
Zhen Yang, Wei Tang, Chu Chen, Rui Qian, Yixuan Chen, Fan Yang, Kangning Cui (2026). The KL Divergence Is Never Negative, Except in PyTorch. arXiv:2611.30835v1. https://arxiv.org/abs/2611.30835v1
BibTeX
@misc{yang2026divergence,
title = {{The KL Divergence Is Never Negative, Except in PyTorch}},
author = {Zhen Yang and Wei Tang and Chu Chen and Rui Qian and Yixuan Chen and Fan Yang and Kangning Cui},
year = {2026},
eprint = {2611.30835},
archivePrefix = {arXiv},
url = {https://arxiv.org/abs/2611.30835v1}
}