프로필

설정

불러오는 중…

← 홈

도움말·문의

자주 묻는 질문

어떤 기능에 로그인이 필요한가요?

공개 논문의 해설과 논문 정보, 모델 구조, 관련 논문, 용어는 로그인 없이 볼 수 있습니다. 논문 올리기, 내 보관함, 읽기 기록, 논문 평가, 관심 분야 추천, 메일과 알림은 로그인해야 쓸 수 있습니다.

PDF 파일로도 올릴 수 있나요?

논문은 arXiv나 DOI 링크로 올리고, 해설은 모두에게 공개됩니다. 출처와 이용 조건이 확인되지 않아 해설을 공개할 수 없는 논문은 올릴 수 없습니다. PDF 파일 올리기와 나만 보기는 구독 회원만 쓸 수 있고, 파일로 올린 논문은 나만 보기로만 저장합니다. 제목으로 공식 정보를 찾는 검색은 버튼을 누를 때만 합니다.

그림과 AI 해설은 정확한가요?

그림은 논문 원본만 쓰고 이용 허락이 확인된 것만 보여 줍니다. 해설은 AI가 쓴 글이라 틀릴 수 있습니다. 중요한 주장과 수치, 그림의 맥락은 원문 근거로 확인해 주세요.

저작권 문제를 알리고 싶어요.

이용 조건과 원문 출처는 논문 정보 탭에 있습니다. 문제가 있으면 ‘문의하기’에서 ‘논문 내용·그림·저작권’을 골라 논문 링크와 문제가 되는 부분, 권리를 확인할 수 있는 근거를 보내 주세요. 접수만으로 권리가 확정되거나 바로 삭제되지는 않습니다. 검토 결과는 ‘내 문의’에서 볼 수 있습니다.

비밀번호를 잊었어요.

이메일로 가입했다면 로그인 창의 비밀번호 찾기에서 인증한 이메일로 다시 설정할 수 있습니다. Google, 네이버, 카카오로 가입했다면 그 서비스에서 비밀번호를 바꿔 주세요.

문의할 때 무엇을 적어야 하나요?

어느 화면에서 무엇을 하다 생긴 문제인지 논문 링크와 함께 적어 주세요. 비밀번호, API 키, 인증 코드, 전화번호 같은 개인정보는 적지 마세요. 문의와 답변은 Refivu에 저장되고 ‘내 문의’에서 볼 수 있습니다.

회원탈퇴는 어떻게 하나요?

설정의 내 계정에서 회원탈퇴를 누르세요. 지워지는 내용을 확인하고 본인 확인을 마치면 탈퇴됩니다. 다른 요청은 ‘문의하기’에서 ‘계정’을 골라 남겨 주세요.

논문 해설

The KL Divergence Is Never Negative, Except in PyTorch

PyTorch KL 발산 오류를 수식 재작성으로 고침

  • 연구 문제 가까운 두 분포의 KL을 PyTorch 공식으로 계산하면 음수나 틀린 값이 나옵니다. 정밀도를 올려도 오류가 충분히 사라지지 않습니다.
  • 연구 방법 저자들은 KL을 음수가 아닌 항들의 합으로 다시 씁니다. 정밀도를 올리는 대신 식의 모양을 바꿔 합이 음수가 되지 않게 합니다.
  • 주요 결과 고친 공식은 큰 오류의 97%보다 많이 없앱니다.

가까운 분포에서 KL이 무너지는 이유

KL 발산이 가까운 두 분포에서 무너지는 까닭은 수식의 구조에 있습니다. 두 분포가 상대적으로 δ만큼 다르면 KL(P∥Q)는 대개 δ의 제곱 정도로 작아지지만, 거의 모든 닫힌 형태 공식은 이 값을 O(1) 또는 O(δ) 크기의 항들을 부호를 섞어 더한 합으로 계산합니다. 그래서 각 항에 남는 반올림 오차는 단위 반올림 u의 크기 정도가 되고, 참 KL이 u 근처이거나 그보다 작아지면 계산값은 잡음으로 바뀝니다.

