Introduction
The Kullback–Leibler (KL) divergence (Kullback & Leibler, [32 ] ) between two distributions is non-negative, and zero only if they coincide, but code does not always agree. Since 2019, users of PyTorch (Paszke et al., [45 ] ) have repeatedly reported negative values from both of its KL functions, and the answer has been the same each time: this is floating-point error, clamp the result at zero (Appendix § 12 .§ 1.1 ). Clamping hides the symptom and leaves the error. Clamping negative KL estimates sets their values and backpropagated gradients to zero. Many inaccurate KL estimates are positive and finite.
The KL divergence is the regulariser of variational autoencoders (Kingma & Welling, [29 ] ), the trust-region constraint of policy optimisation (Schulman et al., [49 , 50 ] ; Shao et al., [51 ] ), the loss of knowledge distillation (Hinton et al., [20 ] ; Agarwal et al. [1 ] ), and a standard metric for how far a compressed model has moved (Nagel et al., [42 ] ; Xin et al. [60 ] ). These applications often compare closely related distributions: consecutive policies, a student and its teacher, or a model and its quantized copy. Among the 116 PyTorch-based packages we inspected, 39 call at least one of the two KL interfaces (Appendix § 12 ).
Closeness is exactly where the textbook formulas break down. If P P P and Q Q Q differ by a relative amount δ \delta δ , then typically KL ( P ∥ Q ) = O ( δ 2 ) \operatorname{KL}(P \mathbin{\|} Q) = O(\delta^2) KL ( P ∥ Q ) = O ( δ 2 ) , while almost every closed form computes it as a sum of O ( 1 ) O(1) O ( 1 ) or O ( δ ) O(\delta) O ( δ ) terms of mixed sign. The rounding error of those terms is of the order of the unit roundoff u u u (about 6 × 10 − 8 6 \times10^{-8} 6 × 1 0 − 8 in FP32, 5 × 10 − 4 5 \times10^{-4} 5 × 1 0 − 4 in FP16), so the computed divergence is noise once the true KL is of the order of u u u or smaller (Figure 1 ). It may be negative, zero for distinct distributions, or non-zero for identical ones, and its gradient need not point downhill. Low-precision formats (Micikevicius et al., [38 ] ; Kalahar et al. (2019)) move this threshold into the range of practical values.
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 4 \times10^{-8} 4 × 1 0 − 8 in FP32 (4 × 10 − 4 4 \times10^{-4} 4 × 1 0 − 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 10^{-2} 1 0 − 2 , median and range over 10 seeds, other settings in Appendix § 11 ). With the official loss the student’s top-1 predictions leave the teacher’s, whereas with our logits path they do not move.
Numerical failures of softmax and cross-entropy explain stalled grokking (Prieto et al., [46 ] ) and distillation drift (Barron et al., [2 ] ), but the KL divergence itself, across distribution families and interfaces, has not been measured. We measure it in both KL interfaces of PyTorch, torch.distributions.kl_divergence (interface A, closed forms between two distribution objects) and torch.nn.functional.kl_div (interface B, the loss behind nn.KLDivLoss), and show how to remove the error:
7.5 million parameter pairs for the 18 same-family closed forms of interface A and 0.94 million batches for interface B, stratified by the true KL from 10 − 15 10^{-15} 1 0 − 15 to 1 and certified by interval arithmetic, the official results degrade steadily as the distributions approach each other, for every family, on CPU and GPU.
More precision is not the fix, but a different formula is (§ 3 ). Across 18 closed forms, we combine non-negative decompositions, compensated arithmetic, special-function evaluation, and analytic gradients. For F.kl_div, we repair signed elements, reductions, and gradients. The rewrites remove over 97% of significant errors in the working precision, and strict repairs yield no significant errors on 7.2 million scored closed-form samples and correctly round all 567 million interface-B components.
Two error sources must be told apart (§ 1.1 ): the operator error of F.kl_div on the inputs it receives, and the input-representation error already present in rounded (log-)probabilities, which no implementation of F.kl_div can repair and which requires a divergence computed from logits.
The errors change outcomes (§ 4 ), from fitting a single distribution and a sequential Bayesian experiment to distillation, KL-based decisions for a quantized LLM and circuit analysis of GPT-2 models.
Background and Error Model
Floating point. We use the standard model fl ( a ∘ b ) = ( a ∘ b ) ( 1 + ϵ ) \operatorname{fl}(a \circ b)=(a \circ b)(1+\epsilon) fl ( a ∘ b ) = ( a ∘ b ) ( 1 + ϵ ) , ∣ ϵ ∣ ≤ u |\epsilon| \le u ∣ ϵ ∣ ≤ u , for ∘ ∈ { + , − , × , / } \circ\in\{+,-,\times,/ \} ∘ ∈ { + , − , × , / } (Higham, [19 ] ), for binary16 (FP16), binary32 (FP32), binary64 (FP64) (IEEE, [23 ] ) and bfloat16 (BF16). A result is correctly rounded if it equals the exact value rounded to nearest in the output format, and errors in ULP are in units of the spacing of the format at the exact value. Subtracting two nearby floating-point numbers is exact (Sterbenz, [54 ] ), but exposes the rounding errors already present in them (cancellation ) (Goldberg, [14 ] ).
Cancellation near equality
Take two Exponential distributions with rates λ p , λ q \lambda_p,\lambda_q λ p , λ q , for which K L = r − 1 − log r \mathrm{KL}=r-1-\log r KL = r − 1 − log r with r = λ q / λ p = 1 + x r=\lambda_q/\lambda_p=1+x r = λ q / λ p = 1 + x . The exact value is x 2 / 2 + O ( x 3 ) x^2/2+O(x^3) x 2 /2 + O ( x 3 ) , but r − 1 − log r r-1-\log r r − 1 − log r is evaluated near 1, where the absolute rounding error is about 2 u 2u 2 u , and the relative error is therefore about 2 u / x 2 2u/x^2 2 u / x 2 , which exceeds 100% once ∣ x ∣ < 2 u ≈ 3.5 × 10 − 4 |x| < \sqrt{2u} \approx3.5 \times10^{-4} ∣ x ∣ < 2 u ≈ 3.5 × 1 0 − 4 in FP32. For example, for λ p = 1 \lambda_p=1 λ p = 1 and λ q = fl ( 1.0001 ) \lambda_q=\operatorname{fl}(1.0001) λ q = fl ( 1.0001 ) in FP32 the true value is 5.0013 × 10 − 9 5.0013 \times10^{-9} 5.0013 × 1 0 − 9 , but r − log r = 1.000000005 … r-\log r=1.000000005\ldots r − log r = 1.000000005 … rounds to 1 and the official formula returns exactly 0, so two different distributions are reported as identical (Figure 1 a). The same structure, a second-order quantity obtained from first-order or zeroth-order terms, appears in the closed forms we examined (Appendix § 8 ). When only the support changes (Uniform, Pareto), the KL is first order. It is not removed by more precision alone, because FP32 parameters can differ by x = 2 − 24 x=2^{-24} x = 2 − 24 , for which the same formula in FP64, whose unit roundoff is u 64 = 2 − 53 u_{64}=2^{-53} u 64 = 2 − 53 , can have a relative error of 2 u 64 / x 2 ≈ 0.06 2u_{64}/x^2 \approx0.06 2 u 64 / x 2 ≈ 0.06 .
Interfaces. Interface A, kl_divergence(P,Q), dispatches on the types of the two distribution objects to a closed form in their parameters. Gradients come from automatic differentiation, and for families with two parameterisations (probs or logits) the constructors convert and clamp the parameters first. Interface B, F.kl_div(x, t), takes a tensor x x x of log-probabilities and a target t t t of probabilities (or of log-probabilities when log_target=True), evaluates t ( log t − x ) t(\log t-x) t ( log t − x ) or e t ( t − x ) e^{t}(t-x) e t ( t − x ) element-wise, and reduces.
Operator error versus input-representation error. For interface B the inputs are themselves outputs of a rounded computation, typically log_softmax of model logits. Let T o p T_{\mathrm{op}} T op be the exact operator result on its stored inputs and T e 2 e T_{\mathrm{e2e}} T e2e the corresponding result from the original logits, with the same reduction. We call the difference between the computed output and T o p T_{\mathrm{op}} T op the operator error , and T o p − T e 2 e T_{\mathrm{op}}-T_{\mathrm{e2e}} T op − T e2e the input-representation error . Only the first belongs to F.kl_div. A related backward error is Softmax Cancellation [2 ] . The gradient of the forward KL with respect to x x x involves no cancellation. The cancellation happens afterwards, in the backward pass of log_softmax, where q − p q-p q − p , the difference between the input distribution q = e x q=e^{x} q = e x and the target p = t p=t p = t , is formed from two rounded probability vectors, and the result is non-zero even when the two distributions are identical.
Numerical Errors in PyTorch
We first measure the failure, with a reference that is exact for the bit patterns the library receives, so that every reported error belongs to the implementation and not to the test.
Data and ground truth. For interface A we test the 18 distribution-specific same-family closed forms in 23 parameter and dimension configurations (five generic or delegated registrations are out of scope, and the two multivariate families are scored in FP32 only). For each we draw P P P from an ordinary parameter region R0 and from stress regions (very large or small parameters, probabilities near 0 or 1), and construct Q Q Q so that the true KL( P ∥ Q ) (P\mathbin{\|}Q) ( P ∥ Q ) falls in a prescribed decade: one control bin [ 10 − 1 , 1 ) [10^{-1},1) [ 1 0 − 1 , 1 ) and 14 bins down to [ 10 − 15 , 10 − 14 ) [10^{-15},10^{-14}) [ 1 0 − 15 , 1 0 − 14 ) . Two further groups contain pairs whose parameters differ by 1–8 ULP, and identical pairs. This gives 7,542,469 samples, of which 7,234,454 are scored. Cells that the floating-point grid cannot populate remain empty. For interface B we generate 942,200 batches over log_target, FP16/FP32, K ∈ { 2 , 4 , 16 , 256 , 1024 } K \in\{2, 4, 16, 256, 1024\} K ∈ { 2 , 4 , 16 , 256 , 1024 } classes, two batch sizes and all four reductions, from logits stratified in the same way. Parameters are stored in the target format first. The exact KL and every gradient component are then enclosed with Arb ball arithmetic [24 ] tightly enough to determine a unique correctly rounded value in that format (Appendices A and H).
Methods and metrics. OFFICIAL is PyTorch 2.15.0 on CPU, and we repeated the evaluation on an NVIDIA A100 GPU (Appendix D). OFFICIAL+, the natural “just use more precision” baseline, evaluates the unchanged official code after promoting the parameters exactly to the next format (FP32 for FP16 inputs, FP64 for FP32 inputs) and rounds the result once. An output is a significant error if it is off by at least 8 ULP or is qualitatively wrong (negative, NaN or infinite KL where the truth is finite and positive; spurious zero or non-zero; sign-flipped gradient component).
Errors near equality. The error grows as the true KL approaches the unit roundoff u u u (Figure 2 , which pools the 16 scalar-family configurations in R0, with details in Appendix A.1). In the control bin the official values are accurate (0.1% of the FP32 values are off by 1% or more). As the KL approaches u ≈ 6 × 10 − 8 u \approx6 \times10^{-8} u ≈ 6 × 1 0 − 8 most are wrong (86% at 10 − 7 10^{-7} 1 0 − 7 ), and below that nearly all are, with about three in ten negative from 10 − 10 10^{-10} 1 0 − 10 down. FP16 follows the same curve four decades earlier, as its roundoff predicts. Gradients, being first-order quantities, survive longer but fail in a worse way. At 10 − 13 10^{-13} 1 0 − 13 a fifth of the gradient vectors have a cosine below 0.99 with the true one, and at 10 − 15 10^{-15} 1 0 − 15 , 6.8% point into the opposite half-space. No family is exempt (Table 1 , columns OFFICIAL).
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 6 \times10^{-5} 6 × 1 0 − 5 ).
Table 1. Significant KL error rates (%) for interface A, across all KL bins and parameter regions. Entries are percentages of scored inputs with ≥ 8 \ge8 ≥ 8 ULP error or a qualitative failure. N N 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 § 8 .
Precision promotion. Evaluating the same formula one format higher moves the failure; it does not remove it, because two inputs can still differ by one unit in the last place of the input format (§ 1.1 ). For FP32 inputs OFFICIAL+ shifts the curve of Figure 2 about nine decades down (56% off by ≥ 1 % \ge1\% ≥ 1% at 10 − 15 10^{-15} 1 0 − 15 ), and for FP16 inputs it leaves a residue (13% at 10 − 5 10^{-5} 1 0 − 5 ). Over all bins and regions it leaves 7–51% of the FP32 KL values significantly wrong in 22 of 23 configurations (Table 1 ), Uniform being the only exception.
Loss-operator errors. F.kl_div fails in a different way. Its element t ( log t − x ) t(\log t-x) t ( log t − x ) cancels whenever t ≈ e x t \approx e^{x} t ≈ e x . For probability targets 35–70% of the FP32 sum outputs are off by at least 1%, and scaled reductions produce large target-gradient errors (FP16, mean, K = 256 K=256 K = 256 : 95.4% of gradient rows contain a component of the wrong sign). Unlike the closed forms, these operator errors essentially disappear in FP64, but the error inherited from the inputs does not, since T o p T_{\mathrm{op}} T op differs from T e 2 e T_{\mathrm{e2e}} T e2e by ≥ 1 % \ge1\% ≥ 1% on 40–99% of the batches, in any precision of the operator (Appendix C).
CPU and GPU. The failure persists on the GPU. On an A100 the aggregate significant-error rates for interface A differ from the CPU rates by at most 1.5 percentage points. For F.kl_div, 50.0% of forward and 71.1% of non-boundary backward components are correctly rounded (CPU: 52.5% and 76.4%). The two devices nevertheless do not return the same bits, and 27% of the FP32 KL values of OFFICIAL differ. Our strict repair OURS (§ 3 ) has no significant error on either device (Appendix D).
Stable KL Computation
The repairs of the 18 closed forms differ in detail (Appendix § 8 ) but share four ingredients, which we illustrate with the smallest example that needs each. F.kl_div additionally requires accurate signed elements and reductions (Appendix § 9 ).
Stable decompositions. The function
φ ( x ) = x − log 1 p ( x ) ≥ 0 , x > − 1 , (1) \varphi(x) = x - \log1p(x) \ge0,\qquad x > -1, \tag*{(1)} φ ( x ) = x − log 1 p ( x ) ≥ 0 , x > − 1 , (1)
is the Exponential KL with x = ( λ q − λ p ) / λ p x = (\lambda_q - \lambda_p)/\lambda_p x = ( λ q − λ p ) / λ p , and it is the building block of almost every other family. For example, for two normal distributions N p = N ( μ p , σ p 2 ) N_p = \mathcal{N}(\mu_p,\sigma_p^2) N p = N ( μ p , σ p 2 ) and N q = N ( μ q , σ q 2 ) N_q = \mathcal{N}(\mu_q,\sigma_q^2) N q = N ( μ q , σ q 2 ) , with e = ( σ p − σ q ) / σ q e = (\sigma_p-\sigma_q)/\sigma_q e = ( σ p − σ q ) / σ q and w = ( μ p − μ q ) / σ q w = (\mu_p-\mu_q)/\sigma_q w = ( μ p − μ q ) / σ q ,
KL ( N p ∥ N q ) = φ ( e ) + 1 2 e 2 + 1 2 w 2 , (2) \operatorname{KL}(N_p\mathbin{\|}N_q) = \varphi(e) + \frac{1}{2}e^2 + \frac{1}{2}w^2, \tag*{(2)} KL ( N p ∥ N q ) = φ ( e ) + 2 1 e 2 + 2 1 w 2 , (2)
whereas the official code evaluates 1 2 ( r 2 + w 2 − 1 − log r 2 ) \frac{1}{2}(r^2+w^2-1-\log r^2) 2 1 ( r 2 + w 2 − 1 − log r 2 ) with r = σ p / σ q r=\sigma_p/\sigma_q r = σ p / σ q , in which w 2 w^2 w 2 is absorbed by r 2 ≈ 1 r^2\approx1 r 2 ≈ 1 . Analogous identities (Appendix § 8 , which defines each argument) give KL = log 1 p ( r ) \operatorname{KL}=\log1p(r) KL = log 1 p ( r ) with r ≥ 0 r\ge0 r ≥ 0 for Cauchy and Uniform, p φ ( x 1 ) + ( 1 − p ) φ ( x 2 ) p\varphi(x_1)+(1-p)\varphi(x_2) pφ ( x 1 ) + ( 1 − p ) φ ( x 2 ) for Bernoulli, ∑ k p k φ ( ρ k ) \sum_k p_k\varphi(\rho_k) ∑ k p k φ ( ρ k ) for Categorical, ∑ i φ ( N i i ) + 1 2 ∥ N ∥ F 2 + 1 2 ∥ v ∥ 2 \sum_i\varphi(N_{ii})+\frac{1}{2}\lVert N\rVert_F^2+\frac{1}{2}\lVert v\rVert^2 ∑ i φ ( N ii ) + 2 1 ∥ N ∥ F 2 + 2 1 ∥ v ∥ 2 for the multivariate normal, and sums of φ \varphi φ terms and Bregman divergences of convex functions for Gamma, Beta and Dirichlet. Every term is non-negative, so the sum is as accurate as its terms, cannot be negative, and is exactly zero when all terms are. φ \varphi φ itself still cancels as x → 0 x\to0 x → 0 , so on − 3 4 ≤ x ≤ 3 -\frac{3}{4}\le x\le3 − 4 3 ≤ x ≤ 3 we use the exact identities log 1 p ( x ) = 2 atanh ( s ) \log1p(x)=2\operatorname{atanh}(s) log 1 p ( x ) = 2 atanh ( s ) , s = x / ( 2 + x ) s=x/(2+x) s = x / ( 2 + x ) , to write
φ ( x ) = x 2 2 + x − 2 s 3 ∑ k ≥ 1 s 2 ( k − 1 ) 2 k + 1 , (3) \varphi(x)=\frac{x^2}{2+x}-2s^3\sum_{k\ge1}\frac{s^{2(k-1)}}{2k+1}, \tag*{(3)} φ ( x ) = 2 + x x 2 − 2 s 3 k ≥ 1 ∑ 2 k + 1 s 2 ( k − 1 ) , (3)
a convergent series whose truncation after 9/17/36 terms (FP16/FP32/FP64) is bounded rigorously by u / 16 u/16 u /16 relative to φ \varphi φ .
Accurate differences. A non-negative decomposition is only useful if its arguments (x x x , e e e , ρ k \rho_k ρ k , N N N ) are accurate relative to their own size. We therefore compute them from differences of the inputs, which are exact for nearby floating-point numbers (Sterbenz, [54 ] ), and, where a difference of products is needed (e.g. N k = y k S x − x k S y N_k=y_kS_x-x_kS_y N k = y k S x − x k S y for Categorical parameters x , y x,y x , y with sums S x , S y S_x,S_y S x , S y , Appendix § 8 .16), from error-free transformations (Knuth, [31 ] ; Dekker, [10 ] ; Shewchuk, [52 ] ; Ogita et al., [43 ] ). As a consequence, structurally exact zeros are returned as + 0 +0 + 0 , including pairs whose parameters differ but whose distributions coincide (proportional probs, shifted logits, different low-rank factors of one covariance).
Analytic gradients. Automatic differentiation of a cancelling formula inherits the cancellation and adds failure modes of its own. We implement the derivative of the rewritten form directly, e.g. ∂ KL / ∂ σ p = e ( e + 2 ) / σ p \partial\operatorname{KL}/\partial\sigma_p=e(e+2)/\sigma_p ∂ KL / ∂ σ p = e ( e + 2 ) / σ p for Equation (2) , evaluating the resulting products and differences with stable arithmetic. Where a gradient has a genuine zero crossing, the residual cancellation is intrinsic in the working precision and is resolved by the strict mode below.
Strict rounding. Rewrite runs the rewritten algorithm entirely in the target precision, with compensated arithmetic. The strict variant, Ours, evaluates the same algorithm in FP64 and rounds once to the target format. Rounding once matters, because FP64→FP32→FP16 is a double rounding (Appendix § 8 .§ 1 ). For F.kl_div we additionally guard the last rounding. If the FP64 value is close to a rounding boundary than its a-priori error bound, the sum is re-evaluated with interval arithmetic at increasing precision, in the spirit of Ziv [67 ] .
Results on the frozen data. Table 1 compares the four methods on exactly the data of § 2 . The formula does most of the repair. REWRITE, without promoting the input or output format, removes more than 97% of the significant KL errors in every configuration and all of them in seven. What remains (at most 0.7% for FP32 and 2.5% for FP16 inputs, 1.6% in any gradient component, Appendix § 8 ) sits mostly in gradients near their zero crossings and in the Beta and Dirichlet families. The price is arithmetic rather than precision, at 2.4–5.9× the official call on a GPU for five of seven timed families (Appendix § 9 .§ 3 ). Conversely, OFFICIAL+ shows that precision without the formula leaves up to half of the FP32 values wrong. The strict mode removes the residue. OURS has no significant error in the KL value or in any gradient component on any of the 7,234,454 scored samples, returns exactly zero value and (where it exists) gradient at every identity sample, and never returns a negative KL or a NaN.
For interface B (942,200 batches), OURS is correctly rounded on all 83,899,496 forward and 483,279,156 backward scored components, against 52.5% and 74.9% for OFFICIAL, with no regression.
From logits. For teacher logits a a a and student logits c c c , we compute K L ( softmax ( a ) ∥ softmax ( c ) ) \mathrm{KL}(\operatorname{softmax}(a)\mathbin{\|}\operatorname{softmax}(c)) KL ( softmax ( a ) ∥ softmax ( c )) directly from logits. Let q = softmax ( c ) q=\operatorname{softmax}(c) q = softmax ( c ) be computed in FP64, choose r = arg max j c j r=\arg\max_j c_j r = arg max j c j , and form the compensated, centred differences δ j = ( a j − c j ) − ( a r − c r ) \delta_j=(a_j-c_j)-(a_r-c_r) δ j = ( a j − c j ) − ( a r − c r ) (Appendix § 8 .16),
Δ = log 1 p ( ∑ j q j exp 1 ( δ j ) ) , w j = δ j − Δ , K L = ∑ j q j ( w j exp ( w j ) − exp 1 ( w j ) ) , ∂ K L ∂ c j = − q j exp 1 ( w j ) . (4) \begin{aligned}
\Delta&= \log1p\left(\sum_j q_j\exp1(\delta_j)\right),\\
w_j &= \delta_j-\Delta,\\
\mathrm{KL} &= \sum_j q_j\left(w_j\exp(w_j)-\exp1(w_j)\right),\\
\frac{\partial\mathrm{KL}}{\partial c_j} &= -q_j\exp1(w_j). \tag*{(4)}
\end{aligned} Δ w j KL ∂ c j ∂ KL = log 1 p ( j ∑ q j exp 1 ( δ j ) ) , = δ j − Δ , = j ∑ q j ( w j exp ( w j ) − exp 1 ( w j ) ) , = − q j exp 1 ( w j ) . (4)
Here p j = q j e w j p_j=q_j e^{w_j} p j = q j e w j is the teacher probability and h ( w ) = w e w − exp 1 ( w ) ≥ 0 h(w)=we^w-\exp1(w)\ge0 h ( w ) = w e w − exp 1 ( w ) ≥ 0 for every real w w w . Near zero h h h is evaluated by its series ∑ n ≥ 2 ( n − 1 ) w n / n ! \sum_{n\ge2}(n-1)w^n/n! ∑ n ≥ 2 ( n − 1 ) w n / n ! , and at δ = 0 \delta=0 δ = 0 the KL and its logit gradients are exactly zero. This logits path , a row-vectorised form of the Categorical (logits) repair of Table 1 , is what the distillation and language-model experiments use. It is tested against high-precision references and is closely related to the fused soft-target loss of Barron et al. [2 ] .
Downstream Experiments
Do the wrong numbers matter? Four experiments, ordered by scale, compare the official implementation with the repaired one in tasks where nothing else changes.
Parameter Fitting
Setup. Fitting one distribution to another ends where loss and gradient must both vanish, the regime of § 2 . We fit Geo ( p ) \operatorname{Geo}(p) Geo ( p ) to a fixed Geo ( p ⋆ ) \operatorname{Geo}(p^\star) Geo ( p ⋆ ) by optimising the logit θ \theta θ , with p = σ ( θ ) p = \sigma(\theta) p = σ ( θ ) , using Adam (learning rate 10 − 2 10^{-2} 1 0 − 2 , 3000 steps) from 12 shared starts, for p ⋆ ∈ { 0.9 , 0.3 , 0.01 , 0.001 } p^\star\in\{0.9, 0.3, 0.01, 0.001\} p ⋆ ∈ { 0.9 , 0.3 , 0.01 , 0.001 } , FP16 and FP32, both parameterisations and both KL directions (32 settings), with θ \theta θ kept in FP32 and the true KL computed with 60-digit arithmetic.
Result. The official loss can miss a target that it is given exactly. In FP16 with p ⋆ = 0.001 p^\star= 0.001 p ⋆ = 0.001 and KL ( Geo ( p ) ∥ Geo ( p ⋆ ) ) \operatorname{KL}(\operatorname{Geo}(p)\mathbin\Vert\operatorname{Geo}(p^\star)) KL ( Geo ( p ) ∥ Geo ( p ⋆ )) it reaches the target from none of the 12 starts (median relative deviation of the fitted p p p 95%, true KL up to 1.7), while the repaired loss converges to the target bit pattern from all 12. In FP32, for p ⋆ ≤ 0.01 p^\star\le0.01 p ⋆ ≤ 0.01 , it stalls at relative deviations of up to 4.3 × 10 − 4 4.3 \times10^{-4} 4.3 × 1 0 − 4 , almost a hundred times further out than the repaired one. The reason is visible at the optimum itself, where the official code returns a non-zero loss or gradient in 28 of 32 settings (e.g. loss 0.098 and gradient − 100 -100 − 100 for FP16, p ⋆ = 0.001 p^\star= 0.001 p ⋆ = 0.001 ). The repair returns exact zeros in all 32. The official runs do not converge to a biased point but wander (Figure 7 ).
Figure 7. Parameter fitting in FP16 with two Geometric targets (p ⋆ = 0.01 p^\star= 0.01 p ⋆ = 0.01 and 0.002 0.002 0.002 ) and Adam with learning rate 10 − 2 10^{-2} 1 0 − 2 . The curves show the exact KL to the target along the fit, from the same 12 starts for both losses (thin lines), and their median (thick). With the official loss (red) the runs stop improving after about 200 steps, at a median true loss of 0.074, whereas with the repaired loss (blue) they reach the resolution of FP16.
Sequential Bayesian Design
Setup. Bayesian experimental design chooses the next observation by its expected information gain (EIG), the expected KL between the posterior after the observation and the current one ([34 , 8 ] ). We take K = 10 K = 10 K = 10 Bernoulli arms with Beta posteriors. In every round the arm with the largest EIG receives the next m m m observations, 100,000 in total, for m ∈ { 1 , 100 , 1000 , 10 4 } m \in\{1, 100, 1000, 10^4\} m ∈ { 1 , 100 , 1000 , 1 0 4 } , from a cold and from a warm start, with 5 seeds. The KL is the official FP32 kl_divergence(Beta, Beta) or our rewrite, also in FP32. The reference policy uses the exact EIG. A choice is counted as wrong if its exact EIG is more than 0.1% below the maximum. The experiment drives itself into the failing range, because the gain of one more observation shrinks with the number already made, and for Beta ( n + 1 , n ) \operatorname{Beta}(n+1,n) Beta ( n + 1 , n ) against Beta ( n , n ) \operatorname{Beta}(n,n) Beta ( n , n ) with n = 10 5 n = 10^5 n = 1 0 5 the true KL is 2.5 × 10 − 6 2.5 \times10^{-6} 2.5 × 1 0 − 6 and the official code returns +0.31.
Result. The official KL misdirects the experiment: in seven of the eight settings 40–91% of the rounds choose a wrong arm, and 35–60% of the EIG values it computes there are zero or negative (Table 12 ). With the rewrite no round is wrong in any of the 40 runs. The cost depends on the feedback. When the posterior is updated after every observation (m = 1 m = 1 m = 1 ), a wrong choice costs one observation, and the final posterior variance is only 1–10% higher than with the exact policy. When a choice commits a batch, the loss can be much larger. For m = 10 4 m = 10^4 m = 1 0 4 from a warm start the total variance is 1.2 to 5.2 times and that of the worst arm up to 11 times the exact policy’s, because an arm with few observations is passed over in most rounds.
Table 12. Sequential Bayesian design, all settings; 100,000 observations, K = 10 K = 10 K = 10 , ranges over 5 seeds. “Lost”: mean over the rounds of 1 − E I G c h o s e n / E I G max 1 - \mathrm{EIG}_{\mathrm{chosen}}/\mathrm{EIG}_{\max} 1 − EIG chosen / EIG m a x , 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 m = 1 m = 1 ).
Identical-Start Distillation
Setup. A student MLP (32 → 256 → V 32 \to256 \to V 32 → 256 → V ) is initialised as an exact copy of its teacher and trained for 300 steps with the forward KL as the only loss. The exact loss and gradient are zero, so any movement is numerical. We run the full grid of vocabulary V ∈ { 1024 , 32768 , 151936 } V \in\{1024, 32768, 151936\} V ∈ { 1024 , 32768 , 151936 } , precision ∈ { F P 32 , F P 16 , B F 16 } \in\{\mathrm{FP32}, \mathrm{FP16}, \mathrm{BF16}\} ∈ { FP32 , FP16 , BF16 } , optimiser and learning rate (Adam at five rates, SGD at three), four losses and 10 seeds, 2,880 runs in total. The official losses are F.kl_div on softmax/log_softmax outputs (with and without log_target) and the official Categorical(logits) KL. Ours is the logits path.
Result. With the official losses the student moves in all 2,160 runs. With ours it does not move in any of the 720 runs. Every recorded weight change, the initial loss and the initial gradient norm are exactly zero (Table 2 ). The optimiser determines how this small numerical error is translated into a parameter update. In FP32 the spurious initial gradient has a norm of about 5 × 10 − 8 5 \times10^{-8} 5 × 1 0 − 8 . SGD scales its step with this norm and barely moves, whereas Adam normalises it to a full-size step (Kingma & Ba, [28 ] ), so that the drift grows with the learning rate, from below 1% to 31–47% top-1 disagreement in FP32. The largest vocabulary is worse than the smallest in every Adam comparison, most strongly in FP16, where the disagreement reaches 97.4% and the final true KL 3.6 nats. A visible symptom is the one users report. A quarter of the official runs show a negative loss at step 0.
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.
Attribution. The three official variants exhibit similar drift. In the paired FP16 and FP32 tests, replacing F.kl_div alone yields student weights bit-identical to the official runs. The spurious parameter gradient arises in log_softmax backward, which the logits path avoids (see also [2 ] ).
KL in Language Models
Setup. We use Qwen2.5-1.5B-Instruct ([62 ] ) (vocabulary 151,936, FP16 forward) on 16,384 WikiText-2 tokens ([37 ] ) and compute KL(original ∥ \mathbin\Vert ∥ quantized) per token. Part A evaluates six quantized versions (round-to-nearest, RTN, at 8, 4 and 3 bits, GPTQ [13 ] at 8 and 4, AWQ [33 ] at 4). Part B ranks the 28 decoder layers by the KL caused by quantizing one layer alone, and uses the ranking to keep the k ∈ { 4 , 8 } k \in\{4,8\} k ∈ { 4 , 8 } most sensitive layers in FP16, a standard mixed-precision heuristic ([12 , 6 ] ). A decision counts as harmful if it raises the true KL of the mixed model. References are computed in FP64.
Part A: KL Accuracy. The official KL is least reliable for the quantized models closest to the original. For the two near-lossless 8-bit models the official F.kl_div misreports the mean KL by −19.0% and −4.4%, with 30.2% and 12.3% of the tokens negative (Table 3 ), and with reduction="mean" it reports exactly 0. Categorical(logits) returns + ∞ +\infty + ∞ for almost every token, because about 38% of the FP16 softmax probabilities underflow to zero. Repairing the operator alone is not enough. The repaired F.kl_div is correctly rounded for its inputs on every token, yet 98.8% and 96.8% of the tokens remain off by ≥ 1 % \geq1\% ≥ 1% , because the error is already in the FP16 softmax outputs. The logits path equals the rounded FP64 reference on every token of every model in FP16 and FP32.
Table 3. KL errors and layer rankings at 8-bit quantization (FP16). Part A reports signed relative error (%) in mean KL and the percentage of tokens with negative or infinite KL (GPTQ / RTN). Part B reports inverted layer pairs out of 378 and Kendall’s τ b \tau_b τ b (1 indicates perfect agreement). “B fix” repairs F.kl_div on the same rounded probability inputs.
Part B: Layer Ranking. A ranking depends on differences between small numbers, and here it breaks. Single-layer divergences at 8 bits are only 3.6 × 10 − 5 3.6 \times10^{-5} 3.6 × 1 0 − 5 to 2.6 × 10 − 4 2.6 \times10^{-4} 2.6 × 1 0 − 4 . The official FP16 F.kl_div reports a negative mean KL for 24 of 28 layers and inverts 19 of the 378 layer pairs (up to 158 for the BF16 variants), while reduction="mean" reports 0 for all layers and Categorical is infinite, so neither can rank at all. The logits path has no inversion in FP16 or FP32. The decision itself changes at the boundary. For k = 8 k = 8 k = 8 , several configurations protect one wrong layer, and the BF16 Categorical KL protects four, which raises the true KL of the resulting mixed model by 9.8% on the disjoint evaluation set.
Part C: Execution Gaps. The KL also measures how far two executions of one model are apart, such as rollout and training in RL fine-tuning (Qi et al., 2025). Each precision produces gaps of the size that its own KL cannot resolve (Table 4 ). For cached decoding against a full forward pass the official F.kl_div is off by more than 600% in FP32 and FP16 and by 19% in BF16, the logits path by less than 0.05% on all 11 pairs. Nor should a reported KL depend on the batch size, yet in FP16 with the default reduction (mean) the KL to an 8-bit copy is reported as anything between 0 and 58% of the truth, depending on the number of rows per call, because the mean underflows, while the logits path varies by less than 0.5% (Appendix § 11 ).
Table 4. KL between cached decoding and full forward evaluation of the same model. The first numeric column is the FP64 reference KL, and all remaining values are signed relative errors (%) at model precision.
Part D: Circuit Scores. Circuit discovery scores each edge of a model by the KL between the clean output and the output with that edge ablated ([9 ] ). Most edges matter little, so most of these scores are tiny, and many of them fall in the failing range. We score edges one at a time with the ablation loop of the auto-circuit library ([39 ] ); IOI ([58 ] ) and Greater-than ([16 ] ) on GPT-2 small, Docstring ([17 ] ) on a 4-layer attention-only model, and IOI on GPT-2 medium.
In FP32, the default precision, the library’s score is wrong for 19%, 46% and 59% of the edges in the three GPT-2 settings, and thousands of scores are negative (Table 5 ), while the logits path is wrong for none. The errors sit in the scores below about 10 − 6 10^{-6} 1 0 − 6 , so they change which small edges pass a threshold while the ranking of the largest edges changes little, and the larger model is affected more because its scores are smaller (median 3 × 10 − 8 3 \times10^{-8} 3 × 1 0 − 8 against 9 × 10 − 7 9 \times10^{-7} 9 × 1 0 − 7 ). In FP16 the ranking suffers as well. The score is wrong for 54–81% of the edges in three of the four settings, and on GPT-2 medium only 38% of the 1,000 highest-scoring edges are correct, against 99.9% for the logits path. Wrong-score rates alone do not determine ranking stability. In Docstring FP32, 2.4% wrong scores leave the top-1,000 set unchanged, whereas in GPT-2 small IOI with BF16, 2.5% wrong scores yield a top-1,000 overlap of only 0.849.
Table 5. Circuit edge-score accuracy against the FP64 KL of the same stored logits. “Wrong” is the percentage of positive-reference edges with negative scores or relative error above 10%, and “negative” gives their count. Spearman measures ranking agreement, and top-1,000 overlap is the fraction of reference top edges recovered. For GPT-2 medium a stratified 13% sample of the edges is scored. Detailed values appear in Table 18 .
Related Work
The work closest to ours is that of Barron et al. [2 ] , who identify two bugs in standard softmax/cross-entropy code, Softmax Collapse (first diagnosed by Prieto et al. [46 ] ) and Softmax Cancellation , and show that a fused implementation stops distillation drift. Our distillation experiment (§ 4.3 ) observes the same drift independently, and our logits path is closely related to their soft-target loss. They treat the categorical soft-target loss and its training dynamics. We measure and repair the KL interfaces themselves, across 18 families and with certified ground truth, separate operator from input-representation error, and study evaluation and decisions as well as training. Like other work that traces a training failure to one floating-point mechanism ([46 , 40 ] (Wortsman et al. 2023)), we isolate a mechanism, but a mostly silent one. Studies and detectors of numerical defects in deep-learning software ([65 , 57 , 30 , 66 , 61 ] (Hும்பatova et al. 2020)) focus on exceptional values. Our tools are those of classical numerical analysis ([19 , 54 , 10 , 52 , 43 , 67 , 24 ] ). Automatic rewriting ([44 ] ) targets local rewrites, whereas those needed here are global and must also deliver gradients. Low-precision training and inference ([38 , 26 , 63 ] (Qi et al. 2025)) make the regime we study routine (see Appendix § 13 ).
Limitations and Conclusion
Limitations. Error rates are conditional on a sampling design that oversamples small divergences and stress regions on purpose. We evaluate PyTorch 2.15.0 on CPU and 2.4.0 on an A100 GPU. The repairs are unoptimised reference implementations. On a GPU the rewrite costs 2.4–5.9× the official call for five closed forms, and the repairs of Gamma, Beta and F.k1_div far more (Appendix § 9 .§ 3 ). The BF16 results are exploratory. The first three experiments are synthetic or simulated, the training effect is shown for an identical start only, and in the layer-ranking experiment the most common official configuration still made the correct selection. Appendix § 12 .§ 2 lists settings with no measured effect.
Conclusion. Negative KL outputs reveal a broader numerical failure: many inaccurate KL values remain non-negative, finite and unnoticed. The cause is structural: the divergence between nearby distributions is typically a second-order quantity assembled from larger terms. For the closed forms, higher precision alone does not remove the resulting errors. Rewriting does. The practical advice is to compute divergences from parameters or logits rather than rounded probabilities, sum non-negative terms, and add precision only where correct rounding is required.
Impact Statement
This paper aims to make a basic numerical primitive of machine learning more reliable. We do not foresee specific negative societal consequences of this work.
AI Disclosure Statement
ChatGPT and Claude were used to assist with coding, debugging, technical discussions, and grammar checking. All mathematical derivations, implementations, and experimental results were verified by the authors, who take full responsibility for the work.
Measurement and Validation Protocol
Sampling (interface A). For each configuration and precision, samples are organised in cells indexed by a parameter region and a KL group. Regions: R0 (ordinary parameters), and stress regions R1, R2 (and R3 for some families) with very large or very small parameters or probabilities close to 0 or 1; for example, for Dirichlet the concentration components are log-uniform in [ 10 − 2 , 10 2 ] [10^{-2}, 10^{2}] [ 1 0 − 2 , 1 0 2 ] (R0), [ 10 2 , 10 4 ] [10^{2}, 10^{4}] [ 1 0 2 , 1 0 4 ] (R1) and [ 10 − 4 , 10 − 2 ] [10^{-4}, 10^{-2}] [ 1 0 − 4 , 1 0 − 2 ] (R2). KL groups: a control bin [ 10 − 1 , 1 ) [10^{-1}, 1) [ 1 0 − 1 , 1 ) , fourteen bins [ 10 − k − 1 , 10 − k ) [10^{-k-1}, 10^{-k}) [ 1 0 − k − 1 , 1 0 − k ) , k = 1 , … , 14 k = 1, \ldots, 14 k = 1 , … , 14 , a ULP group (Q Q Q obtained by moving parameters of P P P by 1–8 ULP) and an identity group (Q = P Q = P Q = P ). The quota is 10,000 samples per R0 cell and per ULP cell and 1,000 per stress cell. A cell is recorded as empty after 2,000 consecutive failed attempts and as below quota when the quota is not reached within 50 times the quota in attempts; the dominant reason is that Q Q Q rounds to P P P in the target format. For the 16 scalar-family configurations (5,057,067 samples), 1,194 of 1,568 cells are full, 49 below quota and 325 empty (285 of them in FP16); the other 7 configurations (Categorical, ContinuousBernoulli, Dirichlet and the two multivariate normal families, with their sub-configurations; 2,485,402 samples) follow identical rules. Of the 7,542,469 samples, 7,234,454 are scored: the 308,015 FP16 samples of the two multivariate normal families are not scored for any method, because the official implementation does not run on them (Table 1 ). A call of the official implementation that raises an error on a valid input counts as a significant error.
Truth and scoring. For interface A, the reference is the exact KL of the distributions defined by the stored raw constructor arguments, with gradients taken with respect to those arguments. Arb certifies the rounding of each reference value to the target format. Six uncertifiable candidates were rejected. Platform: PyTorch 2.15.0+cpu, Python 3.11.8, python-flint 0.9.0, mpmath 1.4.1, batch size 4,096, single thread. Each output is classified as correctly rounded, off by a stated number of ULP, or qualitatively wrong (negative KL, NaN, Inf, spurious zero, spurious non-zero at a structural zero, sign flip, vanished gradient). A spurious zero is a zero output where the correctly rounded reference is non-zero; a positive KL whose correctly rounded value in the target format is zero is scored as correct when the output is zero. Significant error means ≥ 8 \ge8 ≥ 8 ULP or any qualitative error; gradient vectors are additionally scored by relative L 2 L_2 L 2 error and cosine. Components that are not differentiable at the sample (e.g. Uniform at shared end points, the strict upper triangle of scale_tril) are not scored.
Methods. A: official. B32/B64: official code on exactly promoted parameters, rounded once (OFFICIAL+, abbreviated OFF.+ in tables, is B32 for FP16 inputs and B64 for FP32 inputs). C: rewritten algorithm in the target precision (REWRITE). D32/D64: rewritten algorithm in FP32/FP64, rounded once; D64 is the strict repair (OURS).
Validation. All methods are evaluated on the same frozen inputs for correct rounding, significant errors, structural zeros, and regressions against the official baselines. The diagnostic error estimate E E E uses first-order rounding-error propagation with an empirical safety factor ([19 ] ); series and quadrature truncation bounds are rigorous. A series may be used on a segment only if it comes from an exact identity, converges on the whole segment, and has a rigorous truncation bound of at most u / 16 u/16 u /16 relative to the final result (or, for gradients that can cancel, relative to the approximated term).
Interface B. 20 configurations: log_target ∈ { False , True } × { FP16 , FP32 } × K ∈ { 2 , 4 , 16 , 256 } \texttt{log\_target} \in\{\text{False}, \text{True}\} \times\{\text{FP16}, \text{FP32}\} \times K \in\{2, 4, 16, 256\} log_target ∈ { False , True } × { FP16 , FP32 } × K ∈ { 2 , 4 , 16 , 256 } plus four K = 1024 K = 1024 K = 1024 stress configurations; batch sizes 1 and 8; reductions none, sum, mean, batchmean; gradients with respect to both arguments. Inputs are produced from logits in regions R0 (components uniform in [ − 5 , 5 ] [-5,5] [ − 5 , 5 ] ), R1 (range in [ 10 , 30 ] [10,30] [ 10 , 30 ] ) and R2 (range in [ 30 , 10 3 ] [30,10^3] [ 30 , 1 0 3 ] ) and from boundary strata (zeros, − ∞ -\infty − ∞ , extreme magnitudes). 942,200 batches; 5.69 × 10 8 10^8 1 0 8 certified truths, of which 5.67 × 10 8 5.67 \times10^8 5.67 × 1 0 8 are scored (inputs outside the domain of the operator and target gradients that do not exist are not); 118 of the 1,920 cells were completed by additional sampling, kept as separate strata. Three truths are stored per batch: T o p T_{\mathrm{op}} T op , T e 2 e T_{\mathrm{e2e}} T e2e and their difference.
Error by KL interval
Table 6 gives the numbers behind Figure 2 : the 16 scalar-family configurations pooled, region R0, per decade of the true KL. Figure 3 and Figure 4 resolve the first metric by configuration for all 33 configurations and sub-configurations (the 23 configurations of Table 1 with their dimension variants listed separately), for the official implementation on CPU and on GPU and for OURS. In FP32 every configuration is above 90% by KL ≈ 10 − 8 \approx10^{-8} ≈ 1 0 − 8 , with Normal as the only partial exception (50–99%); the families that fail earliest are Dirichlet, Binomial and Beta. The rows “in FP64” and “in FP32” of Table 6 show that evaluating the official formula in the next precision moves the same pattern nine decades down (FP32 inputs) or leaves a visible residue already at 10 − 4 10^{-4} 1 0 − 4 (FP16 inputs); it does not remove it.
Table 6. Interface A, region R0, 16 scalar-family configurations pooled: share of samples (%) per KL interval. Column heads are the lower edge of the interval (e.g. 10 − 9 10^{-9} 1 0 − 9 means [10 − 9 10^{-9} 1 0 − 9 , 10 − 8 10^{-8} 1 0 − 8 )). “–”: fewer than 300 samples, or (FP16 relative error) true value subnormal. Gradient metrics refer to the full gradient vector.
Figure 3. Interface A, FP32 inputs, region R0. Share of samples whose KL has relative error ≥ 1 % \ge1\% ≥ 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).
Figure 4. Interface A, FP16 inputs, region R0, as Figure 3 . The relative error is defined only while the true KL is a normal FP16 number (above about 6 × 10 − 5 6 \times10^{-5} 6 × 1 0 − 5 ). MultivariateNormal and LowRankMultivariateNormal have no FP16 results because the official implementation does not run.
Interface A: Analysis and Repair of Each Closed Form
For every distribution we give the official formula (PyTorch 2.15.0), the origin of its error, the repair, the reason the repair works, and the result on the frozen data. Rates are significant-error rates in the order FP16 / FP32 unless stated otherwise; “OFF.+” is the official code in the next precision, “REWRITE” the repaired formula in the target precision, and “OURS” the repaired formula in FP64 rounded once. In all 18 distributions OURS has zero significant errors in the KL and in every gradient component and zero new errors; we do not repeat this in each subsection.
Common building blocks
The function φ \varphi φ . φ ( x ) = x − log 1 p ( x ) ≥ 0 \varphi(x) = x - \log1p(x) \ge0 φ ( x ) = x − log 1 p ( x ) ≥ 0 . On − 3 4 ≤ x ≤ 3 -\frac{3}{4} \le x \le3 − 4 3 ≤ x ≤ 3 we evaluate Equation (3) ; with z = s 2 2 ≤ 0.36 z = \frac{s^2}{2} \le0.36 z = 2 s 2 ≤ 0.36 and Q K ( z ) = ∑ k = 1 K z k − 1 / ( 2 k + 1 ) Q_K(z) = \sum_{k=1}^{K} z^{k-1}/(2k + 1) Q K ( z ) = ∑ k = 1 K z k − 1 / ( 2 k + 1 ) (written Q Q Q below) evaluated by Horner’s rule, the remainder R K R_K R K of the series after K K K terms satisfies ∣ R K ∣ / φ ≤ 4 ( 0.6 ) 2 K + 1 / ( 2 K + 3 ) |R_K|/\varphi\le4(0.6)^{2K+1}/(2K + 3) ∣ R K ∣/ φ ≤ 4 ( 0.6 ) 2 K + 1 / ( 2 K + 3 ) , i.e. 1.2 × 10 − 5 1.2 \times10^{-5} 1.2 × 1 0 − 5 , 1.9 × 10 − 9 1.9 \times10^{-9} 1.9 × 1 0 − 9 , 3.4 × 10 − 18 3.4 \times10^{-18} 3.4 × 1 0 − 18 for K = 9 , 17 , 36 K = 9, 17, 36 K = 9 , 17 , 36 (FP16, FP32, FP64), each below u / 16 u/16 u /16 . The two terms have ratio at most about 0.12 for x > 0 x > 0 x > 0 and add for x < 0 x < 0 x < 0 , so there is no cancellation. Outside the segment, φ = x − log 1 p ( x ) \varphi= x - \log1p(x) φ = x − log 1 p ( x ) (x > 3 x > 3 x > 3 ) and φ = x − log ( b / a ) \varphi= x - \log(b/a) φ = x − log ( b / a ) (x < − 3 4 x < -\frac{3}{4} x < − 4 3 , with 1 + x = b / a 1 + x = b/a 1 + x = b / a ) are well conditioned (the subtracted term is at most 0.86 of the result, resp. condition number ≤ 3.4 \le3.4 ≤ 3.4 ). When x = d / a x = d/a x = d / a is formed from d = b − a d = b - a d = b − a , d d d is exact for b ∈ [ a / 2 , 2 a ] b \in[a/2, 2a] b ∈ [ a /2 , 2 a ] ([54 ] ), and the series is evaluated with s = d / ( a + b ) s = d/(a + b) s = d / ( a + b ) computed directly from the inputs. We also use the exponential counterpart ξ ( t ) = e t − 1 − t ≥ 0 \xi(t) = e^t - 1 - t \ge0 ξ ( t ) = e t − 1 − t ≥ 0 .
Error-free transformations. TwoSum returns fl( a + b ) (a+b) ( a + b ) together with the exact error a + b − fl ( a + b ) a+b-\operatorname{fl}(a+b) a + b − fl ( a + b ) ; Dekker’s TwoProduct returns fl( a b ) (ab) ( ab ) together with a b − fl ( a b ) ab-\operatorname{fl}(ab) ab − fl ( ab ) (exact unless the product of the last significant bits underflows, which is checked per sample); Shewchuk’s Grow-Expansion sums such pairs exactly. Double-length arithmetic represents a number as an unevaluated pair (hi, lo) of working-precision numbers and implements + + + , × \times × , ÷ \div ÷ , \sqrt{} on pairs with these primitives.
Mantissa/exponent products. Products and quotients whose intermediate results could overflow or become subnormal although the final result is representable are evaluated on frexp \operatorname{frexp} frexp mantissas, with the exponents added separately and applied by one exact scaling by 2 k 2^k 2 k followed by a single rounding.
Special functions. For Gumbel, Gamma, Beta and Dirichlet we do not call torch.lgamma, digamma or polygamma. We use the Binet function w ( a ) = log Γ ( a ) − ( a − 1 2 ) log a + a − 1 2 log 2 π w(a) = \log\Gamma(a) - (a - \frac{1}{2})\log a + a - \frac{1}{2}\log2\pi w ( a ) = log Γ ( a ) − ( a − 2 1 ) log a + a − 2 1 log 2 π , which is convex, its derivatives through Stirling-type series with rigorous tail bounds, exact-coefficient zeta series near small arguments, exact shifts by integers, and Gauss–Legendre quadrature (5/7/13 nodes for FP16/FP32/FP64) of same-sign integrands for differences at nearby arguments. The quadrature error bound (maximum modulus on a Bernstein ellipse) is rigorous; the node counts were verified on a parameter grid and independently measured as 8.3 × 10 − 10 8.3 \times10^{-10} 8.3 × 1 0 − 10 , 3.9 × 10 − 14 3.9 \times10^{-14} 3.9 × 1 0 − 14 , 6.3 × 10 − 27 6.3 \times10^{-27} 6.3 × 1 0 − 27 maximum relative error.
Notation. ∂ θ \partial_\theta ∂ θ denotes ∂ K L / ∂ θ \partial\mathrm{KL}/\partial\theta ∂ KL / ∂ θ ; ψ = ( log Γ ) ′ \psi= (\log\Gamma)' ψ = ( log Γ ) ′ is the digamma function; B f ( x , y ) = f ( x ) − f ( y ) − f ′ ( y ) ( x − y ) ≥ 0 B_f(x,y) = f(x) - f(y) - f'(y)(x-y) \ge0 B f ( x , y ) = f ( x ) − f ( y ) − f ′ ( y ) ( x − y ) ≥ 0 is the Bregman divergence of a convex function f f f ; σ ( ⋅ ) \sigma(\cdot) σ ( ⋅ ) is the logistic sigmoid and logit its inverse. c log u c_{\log}u c l o g u denotes a bound on the relative error of the library’s log \log log and log 1 p \log1p log 1 p ; c log c_{\log} c l o g is a small constant measured on the platform. e max e_{\max} e m a x and x max x_{\max} x m a x are the largest exponent and the largest finite number of the format, and eps \operatorname{eps} eps is its machine epsilon (2 − 10 2^{-10} 2 − 10 , 2 − 23 2^{-23} 2 − 23 , 2 − 52 2^{-52} 2 − 52 ), the constant with which PyTorch’s constructors clamp probabilities to [eps, 1 − eps].
Range and boundary semantics. We use power-of-two scaling and mantissa/exponent arithmetic for products and quotients near the format limits. The repairs evaluate distributions from raw parameters, bypassing constructor clamps and softmax.
Midpoint-aware final rounding. Computing in FP64 and rounding once to FP16 or FP32 fails when the leading term of the result is exactly a rounding midpoint of the target format and the correction is below FP64 resolution relative to it. This occurs for logit-space gradients near zero (leading term ( w − z ) / 4 (w-z)/4 ( w − z ) /4 for Bernoulli and ( w − z ) / 2 (w-z)/2 ( w − z ) /2 for Geometric, where z z z and w w w are the logits of P P P and Q Q Q ). There we write the result as an exactly representable leading term plus a small series, recover the rounded-away remainder with Fast2Sum, and move one ULP towards the truth when the FP64 result sits on a midpoint.
Cauchy
Official. With locations μ p \mu_p μ p , μ q \mu_q μ q , scales γ p \gamma_p γ p , γ q \gamma_q γ q and N = ( γ p + γ q ) 2 + ( μ p − μ q ) 2 N = (\gamma_p + \gamma_q)^2 + (\mu_p - \mu_q)^2 N = ( γ p + γ q ) 2 + ( μ p − μ q ) 2 : KL = log N − log ( 4 γ p γ q ) = \log N - \log(4\gamma_p\gamma_q) = log N − log ( 4 γ p γ q ) . We write Σ γ = γ p + γ q \Sigma\gamma= \gamma_p + \gamma_q Σ γ = γ p + γ q , Δ γ = γ p − γ q \Delta\gamma= \gamma_p - \gamma_q Δ γ = γ p − γ q and Δ μ = μ p − μ q \Delta\mu= \mu_p - \mu_q Δ μ = μ p − μ q .
Error. For P ≈ Q P \approx Q P ≈ Q both logarithms are ≈ log ( 4 γ 2 ) \approx\log(4\gamma^2) ≈ log ( 4 γ 2 ) with γ ≈ γ p ≈ γ q \gamma\approx\gamma_p \approx\gamma_q γ ≈ γ p ≈ γ q ; each carries an absolute error of order ( c + ∣ log N ∣ ) u (c + \lvert\log N\rvert)u ( c + ∣ log N ∣) u that survives the subtraction, so the relative error is ≈ ( c 1 + 2 ∣ log 4 γ 2 ∣ ) u / K L \approx(c_1 + 2\lvert\log4\gamma^2\rvert)u/\mathrm{KL} ≈ ( c 1 + 2 ∣ log 4 γ 2 ∣) u / KL , with small constants c c c , c 1 c_1 c 1 , and the sign is random once KL is below that error. Autograd gives ∂ K L / ∂ γ p = 2 Σ γ / N − 1 / γ p \partial\mathrm{KL}/\partial\gamma_p = 2\Sigma\gamma/N - 1/\gamma_p ∂ KL / ∂ γ p = 2Σ γ / N − 1/ γ p , a difference of two O ( 1 / γ ) O(1/\gamma) O ( 1/ γ ) terms. In FP16, for small γ \gamma γ both arguments of the logarithms become subnormal and round to the same number, the derivatives 1 / N 1/N 1/ N and 1 / ( 4 γ p γ q ) 1/(4\gamma_p\gamma_q) 1/ ( 4 γ p γ q ) overflow, and the gradient is ∞ − ∞ = N a N \infty- \infty= \mathrm{NaN} ∞ − ∞ = NaN , also at P = Q P = Q P = Q . The μ \mu μ gradient has no cancellation.
Repair. From ( γ p + γ q ) 2 − 4 γ p γ q = ( γ p − γ q ) 2 (\gamma_p+\gamma_q)^2-4\gamma_p\gamma_q=(\gamma_p-\gamma_q)^2 ( γ p + γ q ) 2 − 4 γ p γ q = ( γ p − γ q ) 2 ,
KL = log 1 p ( r ) , r = ( γ p − γ q ) 2 + ( μ p − μ q ) 2 4 γ p γ q ≥ 0. \operatorname{KL}=\log1p(r),\qquad r=\frac{(\gamma_p-\gamma_q)^2+(\mu_p-\mu_q)^2}{4\gamma_p\gamma_q}\ge0. KL = log 1 p ( r ) , r = 4 γ p γ q ( γ p − γ q ) 2 + ( μ p − μ q ) 2 ≥ 0.
r r r is homogeneous of degree zero, so all four quantities are scaled by a power of two 2 k 2^k 2 k with max ( γ p , γ q , ∣ Δ μ ∣ ) 2 k ∈ [ 8 , 16 ) \max(\gamma_p,\gamma_q,\lvert\Delta\mu\rvert)2^k\in[8,16) max ( γ p , γ q , ∣ Δ μ ∣) 2 k ∈ [ 8 , 16 ) (applied as two representable factors); if r r r overflows, a logarithmic fallback is used, which cannot cancel because then KL > log x max \operatorname{KL}>\log x_{\max} KL > log x m a x . Gradients are analytic: ∂ μ p = 2 Δ μ / N = − ∂ μ q \partial_{\mu_p}=2\Delta\mu/N=-\partial_{\mu_q} ∂ μ p = 2Δ μ / N = − ∂ μ q , ∂ γ p = ( Δ γ Σ γ − Δ μ 2 ) / ( γ p N ) \partial_{\gamma_p}=(\Delta\gamma\,\Sigma\gamma-\Delta\mu^2)/(\gamma_pN) ∂ γ p = ( Δ γ Σ γ − Δ μ 2 ) / ( γ p N ) , ∂ γ q = ( − Δ γ Σ γ − Δ μ 2 ) / ( γ q N ) \partial_{\gamma_q}=(-\Delta\gamma\,\Sigma\gamma-\Delta\mu^2)/(\gamma_qN) ∂ γ q = ( − Δ γ Σ γ − Δ μ 2 ) / ( γ q N ) , evaluated on the scaled quantities.
Why it works. The squared differences enter r r r as small numbers instead of being recovered from large ones, and log 1 p \log1p log 1 p is well conditioned for r ≥ 0 r\ge0 r ≥ 0 : the first-order relative error is about ( 6 + c log ) u (6+c_{\log})u ( 6 + c l o g ) u independent of KL. The condition number of the γ \gamma γ gradient drops from κ A = ( 2 γ p Σ γ + N ) / ∣ Δ γ Σ γ − Δ μ 2 ∣ \kappa_A=(2\gamma_p\Sigma\gamma+N)/|\Delta\gamma\Sigma\gamma-\Delta\mu^2| κ A = ( 2 γ p Σ γ + N ) /∣Δ γ Σ γ − Δ μ 2 ∣ to κ C = ( ∣ Δ γ ∣ Σ γ + Δ μ 2 ) / ∣ Δ γ Σ γ − Δ μ 2 ∣ ≤ κ A \kappa_C=(|\Delta\gamma|\Sigma\gamma+\Delta\mu^2)/|\Delta\gamma\Sigma\gamma-\Delta\mu^2|\le\kappa_A κ C = ( ∣Δ γ ∣Σ γ + Δ μ 2 ) /∣Δ γ Σ γ − Δ μ 2 ∣ ≤ κ A ; the remaining cancellation at γ p 2 ≈ γ q 2 + Δ μ 2 \gamma_p^2\approx\gamma_q^2+\Delta\mu^2 γ p 2 ≈ γ q 2 + Δ μ 2 is intrinsic and is the reason REWRITE keeps few errors and Ours does not. After scaling all denominators are positive and bounded away from zero, so no NaN can occur, and P = Q P=Q P = Q gives r = 0 r=0 r = 0 , KL = + 0 =+0 = + 0 and zero gradients.
Frozen data (345,028 samples). KL: OFFICIAL 64.05 / 88.88%; OFF. + 10.60 / 34.84%; REWRITE 0.003 / 0%. P P P -scale gradient: OFFICIAL 53.27 / 82.93%; OFF. + 0.34 / 6.37%; REWRITE 0.18 / 0.09%. REWRITE adds new errors on 41 samples (0.012%), all within the error estimate.
Uniform
Official. With supports [ p l , p h ] [p_l,p_h] [ p l , p h ] and [ q l , q h ] [q_l,q_h] [ q l , q h ] : KL = log q h − q l p h − p l =\log\frac{q_h-q_l}{p_h-p_l} = log p h − p l q h − q l for nested supports, + ∞ +\infty + ∞ otherwise. We write w p = p h − p l w_p=p_h-p_l w p = p h − p l and w q = q h − q l w_q=q_h-q_l w q = q h − q l for the widths.
Error. The two widths are rounded separately and their ratio is ≈ 1 + KL \approx1+\operatorname{KL} ≈ 1 + KL , so the relative error is about 2 u / KL 2u/\operatorname{KL} 2 u / KL (12% at KL = 10 − 6 =10^{-6} = 1 0 − 6 in FP32), and the ratio rounds to 1 for KL < u / 2 <u/2 < u /2 (spurious zero). The gradients ± 1 / w p \pm1/w_p ± 1/ w p and ± 1 / w q \pm1/w_q ± 1/ w q involve no cancellation and are correct in the official code.
Repair. On nested supports w q − w p = ( q h − p h ) + ( p l − q l ) w_q-w_p=(q_h-p_h)+(p_l-q_l) w q − w p = ( q h − p h ) + ( p l − q l ) with both terms non-negative, so
K L = log 1 p ( r ) , r = d 1 + d 2 w p , d 1 = q h − p h ≥ 0 , d 2 = p l − q l ≥ 0. \mathrm{KL}=\log1p(r),\qquad r=\frac{d_1+d_2}{w_p},\qquad d_1=q_h-p_h\geq0,\quad d_2=p_l-q_l\geq0. KL = log 1 p ( r ) , r = w p d 1 + d 2 , d 1 = q h − p h ≥ 0 , d 2 = p l − q l ≥ 0.
All inputs are halved if one of them is ≥ 2 e max − 1 \geq2^{e_{\max}-1} ≥ 2 e m a x − 1 ; if the ratio overflows, K L = log w q − log w p \mathrm{KL}=\log w_q-\log w_p KL = log w q − log w p . Gradients are ± 1 / w p \pm1/w_p ± 1/ w p , ∓ 1 / w q \mp1/w_q ∓ 1/ w q .
Why it works. d 1 , d 2 d_1,d_2 d 1 , d 2 are direct differences of the inputs (exact for nearby end points), the ratio has relative error ≤ 4 u \leq4u ≤ 4 u and log 1 p \log1p log 1 p has condition number ≤ 1 \leq1 ≤ 1 on r ≥ 0 r\geq0 r ≥ 0 , hence the relative error of the KL is at most ( 4 + c log ) u (4+c_{\log})u ( 4 + c l o g ) u . P = Q P=Q P = Q gives + 0 +0 + 0 .
Frozen data (181,798). KL: OFFICIAL 51.62 / 75.08%; OFF.+ 0 / 0.012%; REWRITE 0 / 0% (maximum error 2 ULP). Gradients have no significant error in any method.
Exponential
Official. With r = λ q / λ p r=\lambda_q/\lambda_p r = λ q / λ p : K L = − log r + r − 1 \mathrm{KL}=-\log r+r-1 KL = − log r + r − 1 .
Error. r − log r ≈ 1 + K L r-\log r\approx1+\mathrm{KL} r − log r ≈ 1 + KL is rounded near 1 with absolute error ≈ u \approx u ≈ u while K L ≈ x 2 / 2 \mathrm{KL}\approx x^2/2 KL ≈ x 2 /2 , x = r − 1 x=r-1 x = r − 1 : relative error ≈ 2 u / x 2 \approx2u/x^2 ≈ 2 u / x 2 , spurious zero for K L < u / 2 \mathrm{KL}<u/2 KL < u /2 . Autograd’s 1 − 1 / r 1-1/r 1 − 1/ r cancels with relative error ≈ u / ∣ x ∣ \approx u/\lvert x\rvert ≈ u / ∣ x ∣ . FP64 evaluation leaves 33.5% significant errors for FP32 inputs because x x x can be as small as 2 − 24 2^{-24} 2 − 24 .
Repair. d = λ q − λ p d=\lambda_q-\lambda_p d = λ q − λ p (direct), x = d / λ p x=d/\lambda_p x = d / λ p , K L = φ ( x ) \mathrm{KL}=\varphi(x) KL = φ ( x ) as in Appendix § 8 .§ 1 ; analytic gradients ∂ λ p = − x / λ p \partial_{\lambda_p}=-x/\lambda_p ∂ λ p = − x / λ p , ∂ λ q = x / λ q \partial_{\lambda_q}=x/\lambda_q ∂ λ q = x / λ q .
Why it works. See Appendix § 8 .§ 1 ; KL and gradients are computed from the same rounded value x ~ \tilde{x} x ~ of x x x , whose rounding changes KL by a relative O ( u ) O(u) O ( u ) . P = Q P=Q P = Q gives x = 0 x=0 x = 0 and three exact zeros; a final max ( ⋅ , 0 ) \max(\cdot,0) max ( ⋅ , 0 ) guarantees K L ≥ 0 \mathrm{KL}\geq0 KL ≥ 0 .
Frozen data (308,000). KL: OFFICIAL 72.57 / 85.64%; OFF.+ 0 / 33.49%; REWRITE 0 / 0% (max. 6 ULP). Rate gradient: OFFICIAL 48.78 / 75.11%; all other methods 0. A near-exhaustive FP16 sweep of 3.6 × 10 7 3.6\times10^7 3.6 × 1 0 7 pairs gave at most 7 ULP for REWRITE and 1 ULP for the FP32 evaluation.
Poisson
Official. With rates a = λ p a=\lambda_p a = λ p , b = λ q b=\lambda_q b = λ q : K L = a ( log a − log b ) − ( a − b ) \mathrm{KL}=a(\log a-\log b)-(a-b) KL = a ( log a − log b ) − ( a − b ) . Let x = ( b − a ) / a x=(b-a)/a x = ( b − a ) / a .
Error. Two cancellations: log a − log b ≈ − x \log a-\log b\approx-x log a − log b ≈ − x with each logarithm carrying an error ≈ u ∣ log a ∣ \approx u\lvert\log a\rvert ≈ u ∣ log a ∣ , then a ( ⋅ ) − ( a − b ) a(\cdot)-(a-b) a ( ⋅ ) − ( a − b ) leaves a x 2 / 2 ax^2/2 a x 2 /2 . The relative error is ≈ 4 c log u ∣ log a ∣ / x 2 \approx4c_{\log}u\lvert\log a\rvert/x^2 ≈ 4 c l o g u ∣ log a ∣ / x 2 ; because a a a ranges up to 10 4 10^4 1 0 4 , even the control bin K L ∈ [ 0.1 , 1 ) \mathrm{KL}\in[0.1,1) KL ∈ [ 0.1 , 1 ) has about 39% outputs off by ≥ 8 \geq8 ≥ 8 ULP, and 25–28% of all outputs are negative. Gradients vanish when both logarithms round to the same value.
Repair. K L = a φ ( x ) \mathrm{KL}=a\varphi(x) KL = a φ ( x ) , written so that the small φ \varphi φ is never formed and then multiplied by a large a a a : with d = b − a d=b-a d = b − a , s = d / ( a + b ) s=d/(a+b) s = d / ( a + b ) , z = s 2 z=s^2 z = s 2 ,
K L = d s − 2 ( a s ) z Q ( z ) ( − 3 4 ≤ x ≤ 3 ) , \mathrm{KL}=ds-2(as)zQ(z)\qquad\left(-\frac{3}{4}\leq x\leq3\right), KL = d s − 2 ( a s ) z Q ( z ) ( − 4 3 ≤ x ≤ 3 ) ,
and a max ( x − L , 0 ) \max(x-L,0) max ( x − L , 0 ) or max ( d − a L , 0 ) \max(d-aL,0) max ( d − a L , 0 ) with L = log ( b / a ) L=\log(b/a) L = log ( b / a ) outside. Gradients: ∂ λ p = − L \partial_{\lambda_p}=-L ∂ λ p = − L , ∂ λ q = d / b \partial_{\lambda_q}=d/b ∂ λ q = d / b .
Why it works. The factor a a a cancels exactly between the truncation error and the KL, so the bound of Appendix § 8 .§ 1 is inherited; ∣ d s ∣ \lvert ds\rvert ∣ d s ∣ and ∣ a s ∣ \lvert as\rvert ∣ a s ∣ never exceed ∣ d ∣ \lvert d\rvert ∣ d ∣ , so nothing overflows before the result does.
Frozen data (323,498). KL: OFFICIAL 75.64 / 85.82%; OFF.+ 9.75 / 34.44%; REWRITE 0.002 / 0%. Gradients: OFFICIAL 54.8–78.3%; others 0. Negative KL disappears.
Normal
Official. With means μ p , μ q \mu_p,\mu_q μ p , μ q , standard deviations σ p , σ q \sigma_p,\sigma_q σ p , σ q , δ = μ p − μ q \delta=\mu_p-\mu_q δ = μ p − μ q , r = σ p / σ q r=\sigma_p/\sigma_q r = σ p / σ q and w = δ / σ q w=\delta/\sigma_q w = δ / σ q : K L = 1 2 ( r 2 + w 2 − 1 − log r 2 ) \mathrm{KL}=\frac{1}{2}(r^2+w^2-1-\log r^2) KL = 2 1 ( r 2 + w 2 − 1 − log r 2 ) .
Error. (i) r 2 − 1 − log r 2 r^2-1-\log r^2 r 2 − 1 − log r 2 cancels like the Exponential kernel. (ii) w 2 w^2 w 2 is added to r 2 ≈ 1 r^2\approx1 r 2 ≈ 1 first and is lost when w 2 < u w^2<u w 2 < u (10.6% spurious zeros in FP16); in FP16 w 2 w^2 w 2 can overflow before the KL does. (iii) Autograd’s scale gradients pass through 1 2 − 1 2 r 2 \frac{1}{2}-\frac{1}{2r^2} 2 1 − 2 r 2 1 . (iv) The exact ∂ σ q = ( σ q 2 − σ p 2 − δ 2 ) / σ q 3 \partial_{\sigma_q}=(\sigma_q^2-\sigma_p^2-\delta^2)/\sigma_q^3 ∂ σ q = ( σ q 2 − σ p 2 − δ 2 ) / σ q 3 has a genuine zero on σ q 2 = σ p 2 + δ 2 \sigma_q^2=\sigma_p^2+\delta^2 σ q 2 = σ p 2 + δ 2 , where the official code returns non-zero. FP64 evaluation leaves 13.84% for FP32 inputs. Repair. Equation (2) : K L = φ ( e ) + 1 2 e 2 + 1 2 w 2 \mathrm{KL} = \varphi(e) + \frac{1}{2}e^2 + \frac{1}{2}w^2 KL = φ ( e ) + 2 1 e 2 + 2 1 w 2 , with φ ( e ) \varphi(e) φ ( e ) from Appendix § 8 .§ 1 (s = ( σ p − σ q ) / ( σ p + σ q ) s = (\sigma_p - \sigma_q)/(\sigma_p + \sigma_q) s = ( σ p − σ q ) / ( σ p + σ q ) ) and w 2 / 2 = ( w − 1 2 ) w w^2/2 = (w - \frac{1}{2})w w 2 /2 = ( w − 2 1 ) w . Gradients: ∂ μ p = w / σ q = − ∂ μ q \partial_{\mu_p} = w/\sigma_q = -\partial_{\mu_q} ∂ μ p = w / σ q = − ∂ μ q , ∂ σ p = e ( e + 2 ) / σ p \partial_{\sigma_p} = e(e + 2)/\sigma_p ∂ σ p = e ( e + 2 ) / σ p , ∂ σ q = N / σ q 3 \partial_{\sigma_q} = N/\sigma_q^3 ∂ σ q = N / σ q 3 with N = σ q 2 − σ p 2 − δ 2 N = \sigma_q^2 - \sigma_p^2 - \delta^2 N = σ q 2 − σ p 2 − δ 2 . Where cancellation in N N N is possible (σ q ≥ max ( σ p , ∣ δ ∣ ) / 2 \sigma_q \ge\max(\sigma_p, |\delta|)/2 σ q ≥ max ( σ p , ∣ δ ∣ ) /2 ), N N N is computed exactly in the working precision: δ \delta δ by TwoSum, power-of-two scaling, five Dekker products, and a ten-term Grow-Expansion.
Why it works. Three non-negative terms; the truncation bound is inherited because K L ≥ φ ( e ) \mathrm{KL} \ge\varphi(e) KL ≥ φ ( e ) . With N N N exact, ∂ σ q \partial_{\sigma_q} ∂ σ q suffers only 4–5 roundings. If σ q 2 = σ p 2 + δ 2 \sigma_q^2 = \sigma_p^2 + \delta^2 σ q 2 = σ p 2 + δ 2 holds exactly, a 2-adic argument shows that all scaled operands lie on a common binary grid, every product is exact, and the computed N ^ \hat{N} N ^ is +0; all 109,558 FP16 and 908,771,452 FP32 Pythagorean triples we enumerated return +0. Computing ( σ q − σ p ) ( σ q + σ p ) − δ 2 (\sigma_q - \sigma_p)(\sigma_q + \sigma_p) - \delta^2 ( σ q − σ p ) ( σ q + σ p ) − δ 2 in working precision is not enough: it rounds, e.g. in FP16 for ( μ p , σ p , μ q , σ q ) = ( 329 , 1080 , 0 , 1129 ) (\mu_p, \sigma_p, \mu_q, \sigma_q) = (329, 1080, 0, 1129) ( μ p , σ p , μ q , σ q ) = ( 329 , 1080 , 0 , 1129 ) .
Frozen data (339,499). KL: OFFICIAL 42.40 / 82.18%; OFF.+ 0 / 13.84%; REWRITE 0 / 0%. Scale gradients: OFFICIAL 32.9–61.0%; REWRITE has one new case in FP16.
Laplace
Official. With locations μ p , μ q \mu_p, \mu_q μ p , μ q , scales a = σ p a = \sigma_p a = σ p , b = σ q b = \sigma_q b = σ q , r = a / b r = a/b r = a / b and d = ∣ μ p − μ q ∣ d = |\mu_p - \mu_q| d = ∣ μ p − μ q ∣ : K L = − log r + d / b + r e − d / a − 1 \mathrm{KL} = -\log r + d/b + r e^{-d/a} - 1 KL = − log r + d / b + r e − d / a − 1 .
Error. Four O ( 1 ) O(1) O ( 1 ) terms sum to a small KL (43% spurious zeros and 1.4% negative values in FP16). Autograd’s location gradient ( 1 − e − t ) / b (1 - e^{-t})/b ( 1 − e − t ) / b , t = d / a t = d/a t = d / a , vanishes when e − t e^{-t} e − t rounds to 1 (24.5% in FP16); scale gradients are differences of O ( 1 / b ) O(1/b) O ( 1/ b ) terms and flip sign; in FP16, d / ( a ⋅ a ) d/(a \cdot a) d / ( a ⋅ a ) becomes 0/0 for a < 2 − 12 a < 2^{-12} a < 2 − 12 , d = 0 d = 0 d = 0 . FP64 evaluation leaves 31.95% (KL) and 5.7% (scale gradient) for FP32 inputs.
Repair. With x = ( a − b ) / b x = (a - b)/b x = ( a − b ) / b and t = d / a t = d/a t = d / a ,
K L = φ ( x ) + r ξ ( − t ) , ξ ( − t ) = e − t − 1 + t ≥ 0. \mathrm{KL} = \varphi(x) + r \xi(-t), \qquad\xi(-t) = e^{-t} - 1 + t \ge0. KL = φ ( x ) + r ξ ( − t ) , ξ ( − t ) = e − t − 1 + t ≥ 0.
ξ ( − t ) \xi(-t) ξ ( − t ) and χ ( t ) = 1 − ( 1 + t ) e − t \chi(t) = 1 - (1 + t)e^{-t} χ ( t ) = 1 − ( 1 + t ) e − t use alternating series for t ≤ 1 t \le1 t ≤ 1 (7/11/18 and 8/12/19 terms) and expm1 beyond. Gradients: ∂ μ p = − sgn ( μ p − μ q ) expm1 ( − t ) / b \partial_{\mu_p} = -\operatorname{sgn}(\mu_p - \mu_q)\operatorname{expm1}(-t)/b ∂ μ p = − sgn ( μ p − μ q ) expm1 ( − t ) / b , ∂ a = ( a − b ) / ( a b ) − χ ( t ) / b \partial_a = (a - b)/(ab) - \chi(t)/b ∂ a = ( a − b ) / ( ab ) − χ ( t ) / b , ∂ b = − ( x + r ξ ( − t ) ) / b \partial_b = -(x + r\xi(-t))/b ∂ b = − ( x + r ξ ( − t )) / b . Products of the form t 2 X / b t^2X/b t 2 X / b are evaluated as ( t ⋅ X ) ( t / b ) (t \cdot X)(t/b) ( t ⋅ X ) ( t / b ) to avoid underflow.
Why it works. Two non-negative terms. The series alternate with decreasing terms, so the tail is bounded by the first neglected term: the relative truncation after K K K terms is ≤ 3 / ( K + 2 ) ! \le3/(K + 2)! ≤ 3/ ( K + 2 )! for ξ ( − t ) \xi(-t) ξ ( − t ) and ≤ 6 ( K + 1 ) / ( K + 2 ) ! \le6(K + 1)/(K + 2)! ≤ 6 ( K + 1 ) / ( K + 2 )! for χ \chi χ , below u / 16 u/16 u /16 . There is no structural zero of the scale gradients for d ≠ 0 d \ne0 d = 0 : it would require e − t e^{-t} e − t rational for rational t ≠ 0 t \ne0 t = 0 , impossible by the Lindemann–Weierstrass theorem. The genuine zero crossings of ∂ a \partial_a ∂ a , ∂ b \partial_b ∂ b are resolved by the higher precision.
Frozen data (339,692). KL: OFFICIAL 58.32 / 85.87%; OFF.+ 2.24 / 31.95%; REWRITE 1.46 / 0% (FP16 residue only). Gradients: OFFICIAL 45.4–79.7%; REWRITE ≤ 0.15 % \le0.15\% ≤ 0.15% , with 86 new cases at zero crossings (< 0.03 % < 0.03\% < 0.03% of the repaired ones).
Pareto
Official. For s p ≥ s q s_p \ge s_q s p ≥ s q (scales) and shapes a p , a q a_p, a_q a p , a q : K L = a q log s p s q − log a q a p + a q a p − 1 \mathrm{KL} = a_q \log\frac{s_p}{s_q} - \log\frac{a_q}{a_p} + \frac{a_q}{a_p} - 1 KL = a q log s q s p − log a p a q + a p a q − 1 .
Error. Four O ( 1 ) O(1) O ( 1 ) terms for a small KL (33.6% spurious zeros in FP16); autograd’s shape gradients pass through 1 − 1 / ( a q / a p ) 1 - 1/(a_q/a_p) 1 − 1/ ( a q / a p ) . Scale gradients are accurate. FP64 evaluation leaves 6.99% for FP32 inputs.
Repair. With x = ( s p − s q ) / s q ≥ 0 x = (s_p - s_q)/s_q \ge0 x = ( s p − s q ) / s q ≥ 0 and y = ( a p − a q ) / a p y = (a_p - a_q)/a_p y = ( a p − a q ) / a p ,
K L = a q log 1 p ( x ) + φ ( y ) . \mathrm{KL} = a_q \log1p(x) + \varphi(y). KL = a q log 1 p ( x ) + φ ( y ) .
Gradients: ∂ s p = a q / s p \partial_{s_p} = a_q/s_p ∂ s p = a q / s p , ∂ s q = − a q / s q \partial_{s_q} = -a_q/s_q ∂ s q = − a q / s q , ∂ a p = ( ( a p − a q ) / a p ) / a p \partial_{a_p} = ((a_p - a_q)/a_p)/a_p ∂ a p = (( a p − a q ) / a p ) / a p , ∂ a q = log 1 p ( x ) + ( a q − a p ) / ( a p a q ) \partial_{a_q} = \log1p(x) + (a_q - a_p)/(a_p a_q) ∂ a q = log 1 p ( x ) + ( a q − a p ) / ( a p a q ) ; when the second, negative, term of ∂ a q \partial_{a_q} ∂ a q overflows alone while the sum is finite, the merged numerator ( a q log 1 p ( x ) + ( a q − a p ) / a p ) / a q (a_q\log1p(x) + (a_q - a_p)/a_p)/a_q ( a q log 1 p ( x ) + ( a q − a p ) / a p ) / a q is used.
Why it works. Two non-negative terms; the series occurs only in φ ≤ K L \varphi\le\mathrm{KL} φ ≤ KL . For s p ≠ s q s_p \ne s_q s p = s q , log 1 p ( x ) \log1p(x) log 1 p ( x ) is the logarithm of a rational number ≠ 1 \ne1 = 1 , hence transcendental, so ∂ a q \partial_{a_q} ∂ a q has no structural zero.
Frozen data (206,950). KL: OFFICIAL 73.52 / 83.76%; OFF.+ 0 / 6.99%; REWRITE 0 / 0%. Shape gradients: OFFICIAL 47.9–81.4%; REWRITE 0.40 / 0.50% on ∂ a q \partial_{a_q} ∂ a q (14 new cases at zero crossing).
Bernoulli (probs and logits)
Official. With logits l p , l q l_p,l_q l p , l q and probabilities p = σ ( l p ) p=\sigma(l_p) p = σ ( l p ) , q = σ ( l q ) q=\sigma(l_q) q = σ ( l q ) : K L = p ( softplus ( − l q ) − softplus ( − l p ) ) + ( 1 − p ) ( softplus ( l q ) − softplus ( l p ) ) \mathrm{KL}=p\left(\operatorname{softplus}(-l_q)-\operatorname{softplus}(-l_p)\right)+(1-p)\left(\operatorname{softplus}(l_q)-\operatorname{softplus}(l_p)\right) KL = p ( softplus ( − l q ) − softplus ( − l p ) ) + ( 1 − p ) ( softplus ( l q ) − softplus ( l p ) ) . The probs constructor first forms l = log c − log 1 p ( − c ) l=\log c-\log1p(-c) l = log c − log 1 p ( − c ) from c = clamp ( p , e p s , 1 − e p s ) c=\operatorname{clamp}(p,\mathrm{eps},1-\mathrm{eps}) c = clamp ( p , eps , 1 − eps ) .
Error. Each term is a probability times a difference of two nearly equal softplus values, and the two terms have opposite signs, while K L ≈ ( p − q ) 2 / ( 2 p ( 1 − p ) ) \mathrm{KL}\approx(p-q)^2/(2p(1-p)) KL ≈ ( p − q ) 2 / ( 2 p ( 1 − p )) : 17.5–20.8% of the outputs are negative. Gradients inherit the same chain plus the sigmoid/logit conversion and the clamp. For large ∣ l ∣ |l| ∣ l ∣ the probability is subnormal. FP64 evaluation leaves 27.15% (probs) and 25.48% (logits) for FP32 inputs.
Repair (both parameterisations). With x 1 = q / p − 1 x_1=q/p-1 x 1 = q / p − 1 and x 2 = ( 1 − q ) / ( 1 − p ) − 1 x_2=(1-q)/(1-p)-1 x 2 = ( 1 − q ) / ( 1 − p ) − 1 ,
K L = p φ ( x 1 ) + ( 1 − p ) φ ( x 2 ) \mathrm{KL}=p\varphi(x_1)+(1-p)\varphi(x_2) KL = pφ ( x 1 ) + ( 1 − p ) φ ( x 2 )
with series arguments s 1 = ( q − p ) / ( p + q ) s_1=(q-p)/(p+q) s 1 = ( q − p ) / ( p + q ) , s 2 = ( p − q ) / ( ( 1 − p ) + ( 1 − q ) ) s_2=(p-q)/((1-p)+(1-q)) s 2 = ( p − q ) / (( 1 − p ) + ( 1 − q )) . Probs: no clamp; ∂ p = log 1 p ( x 2 ) − log 1 p ( x 1 ) \partial_p=\log1p(x_2)-\log1p(x_1) ∂ p = log 1 p ( x 2 ) − log 1 p ( x 1 ) , ∂ q = ( q − p ) / ( q ( 1 − q ) ) \partial_q=(q-p)/(q(1-q)) ∂ q = ( q − p ) / ( q ( 1 − q )) ; closed forms at p , q ∈ { 0 , 1 } p,q\in\{0,1\} p , q ∈ { 0 , 1 } . Logits (z = l p z=l_p z = l p , w = l q w=l_q w = l q ): ∂ z = p ( 1 − p ) ( z − w ) \partial_z=p(1-p)(z-w) ∂ z = p ( 1 − p ) ( z − w ) , ∂ w = q − p \partial_w=q-p ∂ w = q − p ; probabilities, log-ratios and p − q p-q p − q are written in logit space (σ \sigma σ through e − ∣ z ∣ e^{-|z|} e − ∣ z ∣ ; a softplus difference written by hand, because torch.nn.functional.softplus returns its argument y y y for y > 20 y>20 y > 20 and thereby drops log 1 p ( e − y ) \log1p(e^{-y}) log 1 p ( e − y ) in FP64; p − q = p ( 1 − q ) ( 1 − e w − z ) p-q=p(1-q)(1-e^{w-z}) p − q = p ( 1 − q ) ( 1 − e w − z ) for ∣ z − w ∣ ≤ 2 |z-w|\le2 ∣ z − w ∣ ≤ 2 ). Where a probability is subnormal (∣ logit ∣ > 9.70 , 87.34 , 708.40 |\operatorname{logit}|>9.70,87.34,708.40 ∣ logit ∣ > 9.70 , 87.34 , 708.40 for FP16, FP32, FP64), every “probability × factor” is evaluated as a product of two or four normal factors e z / 2 , e z / 4 e^{z/2},e^{z/4} e z /2 , e z /4 with one rounding. OURS uses the midpoint-aware final rounding of Appendix § 8 .§ 1 for ∣ z ∣ , ∣ w ∣ ≤ 1 / 16 |z|,|w|\le1/16 ∣ z ∣ , ∣ w ∣ ≤ 1/16 .
Why it works. Two non-negative terms; KL cannot be negative; the interior identity p = q p=q p = q gives three exact +0 (including −0 versus +0 logits). The midpoint rule is necessary because for ∣ z ∣ , ∣ w ∣ ≈ 10 − 4 |z|,|w|\approx10^{-4} ∣ z ∣ , ∣ w ∣ ≈ 1 0 − 4 the true gradient lies within 10 − 7 10^{-7} 1 0 − 7 ULP of an FP16 subnormal midpoint (its leading term ( w − z ) / 4 (w-z)/4 ( w − z ) /4 is a midpoint); without it, the FP32-evaluated variant misrounds 7 samples of the benchmark.
Frozen data (327,099 probs; 353,392 logits). KL, probs: OFFICIAL 61.43 / 81.06%; OFF.+ 0.29 / 27.15%; REWRITE 0.41 / 0%. KL, logits: OFFICIAL 49.92 / 75.95%; OFF.+ 1.29 / 25.48%; REWRITE 0.012 / 0.012%. P P P -gradient: OFFICIAL 60.3–78.0%; OFF.+ 1.5–9.5%; REWRITE ≤ 0.002 % \le0.002\% ≤ 0.002% . Exhaustive check of all 2.36 × 10 8 2.36\times10^8 2.36 × 1 0 8 FP16 pairs ( p , q ) (p,q) ( p , q ) : REWRITE at most 6 ULP (KL), FP32 evaluation at most 1 ULP.
Binomial (probs and logits)
Official. K L = n ( p ( l p − l q ) + log 1 p ( − p ) − log 1 p ( − q ) ) \mathrm{KL}=n\left(p(l_p-l_q)+\log1p(-p)-\log1p(-q)\right) KL = n ( p ( l p − l q ) + log 1 p ( − p ) − log 1 p ( − q ) ) (equal total counts n ∈ { 1 , 10 , 100 , 1000 } n\in\{1,10,100,1000\} n ∈ { 1 , 10 , 100 , 1000 } in our data).
Error. Three terms of mixed sign: 13.4–23.2% negative and 16.6–30.2% spurious zeros. When q q q rounds to 1, log 1 p ( − q ) = − ∞ \log1p(-q)=-\infty log 1 p ( − q ) = − ∞ : the logits configuration still returns ∞ \infty ∞ for 2.2% (FP32 evaluation) and 5.3% (FP64 evaluation) of FP16 inputs. FP64 evaluation leaves 37.5% (probs) and 43.8% (logits) for FP32 inputs.
Repair. K L = n ⋅ K L B e r n o u l l i \mathrm{KL}=n\cdot\mathrm{KL}_{\mathrm{Bernoulli}} KL = n ⋅ KL Bernoulli with the Bernoulli algorithm, but n n n must enter before any subnormal intermediate is formed and never in a product with an intermediate that can overflow: e.g. inside the series segment n φ = ( ( n x ) s ) − ( ( ( ( 2 n ) s ) s ) s ) Q ( z ) n\varphi=((nx)s)-((((2n)s)s)s)Q(z) n φ = (( n x ) s ) − (((( 2 n ) s ) s ) s ) Q ( z ) , then multiplied by p p p or 1 − p 1-p 1 − p ; in logit space n n n multiplies only normal factors; the midpoint rule includes n n n in its exact leading term.
Why it works. Each expression is n n n times an already verified Bernoulli quantity with the multiplications reordered; after n n n has entered, every further step multiplies by a factor ≤ 1 \le1 ≤ 1 or is an exact addition. Multiplying by n n n last would make the same-precision FP16 KL wrong by up to 316 ULP and misround 7 gradients in the FP32-evaluated variant.
Frozen data (329,885 probs; 345,715 logits). KL, probs: OFFICIAL 83.86 / 85.60%; OFF.+ 10.43 / 37.51%; REWRITE 0.32 / 0%. KL, logits: OFFICIAL 69.69 / 86.95%; OFF.+ 34.93 / 43.79% (6.12% for FP16 inputs even in FP64); REWRITE 0.020 / 0.031%. P P P -gradient: OFFICIAL 73.7–87.8%.
Geometric (probs and logits)
Official. For the failure-count Geometric P ( k ) = p ( 1 − p ) k P(k)=p(1-p)^k P ( k ) = p ( 1 − p ) k : K L = − H ( p ) − log 1 p ( − q ) / p − logit ( q ) \mathrm{KL}=-H(p)-\log1p(-q)/p-\operatorname{logit}(q) KL = − H ( p ) − log 1 p ( − q ) / p − logit ( q ) , where the entropy H ( p ) H(p) H ( p ) of P P P is computed as binary_cross_entropy_with_logits(logits,probs)/p.
Error. Three terms, each a logarithm or a logarithm divided by p p p , sum to a much smaller KL: the worst family in our study (91–97% significant KL errors, 19–27% negative). With logits, q q q rounding to 1 gives − ∞ -\infty − ∞ : 2.8–12.2% infinite and 1.6–2.5% NaN KL values, and 4.4–15.8% NaN gradients. FP64 evaluation leaves 48.4% (probs) and 51.5% (logits) for FP32 inputs.
Repair. The Geometric KL equals the Bernoulli KL divided by p p p . With x 1 = q / p − 1 x_1 = q/p - 1 x 1 = q / p − 1 , x 2 = ( 1 − q ) / ( 1 − p ) − 1 x_2 = (1 - q)/(1 - p) - 1 x 2 = ( 1 − q ) / ( 1 − p ) − 1 , φ ˉ ( x ) = φ ( x ) / x \bar{\varphi}(x) = \varphi(x)/x φ ˉ ( x ) = φ ( x ) / x and g ( x ) = log 1 p ( x ) / x g(x) = \log1p(x)/x g ( x ) = log 1 p ( x ) / x (with φ ˉ ( 0 ) = 0 \bar{\varphi}(0) = 0 φ ˉ ( 0 ) = 0 and g ( 0 ) = 1 g(0) = 1 g ( 0 ) = 1 ), all outputs are single products:
K L = x 1 ( φ ˉ ( x 1 ) − φ ˉ ( x 2 ) ) , \mathrm{KL} = x_1\left(\bar{\varphi}(x_1) - \bar{\varphi}(x_2)\right), KL = x 1 ( φ ˉ ( x 1 ) − φ ˉ ( x 2 ) ) ,
where φ ˉ ( x 1 ) \bar{\varphi}(x_1) φ ˉ ( x 1 ) and φ ˉ ( x 2 ) \bar{\varphi}(x_2) φ ˉ ( x 2 ) have opposite signs, so their difference does not cancel; inside the series segment φ ˉ = s − a ( 1 − s ) \bar{\varphi} = s - a(1 - s) φ ˉ = s − a ( 1 − s ) and g = ( 1 − s ) ( 1 + a ) g = (1 - s)(1 + a) g = ( 1 − s ) ( 1 + a ) with a = s 2 Q ( s 2 ) a = s^2Q(s^2) a = s 2 Q ( s 2 ) . Probs: ∂ p = ( ( − x 1 ) g ( x 2 ) ) / p / ( 1 − p ) \partial_p = ((-x_1)g(x_2))/p/(1 - p) ∂ p = (( − x 1 ) g ( x 2 )) / p / ( 1 − p ) , ∂ q = ( x 1 / q ) / ( 1 − q ) \partial_q = (x_1/q)/(1 - q) ∂ q = ( x 1 / q ) / ( 1 − q ) . Logits (z z z and w w w the logits of P P P and Q Q Q ): ∂ w = x 1 \partial_w = x_1 ∂ w = x 1 , ∂ z = − x 1 g ( x 2 ) \partial_z = -x_1g(x_2) ∂ z = − x 1 g ( x 2 ) , with x 1 = σ ( − w ) expm1 ( w − z ) x_1 = \sigma(-w)\operatorname{expm1}(w - z) x 1 = σ ( − w ) expm1 ( w − z ) evaluated in three branches by the signs of w − z w - z w − z and w w w (the difference z − w z - w z − w exact by TwoSum where Sterbenz’s lemma does not apply) and small or large factors ( σ ( − w ) , e − z ) (\sigma(-w), e^{-z}) ( σ ( − w ) , e − z ) multiplied last through split exponents. Midpoint-aware rounding for ∣ z ∣ , ∣ w ∣ ≤ 1 / 16 |z|, |w| \le1/16 ∣ z ∣ , ∣ w ∣ ≤ 1/16 (leading term ( w − z ) / 2 (w - z)/2 ( w − z ) /2 ).
Why it works. The identities used are r x 2 = − x 1 r x_2 = -x_1 r x 2 = − x 1 with r = ( 1 − p ) / p r = (1 - p)/p r = ( 1 − p ) / p , and log 1 p x = 2 atanh s \log1p x = 2\operatorname{atanh}s log 1 p x = 2 atanh s only; the KL is a single product, so there is no cancellation, no subnormal intermediate and no premature overflow. As a check, the truth was also evaluated from the official formula at 1,500 digits; it agrees after rounding.
Frozen data (304,861 probs; 352,178 logits). KL, probs: OFFICIAL 91.17 / 94.19%; OFF.+ 36.53 / 48.35%; REWRITE 0 / 0%. KL, logits: OFFICIAL 94.35 / 96.62%; OFF.+ 42.77 / 51.47% (6.60% for FP16 inputs in FP64); REWRITE 0.17% / one sample. P P P -gradient: OFFICIAL 78.5–92.5%; OFF.+ 13.8–19.5%.
Gumbel
Official. With P = ( m , b ) P = (m, b) P = ( m , b ) , Q = ( n , c ) Q = (n, c) Q = ( n , c ) (location, scale) and Euler’s constant γ \gamma γ : K L = − log b c − n c + m c + γ b c + exp ( n c + log Γ ( 1 + b c ) − m c ) − ( 1 + γ ) \mathrm{KL} = -\log\frac{b}{c} - \frac{n}{c} + \frac{m}{c} + \gamma\frac{b}{c} + \exp\left(\frac{n}{c} + \log\Gamma\left(1 + \frac{b}{c}\right) - \frac{m}{c}\right) - (1 + \gamma) KL = − log c b − c n + c m + γ c b + exp ( c n + log Γ ( 1 + c b ) − c m ) − ( 1 + γ ) .
Error. n / c n/c n / c and m / c m/c m / c are rounded separately, so for large ∣ loc ∣ / scale |\operatorname{loc}|/\operatorname{scale} ∣ loc ∣/ scale their absolute error exceeds the KL; four O ( 1 ) O(1) O ( 1 ) terms then sum to a small value (10–14% negative, 17–36% spurious zeros). Gradients inherit the cancellation; 7.28% of the FP16 Q Q Q -scale gradients are NaN. FP64 evaluation leaves 38.4% for FP32 inputs.
Repair. With t = ( m − n ) / c t = (m - n)/c t = ( m − n ) / c , r = b / c r = b/c r = b / c , y = log Γ ( 1 + r ) − t y = \log\Gamma(1 + r) - t y = log Γ ( 1 + r ) − t and x = expm1 ( y ) x = \operatorname{expm1}(y) x = expm1 ( y ) ,
K L = φ ( x ) + H ( r ) , H ( r ) = log Γ ( r ) + γ ( r − 1 ) ≥ 0 , \mathrm{KL} = \varphi(x) + H(r), \qquad H(r) = \log\Gamma(r) + \gamma(r - 1) \ge0, KL = φ ( x ) + H ( r ) , H ( r ) = log Γ ( r ) + γ ( r − 1 ) ≥ 0 ,
where H H H is convex with H ( 1 ) = H ′ ( 1 ) = 0 H(1) = H'(1) = 0 H ( 1 ) = H ′ ( 1 ) = 0 . Gradients: ∂ m = − x / c \partial_m = -x/c ∂ m = − x / c , ∂ n = x / c \partial_n = x/c ∂ n = x / c ; c ∂ b c\partial_b c ∂ b has two exactly equivalent forms, x ψ ( 1 + r ) + ( ψ ( r ) + γ ) x\psi(1 + r) + (\psi(r) + \gamma) x ψ ( 1 + r ) + ( ψ ( r ) + γ ) and e y ψ ( 1 + r ) + ( γ − 1 / r ) e^y\psi(1 + r) + (\gamma- 1/r) e y ψ ( 1 + r ) + ( γ − 1/ r ) , of which the one with the smaller terms is chosen; c ∂ c = − ( t c ∂ m + r c ∂ b ) c\partial_c = -(t\,c\partial_m + r\,c\partial_b) c ∂ c = − ( t c ∂ m + r c ∂ b ) by scale invariance. log Γ \log\Gamma log Γ and ψ \psi ψ are implemented from exact-coefficient zeta series in four ranges of r r r (Appendix B.1). Eight FP16 range guards handle overflow of m − n m - n m − n , of x x x , and of individual products.
Why it works. Two non-negative terms; the identities used are log Γ ( 1 + r ) − log r = log Γ ( r ) \log\Gamma(1 + r) - \log r = \log\Gamma(r) log Γ ( 1 + r ) − log r = log Γ ( r ) , ψ ( 1 + r ) − 1 / r = ψ ( r ) \psi(1 + r) - 1/r = \psi(r) ψ ( 1 + r ) − 1/ r = ψ ( r ) and log 1 p ( x ) = y \log1p(x) = y log 1 p ( x ) = y . Residual cancellation in the gradients occurs only at genuine zeros (y ≈ 0 y \approx0 y ≈ 0 , ∂ c \partial_c ∂ c crossing zero).
Frozen data (339,249). KL: OFFICIAL 66.18 / 90.02%; OFF.+ 13.78 / 38.42%; REWRITE 0.007 / 0%. Gradients: OFFICIAL 73.7–92.5%; OFF.+ 2.4–8.7%; REWRITE 0.31–0.75% (117 new cases near gradient zeros, < 0.02 % < 0.02\% < 0.02% of the repaired ones).
Gamma
Official. With P = ( a p , b p ) P = (a_p, b_p) P = ( a p , b p ) , Q = ( a q , b q ) Q = (a_q, b_q) Q = ( a q , b q ) (concentration, rate): K L = a q log b p b q + log Γ ( a q ) − log Γ ( a p ) + ( a p − a q ) ψ ( a p ) + ( b q − b p ) a p b p \mathrm{KL} = a_q\log\frac{b_p}{b_q} + \log\Gamma(a_q) - \log\Gamma(a_p) + (a_p - a_q)\psi(a_p) + (b_q - b_p)\frac{a_p}{b_p} KL = a q log b q b p + log Γ ( a q ) − log Γ ( a p ) + ( a p − a q ) ψ ( a p ) + ( b q − b p ) b p a p .
Error. Four terms of size O ( a ) O(a) O ( a ) or O ( a log a ) O(a\log a) O ( a log a ) for a KL between 10 − 15 10^{-15} 1 0 − 15 and 1; the cancellation grows with a a a (up to 10 4 10^4 1 0 4 in R1): about 27% negative. Autograd differentiates through digamma; in FP16 log Γ \log\Gamma log Γ overflows for a a a above about 8200 (about 4% NaN and 4% infinite concentration gradients). FP64 evaluation leaves 36.9% for FP32 inputs.
Repair. With α = a q / a p − 1 \alpha= a_q/a_p - 1 α = a q / a p − 1 and z = a p b q a q b p − 1 z = \frac{a_p b_q}{a_q b_p} - 1 z = a q b p a p b q − 1 (ratio of the two means minus one),
K L = a q φ ( z ) + 1 2 φ ( α ) + B w ( a q , a p ) , \mathrm{KL} = a_q\varphi(z) + \frac{1}{2}\varphi(\alpha) + B_w(a_q,a_p), KL = a q φ ( z ) + 2 1 φ ( α ) + B w ( a q , a p ) ,
where B w B_w B w is the Bregman divergence of the convex Binet function w w w ; all three terms are non-negative. Gradients: ∂ a p = ( a q / a p ) z − α ( 1 / 2 + g ( a p ) ) / a p \partial_{a_p} = (a_q/a_p)z - \alpha(1/2 + g(a_p))/a_p ∂ a p = ( a q / a p ) z − α ( 1/2 + g ( a p )) / a p with g ( s ) = s 2 w ′ ′ ( s ) g(s) = s^2w''(s) g ( s ) = s 2 w ′′ ( s ) ; ∂ b p = − a q z / b p \partial_{b_p} = -a_qz/b_p ∂ b p = − a q z / b p ; ∂ a q = Δ L − log 1 p ( z ) \partial_{a_q} = \Delta L - \log1p(z) ∂ a q = Δ L − log 1 p ( z ) with $L = \psi - \log and Δ L = L ( a q ) − L ( a p ) \Delta L = L(a_q) - L(a_p) Δ L = L ( a q ) − L ( a p ) ; ∂ b q = a q z / b q \partial b_q = a_q z/b_q ∂ b q = a q z / b q . The product difference in z z z is formed exactly using scaled TwoProduct and TwoSum before division, so equal means give z = 0 z = 0 z = 0 exactly. For near pairs B w B_w B w and Δ L \Delta L Δ L are same-sign integrals evaluated by Gauss–Legendre quadrature; for far pairs w w w is evaluated by shifts and series. Eight FP16 range guards use the mantissa/exponent form.
Why it works. Three non-negative terms, an exact product difference for z z z , and same-sign quadrature sums. Equivalence with the official formula was checked at 60 and 70 digits; the truth is computed from the official formula at 120–160 digits and does not depend on the rewriting.
Frozen data (331,067). KL: OFFICIAL 78.47 / 88.67%; OFF.+ 9.09 / 36.92%; REWRITE 0.003 / 0.002%. Gradients: OFFICIAL 64.4–82.5%; REWRITE ≤ 0.21 % \le0.21\% ≤ 0.21% (21 new cases near gradient zeros).
Beta
Official. With concentrations P = ( a , b ) P = (a,b) P = ( a , b ) , Q = ( c , d ) Q = (c,d) Q = ( c , d ) and the Beta function B B B : KL = log B ( c , d ) − log B ( a , b ) + ( a − c ) ψ ( a ) + ( b − d ) ψ ( b ) + ( c − a + d − b ) ψ ( a + b ) = \log B(c,d) - \log B(a,b) + (a-c)\psi(a) + (b-d)\psi(b) + (c-a+d-b)\psi(a+b) = log B ( c , d ) − log B ( a , b ) + ( a − c ) ψ ( a ) + ( b − d ) ψ ( b ) + ( c − a + d − b ) ψ ( a + b ) , i.e. six lgamma and three digamma terms.
Error. Nine terms of size O ( a log a ) O(a\log a) O ( a log a ) : about one third of the non-identity outputs are negative; in FP16 lgamma( a + b ) (a+b) ( a + b ) overflows (2.4% NaN). The gradients are differences of first-order terms and, for small parameters, of terms ≈ − 1 / a \approx-1/a ≈ − 1/ a and ≈ − 1 / b \approx-1/b ≈ − 1/ b . FP64 evaluation leaves 43.8% for FP32 inputs.
Repair. Let s = a + b s = a+b s = a + b , s q = c + d s_q = c+d s q = c + d , α = c / a − 1 \alpha= c/a - 1 α = c / a − 1 , β = d / b − 1 \beta= d/b - 1 β = d / b − 1 , z = a d / ( b c ) − 1 z = ad/(bc) - 1 z = a d / ( b c ) − 1 , v ( x ) = log Γ ( x ) − x log x + x v(x) = \log\Gamma(x) - x\log x + x v ( x ) = log Γ ( x ) − x log x + x and ω ( x ) = x v ′ ′ ( x ) \omega(x) = xv''(x) ω ( x ) = x v ′′ ( x ) (decreasing). Then
K L = c φ ( r 1 ) + d φ ( r 0 ) + B V , r 1 = b s z , r 0 = − a s z 1 + z \mathrm{KL} = c\varphi(r_1) + d\varphi(r_0) + B_V,\qquad r_1 = \frac{b}{s}z,\qquad r_0 = -\frac{a}{s}\frac{z}{1+z} KL = c φ ( r 1 ) + d φ ( r 0 ) + B V , r 1 = s b z , r 0 = − s a 1 + z z
where B V = B v ( c , a ) + B v ( d , b ) − B v ( s q , s ) B_V = B_v(c,a) + B_v(d,b) - B_v(s_q,s) B V = B v ( c , a ) + B v ( d , b ) − B v ( s q , s ) is the Bregman divergence of the convex function V ( a , b ) = v ( a ) + v ( b ) − v ( a + b ) V(a,b) = v(a) + v(b) - v(a+b) V ( a , b ) = v ( a ) + v ( b ) − v ( a + b ) . Adding three B v B_v B v directly cancels when one parameter is much smaller than the other (by a factor of about 100 in our samples), so for near pairs
B V = 1 2 Q + T 3 ( c , a ) + T 3 ( d , b ) − T 3 ( s q , s ) , Q = a ( ω ( a ) − ω ( s ) ) α 2 + b ( ω ( b ) − ω ( s ) ) β 2 + ω ( s ) a d b ( β − α ) 2 B_V = \frac{1}{2}Q + T_3(c,a) + T_3(d,b) - T_3(s_q,s),\qquad Q = a\bigl(\omega(a)-\omega(s)\bigr)\alpha^2 + b\bigl(\omega(b)-\omega(s)\bigr)\beta^2 + \omega(s)\frac{ad}{b}(\beta-\alpha)^2 B V = 2 1 Q + T 3 ( c , a ) + T 3 ( d , b ) − T 3 ( s q , s ) , Q = a ( ω ( a ) − ω ( s ) ) α 2 + b ( ω ( b ) − ω ( s ) ) β 2 + ω ( s ) b a d ( β − α ) 2
with three non-negative terms in Q Q Q and the third-order remainders T 3 ( x , y ) = B v ( x , y ) − 1 2 ( x − y ) 2 v ′ ′ ( y ) = ∫ y x 1 2 ( x − t ) 2 v ′ ′ ′ ( t ) d t T_3(x,y) = B_v(x,y) - \frac{1}{2}(x-y)^2v''(y) = \int_y^x \frac{1}{2}(x-t)^2v'''(t)\,\mathrm{d}t T 3 ( x , y ) = B v ( x , y ) − 2 1 ( x − y ) 2 v ′′ ( y ) = ∫ y x 2 1 ( x − t ) 2 v ′′′ ( t ) d t , evaluated through t 3 v ′ ′ ′ ( t ) = t 3 w ′ ′ ′ ( t ) − 1 t^3v'''(t) = t^3w'''(t)-1 t 3 v ′′′ ( t ) = t 3 w ′′′ ( t ) − 1 with the Binet function w w w ; for far pairs the three B v B_v B v are used directly. Gradients use identities that are exact for arbitrary shifts, e.g. ∂ a = − α ( ω ( a ) − ω ( s ) ) + b s ( β − α ) ( 1 + ω ( s ) ) \partial_a = -\alpha\bigl(\omega(a)-\omega(s)\bigr) + \frac{b}{s}(\beta-\alpha)(1+\omega(s)) ∂ a = − α ( ω ( a ) − ω ( s ) ) + s b ( β − α ) ( 1 + ω ( s )) . The shared numerator a d − b c ad-bc a d − b c is formed exactly from scaled mantissas before evaluating z z z , r 1 r_1 r 1 , r 0 r_0 r 0 and β − α \beta-\alpha β − α .
Why it works. All leading terms are non-negative, with their ratio numerators computed exactly; residual cancellation is confined to the third-order remainders, to the Q Q Q -side gradients near their zeros and to far pairs, all inside the error estimate.
Frozen data (329,156). KL: OFFICIAL 85.38 / 92.62%; OFF.+ 40.32 / 43.77%; REWRITE 2.11 / 0.65%. Gradients: OFFICIAL 73.9–87.6%; OFF.+ 0.7–2.9%; REWRITE 0.15–1.57%. REWRITE introduces 961 new cases, mostly Q Q Q -side gradients at small parameters (at most 0.29% of the repaired ones). This is the family in which the same-precision variant is weakest.
Dirichlet (K = 2 , 4 , 16 K = 2, 4, 16 K = 2 , 4 , 16 )
Official. With concentrations a 1 , … , a K a_1,\ldots,a_K a 1 , … , a K of P P P and c 1 , … , c K c_1,\ldots,c_K c 1 , … , c K of Q Q Q : KL = log Γ ( s ) − ∑ j log Γ ( a j ) − log Γ ( s q ) + ∑ j log Γ ( c j ) + ∑ j ( a j − c j ) ( ψ ( a j ) − ψ ( s ) ) = \log\Gamma(s) - \sum_j\log\Gamma(a_j) - \log\Gamma(s_q) + \sum_j\log\Gamma(c_j) + \sum_j(a_j-c_j)\bigl(\psi(a_j)-\psi(s)\bigr) = log Γ ( s ) − ∑ j log Γ ( a j ) − log Γ ( s q ) + ∑ j log Γ ( c j ) + ∑ j ( a j − c j ) ( ψ ( a j ) − ψ ( s ) ) , s = ∑ a j s = \sum a_j s = ∑ a j , s q = ∑ c j s_q = \sum c_j s q = ∑ c j .
Error. Large lgamma/digamma terms cancel almost completely: the KL is not correctly rounded in 98.76% (FP16) and 99.92% (FP32) of the samples, negative in 37.6% / 32.8%, NaN in 3.49% of FP16 samples, and the gradient direction is reversed in 6.29% / 1.45%. In FP64, 56.3% of FP32-input KL values are still not correctly rounded and 2.1% are negative.
Repair. The Beta construction generalises. With α j = c j / a j − 1 \alpha_j = c_j/a_j - 1 α j = c j / a j − 1 , γ = ( s q − s ) / s \gamma= (s_q-s)/s γ = ( s q − s ) / s , δ j = α j − γ \delta_j = \alpha_j-\gamma δ j = α j − γ , r j = a j s q / ( c j s ) − 1 r_j = a_js_q/(c_js)-1 r j = a j s q / ( c j s ) − 1 ,
K L = ∑ j c j φ ( r j ) + 1 2 Q + ∑ j T 3 ( c j , a j ) − T 3 ( s q , s ) , Q = ∑ j a j ( ω ( a j ) − ω ( s ) ) α j 2 + ω ( s ) ∑ j a j δ j 2 \mathrm{KL} = \sum_j c_j\varphi(r_j) + \frac{1}{2}Q + \sum_j T_3(c_j,a_j) - T_3(s_q,s),\qquad Q = \sum_j a_j\bigl(\omega(a_j)-\omega(s)\bigr)\alpha_j^2 + \omega(s)\sum_j a_j\delta_j^2 KL = j ∑ c j φ ( r j ) + 2 1 Q + j ∑ T 3 ( c j , a j ) − T 3 ( s q , s ) , Q = j ∑ a j ( ω ( a j ) − ω ( s ) ) α j 2 + ω ( s ) j ∑ a j δ j 2
with every term of Q Q Q non-negative and T 3 T_3 T 3 as for Beta; with a far pair, KL = ∑ j c j φ ( r j ) + ∑ j B v ( c j , a j ) − B v ( s q , s ) = \sum_j c_j\varphi(r_j) + \sum_j B_v(c_j,a_j) - B_v(s_q,s) = ∑ j c j φ ( r j ) + ∑ j B v ( c j , a j ) − B v ( s q , s ) . δ j \delta_j δ j and r j r_j r j are formed from double-length ratios, never as α j − γ \alpha_j-\gamma α j − γ . When ∑ a j \sum a_j ∑ a j overflows in FP16, s s s is represented as 16 s ˉ 16\bar{s} 16 s ˉ with s ˉ \bar{s} s ˉ an exact expansion of ∑ j a j / 16 \sum_j a_j/16 ∑ j a j /16 .
Why it works. As for Beta, to which the formula reduces for K = 2 K = 2 K = 2 .
Frozen data (314,451). KL: OFFICIAL 84.3–89.0 / 92.1–93.8%; OFF.+ 29.6–55.9 / 41.6–49.8%; REWRITE 0.009–2.45 / 0.003–0.69%. Gradients: OFFICIAL 79–95%. OURS is correctly rounded on every sample.
Categorical (probs and logits; K = 2 , 4 , 16 K = 2, 4, 16 K = 2 , 4 , 16 )
Official. Over K K K categories with probabilities p k p_k p k (P P P ) and q k q_k q k (Q Q Q ): KL = ∑ k p k ( log p k − log q k ) = \sum_k p_k(\log p_k - \log q_k) = ∑ k p k ( log p k − log q k ) , term by term, with terms where q k = 0 q_k = 0 q k = 0 set to + ∞ +\infty + ∞ . The constructor produces probabilities and log-probabilities first: probs uses p = x / ∑ x p = x/\sum x p = x / ∑ x for the raw parameters x x x and log ( clamp ( p , eps , 1 − eps ) ) \log(\operatorname{clamp}(p,\operatorname{eps},1-\operatorname{eps})) log ( clamp ( p , eps , 1 − eps )) ; logits uses z − logsumexp ( z ) z-\operatorname{logsumexp}(z) z − logsumexp ( z ) and softmax for the raw logits z z z .
Error. Five sources. (i) Cancellation : for close distributions each term is first order (≈ p k ρ k \approx p_k\rho_k ≈ p k ρ k ) and the sum second order, because ∑ k p k ρ k = 0 \sum_k p_k\rho_k = 0 ∑ k p k ρ k = 0 exactly; in addition log p k \log p_k log p k and log q k \log q_k log q k carry errors of about u ∣ log p k ∣ u\lvert\log p_k\rvert u ∣ log p k ∣ . (ii) Clamp (probs): probabilities below eps are replaced by eps in value and gradient. (iii) Spurious + ∞ +\infty + ∞ (logits): softmax underflows, q k q_k q k is computed as 0 0 0 and the term is set to ∞ \infty ∞ although the true probability is positive. (iv) Normalisation : rounding of p = x / ∑ x p = x/\sum x p = x / ∑ x makes ∑ p ≠ 1 \sum p \ne1 ∑ p = 1 , which is amplified in the gradient. (v) Argument validation (FP16 probs): the simplex check uses a tolerance of 10 − 6 10^{-6} 1 0 − 6 , below FP16 resolution, and rejects about 25% of valid inputs. FP64 evaluation leaves 32–38% for FP32 inputs.
Repair, probs (raw parameters x x x of P P P and y y y of Q Q Q ; S x = ∑ x S_x = \sum x S x = ∑ x , S y = ∑ y S_y = \sum y S y = ∑ y ). With ρ k = q k / p k − 1 \rho_k = q_k/p_k - 1 ρ k = q k / p k − 1 and the linear term removed by ∑ k p k ρ k = 0 \sum_k p_k\rho_k = 0 ∑ k p k ρ k = 0 ,
K L = ∑ k p k φ ( ρ k ) , ρ k = N k x k S y , N k = y k S x − x k S y , \mathrm{KL} = \sum_k p_k\varphi(\rho_k), \qquad\rho_k = \frac{N_k}{x_kS_y}, \qquad N_k = y_kS_x - x_kS_y, KL = k ∑ p k φ ( ρ k ) , ρ k = x k S y N k , N k = y k S x − x k S y ,
∂ K L ∂ y k = N k y k S x S y , ∂ K L ∂ x k = − log 1 p ( ρ k ) + K L S x = 1 S x ∑ j ≠ k p j log y j x k x j y k . \frac{\partial\mathrm{KL}}{\partial y_k} = \frac{N_k}{y_kS_xS_y}, \qquad\frac{\partial\mathrm{KL}}{\partial x_k} = -\frac{\log1p(\rho_k)+\mathrm{KL}}{S_x} = \frac{1}{S_x}\sum_{j\ne k}p_j\log\frac{y_jx_k}{x_jy_k}. ∂ y k ∂ KL = y k S x S y N k , ∂ x k ∂ KL = − S x log 1 p ( ρ k ) + KL = S x 1 j = k ∑ p j log x j y k y j x k .
S x , S y S_x,S_y S x , S y are exact expansions; N k N_k N k is computed exactly from 4 K 4K 4 K Dekker products. Of the two equivalent forms of ∂ x k \partial_{x_k} ∂ x k the one with the smaller sum of absolute terms is used.
Repair, logits (raw logits z z z of P P P and w w w of Q Q Q ; d k = w k − z k d_k = w_k-z_k d k = w k − z k ). For any constant a a a and t k = d k − a t_k = d_k-a t k = d k − a ,
K L = log 1 p ( E ) − M = ∑ k p k ξ ( t k ) − φ ( E ) , E = ∑ k p k expm1 ( t k ) , M = ∑ k p k t k , \mathrm{KL} = \log1p(E)-M = \sum_k p_k\xi(t_k)-\varphi(E), \qquad E = \sum_k p_k\operatorname{expm1}(t_k), \qquad M = \sum_k p_kt_k, KL = log 1 p ( E ) − M = k ∑ p k ξ ( t k ) − φ ( E ) , E = k ∑ p k expm1 ( t k ) , M = k ∑ p k t k ,
∂ K L ∂ z k = − p k ( t k − M ) , ∂ K L ∂ w k = p k ( e t k − L − 1 ) , L = log 1 p ( E ) . \frac{\partial\mathrm{KL}}{\partial z_k} = -p_k(t_k-M), \qquad\frac{\partial\mathrm{KL}}{\partial w_k} = p_k(e^{t_k-L}-1), \qquad L = \log1p(E). ∂ z k ∂ KL = − p k ( t k − M ) , ∂ w k ∂ KL = p k ( e t k − L − 1 ) , L = log 1 p ( E ) .
The centre is chosen as follows: with r = arg max z r = \arg\max z r = arg max z and s k = d k − d r s_k = d_k-d_r s k = d k − d r , c = fl ( ∑ k p k s k ) c = \operatorname{fl}(\sum_k p_ks_k) c = fl ( ∑ k p k s k ) and t k = s k − c t_k = s_k-c t k = s k − c , so that M M M is of rounding size. p k = e z k − z max / Z p_k = e^{z_k-z_{\max}}/Z p k = e z k − z m a x / Z , with z max = max j z j z_{\max} = \max_j z_j z m a x = max j z j and Z = ∑ j e z j − z max Z = \sum_j e^{z_j-z_{\max}} Z = ∑ j e z j − z m a x , is carried as (mantissa, exponent) and cannot underflow to zero; s k , t k s_k,t_k s k , t k are exact expansions of the inputs. For E > 1 E > 1 E > 1 the form log ( ∑ k p k e t k ) − M \log(\sum_k p_ke^{t_k})-M log ( ∑ k p k e t k ) − M is used. Neither softmax, log_softmax nor a clamp is called. The vectorised form used downstream (Equation (4) ) is an equivalent arrangement of this identity, with the weights taken from the second argument, and is tested against the certified implementation. It is evaluated in FP64 and rounded once. The difference a j − c j a_j-c_j a j − c j is centred at the largest student logit, so that a common offset between a a a and c c c gives exactly zero value and gradient; its rounding error, if any, is recovered by TwoSum and added back; and where δ j \delta_j δ j is large, q j e δ j q_j e^{\delta_j} q j e δ j is formed as exp ( log q j + δ j ) \exp(\log q_j+\delta_j) exp ( log q j + δ j ) . It is not itself certified by interval arithmetic.
Zero probabilities. A category with p k = 0 < q k p_k = 0 < q_k p k = 0 < q k contributes lim p → 0 p φ ( q k / p − 1 ) = q k \lim_{p\to0}p\,\varphi(q_k/p-1)=q_k lim p → 0 p φ ( q k / p − 1 ) = q k . Such inputs are reduced to the support S S S of P P P : K L ( P ∥ Q ) = K L ( P S ∥ Q S ) − log Q ( S ) \mathrm{KL}(P\mathbin{\|}Q)=\mathrm{KL}(P_S\mathbin{\|}Q_S)-\log Q(S) KL ( P ∥ Q ) = KL ( P S ∥ Q S ) − log Q ( S ) , a sum of two non-negative terms; q k = 0 < p k q_k = 0 < p_k q k = 0 < p k gives + ∞ +\infty + ∞ .
Why it works. The cancellation is done algebraically: the probs KL is a sum of non-negative terms, while in the logits KL, S = ∑ k p k ξ ( t k ) S=\sum_k p_k\xi(t_k) S = ∑ k p k ξ ( t k ) satisfies E = M + S E=M+S E = M + S and K L = S − φ ( E ) \mathrm{KL}=S-\varphi(E) KL = S − φ ( E ) . When ∣ M ∣ ≪ S ≪ 1 \lvert M\rvert\ll S \ll1 ∣ M ∣ ≪ S ≪ 1 , φ ( E ) / S ≈ S / 2 \varphi(E)/S \approx S/2 φ ( E ) / S ≈ S /2 ; for E > 1 E>1 E > 1 the other form is used. N k N_k N k is exact, so the relative error of ρ k \rho_k ρ k does not depend on how close p p p and q q q are. Proportional probs and shifted logits (different parameters, same distribution) give exactly + 0 +0 + 0 . Residual cancellation in the same-precision variant occurs where a gradient component itself crosses zero; there its ULP error can be large while its error relative to the gradient vector is of order u u u .
Frozen data (372,429 probs; 367,746 logits). KL, probs: OFFICIAL 46.6–47.6 / 86.0–86.9%; OFF.+ 3.4–4.6 / 32.2–32.5%; REWRITE ≤ 0.01 % \leq0.01\% ≤ 0.01% . KL, logits: OFFICIAL 59.4–62.7 / 88.3–90.5%; OFF.+ 12.4–18.3 / 35.8–38.4%; REWRITE < 0.01 % < 0.01\% < 0.01% / 0. Gradients: OFFICIAL 47.5–65.3 / 75.0–88.9%; REWRITE at most 0.81% (Q Q Q -side, logits K = 16 K = 16 K = 16 , FP32). REWRITE returns ∞ \infty ∞ for a batch of probs values at the overflow threshold, eight of which (K = 2 K = 2 K = 2 ) have a finite true KL and are genuine errors. OURS is correctly rounded on every sample.
ContinuousBernoulli (probs and logits)
Official. With probability parameters λ p , λ q \lambda_p,\lambda_q λ p , λ q , natural parameters η = logit ( λ ) \eta= \operatorname{logit}(\lambda) η = logit ( λ ) , mean μ p \mu_p μ p of P P P and log-normaliser C ( λ ) C(\lambda) C ( λ ) : K L = μ p ( η p − η q ) + [ C ( λ p ) + log 1 p ( − λ p ) ] − [ C ( λ q ) + log 1 p ( − λ q ) ] KL = \mu_p(\eta_p-\eta_q) + [C(\lambda_p) + \log1p(-\lambda_p)] - [C(\lambda_q) + \log1p(-\lambda_q)] K L = μ p ( η p − η q ) + [ C ( λ p ) + log 1 p ( − λ p )] − [ C ( λ q ) + log 1 p ( − λ q )] . The constructor clamps λ \lambda λ to [ eps , 1 − eps ] [\operatorname{eps},1-\operatorname{eps}] [ eps , 1 − eps ] (for logits after a sigmoid, while η \eta η keeps the raw value); C C C and the mean use a truncated Taylor polynomial for λ ∈ ( 0.499 , 0.501 ] \lambda\in(0.499,0.501] λ ∈ ( 0.499 , 0.501 ] and closed forms elsewhere.
Error. (i) Clamp: outside [ eps , 1 − eps ] [\operatorname{eps},1-\operatorname{eps}] [ eps , 1 − eps ] the normaliser and mean belong to a different distribution than the input; with logits z z z this happens for ∣ z ∣ > log ( 1 / eps ) |z| > \log(1/\operatorname{eps}) ∣ z ∣ > log ( 1/ eps ) (about 6.9, 15.9, 36 for FP16, FP32, FP64), where one term uses raw logits and the other two clamped probabilities, so the result is wrong in any precision. (ii) Near pairs: three first-order terms with a second-order sum. (iii) Near λ = 1 2 \lambda= \frac{1}{2} λ = 2 1 outside the window: the mean is a difference of two numbers ≈ 1 / ( 2 ∣ 2 λ − 1 ∣ ) \approx1/(2|2\lambda-1|) ≈ 1/ ( 2∣2 λ − 1∣ ) , cancelling by a factor of about 500 at the window edge. (iv) Inside the window the polynomial is an approximation, not an identity. (v) NaN gradients in FP16 from the unselected branch of torch.where.
Repair. Write the log-partition function as A ( η ) = η / 2 + g ( η ) A(\eta) = \eta/2 + g(\eta) A ( η ) = η /2 + g ( η ) with
g ( x ) = log sinh ( x / 2 ) x / 2 = ∑ k ≥ 1 c k x 2 k , c k = B 2 k 2 k ( 2 k ) ! , g(x) = \log\frac{\sinh(x/2)}{x/2} = \sum_{k\geq1} c_k x^{2k}, \qquad c_k = \frac{B_{2k}}{2k(2k)!}, g ( x ) = log x /2 sinh ( x /2 ) = k ≥ 1 ∑ c k x 2 k , c k = 2 k ( 2 k )! B 2 k ,
where B 2 k B_{2k} B 2 k are the Bernoulli numbers, so that the linear part cancels exactly and, with p = η p p = \eta_p p = η p , q = η q q = \eta_q q = η q , d = q − p d = q-p d = q − p ,
K L = g ( q ) − g ( p ) − d g ′ ( p ) , ∂ p K L = − d g ′ ′ ( p ) , ∂ q K L = g ′ ( q ) − g ′ ( p ) . KL = g(q)-g(p)-d\,g'(p), \qquad\partial_p KL = -d\,g''(p), \qquad\partial_q KL = g'(q)-g'(p). K L = g ( q ) − g ( p ) − d g ′ ( p ) , ∂ p K L = − d g ′′ ( p ) , ∂ q K L = g ′ ( q ) − g ′ ( p ) .
Three regions in ( ∣ p ∣ , ∣ q ∣ ) (|p|,|q|) ( ∣ p ∣ , ∣ q ∣ ) , each with an exact identity: (A) both ≤ 4 \leq4 ≤ 4 : K L = d 2 ∑ k c k H 2 k − 2 ( p , q ) KL = d^2 \sum_k c_k H_{2k-2}(p,q) K L = d 2 ∑ k c k H 2 k − 2 ( p , q ) with the polynomials H n − 2 H_{n-2} H n − 2 defined by q n − p n − n p n − 1 d = d 2 H n − 2 ( p , q ) q^n-p^n-np^{n-1}d = d^2H_{n-2}(p,q) q n − p n − n p n − 1 d = d 2 H n − 2 ( p , q ) , leading term d 2 / 24 d^2/24 d 2 /24 , with 17/27/50 terms; (B) same sign, both away from 0: K L = φ ( ρ ) − φ ( τ ) − h p ξ ( − D ) KL = \varphi(\rho)-\varphi(\tau)-h_p\xi(-D) K L = φ ( ρ ) − φ ( τ ) − h p ξ ( − D ) with D = ∣ q ∣ − ∣ p ∣ D = |q|-|p| D = ∣ q ∣ − ∣ p ∣ , ρ = D / ∣ p ∣ \rho= D/|p| ρ = D /∣ p ∣ , E p = e − ∣ p ∣ E_p = e^{-|p|} E p = e − ∣ p ∣ , E q = e − ∣ q ∣ E_q = e^{-|q|} E q = e − ∣ q ∣ , τ = ( E p − E q ) / ( 1 − E p ) \tau= (E_p-E_q)/(1-E_p) τ = ( E p − E q ) / ( 1 − E p ) and h p = E p / ( 1 − E p ) h_p = E_p/(1-E_p) h p = E p / ( 1 − E p ) ; (C) far pairs: g ( ∣ q ∣ ) + [ ∣ p ∣ g ′ ( ∣ p ∣ ) − g ( ∣ p ∣ ) ] − sgn ( p q ) ∣ q ∣ g ′ ( ∣ p ∣ ) g(|q|) + [|p|g'(|p|)-g(|p|)]-\operatorname{sgn}(pq)|q|g'(|p|) g ( ∣ q ∣ ) + [ ∣ p ∣ g ′ ( ∣ p ∣ ) − g ( ∣ p ∣ )] − sgn ( pq ) ∣ q ∣ g ′ ( ∣ p ∣ ) , whose three terms are non-negative for opposite signs. For probs, d = log ( λ q / λ p ) + log ( λ ˉ p / λ ˉ q ) d = \log(\lambda_q/\lambda_p) + \log(\bar{\lambda}_p/\bar{\lambda}_q) d = log ( λ q / λ p ) + log ( λ ˉ p / λ ˉ q ) with λ ˉ = 1 − λ \bar{\lambda} = 1-\lambda λ ˉ = 1 − λ by TwoSum; the two logarithms have the same sign, and the factor 1 / ( λ ( 1 − λ ) ) 1/(\lambda(1-\lambda)) 1/ ( λ ( 1 − λ )) of the gradient is merged into one product with one rounding. Midpoint-aware final rounding on the logits path.
Why it works. No clamp: logits up to ∣ z ∣ = 1005 |z| = 1005 ∣ z ∣ = 1005 and subnormal λ \lambda λ are evaluated for the distribution that was passed in. The linear term is removed before any arithmetic; the series converges for ∣ η ∣ ≤ 4 < 2 π |\eta| \leq4 < 2\pi ∣ η ∣ ≤ 4 < 2 π , with the remainders of all six series asserted ≤ u / 16 \leq u/16 ≤ u /16 at import time; there is no window. The remaining cancellation is bounded by a factor of 5–9 per region and enters the error estimate.
Frozen data (342,070 probs; 376,691 logits). KL, probs: OFFICIAL 78.37 / 89.75%; OFF.+ 6.27 / 38.92%; REWRITE 0.09 / 0.04%. KL, logits: OFFICIAL 86.17 / 90.89%; OFF.+ 27.81 / 42.56% (5.07% for FP16 inputs in FP64); REWRITE < 0.01%. Gradients: OFFICIAL 78.6–90.8%. For 938 probs gradients REWRITE returns ∞ \infty ∞ where the true value exceeds the format; these are not counted as errors but carry no finite error guarantee.
MultivariateNormal (d = 2 , 4 d = 2, 4 d = 2 , 4 ; scale_tril)
Official. With dimension d d d , means μ p , μ q \mu_p,\mu_q μ p , μ q , lower-triangular Cholesky factors L p , L q L_p,L_q L p , L q of the covariances (scale_tril), M = L q − 1 L p M = L_q^{-1}L_p M = L q − 1 L p and v = L q − 1 ( μ p − μ q ) v = L_q^{-1}(\mu_p-\mu_q) v = L q − 1 ( μ p − μ q ) : K L = [ ∑ i log L q , i i − ∑ i log L p , i i ] + 1 2 ( ∥ M ∥ F 2 + ∥ v ∥ 2 − d ) KL = [\sum_i \log L_{q,ii}-\sum_i \log L_{p,ii}] + \frac{1}{2}(\lVert M\rVert_F^2+\lVert v\rVert^2-d) K L = [ ∑ i log L q , ii − ∑ i log L p , ii ] + 2 1 (∥ M ∥ F 2 + ∥ v ∥ 2 − d ) .
Error. For close pairs ∥ M ∥ F 2 − d \lVert M\rVert_F^2-d ∥ M ∥ F 2 − d and the log-determinant difference are both first order and their sum is second order; the log-determinant difference itself cancels. The dominant cause is cancellation, not ill-conditioning: the KL error rate is similar for condition numbers ≤ 100 \leq100 ≤ 100 , up to 10 4 10^4 1 0 4 , and for large means. 16.4% (d = 2 d = 2 d = 2 ) and 11.1% (d = 4 d = 4 d = 4 ) of non-identity outputs are negative. FP64 evaluation fixes most gradients but leaves about 36% of the KL values.
Repair. M M M is lower triangular with positive diagonal. With N = M − I N = M-I N = M − I and, for each diagonal entry n = N i i n = N_{ii} n = N ii ,
( 1 + n ) 2 − 1 − 2 log ( 1 + n ) = n 2 + 2 φ ( n ) , (1+n)^2-1-2\log(1+n)=n^2+2\varphi(n), ( 1 + n ) 2 − 1 − 2 log ( 1 + n ) = n 2 + 2 φ ( n ) ,
K L = ∑ i φ ( N i i ) + 1 2 ∥ N ∥ F 2 + 1 2 ∥ v ∥ 2 , N = L q − 1 ( L p − L q ) , (5) KL = \sum_i \varphi(N_{ii}) + \frac{1}{2}\lVert N\rVert_F^2 + \frac{1}{2}\lVert v\rVert^2,\qquad N = L_q^{-1}(L_p-L_q), \tag*{(5)} K L = i ∑ φ ( N ii ) + 2 1 ∥ N ∥ F 2 + 2 1 ∥ v ∥ 2 , N = L q − 1 ( L p − L q ) , (5)
∂ μ p = − ∂ μ q = L q − T v , ∂ L p = tril ( L q − T N ) + diag ( N i i / L p , i i ) , ∂ L q = − tril ( L q − T ( N + N T + N N T + v v T ) ) . \partial_{\mu_p}=-\partial_{\mu_q}=L_q^{-\mathsf{T}}v,\qquad\partial_{L_p}=\operatorname{tril}(L_q^{-\mathsf{T}}N)+\operatorname{diag}(N_{ii}/L_{p,ii}),\qquad\partial_{L_q}=-\operatorname{tril}\left(L_q^{-\mathsf{T}}(N+N^{\mathsf{T}}+NN^{\mathsf{T}}+vv^{\mathsf{T}})\right). ∂ μ p = − ∂ μ q = L q − T v , ∂ L p = tril ( L q − T N ) + diag ( N ii / L p , ii ) , ∂ L q = − tril ( L q − T ( N + N T + N N T + v v T ) ) .
N N N is obtained by forward substitution from the exact difference L p − L q L_p-L_q L p − L q (TwoSum), never as M − I M-I M − I . All matrix operations are element-wise in double-length arithmetic (d ≤ 4 d\le4 d ≤ 4 ; no call to torch.linalg).
Why it works. Three non-negative terms; N N N is small because it is solved from an exact small right-hand side; mean-only perturbations give N = 0 N=0 N = 0 and covariance-only perturbations give v = 0 v=0 v = 0 exactly. Double-length arithmetic absorbs the condition number of the triangular solves: solving in plain FP32 would be worse than the official code on 5–15% of the low-rank outputs.
Frozen data (202,000; FP32 only, because the official FP16 implementation is unsupported). KL: OFFICIAL 88.56 / 88.86% (d = 2 / 4 d=2/4 d = 2/4 ); OFF.+ 35.81 / 35.78%; REWRITE 0 (max. 2 ULP). Gradients: OFFICIAL 27.1–43.0%; OFF.+ 4.2–7.5%; REWRITE all correctly rounded. OURS is correctly rounded on every sample. Gradient components in the strict upper triangle of scale_tril are not scored; the official code leaks non-zero gradient there.
LowRankMultivariateNormal (d = 2 , 4 d=2,4 d = 2 , 4 ; r = 1 , 2 r=1,2 r = 1 , 2 )
Official. With covariances Σ = W W T + diag ( D ) \Sigma=WW^{\mathsf{T}}+\operatorname{diag}(D) Σ = W W T + diag ( D ) , where W ∈ R d × r W\in\mathbb{R}^{d\times r} W ∈ R d × r is the factor of rank r r r and D D D the positive diagonal, the Woodbury identity and capacitance matrices give KL = 1 2 [ log det Σ q − log det Σ p + tr ( Σ q − 1 Σ p ) + ( μ q − μ p ) T Σ q − 1 ( μ q − μ p ) − d ] \operatorname{KL}=\frac{1}{2}\left[\log\det\Sigma_q-\log\det\Sigma_p+\operatorname{tr}(\Sigma_q^{-1}\Sigma_p)+(\mu_q-\mu_p)^{\mathsf{T}}\Sigma_q^{-1}(\mu_q-\mu_p)-d\right] KL = 2 1 [ log det Σ q − log det Σ p + tr ( Σ q − 1 Σ p ) + ( μ q − μ p ) T Σ q − 1 ( μ q − μ p ) − d ] , each part computed separately.
Error. The same second-order cancellation as for the full-covariance case; in addition D D D is swamped by the rounding of W W T WW^{\mathsf{T}} W W T when the covariance is assembled; and the parameterisation is not unique (column permutations and sign flips of W W W , transfers between W W T WW^{\mathsf{T}} W W T and D D D ), so P = Q P=Q P = Q can hold with different parameters. 19.8–21.3% of non-identity outputs are negative; in FP64 about 40% of the KL values are still wrong and 0.54% negative.
Repair. We return to the form of the previous subsection without forming the Cholesky factor of Σ p \Sigma_p Σ p . With L q = chol ( Σ q ) L_q=\operatorname{chol}(\Sigma_q) L q = chol ( Σ q ) , δ = μ p − μ q \delta=\mu_p-\mu_q δ = μ p − μ q , v = L q − 1 δ v=L_q^{-1}\delta v = L q − 1 δ , Δ W = W p − W q \Delta W=W_p-W_q Δ W = W p − W q and Δ D = D p − D q \Delta D=D_p-D_q Δ D = D p − D q ,
E = Σ p − Σ q = Δ W W p T + W q Δ W T + diag ( Δ D ) , X = L q − 1 E L q − T , I + X = G G T , E=\Sigma_p-\Sigma_q=\Delta W W_p^{\mathsf{T}}+W_q\Delta W^{\mathsf{T}}+\operatorname{diag}(\Delta D),\qquad X=L_q^{-1}EL_q^{-\mathsf{T}},\qquad I+X=GG^{\mathsf{T}}, E = Σ p − Σ q = Δ W W p T + W q Δ W T + diag ( Δ D ) , X = L q − 1 E L q − T , I + X = G G T ,
and N = G − I N=G-I N = G − I is computed by a differential Cholesky recursion,
s j = X j j − ∑ t < j G j t 2 , N j j = s j 1 + 1 + s j , G i j = X i j − ∑ t < j G i t G j t G j j , s_j=X_{jj}-\sum_{t<j}G_{jt}^{2},\qquad N_{jj}=\frac{s_j}{1+\sqrt{1+s_j}},\qquad G_{ij}=\frac{X_{ij}-\sum_{t<j}G_{it}G_{jt}}{G_{jj}}, s j = X j j − t < j ∑ G j t 2 , N j j = 1 + 1 + s j s j , G ij = G j j X ij − ∑ t < j G i t G j t ,
after which KL = ∑ i φ ( N i i ) + 1 2 ∥ N ∥ F 2 + 1 2 ∥ v ∥ 2 \operatorname{KL}=\sum_i\varphi(N_{ii})+\frac{1}{2}\lVert N\rVert_F^2+\frac{1}{2}\lVert v\rVert^2 KL = ∑ i φ ( N ii ) + 2 1 ∥ N ∥ F 2 + 2 1 ∥ v ∥ 2 . Gradients: H p = L q − T X ( I + X ) − 1 L q − 1 H_p=L_q^{-\mathsf{T}}X(I+X)^{-1}L_q^{-1} H p = L q − T X ( I + X ) − 1 L q − 1 , H q = L q − T [ L q − 1 ( E + δ δ T ) L q − T ] L q − 1 H_q=L_q^{-\mathsf{T}}\left[L_q^{-1}(E+\delta\delta^{\mathsf{T}})L_q^{-\mathsf{T}}\right]L_q^{-1} H q = L q − T [ L q − 1 ( E + δ δ T ) L q − T ] L q − 1 , and ∂ W p = H p W p \partial_{W_p}=H_pW_p ∂ W p = H p W p , ∂ D p = 1 2 diag ( H p ) \partial_{D_p}=\frac{1}{2}\operatorname{diag}(H_p) ∂ D p = 2 1 diag ( H p ) , ∂ W q = − H q W q \partial_{W_q}=-H_qW_q ∂ W q = − H q W q , ∂ D q = − 1 2 diag ( H q ) \partial_{D_q}=-\frac{1}{2}\operatorname{diag}(H_q) ∂ D q = − 2 1 diag ( H q ) , ∂ μ p = L q − T v = − ∂ μ q \partial_{\mu_p}=L_q^{-\mathsf{T}}v=-\partial_{\mu_q} ∂ μ p = L q − T v = − ∂ μ q . E E E is built from the exact parameter differences. Three refinements are necessary: the double-length square root is corrected to be correctly rounded (the vectorised platform square root differed by 1 ULP from the correctly rounded one on 17.2% of FP32 and 1.3% of FP64 results); H q H_q H q adds E + δ δ T E+\delta\delta^{\mathsf{T}} E + δ δ T before solving, so that an exactly vanishing sum gives an exact zero; and semantic identity is decided exactly: if μ p = μ q \mu_p=\mu_q μ p = μ q and W p W p T + diag ( D p ) = W q W q T + diag ( D q ) W_pW_p^{\mathsf{T}}+\operatorname{diag}(D_p)=W_qW_q^{\mathsf{T}}+\operatorname{diag}(D_q) W p W p T + diag ( D p ) = W q W q T + diag ( D q ) as rational numbers (tested with error-free expansions, no tolerance), all outputs are + 0 +0 + 0 .
Why it works. L q G L_qG L q G is the Cholesky factor of Σ p \Sigma_p Σ p , so the non-negative formula of the full-covariance case applies with M = G M=G M = G ; E E E is an exact small quantity; 1 + s − 1 \sqrt{1+s}-1 1 + s − 1 is written without cancellation.
Frozen data (202,000; FP32 only). KL: OFFICIAL 91.1–93.4%; OFF.+ 39.5–41.9%; REWRITE 0 (max. 3 ULP). Gradients: OFFICIAL 59.3–71.0%; OFF.+ 10.8–24.4%; of about 4.24 million gradient values REWRITE misrounds 72 and has one significant error, shared with OFFICIAL. OURS is correctly rounded on every sample.
Interface B: torch.nn.functional.kl_div
Official implementation and its errors
Element-wise, the official code computes ℓ = x log y ( t , t ) − t x \ell=x\log y(t,t)-tx ℓ = x log y ( t , t ) − t x , where xlogy ( t , t ) = t log t \operatorname{xlogy}(t,t)=t\log t xlogy ( t , t ) = t log t and 0 0 0 at t = 0 t=0 t = 0 (log_target=False), or ℓ = e t ( t − x ) \ell=e^t(t-x) ℓ = e t ( t − x ) (log_target=True), then sums and divides by a factor den that depends on the reduction (1 for sum, the batch size for batchmean, the number of elements for mean). Gradients are produced by autograd. We found six classes of behaviour; the first five are operator errors that a better implementation removes, and the first four of them also disappear in FP64.
Element-wise cancellation (log_target=False). When t ≈ e x t \approx e^x t ≈ e x , log t \log t log t and x x x are nearly equal, and the rounding error u ∣ log t ∣ u|\log t| u ∣ log t ∣ of the logarithm is amplified by the subtraction. In FP32, 65–99% of sum outputs are off by ≥ 8 \ge8 ≥ 8 ULP and 35–70% by ≥ 1 % \ge1\% ≥ 1% , the more so the smaller the KL. With log_target=True the element-wise error is small (≤ 0.3 % \le0.3\% ≤ 0.3% at ≥ 8 \ge8 ≥ 8 ULP).
Gradient with respect to the target under scaling. Autograd writes the derivative of x log y x\log y x log y in its second argument as ( g t ) / t (g\,t)/t ( g t ) / t , where g g g is the upstream factor (1 / ( B K ) 1/(BK) 1/ ( B K ) for mean, with batch size B B B and K K K classes). The exact value of this term is g g g , but the product is formed first: when g t g\,t g t is subnormal it loses precision and when it underflows the term vanishes. With FP16 and K = 256 K = 256 K = 256 , 99.6% of gradient rows have relative L 2 L_2 L 2 error ≥ 1 % \ge1\% ≥ 1% and 95.4% contain a component of the wrong sign; with K = 1024 K = 1024 K = 1024 every row has cosine below 0.9. The same term makes the gradient 0 / 0 = N a N 0/0 = \mathrm{NaN} 0/0 = NaN at t = 0 t = 0 t = 0 . Evaluating ( g log t + ( g t ) / t ) + ( − g ) x (g\log t + (g\,t)/t) + (-g)\,x ( g log t + ( g t ) / t ) + ( − g ) x in this order reproduces the official gradient bit for bit on 39,513,600 components (including 57,706 NaNs).
Components rounded to zero under mean (log_target=True). e t e^t e t is rounded once and its product with g g g then lands on a midpoint of the subnormal grid and is rounded to 0 (20.1% of target-gradient rows and 14.6% of input-gradient rows for FP16, K = 256 K = 256 K = 256 ).
Overflow before scaling. The exact mean/batchmean is finite but the sum overflows first (extreme strata only).
NaN at boundary inputs. log_target=True with a target of − ∞ -\infty − ∞ (probability zero) returns NaN on all 20,400 such batches; so do x = − ∞ x = -\infty x = − ∞ with t = 0 t = 0 t = 0 and the target gradient at t = 0 t = 0 t = 0 . These are not removed by higher precision.
Input-representation error. T o p T_{\mathrm{op}} T op differs from T e 2 e T_{\mathrm{e2e}} T e2e by ≥ 1 % \ge1\% ≥ 1% on 40–99% of the batches; evaluating the operator in FP64 changes the total error by less than 3 percentage points; with log_target=False two identical distributions give a non-zero T o p T_{\mathrm{op}} T op . This cannot be repaired inside the function.
Repair
The repair keeps the signature (plus a method argument) and computes in FP64 with merged formulas and a single final rounding.
Forward, log_target=False. Write t = m 2 k t = m\,2^k t = m 2 k with an integer k k k and m ∈ [ 1 / 2 , 2 ) m \in[\sqrt{1/2}, \sqrt{2}) m ∈ [ 1/2 , 2 ) . Then log t − x = ( k ln 2 h i − x ) + log m + k ln 2 l o \log t - x = (k\ln2_{\mathrm{hi}} - x) + \log m + k\ln2_{\mathrm{lo}} log t − x = ( k ln 2 hi − x ) + log m + k ln 2 lo , where ln 2 = ln 2 h i + ln 2 l o \ln2 = \ln2_{\mathrm{hi}} + \ln2_{\mathrm{lo}} ln 2 = ln 2 hi + ln 2 lo is split so that ln 2 h i \ln2_{\mathrm{hi}} ln 2 hi has few significant bits; k ln 2 h i k\ln2_{\mathrm{hi}} k ln 2 hi is then exact and cancels against x x x without error; the remaining error comes from ∣ log m ∣ < 0.35 |\log m| < 0.35 ∣ log m ∣ < 0.35 . The four terms are accumulated with TwoSum.
Forward, log_target=True. e t e^t e t and t − x t-x t − x are multiplied in FP64; if t − x = 0 t-x = 0 t − x = 0 the result is 0 regardless of e t e^t e t .
Reduction. Compensated pairwise summation of the unrounded element values, division by d e n den d e n , one rounding.
Backward. Merged analytic gradients replace autograd’s term-by-term evaluation (G G G is the incoming gradient of the reduced loss, so that g = G / d e n g = G/den g = G / d e n above):
Table 21.
The bracket log t + 1 − x \log t + 1 - x log t + 1 − x uses the forward decomposition; t − x + 1 t-x+1 t − x + 1 is an error-free three-term sum, which also decides exactly whether it is zero. Each component is resolved in a fixed order: outside the domain → \to → non-finite G → G = 0 → G \to G = 0 \to G → G = 0 → undefined cell (NaN) → \to → exact zero factor → \to → formula.
Certified rounding. When an intermediate of the fast path is not finite (e.g. e t e^t e t overflows although the result is finite), or when the FP64 value is closer to a rounding boundary of the target format than the a-priori error bound of the fast path, the sum is rewritten as R + ∑ τ c τ f ( τ ) R + \sum_\tau c_\tau f(\tau) R + ∑ τ c τ f ( τ ) , where τ \tau τ runs over the distinct target values, f f f is exp (log_target=True) or log (log_target=False) and R , c τ R, c_\tau R , c τ are exact rationals, and evaluated by interval arithmetic on a precision ladder from 128 to 16,384 bits until both end points round to the same value. If they still differ at 16,384 bits, the implementation raises an error and returns no value; this did not occur on the benchmark. The guard is necessary, e.g. with log_target=True for t = ( 0 , 0 , − 1000 ) t = (0, 0, -1000) t = ( 0 , 0 , − 1000 ) , x = ( − 1 , − 2 − 24 , − 1001 ) x = (-1, -2^{-24}, -1001) x = ( − 1 , − 2 − 24 , − 1001 ) , whose exact value 1 + 2 − 24 + e − 1000 1 + 2^{-24} + e^{-1000} 1 + 2 − 24 + e − 1000 sits next to a rounding midpoint that the dropped e − 1000 e^{-1000} e − 1000 decides. FP64→FP16 rounding goes through a round-to-odd FP32 value, which is equivalent to a single rounding.
Why it works. The large term k ln 2 h i k \ln2_{\mathrm{hi}} k ln 2 hi is exact, so the residual error is independent of ∣ log t ∣ |\log t| ∣ log t ∣ ; the backward pass never forms ( g t ) / t (g\,t)/t ( g t ) / t ; the unit roundoff of FP64 is 2 29 2^{29} 2 29 (FP32) or 2 42 2^{42} 2 42 (FP16) times smaller than that of the target, and the few results too close to a rounding boundary are certified by interval arithmetic. The guard uses an a-priori error bound of the fast path that assumes FP64 log and exp accurate to 1 ULP; on the benchmark, every scored component equals the certified rounding. Zeros (t = x t = x t = x , t − x + 1 = 0 t - x + 1 = 0 t − x + 1 = 0 , G = 0 G = 0 G = 0 ) are decided exactly.
Results on the frozen data
Table 22.
Subnormal gradients. For 233 FP16 vectors with subnormal reference gradients, componentwise correct rounding improves relative L 2 L_2 L 2 error but can reduce cosine similarity. All corresponding components are correctly rounded.
Comparison methods. Evaluating the repaired formulas in FP32 for FP16 inputs fully repairs 7 of 10 forward cells; evaluating them in the input precision repairs 4 of 20 forward and 0 of 20 backward cells completely, because correct rounding is lost and FP16 subnormal results are rounded twice. This is why the strict method computes in FP64.
Cost and scope. The reference implementation is 28–48× slower on CPU (B = 64 B = 64 B = 64 , K = 1024 K = 1024 K = 1024 ); Table 8 reports CPU and GPU costs, reaching 222× for larger inputs. The full benchmark was repeated on an A100 with identical correctly rounded component counts (Appendix § 10 ).
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.
What the operator repair does not do. In the distillation experiment (§ 4.3 ), replacing F.kl_div alone gives bit-identical training trajectories; the spurious gradient arises in log_softmax backward. In the language-model experiment (§ 4.4 ), the dominant error comes from rounded probability inputs. The logits path of Equation (4) addresses both sources.
Cost of the reference implementations
Tables 7 to 9 give running times relative to the official call (forward plus backward; median of 7 repetitions, each the mean of several calls) on one A100 GPU and on four CPU threads of the same node (PyTorch 2.4.0). The node was shared with other jobs, so the CPU columns are less reliable than the GPU columns. None of the repairs has been optimised.
Closed forms. The official code and ours are both compositions of tensor operations in Python. On the GPU REWRITE costs 2.4–5.9× the official call for Exponential, Laplace, Poisson, Normal and Bernoulli, and the strict mode 3.4–12×. Gamma (7–14× and about 30×) and Beta (54–116× and about 320×) are much slower because their repairs evaluate a quadrature. Precision is not the cost: the official formulas in FP64 run at 1.0–1.1× on the GPU (1.6× for Beta at the larger size), and the overhead of the strict mode over REWRITE comes from its additional rounding and conversion steps. The cost of REWRITE is the additional arithmetic: series instead of one logarithm, all branches of a piecewise formula evaluated and then selected, double-length sums, and hand-written gradients. On CPU the factors are larger (REWRITE 2.7–22× for the five families).
Interface B. The official F.kl_div is a compiled composite; the repair is 27–59× slower on the GPU and 28–222× on CPU, growing with the number of classes. Skipping the boundary check that certifies the final rounding saves 24–31% on the GPU. The remainder is error-free arithmetic and the unfused evaluation of many small tensor operations.
Logits path. It evaluates a 16-term series in FP64 for every element. On the GPU it costs 3–10× the official call for FP32 logits and 5–22× for FP16 or BF16 logits, the latter at a vocabulary of 151,936, where the official call in FP64 is itself 4–5× slower than in half precision; one call on 512 × 151,936 BF16 logits takes 72 ms against 3.2 ms.
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.
Repetition on a GPU
Setup. All measurements of Section 3 and all repairs were repeated on one NVIDIA A100 (40 GB) with PyTorch 2.4.0+cu124, on the same frozen inputs and against the same reference values, with the scoring code of the CPU study. Interface A: the 33 configurations and sub-configurations (2,707,000 scored FP16 and 4,527,454 scored FP32 samples); the official implementation and the repairs were run on the GPU and, in the same PyTorch build, on the CPU for a bit-wise comparison. Interface B: the 20 configurations (942,200 batches, 83.9 million forward and 483.3 million backward components). The multivariate-normal repairs were evaluated on the A100 using the same frozen inputs and references; both devices showed no significant errors.
Results. Table 10 summarises the two devices; Figure 3 to Figure 6 resolve the relative error by configuration and KL interval. The official implementations fail on the GPU as they do on the CPU. For interface A the rates agree within 0.6 points for all configurations with two exceptions: Gumbel with FP16 inputs (significant-error rate 93.5% on the GPU, 66.2% on the CPU; the share with relative error ≥ 1 % \ge1\% ≥ 1% in R0 is practically the same, 73.2% and MultivariateNormal with d = 2 d = 2 d = 2 (86.6% against 88.6%). For F.kl_div with log_target=True and FP32 inputs, 28–50% of the forward and 32–34% of the backward components are not correctly rounded on the GPU, against 17–44% and 11–13% on the CPU. The opposite also occurs: with FP16 probability targets and many classes the sum of the official implementation is more accurate on the GPU (K = 1024 K = 1024 K = 1024 , KL ∈ [ 10 − 2 , 10 − 1 ) \in[10^{-2}, 10^{-1}) ∈ [ 1 0 − 2 , 1 0 − 1 ) : 10% of the samples off by ≥ 1 % \ge1\% ≥ 1% against 65% on the CPU). Ours gives no significant error for interface A on either device, and for F.kl_div the counts of correctly rounded components are the same on both devices for each of the 20 configurations.
Table 10. Official implementation and OURS on 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.
Figure 6. Interface B, FP16 inputs, as Figure 5 . Blank cells have fewer than 100 samples.
Figure 5. Interface B, FP32 inputs, region R0, batches of one row, reduction="sum". Share of samples whose output has relative error ≥ 1 % \ge1\% ≥ 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).
The devices disagree bit-wise. In the same PyTorch build, the KL value of the official interface-A implementation differs between CPU and GPU for 27.3% of the FP32 and 5.6% of the FP16 samples. For F.kl_div, 12–13% of the element-wise outputs and 33% (FP16) to 49% (FP32) of the sum outputs differ between the GPU run and the CPU run; this comparison is across the two PyTorch versions.
Table 9. Logits path: running time relative to F.kl_div on log_softmax outputs (log_target=True) in the precision of the logits. “FP64”: the same official call on logits cast to FP64.
Downstream Experiments: Details
Parameter Fitting
Protocol. Loss: kl_divergence(Geometric, Geometric), failure-count convention. Parameterisations: probs=p = σ ( θ ) p=\sigma(\theta) p = σ ( θ ) , with the logistic sigmoid σ \sigma σ , or logits=θ \theta θ . Directions: trainable first argument, KL(Geo(p p p )∥ \Vert ∥ Geo(p ∗ p^* p ∗ )), and trainable second argument. The target is rounded to the computation precision first, so the rounded value is the exact optimum. Methods: official (PyTorch 2.15.0); the repaired formula in the target precision; the repaired formula in FP64 with one rounding of loss and gradient. Optimisers: Adam, learning rate 10 − 2 10^{-2} 1 0 − 2 , 3000 steps (main); Adam 10 − 3 10^{-3} 1 0 − 3 and SGD with momentum 0.9 at 0.1, 10,000 steps (robustness). True KL by 60-digit arithmetic. CPU only.
Table 11. Parameter fitting: 12 starts per target, shared by all settings and methods (log-uniform in [p ∗ / 5 p^*/5 p ∗ /5 , min ( 5 p ∗ , 0.95 ) \min(5p^*, 0.95) min ( 5 p ∗ , 0.95 ) ]; the target is rounded once to the format of the loss). Relative deviation of the fitted p p p from the target after 3000 Adam steps (median / maximum over starts) and the largest true KL.
Further observations. With the trainable distribution in the second argument the official code usually works, but not always (fourth row). With a logit parameterisation, 3 of the 12 official FP16 runs for p ∗ = 0.001 p^* = 0.001 p ∗ = 0.001 abort with non-finite gradients. With SGD in FP16 and p ∗ = 0.001 p^* = 0.001 p ∗ = 0.001 the official loss diverges to p = 1 p = 1 p = 1 from all three tested starts (true KL 6.9). In a two-parameter version (the sum of two Geometric KLs, targets 0.01 and 0.002 in FP16, 0.01 and 0.001 in FP32; same 12-start protocol) the final true loss over 12 starts is, median / maximum, 0.074 / 0.73 (official) against 7.5 × 10 − 7 7.5 \times10^{-7} 7.5 × 1 0 − 7 / 5.2 × 10 − 6 5.2 \times10^{-6} 5.2 × 1 0 − 6 (repaired) in FP16, and 6.9 × 10 − 9 6.9 \times10^{-9} 6.9 × 1 0 − 9 / 4.9 × 10 − 7 4.9 \times10^{-7} 4.9 × 1 0 − 7 against 4.0 × 10 − 13 4.0 \times10^{-13} 4.0 × 1 0 − 13 / 8.0 × 10 − 12 8.0 \times10^{-12} 8.0 × 1 0 − 12 in FP32. On a 15 × \times × 15 grid around the region visited by the official FP16 trajectories, the official descent direction is within 25 ∘ 25^\circ 2 5 ∘ of the true one at 54% of the points and more than 90 ∘ 90^\circ 9 0 ∘ away at 5%; the official runs stall where the directions oppose. Figure 7 shows the true loss along the 12 runs.
The failure is not convergence to a biased point. In the two-parameter version (Figure 7 ), the official runs stop improving but do not stop moving: the worst one travels a path of length 0.45 in its last 500 steps for a net displacement of 0.0024, about 1.0 away from the target in logit units; after step 500, 82% of its gradients make an angle of more than 90 ∘ 90^\circ 9 0 ∘ with the true gradient (median cosine − 0.999 -0.999 − 0.999 ). Its reported loss jumps between about +3 and − 1.5 -1.5 − 1.5 while the true loss stays at 0.73, so the loss curve cannot be used for monitoring either; in three of the four combinations of precision and direction, about a third of the official training steps report a negative KL.
Limits. One or two scalar parameters, no model and no data noise, one distribution family, CPU arithmetic.
Sequential Bayesian Design
Setup. Bayesian experimental design chooses the next observation by its expected information gain, the expected KL between the posterior after the observation and the current one ([34 , 8 ] ). We take K = 10 K = 10 K = 10 Bernoulli arms with unknown rates and Beta posteriors; an arm with posterior Beta ( a , b ) \operatorname{Beta}(a,b) Beta ( a , b ) has
EIG ( a , b ) = a a + b KL ( Beta ( a + 1 , b ) ∥ Beta ( a , b ) ) + b a + b KL ( Beta ( a , b + 1 ) ∥ Beta ( a , b ) ) , \operatorname{EIG}(a,b) = \frac{a}{a+b}\operatorname{KL}\left(\operatorname{Beta}(a+1,b) \mathbin{\|} \operatorname{Beta}(a,b)\right)
+ \frac{b}{a+b}\operatorname{KL}\left(\operatorname{Beta}(a,b+1) \mathbin{\|} \operatorname{Beta}(a,b)\right), EIG ( a , b ) = a + b a KL ( Beta ( a + 1 , b ) ∥ Beta ( a , b ) ) + a + b b KL ( Beta ( a , b + 1 ) ∥ Beta ( a , b ) ) ,
and in every round the arm with the largest EIG receives the next m m m observations, for a total of 100,000. The KL is computed with the official FP32 kl_divergence(Beta, Beta) or with our rewrite, also in FP32; the reference policy uses the exact EIG. We run batch sizes m ∈ { 1 , 100 , 1000 , 10 4 } m \in\{1, 100, 1000, 10^4\} m ∈ { 1 , 100 , 1000 , 1 0 4 } from a cold start (no observations) and from a warm start (each arm already has 10 2 10^2 1 0 2 to 10 5 10^5 1 0 5 observations), with 5 seeds and the same outcomes for all policies.
Why this setting. The information gain of one more observation shrinks like the reciprocal of the number of observations already made, so the experiment itself drives the KL into the range where the closed form fails: for Beta ( n + 1 , n ) \operatorname{Beta}(n+1,n) Beta ( n + 1 , n ) against Beta ( n , n ) \operatorname{Beta}(n,n) Beta ( n , n ) the true KL is 2.5 × 10 − 4 2.5 \times10^{-4} 2.5 × 1 0 − 4 , 2.5 × 10 − 5 2.5 \times10^{-5} 2.5 × 1 0 − 5 and 2.5 × 10 − 6 2.5 \times10^{-6} 2.5 × 1 0 − 6 for n = 10 3 n = 10^3 n = 1 0 3 , 10 4 10^4 1 0 4 , 10 5 10^5 1 0 5 , and the official FP32 code returns − 1.5 × 10 − 3 -1.5 \times10^{-3} − 1.5 × 1 0 − 3 , − 5.6 × 10 − 3 -5.6 \times10^{-3} − 5.6 × 1 0 − 3 and + 0.31 +0.31 + 0.31 .
Summary of the result. With the official KL, 40–91% of the rounds choose a wrong arm in seven of the eight settings (Table 12 ), and 35–60% of the EIG values it computes there are zero or negative. With the rewrite no round is wrong in any of the 40 runs: its EIG is within a relative 4.4 × 10 − 7 4.4 \times10^{-7} 4.4 × 1 0 − 7 of the exact value, and its allocation of observations is that of the exact policy (identical in 39 runs, one observation apart in the other). The consequence for the experiment depends on the feedback. When the posterior is updated after every observation (m = 1 m = 1 m = 1 ), a wrong choice costs one observation, and the total posterior variance at the end is only 1–10% higher than with the exact policy. When a choice commits a batch, the loss can be much larger: for m = 1000 m = 1000 m = 1000 the worst arm ends with up to 2.5 times the variance, and for m = 10 4 m = 10^4 m = 1 0 4 from a warm start the total variance is 1.2 to 5.2 times and the worst arm up to 11 times that of the exact policy, because an arm with few observations is passed over in most rounds. From a cold start with m = 10 4 m = 10^4 m = 1 0 4 every round goes to an arm without observations, where the official value is accurate, and nothing changes.
Protocol. Arm rates are drawn uniformly from [ 0.05 , 0.95 ] [0.05, 0.95] [ 0.05 , 0.95 ] ; the prior is Beta ( 1 , 1 ) \operatorname{Beta}(1,1) Beta ( 1 , 1 ) , so an arm with s s s successes and f f f failures has the posterior Beta ( 1 + s , 1 + f ) \operatorname{Beta}(1+s,1+f) Beta ( 1 + s , 1 + f ) . In the warm start arm k k k has round( 10 y k ) (10^y k) ( 1 0 y k ) earlier observations with y k y_k y k drawn uniformly from [ 2 , 5 ] [2,5] [ 2 , 5 ] . The outcome of the j j j -th observation of an arm is the same for all policies, and ties are broken by the lowest index. The policies differ only in the two KL values of the EIG: torch.distributions.kl_divergence(Beta, Beta) in FP32 (official), the rewrite of Appendix B evaluated in FP32 (ours), and the identity KL ( Beta ( a + 1 , b ) ∥ Beta ( a , b ) ) = log a + b a + ψ ( a + 1 ) − ψ ( a + b + 1 ) \operatorname{KL}(\operatorname{Beta}(a+1,b) \mathbin{\|} \operatorname{Beta}(a,b)) = \log\frac{a+b}{a} + \psi(a+1) - \psi(a+b+1) KL ( Beta ( a + 1 , b ) ∥ Beta ( a , b )) = log a a + b + ψ ( a + 1 ) − ψ ( a + b + 1 ) , with the digamma function ψ \psi ψ , in FP64 (exact), which agrees with 60-digit arithmetic to 1.1 × 10 − 8 1.1 \times10^{-8} 1.1 × 1 0 − 8 on posteriors with up to 5 × 10 6 5 \times10^{6} 5 × 1 0 6 observations. The weights a / ( a + b ) a/(a+b) a / ( a + b ) and b / ( a + b ) b/(a+b) b / ( a + b ) and the combination are computed in FP32 for the official code and for ours. A round counts as wrong if the exact EIG of the chosen arm is below ( 1 − 10 − 3 ) (1 - 10^{-3}) ( 1 − 1 0 − 3 ) times the largest exact EIG. The posterior variance of an arm rate is a b / ( ( a + b ) 2 ( a + b + 1 ) ) ab/((a+b)^2(a+b+1)) ab / (( a + b ) 2 ( a + b + 1 )) , the expected squared error of its estimate.
Results. Table 12 lists all settings. From a cold start with m = 1 m = 1 m = 1 the first wrong choice occurs after about 380 observations, that is, when each arm has about 38; from then on the share of wrong rounds grows, and the observations per arm at the end range from 8,308 to 16,176 instead of 9,998 to 10,001. The EIG computed by the official code is off by factors of up to 3 × 10 4 3 \times10^{4} 3 × 1 0 4 ; that of the rewrite by at most 4.4 × 10 − 7 4.4 \times10^{-7} 4.4 × 1 0 − 7 in relative terms. Evaluating the rewrite in FP64 and rounding once (strict mode) gives the same choices as the FP32 rewrite in the m = 1 m = 1 m = 1 runs. The outcome is sensitive to which rounds go wrong: for the warm start with m = 10 4 m = 10^{4} m = 1 0 4 the ratio of the total variance is 1.17, 1.19, 1.22, 2.55 and 5.16 in the five seeds, and in the last one an arm that starts with 576 observations receives none of the ten batches, while the exact policy gives it 10,000.
Limits. Simulated Bernoulli arms, one acquisition rule (the arm with the largest one-step EIG), K = 10 K = 10 K = 10 , five seeds. For m = 1 m = 1 m = 1 the effect on the final variance is small, and for the cold start with m = 10 4 m = 10^{4} m = 1 0 4 the official code makes no wrong choice. Only the Beta closed form is exercised.
Identical-Start Distillation
Protocol. Teacher and student: MLP 32 → \to → 256 → V \to V → V with identical weights (seeded); inputs: fixed random batches; loss: forward KL of the output distributions, mean over the batch; 300 steps; metrics at the last step: top-1 disagreement with the teacher, exact KL (FP64), relative weight change. Grid: V ∈ { 1024 , 32768 , 151936 } × { F P 32 , F P 16 , B F 16 } × { A d a m 10 − 4 , 3 × 10 − 4 , 10 − 3 , 3 × 10 − 3 , 10 − 2 } V \in\{1024, 32768, 151936\} \times\{\mathrm{FP32}, \mathrm{FP16}, \mathrm{BF16}\} \times\{\mathrm{Adam}\ 10^{-4}, 3 \times10^{-4}, 10^{-3}, 3 \times10^{-3}, 10^{-2}\} V ∈ { 1024 , 32768 , 151936 } × { FP32 , FP16 , BF16 } × { Adam 1 0 − 4 , 3 × 1 0 − 4 , 1 0 − 3 , 3 × 1 0 − 3 , 1 0 − 2 } ; SGD 0.01 0.01 0.01 , 0.1 0.1 0.1 , 1 } × 4 1\} \times4 1 } × 4 losses × 10 \times10 × 10 seeds = 2 , 880 = 2,880 = 2 , 880 runs on one A100 GPU (PyTorch 2.4.0). Adam uses the default β = ( 0.9 , 0.999 ) \beta= (0.9, 0.999) β = ( 0.9 , 0.999 ) and ϵ = 10 − 8 \epsilon= 10^{-8} ϵ = 1 0 − 8 . Weights, optimiser state and the forward pass of both networks are FP32; the logits are cast to the stated format, in which the loss and the start of the backward pass are computed, without autocast or gradient scaling. All runs completed; none was non-finite; 740 runs repeated in an independent execution are bit-identical.
Complete results. Figure 8 plots Table 2 . Under Adam all 27 curves (3 vocabularies × \times × 3 precisions × \times × 3 official variants) increase strictly with the learning rate. In the 45 Adam comparisons between V = 1024 V = 1024 V = 1024 and V = 151,936 V = 151{,}936 V = 151 , 936 the larger vocabulary is always worse; between V = 32,768 V = 32{,}768 V = 32 , 768 and 151,936 three comparisons are reversed (two FP32, one BF16), within the seed range. Under SGD the largest median is 2.1% (V = 151,936 V = 151{,}936 V = 151 , 936 , FP16, learning rate 1). 24.4% of the official runs report a negative loss at step 0 (e.g. median − 1.7 × 10 − 8 -1.7 \times10^{-8} − 1.7 × 1 0 − 8 for V = 151,936 V = 151{,}936 V = 151 , 936 , FP32). The median initial gradient norm of the official F.kl_div loss is 4 4 4 –5 × 10 − 8 5 \times10^{-8} 5 × 1 0 − 8 in FP32, 2 × 10 − 4 2 \times10^{-4} 2 × 1 0 − 4 to 1.6 × 10 − 2 1.6 \times10^{-2} 1.6 × 1 0 − 2 in FP16 and about 1.5 × 10 − 3 1.5 \times10^{-3} 1.5 × 1 0 − 3 in BF16.
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).
Limits. Synthetic MLP, identical initialisation, 300 steps. The logits path in BF16 is exploratory (BF16 is not covered by the certified evaluation).
KL in Language Models
Models. Qwen2.5-1.5B-Instruct, FP16 forward pass; perplexity of the original model 11.66 on the 16,384 selection tokens. Quantized versions and their perplexity: RTN 8-bit per channel 11.68; GPTQ 8-bit 11.67; AWQ 4-bit 12.74; GPTQ 4-bit 13.32; RTN 4-bit (group 128) 13.23; RTN 3-bit (group 128) 31.14. Published GPTQ/AWQ weights were dequantized to FP16 and run through ordinary linear layers. Only the KL computation changes precision.
Table 13. Language models, Part A. Reported mean KL (batchmean) and its deviation from the FP64 reference. “inf”: the reported value is infinite.
Part A, further observations. For the 4- and 3-bit models, whose KL is 0.1–1 nat, all finite methods agree with the reference within 0.1%. The six models are far apart compared with these errors (the closest pair, GPTQ and RTN at 4 bits, differs by 15%). The repaired F.kl_div reduces the share of tokens with operator error ≥ 1 % \ge1\% ≥ 1% from 97.6 / 95.5% to 0.3 / 0.1%, while 98.8 / 96.8% of the tokens have input-representation error ≥ 1 % \ge1\% ≥ 1% ; the logits path has no input-representation error. Casting the FP16 logits to BF16 before computing the KL changes the divergence itself (reported values off by 31–124% at 8 bits for every method, including the logits path, which is then correctly rounded for the BF16 logits): the KL should be computed from the logits in the precision in which the model produced them. All 15 model pairs are ordered correctly by every finite method except FP16 reduction="mean", which reports both 8-bit models as 0 (a tie). The references use a cancellation-free formula in FP64, and the logits path reproduces the reference mean to four digits. The official Categorical KL is infinite because it treats an underflowed zero in Q Q Q as a true zero.
Table 14. *All of these tokens have exact KL ≤ 2.8 × 10 − 6 \leq2.8 \times10^{-6} ≤ 2.8 × 1 0 − 6 , below the smallest normal FP16 number; they are correctly rounded.
Table 15. Language models, Part B. Ranking of 28 single-layer quantizations: strict inversions among 378 pairs / reported ties, and Kendall’s τ b \tau_b τ b against the reference.
Part B, decisions. At 4 bits, where single-layer divergences are two orders of magnitude larger, inversions are rare (1–2 pairs in FP16 with batchmean). A decision counts as harmful if the mixed model has a higher true KL on a disjoint 4,096-token evaluation set. The reference protects layers { 0 , 1 , 2 , 3 , 5 , 19 , 26 , 27 } \{0, 1, 2, 3, 5, 19, 26, 27\} { 0 , 1 , 2 , 3 , 5 , 19 , 26 , 27 } for 8 bits and k = 8 k = 8 k = 8 . Official log_target FP16, the official F.kl div forms in BF16 and the BF16 logits path select layer 25 instead of layer 5; the reference KL of layers 5, 23 and 25 is ( 5.787 , 5.759 , 5.474 ) × 10 − 5 (5.787, 5.759, 5.474) \times10^{-5} ( 5.787 , 5.759 , 5.474 ) × 1 0 − 5 , and the resulting mixed model has 0.25% lower true KL on the disjoint evaluation set (+0.87% on the selection set). Categorical BF16 selects { 1 , 2 , 6 , 9 , 15 , 22 , 26 , 27 } \{1, 2, 6, 9, 15, 22, 26, 27\} { 1 , 2 , 6 , 9 , 15 , 22 , 26 , 27 } (four wrong layers): +9.78% true KL on the evaluation set, +15.31% on the selection set, perplexity difference −0.009. All rankable methods agree with the reference for 8 bits with k = 4 k = 4 k = 4 and for 4 bits with k ∈ { 4 , 8 } k \in\{4, 8\} k ∈ { 4 , 8 } . The reported per-layer mean of the official FP16 F.kl div deviates from the reference by −233% to −32% at 8 bits (24 layers negative) and by −3.5% to −0.3% at 4 bits; the logits path by ±0.02%.
Limits. One model, one dataset, round-to-nearest quantizers, two values of k k k ; references are FP64 (not interval-certified), spot-checked at 150 digits. The most common official configuration, FP16 F.kl div with batchmean, still selects the correct layers, and perplexity differences are within ±0.01 throughout.
Part C, protocol. Qwen2.5-1.5B-Instruct with the default (sdpa) attention implementation of transformers; WikiText-2 training text; nothing is trained. Executions. For each of FP32, FP16 and BF16 the same weights are run in four ways: one full forward pass with batch size 8 (the reference execution), batch size 1, token-by-token decoding with a key–value cache (what a rollout engine does), and the eager attention implementation; 8 × 256 = 2,048 8 \times256 = 2{,}048 8 × 256 = 2 , 048 positions. Each alternative is compared with the reference execution of the same precision, and the three reference executions with each other. The official calls are evaluated in the precision of the model (in FP32 for pairs of different precisions), 128 rows per call, batchmean; the sampled estimators use tokens drawn from the first execution and FP32 log-probabilities, as the RL fine-tuning frameworks we inspected do (k3_k1 of verl, the KL estimators of OpenRLHF). Reproducibility. The logits of the model and of five round-to-nearest copies (8, 7, 6 and 5 bits per output channel, 4 bits with group size 128) are computed once on 8 × 512 = 4,096 8 \times512 = 4{,}096 8 × 512 = 4 , 096 positions in FP16 and in BF16. The mean KL is then computed under settings that cannot change its value: 1, 16, 128, 512 or all rows per call; five reductions (batchmean, sum divided by the rows, mean times V V V , none summed in the same precision or in FP32); two random row orders; CPU instead of GPU.
Part C, results. Table 16 lists all pairs. The gap between two executions grows with the coarseness of the precision (about 10 − 10 10^{-10} 1 0 − 10 , 2 × 10 − 5 2 \times10^{-5} 2 × 1 0 − 5 and 10 − 3 10^{-3} 1 0 − 3 ), and in each precision the official KL of that precision cannot measure it; computed one precision higher, the official calls agree with the reference (within 0.1% in FP32 for the FP16 and BF16 pairs, within 10 − 6 10^{-6} 1 0 − 6 in FP64 for all pairs). In BF16 the most likely token differs at 1.9% of the positions between cached decoding and the full forward pass. Table 17 shows the dependence on the batch size: with mean the result is of the order of K L / V \mathrm{KL}/V KL / V , which is subnormal or zero in FP16, so that the reported value depends on how many rows are averaged at once; the same underflow makes FP16 mean report zero for all layers in Part B. With the other reductions the official value is stable over batch sizes, row orders and devices, with a bias of up to 5% for the 8-bit copy; log_target behaves like the probability target; the FP16 Categorical KL is non-finite in all 17 settings. With a BF16 forward pass the official values vary by at most 3.6% and are off by at most 6.2%. The logits path varies by at most 0.41% and is off by at most 0.33% in every setting of both precisions. The order of the five copies is correct in every setting that returns finite values.
Table 16. Language models, Part C: relative error (%) of the mean KL between two executions of the same weights. Rows with one precision: the named execution against the full forward pass with batch size 8, KL computed in that precision; rows with two precisions: KL computed in FP32. Last column: sampled estimator e x − x − 1 expm1 ( x ) − x \frac{e^x-x-1}{\operatorname{expm1}(x)-x} expm1 ( x ) − x e x − x − 1 , with x x x the log-probability ratio of the two executions at a sampled token, in FP32, relative to the same estimator in FP64.
Table 17. Language models, Part C: reported KL as a percentage of the truth, FP16, official F.kl div with a probability target. Columns 3–7: reduction="mean" for different numbers of rows per call; column 8: range over all 27 settings with another reduction; column 9: range of the logits path over its 12 settings.
Part C, limits. One model, one text, a single run. The executions are variants within one framework, not a rollout engine against a training framework. The FP32 gap of about 10 − 10 10^{-10} 1 0 − 10 has no practical consequence. The dependence on the batch size is confined to FP16 with reduction="mean". The FP16 forward pass with eager attention is non-finite at every position for this model, so that pair is omitted.
Part D, protocol. auto-circuit 1.0.1 ([39 ] ), unmodified, with transformer-lens 2.4.0; models without weight processing; the prompts shipped with the library; first batch, last token position; factorised graph with separate query, key and value inputs. The settings are IOI ([58 ] ) on GPT-2 small (batch of 64, 32,491 edges) and on GPT-2 medium (batch of 64; 29,999 of 231,877 edges, sampled at random with the same fraction from each of the 97 destination modules), Greater-than ([16 ] ) on GPT-2 small (batch of 64, 32,491 edges), and Docstring ([17 ] ) on the 4-layer attention-only model of that study (batch of 128, 1,281 edges, V = 48 , 262 V = 48,262 V = 48 , 262 ).
The loop is the library’s ACDC loop (Conmy et al. [9 ] ) (same ablation tensors, patch mode, forward call and output slice) with one change: every edge is restored after it has been scored, so that the scores are independent of each other. For each edge we record, on the same output logits, the library’s score (F.kl_div with log_target, reduction="sum", divided by the number of rows, in the precision of the model), the logits path, and as the reference the KL of the two logit tensors evaluated in FP64. A score counts as wrong if it is negative or deviates from the reference by more than 10%. BF16 was run for the first setting only. The edge counts in Table 5 and Table 18 are the edges with a positive reference score (32,477, 32,477, 1,272 and 29,999 of the 32,491, 32,491, 1,281 and 29,999 edges; 32,476 for Greater-than in FP16); the others have a reference of exactly zero.
Table 18. Language models, Part D, all settings. “Wrong”: negative or more than 10% from the FP64 KL of the same logits, among the edges with a positive reference. “Selected differently”: edges whose decision score ≥ τ \ge\tau ≥ τ differs from the reference’s. Spearman and top-k k k overlap are with the reference ranking of the same model; the Docstring model has fewer than 5,000 edges.
Part D, results. Table 18 lists all settings. FP32. The errors are confined to small scores. On GPT-2 small with IOI the median reference score is 8.8 × 10 − 7 8.8 \times10^{-7} 8.8 × 1 0 − 7 , and the library’s score is wrong for 73% of the edges between 10 − 8 10^{-8} 1 0 − 8 and 10 − 7 10^{-7} 1 0 − 7 , for at least 97% below 10 − 8 10^{-8} 1 0 − 8 , for 9% between 10 − 7 10^{-7} 1 0 − 7 and 10 − 6 10^{-6} 1 0 − 6 and for none above; the other GPT-2 settings show the same profile with smaller medians (8.8 × 10 − 8 8.8 \times10^{-8} 8.8 × 1 0 − 8 for Greater-than, 3.0 × 10 − 8 3.0 \times10^{-8} 3.0 × 1 0 − 8 on GPT-2 medium) and correspondingly more wrong scores. With the library’s thresholds τ = 10 − 6 , 10 − 5 , 10 − 4 , 10 − 3 \tau= 10^{-6}, 10^{-5}, 10^{-4}, 10^{-3} τ = 1 0 − 6 , 1 0 − 5 , 1 0 − 4 , 1 0 − 3 the numbers of edges selected differently are 84, 7, 0, 0 (IOI, small), 25, 1, 0, 0 (Greater-than) and 23, 1, 0, 0 (IOI, medium), and the 1,000 highest-scoring edges are the same in every setting. The relative error of the logits path has a median of about 2 × 10 − 8 2 \times10^{-8} 2 × 1 0 − 8 and a 95th percentile of at most 3.6 × 10 − 7 3.6 \times10^{-7} 3.6 × 1 0 − 7 . On the Docstring model the median score is 1.9 × 10 − 4 1.9 \times10^{-4} 1.9 × 1 0 − 4 and only 30 of 1,272 scores are wrong. FP16. The median relative error of the library’s score is 24% (IOI, small), 3% (Greater-than), 12% (Docstring) and 28% (IOI, medium). On GPT-2 medium the threshold τ = 10 − 4 \tau= 10^{-4} τ = 1 0 − 4 selects 17,192 edges by the reference and 9,829 edges are decided differently by the library’s score, 3 by the logits path. On GPT-2 small with IOI the library’s score is wrong for 341 of the 739 edges of the published circuit (Wang et al. [58 ] ). The logits path is wrong for 5 and 2 edges in two settings; these have a reference below 10 − 7 10^{-7} 1 0 − 7 , where FP16 has at most one significant bit (its smallest positive number is 6 × 10 − 8 6 \times10^{-8} 6 × 1 0 − 8 ), and the same value rounded to FP32 instead is wrong for none. BF16 (IOI, small). The library’s score is wrong for 2.5% of the edges.
Part D, limits. One batch and a single run per setting; GPT-2 medium is a 13% sample of its edges. In FP32, threshold decisions change, but the top 1,000 edges are unchanged. That the larger model is affected more rests on one pair of models on one task. Half-precision scores on the GPT-2 models are mostly noise of the forward pass (median 2.1 × 10 − 4 2.1 \times10^{-4} 2.1 × 1 0 − 4 in FP16 against 8.8 × 10 − 7 8.8 \times10^{-7} 8.8 × 1 0 − 7 in FP32 for IOI on GPT-2 small): the logits path recovers the score of the half-precision model, not that of the FP32 model, whose ranking the FP16 reference itself reproduces only with a Spearman correlation of 0.63 (IOI, small), 0.63 (Greater-than) and 0.39 (IOI, medium); for the Docstring model it is 0.999. With the library’s sequential ACDC (three KL computations, GPT-2 small, IOI) the logits path did not bring the half-precision circuits measurably closer to the FP32 circuit (at most 3.3% more edges in agreement), because each decision changes all later ones, so that two accurate KL computations differ from each other by as many edges as either differs from the library’s, and because in BF16 the forward pass, not the KL, decides the circuit (over 99.9% of the edges are kept for τ ≤ 10 − 4 \tau\le10^{-4} τ ≤ 1 0 − 4 with every KL computation).
Use of the Interfaces, User Reports, and Settings Without a Measurable Effect
This appendix collects material that bounds the practical reach of the errors from both sides: where the two interfaces are called (Appendix § 12 .§ 1 ), earlier reports of the same failure by users (Appendix § 12 .§ 1.1 ), and the settings we tested in which replacing the official KL changed nothing measurable (Appendix § 12 .§ 2 ). The experiments of Appendix § 12 .§ 2 are exploratory.
Call sites in PyTorch-based libraries
We downloaded the current release of 116 PyTorch-based packages from PyPI on 14 November 2026 and searched their Python sources, excluding tests, documentation and examples, for calls of torch.distributions.kl_divergence (interface A) and of F.kl_div or nn.KLDivLoss (interface B). A call was counted only if the name resolves to PyTorch in that file; functions of the same name that a package defines for itself were not counted. Interface A is referenced in 20 packages and interface B in 22; 39 packages use at least one (Table 19 ). The packages were chosen by us from reinforcement learning, probabilistic modelling, distillation, speech, compression, interpretability, robustness and uncertainty estimation. Whether a call is affected depends on how close its two distributions are and on the precision. The call sites whose two arguments are close by construction are those that compare a policy before and after an update (cleanrl, garage, pfrl, rsl-rl-lib, skrl, stable-baselines3 with sb3-contrib, tianshou, torchrl), a student with its teacher, or a model with an ablated or perturbed copy of itself (auto-circuit, sae-lens, inseq, easyeditor, the adversarial-training code of adversarial-robustness-toolbox and torchattacks). The metric module of auto-circuit clamps its KL at zero with the comment that numerical errors can cause tiny negative values.
Table 19. Packages (of 116 inspected) whose non-test code calls interface A (kl_divergence) or interface B (F.kl_div, KLDivLoss): number of source files with at least one call. The use is our reading of the calling files. sb3-contrib 2.9.2 (TRPO) calls interface A through the helper of stable-baselines3 and is not counted separately.
Earlier user reports
The failure for nearly identical distributions has been reported repeatedly by users. We found five reports between 2019 and 2023 by searching the PyTorch issue tracker and forum.
Forum thread 48470 (2019): the Categorical KL of two close distributions is negative (− 1.65 × 10 − 8 -1.65 \times10^{-8} − 1.65 × 1 0 − 8 ), and the probs and logits parameterisations disagree. https://discuss.pytorch.org/t/48470
Issue 32520 (2020): F.kl_div is negative, or non-zero where it should be zero. It was closed when the log-target flag was added in version 1.6. https://github.com/pytorch/pytorch/issues/32520
Issue 80488 (2022): F.kl_div is still negative after that change. The answer was that this is numerical error, that removing it in the core would cost performance, and that the result can be clamped. https://github.com/pytorch/pytorch/issues/80488
Forum thread 149312 (2022): under automatic mixed precision the Categorical KL is negative in more than 40% of the cases (under 1% without); in the example the true value is 4.1 × 10 − 6 4.1 \times10^{-6} 4.1 × 1 0 − 6 , the FP16 Categorical KL − 8.79 × 10 − 4 -8.79 \times10^{-4} − 8.79 × 1 0 − 4 and the FP16 F.kl_div − 1.52 × 10 − 4 -1.52 \times10^{-4} − 1.52 × 1 0 − 4 . https://discuss.pytorch.org/t/149312
Forum thread 166383 (2023): F.kl_div is negative for nearly equal outputs; the answer was that this is expected floating-point error and that the result can be clamped. https://discuss.pytorch.org/t/166383
Clamping removes negative outputs but cannot recover the true divergence or its gradient. It also leaves inaccurate positive values unchanged. Reports of a different kind (overflow for extreme parameters, masked classes, logic errors) are not listed.
Settings in which we measured no effect
The experiments of § 4 show where the errors change an outcome. In none of the settings below did the choice of KL implementation change the outcome beyond the run-to-run spread (Table 20 ).
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.
Distillation of an LLM from a nearby start. We copied the loss of the generalised knowledge distillation trainer of TRL ([56 ] (log-softmax followed by F.kl_div with log_target) and trained a Qwen2.5-1.5B student towards the original model for 320 steps (AdamW with β = ( 0.9 , 0.999 ) \beta= (0.9, 0.999) β = ( 0.9 , 0.999 ) , eps = 10 − 8 \operatorname{eps} = 10^{-8} eps = 1 0 − 8 and no weight decay, learning rate 2 × 10 − 5 2 \times10^{-5} 2 × 1 0 − 5 , 10 seeds that fix the data order), with BF16 logits as a DeepSpeed launch would produce them, with logits cast to FP32, and with the logits path. From an identical start the result of § 4.3 carries over to the LLM: with either official variant the student ends at an eval KL of about 0.10 (0.097–0.103 over the 10 seeds) with 13% top-1 disagreement, while with the logits path no weight changes in any seed. From the two nearby starts (round-to-nearest copies at 8 and 4 bits, eval KL 0.025 and 0.22) the three losses are indistinguishable: the median paired difference of the final eval KL between the logits path and the BF16 loss is +1.4% (95% bootstrap interval −1.7% to +3.0%; 4 wins in 10) and −0.3% (−1.4% to +1.4%; 6 wins in 10), against a median seed-to-seed difference of 2.8% and 1.9% for a fixed loss. The loss reported by the BF16 variant is off by 0.11% in the median, and its parameter gradient has a cosine of 0.998 with the exact one. The 8-bit student also ends further from the teacher than it started (0.10 against 0.025) with every loss.
LoRA. With rank-16 adapters (Hu et al. (2022)) at learning rates 10 − 4 10^{-4} 1 0 − 4 and 3 × 10 − 4 3 \times10^{-4} 3 × 1 0 − 4 (3 seeds) the picture is the same: from an identical start the official losses move the student to a median eval KL of 0.025–0.037 and the logits path leaves the adapter exactly at zero, while from the two quantized starts and for a task loss with a KL anchor to the base model the paths differ by less than the seeds do, without a consistent sign. Two stronger constraints were also tested: a KL-only objective from a slightly perturbed adapter (start KL 1.5 × 10 − 3 1.5 \times10^{-3} 1.5 × 1 0 − 3 to 1.2 × 10 − 2 1.2 \times10^{-2} 1.2 × 1 0 − 2 , so that a KL of zero is reachable), and a task loss with the KL weighted by 10, 100 and 1000. In all 21 cells (7 tasks, 3 KL paths) the median final eval KL lies between 0.018 and 0.041 (single runs: 0.006 to 0.045), above the start, whatever the KL path; in particular the logits path does not return to the start either.
Policy optimisation. Libraries for PPO and TRPO compare the policy before and after an update with interface A, in FP32. (a) For the rule of rsl-rl-lib that raises or lowers the learning rate when the KL leaves [ d / 2 , 2 d ] [d/2, 2d] [ d /2 , 2 d ] with d = 0.01 d = 0.01 d = 0.01 , a simulation with the Beta policy of that library predicted changed decisions for large concentration parameters and a KL far below the target (up to 90 of 200 decisions). In real training runs with the unmodified library (a reaching task with 12 actions, two configurations, 8,000 decisions each) no decision differs from the one taken with an FP64 KL. (b) For synthetic categorical policies with 6 to 50,000 actions and a true KL between 2 × 10 − 3 2 \times10^{-3} 2 × 1 0 − 3 and 5 × 10 − 2 5 \times10^{-2} 5 × 1 0 − 2 , the official FP32 KL is within a relative 2.5 × 10 − 5 2.5 \times10^{-5} 2.5 × 1 0 − 5 of the truth and changes none of 960 threshold decisions. (c) The Fisher-vector product that TRPO obtains by differentiating the official KL twice at the old policy agrees with the exact Fisher matrix to 3.3 × 10 − 7 3.3 \times10^{-7} 3.3 × 1 0 − 7 (categorical) and 7.9 × 10 − 8 7.9 \times10^{-8} 7.9 × 1 0 − 8 (diagonal normal). (d) On LLM logits, the sampled estimators that RL fine-tuning frameworks log and penalise ([48 , 51 ] ), evaluated on FP32 log-probabilities as these frameworks do, have a batch mean within a relative 7.8 × 10 − 6 7.8 \times10^{-6} 7.8 × 1 0 − 6 of the exact value for a true KL of 10 − 3 10^{-3} 1 0 − 3 to 1.4 × 10 − 2 1.4 \times10^{-2} 1.4 × 1 0 − 2 .
Entropy calibration. Post-training quantization tools choose a clipping threshold by minimising a KL between histograms. On four synthetic activation distributions the threshold chosen with the official FP32 KL equals the one chosen in FP64 in all 24 trials (minimum KL 10 − 4 10^{-4} 1 0 − 4 to 2 × 10 − 3 2 \times10^{-3} 2 × 1 0 − 3 ).
Sequential circuit discovery. See the limits of Part D in Appendix § 11 .
Why the intuition fails. Three mechanisms explain these outcomes, and they also describe where an effect should not be expected. First , the spurious part of the gradient is absolute, not relative: once student and teacher differ, the true gradient is orders of magnitude larger and the two cannot be told apart in the result. The identical start is the only training setting we found in which the spurious part is all there is. Second , two BF16 executions that are not bitwise identical are apart by a KL of about 10 − 3 10^{-3} 1 0 − 3 or more (Table 4 ), and trained students remain at an eval KL of 0.02–0.1 with every loss. The error region of the official KL lies below that floor. Third , algorithms that control a KL in a closed loop hold it near their target (about 10 − 2 10^{-2} 1 0 − 2 for PPO-type rules), again above the region in which FP32 closed forms fail; the failures of the official code start where the KL is several orders of magnitude below the working point. The sequential design of § 4.2 is a closed loop of the opposite kind: there the information gain falls as the data accumulate, so the loop itself moves the KL into the failing range. The errors therefore matter where the KL value is the product (evaluation of near-lossless changes, monitoring, rankings and thresholds on small divergences; § 4.2 and § 4.4 ) or where the distributions are identical or nearly so by construction (§ 4.1 and § 4.3 ), and we found no case in which they change the result of ordinary training from a start that is already some distance away.
Extended Related Work
Softmax, cross-entropy and soft targets. The work closest to ours is that of Barron et al. [2 ] , who identify two bugs in standard softmax/cross-entropy code: Softmax Collapse , first diagnosed by Prieto et al. [46 ] in the context of grokking, and Softmax Cancellation , a non-zero gradient for identical student and teacher logits; they give fused implementations in JAX (Bradbury et al. [5 ] ) and show that the fix stops distillation drift. Our distillation experiment (§ 4.3 ) observes the same drift independently and our logits path is closely related to their soft-target loss. The two papers are otherwise complementary: they treat the categorical soft-target loss and its training dynamics; we measure and repair the KL interfaces themselves, across 18 families, with certified ground truth, separate the operator error of F.kl_div from the input-representation error, and study evaluation and decision making as well as training. More broadly, a line of work traces an occasional training failure to one floating-point mechanism: absorption in the softmax (Prieto et al. [46 ] ), the representation limits of hyperbolic embeddings (Mishne et al. [40 ] ), and instabilities of low-precision training of large models (Wortsman et al. (2023)). We follow the same approach for the KL divergence, with the difference that the failure we study is mostly silent. Blanchard et al. [4 ] analyse the rounding error of the log-sum-exp and softmax function values; our results concern second-order quantities built from two such evaluations, which those bounds do not cover.
Numerical analysis. Our tools are standard: the rounding-error model and running error bounds of Higham [19 ] , Sterbenz’s lemma (Sterbenz [54 ] ), error-free transformations and double-length arithmetic (Knuth [31 ] ; Dekker [10 ] ; Shewchuk [52 ] ; Ogita et al. [43 ] ; Muller et al. [41 ] ), compensated summation (Kahan [25 ] ), and Ziv’s strategy for correct rounding (Ziv [67 ] ), also used by correctly rounded mathematical libraries (Sibidanov et al. [53 ] ); ground truth relies on ball arithmetic (Johansson [24 ] ). Herbie (Panchekha et al. [44 ] ) searches for accurate rewrites automatically; the rewrites needed here go beyond local algebraic rewriting and must also deliver gradients.
Numerical defects in deep-learning software. Empirical studies catalogue numerical bugs in TensorFlow and PyTorch programs (Zhang et al. [65 ] ; Humbatova et al. [22 ] ; Wang et al. [57 ] ) and in the libraries themselves (Kloberdanz et al. [30 ] ), and tools detect NaN/Inf-producing operations statically or by gradient-guided search (Zhang et al. [66 ] ; Yan et al. [61 ] ). These works focus on exceptional values. Most of the errors we measure are silent: finite, plausible, and wrong. Other probabilistic programming systems have similar KL registries (Dillon et al. [11 ] ; Bingham et al. [3 ] ; Carpenter et al. [7 ] ).
Low-precision training and inference. Mixed-precision training (Micikevicius et al. [38 ] ) and BF16 (Kalamar et al. [26 ] ; Zamirai et al. [64 ] ) are now defaults for large models. Qi et al. (2025) trace the training–inference mismatch in reinforcement-learning fine-tuning of language models to BF16 rounding and recommend FP16; Yuan et al. [63 ] show that limited precision makes model outputs depend on batch size and hardware. Part C of § 4.4 measures such gaps exactly.
Where the KL is used. The KL between close distributions is the object of interest in trust-region and proximal policy optimisation (Schulman et al. [49 , 50 ] ), where sample-based estimators are also common (Schulman [48 ] ; Shao et al. [51 ] ); in variational autoencoders and their variants (Kingma & Welling [29 ] ; Higgins et al. [18 ] ; Loaiza-Ganem & Cunningham [36 ] ); in knowledge distillation (Hinton et al. [20 ] ; Kim et al. [27 ] ), including distillation of language models (Agarwal et al. [1 ] ; Gu et al. (2024)); in circuit discovery (Conmy et al. [9 ] ); and in model compression, both as a recovery loss for quantized models (Liu et al. [35 ] ; Xin et al. [60 ] ) and as a sensitivity metric for mixed-precision assignment (Dong et al. [12 ] ; Cai et al. [6 ] ; Nagel et al. [42 ] ).
Additional Details for Sections 1, 3 and 4
This section gives the full versions of passages that are stated briefly in § 1 , § 2 and § 3 .
Data. Interface A covers 18 distribution-specific same-family KL implementations. We exclude five generic or delegated registrations: ExponentialFamily, HalfNormal, Independent, OneHotCategorical, and TransformedDistribution. The 23 configurations include both parameterisations where applicable, categorical dimensions K ∈ { 2 , 4 , 16 } K \in\{2, 4, 16\} K ∈ { 2 , 4 , 16 } , and multivariate dimensions d ∈ { 2 , 4 } d \in\{2, 4\} d ∈ { 2 , 4 } with ranks r ∈ { 1 , 2 } r \in\{1, 2\} r ∈ { 1 , 2 } . For each configuration we draw P P P from an ordinary parameter region R0 and from stress regions (very large or small parameters, probabilities near 0 or 1), and construct Q Q Q so that the true KL( P ∥ Q ) (P\mathbin{\|}Q) ( P ∥ Q ) falls in a prescribed decade: one control bin [ 10 − 1 , 1 ) [10^{-1}, 1) [ 1 0 − 1 , 1 ) and 14 bins down to [ 10 − 15 , 10 − 14 ) [10^{-15}, 10^{-14}) [ 1 0 − 15 , 1 0 − 14 ) . Two further groups contain pairs whose parameters differ by 1–8 ULP, and identical pairs P = Q P = Q P = Q . Parameters are stored in the target format first, so that the truth refers to the bit patterns the library actually receives. Cells that the floating-point grid cannot populate (mostly FP16 pairs in the smallest KL bins, where rounding Q Q Q makes it identical to P P P ) stay empty and are reported as such. This gives 7,542,469 samples (3.0M FP16, 4.5M FP32). For interface B we generate 942,200 batches over log_target ∈ { F a l s e , T r u e } \in\{\mathrm{False}, \mathrm{True}\} ∈ { False , True } , FP16/FP32, K ∈ { 2 , 4 , 16 , 256 , 1024 } K \in\{2, 4, 16, 256, 1024\} K ∈ { 2 , 4 , 16 , 256 , 1024 } , batch sizes 1 and 8, and all four reductions, from logits stratified in the same way.
Ground truth. For every sample, the exact KL and every gradient component are enclosed with Arb ball arithmetic Johansson, [24 ] tightly enough that the enclosure determines a unique correctly rounded value in the target format; samples that cannot be certified are excluded and counted. Truth and output are always compared in the same format. For interface B, an independent cross-check with mpmath The mpmath development team, [55 ] on 26 million values found no disagreement.
Methods. OFFICIAL is PyTorch 2.15.0 on CPU; every measurement and every repair was repeated on an NVIDIA A100 GPU with PyTorch 2.4.0 (Appendix § 10 ). OFFICIAL+ evaluates the unchanged official code after promoting the parameters exactly to the next format (FP32 for FP16 inputs, FP64 for FP32 inputs) and rounds the result once to the target format; it is the natural “just use more precision” baseline.
Metrics. We report the fraction of samples with relative error ≥ 1 % \ge1\% ≥ 1% and with negative KL, the relative L 2 L_2 L 2 error and cosine of the gradient vector, and one summary rate: an output is a significant error if it is off by at least 8 ULP or is qualitatively wrong (negative, NaN or infinite KL where the truth is finite and positive; spurious zero or non-zero; sign-flipped gradient component).
Extreme parameters. In stress regions even FP64 does not help where the constructor clamps probabilities before the closed form is evaluated (ContinuousBernoulli) or where log 1 p \log1p log 1 p of a rounded probability returns − ∞ -\infty − ∞ (Binomial, Geometric with logits).
Additional interface-B results. For probability targets (log_target=False), 65–99% of the FP32 sum outputs are off by at least 8 ULP and 35–70% by at least 1%, increasing as KL decreases; with log_target=True the forward value is accurate. Scaled reductions produce substantial target-gradient errors in FP16: with reduction="mean", FP16 and K = 256 K = 256 K = 256 , 99.6% of gradient rows have relative L 2 L_2 L 2 error ≥ 1 % \ge1\% ≥ 1% and 95.4% contain a component of the wrong sign, because autograd evaluates the exact upstream factor g g g as ( g t ) / t (g t)/t ( g t ) / t and g t g t g t is subnormal. Overall the official implementation is correctly rounded on 52.5% of forward and 74.9% of backward components. Unlike interface A, these operator errors essentially disappear in FP64 (NaNs at boundary inputs remain). What does not disappear is the input-representation error: T o p T_{\mathrm{op}} T op differs from T e 2 e T_{\mathrm{e2e}} T e2e by ≥ 1 % \ge1\% ≥ 1% on 40–99% of the batches, in any precision of the operator (Appendix § 9 ).
Additional GPU results. On the A100 the significant-error rate of OFFICIAL on the interface-A data is 87.7% for FP32 and 71.5% for FP16 inputs (CPU: 87.7% and 70.1%), and the per-interval error maps of the two devices agree within one percentage point in 583 of 616 cells (Figure 3 and Figure 4 ). For kl_div only 50.0% of the forward and 71.1% of the non-boundary backward components are correctly rounded on the GPU (CPU: 52.5% and 76.4% of the same components); with log_target=True and FP32 inputs the share of incorrectly rounded gradient components rises from 11–13% on CPU to 32–34%. The two devices do not return the same bits: with the same PyTorch build, 27% of the FP32 KL values of OFFICIAL differ between CPU and GPU. OURS is unaffected: no significant error for interface A and the same counts of correctly rounded components for F.kl_div on both devices. The detailed GPU results are in Appendix § 10 : the summary by interface and precision (Table 10 ), the per-interval maps for both interfaces, the bit-wise comparison of the two devices, and the cases in which the GPU is the more accurate one.
Error-free transformations. Where a difference of products is needed (e.g. N k = y k S x − x k S y N_k = y_k S_x - x_k S_y N k = y k S x − x k S y for Categorical parameters (Appendix § 8 .16), $\sigma_q^2 - \sigma_p^2 - \delta^2$ in the Normal scale gradient, $L_q^{-1}(L_p - L_q)$ for the KL divergence of the multivariate normal), we use error-free transformations: TwoSum [31 ] , Dekker’s TwoProduct {citet}[10 ] , expansion sums {citet}[52 ] and double-length arithmetic {citet}[43 ] `.
Autodiff errors. Besides inheriting the cancellation of the formula it differentiates, automatic differentiation adds failure modes of its own, e.g. ( g t ) / t (g t)/t ( g t ) / t in F.kl_div, or ∞ − ∞ \infty- \infty ∞ − ∞ through torch.where.
Double rounding. FP64→FP32→FP16 is a double rounding; results whose leading term is itself a rounding midpoint are handled as described in Appendix § 8 .§ 1 .
Results of REWRITE. The residue of REWRITE is largest for Beta and Dirichlet; its few new errors are documented in Appendix § 8 . Its cost is moderate for five of the seven timed families and higher for Gamma and Beta (Appendix § 9 .§ 3 ).
The logits path. Equation (4) is a row-vectorised re-implementation of the certified Categorical(logits) repair of Table 1 , tested against it. It is closely related to the fused soft-target cross-entropy proposed concurrently by Barron et al. [2 ] ; we arrive at it from the Categorical closed form and also repair the probs parameterisation.