계산값은 음수일 수도, 서로 다른 분포에서 0일 수도, 같은 분포에서 0이 아닌 값일 수도 있으며, 그 기울기는 내려가는 방향을 가리키지 않을 수 있습니다. FP32에서 u는 약 6×10⁻⁸이고 FP16에서는 약 5×10⁻⁴이어서, 저정밀도 형식은 이 경계를 실무에서 쓰는 값의 범위 안으로 옮겨 놓습니다. 음수를 0으로 자르는 처리는 값과 역전파되는 기울기를 함께 0으로 만들기 때문에 증상만 가리고 오차는 그대로 둡니다. 더구나 부정확한 KL 추정값 중 상당수는 양수이면서 유한한 값입니다. 참 KL이 줄어들 때 계산값이 잡음으로 바뀌는 과정은 그림 1에 나타납니다.

KL은 변분 오토인코더의 정규화항, 정책 최적화의 신뢰 영역 제약, 지식 증류의 손실, 압축 모델이 얼마나 멀리 움직였는지 재는 지표로 쓰입니다. 이 응용들은 연속된 정책, 학생과 교사 모델, 모델과 그 양자화 복사본처럼 서로 가까운 분포를 비교하는 경우가 많습니다. 저자들은 검사한 PyTorch 기반 패키지 116개 중 39개가 두 KL 인터페이스 중 하나 이상을 호출한다는 점을 확인했습니다. 앞선 연구는 softmax와 cross-entropy의 수치 실패로 grokking이 멈추는 현상과 증류 드리프트를 설명했지만, 분포 족과 인터페이스를 가로질러 KL 자체가 측정된 적은 없었습니다. 저자들은 PyTorch의 두 인터페이스, 즉 두 분포 객체 사이의 닫힌 형태 공식을 쓰는 torch.distributions.kl_divergence(인터페이스 A)와 nn.KLDivLoss 뒤의 손실인 torch.nn.functional.kl_div(인터페이스 B)에서 이 오차를 측정했습니다.

정밀도보다 수식의 형태가 먼저인 까닭

지수 분포 두 개를 예로 들면, 두 분포의 비율 r에 대한 KL은 r−1−log r로 계산됩니다. r이 1에 가까워지면 이 식은 1 근처의 값을 빼는 계산이 되고, 그 자리에서 생기는 절대 반올림 오차는 약 u로 남습니다. 참값은 x의 제곱에 비례해 작아지는데 오차는 상수로 그대로 남기 때문에, 상대 오차는 약 2u/x²가 됩니다. 그래서 FP32에서 |x|가 √2u, 약 3.5×10⁻⁴보다 작아지면 상대 오차가 100%를 넘습니다.

서로 다른 두 분포가 같다고 판정되는 것이며, 이 장면은 Figure 1a에 나타나 있습니다.

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)R…

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쪽에서 그림 영역을 추출했습니다.

지지 집합(support)만 달라지는 경우, 예를 들어 Uniform과 Pareto에서는 KL이 1차 양이 됩니다. 이 경우에는 제곱으로 작아지는 구조가 없어서 정밀도를 높인다고 해서 오차가 사라지지 않습니다. 파라미터가 FP32로 저장되면 두 값은 2^-24 정도 차이날 수 있고, 같은 공식을 FP64에서 계산하더라도 단위 반올림 오차가 2^-53이면 상대 오차가 2u64/x² ≈ 0.06까지 나올 수 있습니다. 저자들은 그래서 정밀도를 한 단계 올리는 것보다 수식을 어떤 형태로 쓰는지가 더 중요하다고 봅니다.

비음수 분해와 정확한 차이로 다시 쓰기

KL을 음수가 아닌 항들의 합으로 다시 쓰는 출발점은 φ(x)=x−log1p(x)입니다. 이 함수는 항상 0 이상이므로, 지수 분포의 KL은 x에 (λq−λp)/λp를 넣은 φ와 같아집니다. Cauchy와 Uniform에서는 KL이 log1p(r)이 되고, Bernoulli는 φ 두 개의 가중합으로, Categorical은 확률마다 φ를 더한 합으로 적힙니다. 다변량 정규 분포는 φ(Nii)를 모두 더한 값에 행렬 N의 프로베니우스 노름 제곱의 절반과 벡터 v 노름 제곱의 절반을 더합니다. Gamma, Beta, Dirichlet는 φ 항들과 볼록 함수의 Bregman divergence를 더한 형태가 됩니다.

항이 모두 0 이상이므로 합은 음수가 될 수 없고, 합의 정확도는 항들의 정확도만큼이며, 모든 항이 0일 때만 0이 됩니다.

다만 φ 자체도 x가 0 근처에서는 상쇄가 생깁니다. s=x/(2+x)로 놓으면 φ(x)는 s의 거듭제곱을 합한 급수로 적히고, 이 급수를 FP16, FP32, FP64에서 각각 9, 17, 36항에서 끊어도 오차는 φ의 u/16 이내로 묶입니다. 여기서 u는 반올림 단위입니다.

분해가 쓸모 있으려면 인자들인 x, e, ρk, N이 자기 크기에 비해 정확해야 합니다. 그래서 이 값들을 입력의 차이로 직접 계산하며, 가까운 부동소수점 수의 차는 Sterbenz 보조정리에 따라 정확합니다. 곱의 차가 필요한 곳, 예를 들어 Categorical 매개변수 x, y에서 Nk=ykSx−xkSy를 구할 때는 Knuth, Dekker, Shewchuk, Ogita 등의 오류 없는 변환을 씁니다. 그 결과 비례하는 확률, 평행 이동한 로짓, 같은 공분산의 서로 다른 저랭크 인수처럼 분포가 같은 쌍은 구조적으로 정확한 0인 +0을 반환합니다.

자동 미분은 상쇄가 있는 식을 그대로 따라가므로 상쇄를 물려받고 실패 경로도 따로 더합니다. 그래서 저자들은 다시 쓴 형태의 도함수를 직접 구현하며, 예를 들어 식 (2)에 대해 ∂KL/∂σp를 e(e+2)/σp로 계산합니다. 이 도함수의 곱과 차도 안정된 연산으로 평가합니다. 기울기가 실제로 0을 가로지르는 곳에서는 잔여 상쇄가 작업 정밀도에 내재하며, 이는 아래의 strict 모드로 처리합니다.

REWRITE는 다시 쓴 알고리즘 전체를 목표 정밀도에서 보상 연산으로 실행합니다. 반면 OURS는 같은 알고리즘을 FP64에서 실행한 뒤 목표 형식으로 한 번만 반올림합니다. 한 번만 반올림하는 것이 중요한 까닭은 FP64에서 FP32를 거쳐 FP16으로 가면 이중 반올림이 생기기 때문입니다(부록 B.1). F.kl_div에서는 마지막 반올림을 한 번 더 보호합니다.

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…

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쪽에서 그림 영역을 추출했습니다.

고정된 데이터에서의 정확도 비교

OFFICIAL은 PyTorch의 기본 구현이고, OFF.+는 그 공식은 그대로 둔 채 계산 정밀도만 올린 방법입니다. REWRITE는 입력과 출력 형식을 올리지 않고 같은 형식 안에서 새로 쓴 식이며, OURS는 여기에 엄격한 수정을 더한 방법입니다. Table 1은 네 방법을 3절과 정확히 같은 데이터로 비교하는데, 기준은 8 ULP 이상 어긋나거나 질적으로 실패한 입력의 비율입니다. ULP는 부동소수점 수에서 가장 낮은 자리 한 칸만큼의 차이를 뜻합니다.

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…

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쪽에서 그림 영역을 추출했습니다.

FP16 입력의 Geometric (logits) 행을 보면 차이가 잘 드러납니다. REWRITE는 형식을 올리지 않고도 모든 구성에서 유의미한 오류의 97%를 넘게 없앴고, 일곱 개 구성에서는 전부 없앴습니다. 남은 오류는 FP32 입력에서 최대 0.7%, FP16 입력에서 최대 2.5%였고, 기울기 성분에서는 어느 성분이든 1.6%를 넘지 않았습니다. 이 잔여분은 대부분 기울기가 0을 지나는 근처와 Beta, Dirichlet 계열에 몰렸습니다.

OFF.+는 정밀도만 올리면 무엇이 남는지를 보여줍니다. FP32 입력에서도 값의 절반까지 틀렸으니, 공식을 고치지 않은 정밀도 상승만으로는 부족합니다. 그래서 OURS는 엄격 모드로 이 잔여분을 없앴고, 7,234,454개 평가 샘플 전부에서 KL 값과 모든 기울기 성분에 유의미한 오류가 없었습니다. 항등 샘플에서는 값과 기울기가 정확히 0이었고, 음수 KL이나 NaN은 한 번도 나오지 않았습니다. 대가는 정밀도가 아니라 연산량이었습니다. GPU에서 시간을 잰 일곱 계열 중 다섯 계열에서 공식 호출보다 2.4에서 5.9배 느렸습니다(부록 C.4).

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, f…

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쪽에서 그림 영역을 추출했습니다.
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 o…

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…

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쪽에서 그림 영역을 추출했습니다.

interface B에서는 942,200개 배치를 대상으로 했습니다. OURS는 순방향 83,899,496개와 역방향 483,279,156개 평가 성분을 모두 올바르게 반올림했고, 같은 기준에서 OFFICIAL은 각각 52.5%와 74.9%를 맞혔습니다. 저자들은 Table 1의 수치가 샘플링 설계와 특정 응력 영역에 따라 달라진다고 봅니다.

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: sign…

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 an…

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

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쪽에서 그림 영역을 추출했습니다.

하류 작업에서 드러난 차이

저자들은 KL 값의 오류가 실제 결정을 바꾸는지 네 가지 하류 실험으로 확인했습니다. 순차 베이즈 설계 실험에서는 공식 FP32 KL을 쓴 경우 여러 설정에서 40~91%의 라운드가 잘못된 팔을 골랐습니다. 반면 재작성 구현은 40회 실행 중 어떤 라운드도 잘못 고르지 않았다고 보고됩니다. 증류 실험은 학생과 교사를 동일하게 초기화한 뒤 KL 손실만으로 학습한 것으로, 공식 손실에서는 학생이 움직였지만 logits 경로에서는 가중치가 변하지 않았습니다. 이 실험은 이상적인 시작점에서 생긴 수치적 드리프트를 보여 주며, 언어 모델 양자화 실험은 교사와 양자화 모델 사이 KL의 부호와 레이어 순위가 공식 구현에서 흔들린다는 것을 보입니다.

원문은 이 결과들이 KL 값 자체가 결과인 경우에 중요하고, 충분히 떨어진 시작점에서 일반적인 학습이 달라지는 경우는 찾지 못했다고 한정합니다.

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…

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 neg…

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쪽에서 그림 영역을 추출했습니다.
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…

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쪽에서 그림 영역을 추출했습니다.
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…

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쪽에서 그림 영역을 추출했습니다.
Table 13: Language models, Part A. Reported mean KL ( batchmean) and its deviation from the FP64 reference. “inf”: the reported
value is infinite

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 FP…

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 re…

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쪽에서 그림 영역을 추출했습니다.

한계와 적용 범위

네 가지 하류 실험 가운데 처음 세 실험은 합성 데이터나 시뮬레이션에 기반합니다. 샘플링이 작은 발산과 응력 영역을 일부러 많이 뽑도록 설계되어 있기 때문에, 오류율을 그대로 실제 빈도로 옮길 수 없습니다. 학습 효과는 시작점을 똑같이 맞춘 경우에만 확인했습니다. 여러 학습 설정에서 공식 KL이 항상 결과를 바꾼다는 증거는 얻지 못했습니다. 레이어 순위 실험에서는 가장 흔한 공식 설정이 여전히 올바른 선택을 했습니다. 측정된 효과가 없었던 설정은 Appendix F.3에 따로 정리되어 있고, Beta와 F.kl div 쪽 설정은 Appendix C.4에 더 자세히 실려 있습니다. BF16 결과는 탐색적 수준에 머물렀습니다.

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…

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쪽에서 그림 영역을 추출했습니다.

음수 KL 출력은 더 넓은 수치 실패의 한 징후입니다. 음수가 나오지 않는 부정확한 KL 값은 유한하고 음이 아니어서, 대부분 눈에 띄지 않은 채 남습니다. 원인은 구조적입니다. 가까운 두 분포 사이의 발산은 보통 큰 항들로 조립된 2차 양이기 때문입니다. 닫힌 형태(closed form)에서는 정밀도를 높이는 것만으로 생기는 오류가 사라지지 않고, 식을 다시 쓰는 것이 해결책이었습니다. 저자들의 실용적 조언은 반올림된 확률 대신 파라미터나 logits에서 발산을 계산하고, 음이 아닌 항들을 더하며, 정확한 반올림이 필요한 곳에서만 정밀도를 올리는 것입니다. 저자들은 이 작업이 기계학습의 기본 수치 연산을 더 믿을 만하게 만드는 것이 목적이며, 구체적인 부정적 사회적 결과는 예상하지 않는다고 봅니다.

논문 정보

저자
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
제공 범위
논문 정보, 해설, 허용된 원문 그림

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

원문 인용

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}
}

관련 논문 보기다른 논문 둘러보기

논문 미리 보기
계정 보안

Google 계정 연결

Google 계정을 연결하면 그 계정으로도 로그인할 수 있습니다.

Refivu

회원탈퇴

Refivu
Refivu

회원가입