jax icon indicating copy to clipboard operation
jax copied to clipboard

jax.scipy.special.rel_entr / kl_div lose all precision for p close to q and return nan for large p (p*log(p) - p*log(q))

Open the-Shallow opened this issue 2 months ago • 2 comments

Description

Description

jax.scipy.special.rel_entr(p, q) computes p*log(p) - p*log(q) (_xlogx(p) - xlogy(p, q)) instead of p*log(p/q). When p and q are close the two terms cancel, and for large p both overflow to inf and their difference is nan. kl_div is rel_entr(p, q) - p + q and inherits the error, including negative results although kl_div >= 0. SciPy evaluates x * log(x / y).

Steps to reproduce

import jax; jax.config.update("jax_enable_x64", True)
from jax.scipy.special import rel_entr, kl_div
print(rel_entr(1e15, 1e15 + 1))                               # 0.0   (exact -0.9992)
print(rel_entr(1e308, 1e308))                                 # nan   (exact 0)
print(kl_div(9.999999999999978e29, 9.999998737240631e29))     # -1.4e14 (must be >= 0; SciPy 7.9e15)

Expected

rel_entr(1e15, 1e15 + 1) about -0.9992, rel_entr(1e308, 1e308) = 0, and a non-negative kl_div.

Suggested fix

Compute p * log(p / q) (for example p * log1p((p - q) / q) when p and q are close), as SciPy does.

System info (python version, jaxlib version, accelerator, etc.)

Environment

JAX / jaxlib 0.11.2 (the latest release, CPU) and 0.10.1, Python 3.12, Ubuntu 24.04, x86_64

the-Shallow avatar Oct 01 '26 21:10 the-Shallow

Related to #38239 (see also #38651)

jakevdp avatar Oct 01 '26 21:10 jakevdp

Confirming the root cause in jax/_src/scipy/special.py:1378:

log_val = lax.sub(_xlogx(safe_p), xlogy(safe_p, safe_q))

The definition $p \log(p / q)$ is currently expanded into $_xlogx(p) - xlogy(p, q) = p \log(p) - p \log(q)$. This causes two issues:

  1. Cancellation for $p \approx q$: When $p$ and $q$ are large and close, the terms $p \log(p)$ and $p \log(q)$ cancel out the lower significand bits.
  2. Overflow to NaN: When $p > \approx 10^{308}$, both $_xlogx(p)$ and $xlogy(p, q)$ overflow to +inf, resulting in inf - inf = nan even when $p = q$.

In SciPy (scipy.special.rel_entr), the calculation is evaluated directly as xlogy(x, x / y):

  • Evaluating xlogy(p, p / q) immediately fixes the overflow for large $p = q = 10^{308}$, giving 0.0 instead of nan.
  • For $p \approx q$ (e.g. when $|p - q| < 0.5 q$), evaluating via p * log1p((p - q) / q) retains full double precision:
# p = 1e15, q = 1e15 + 1 (with jax_enable_x64=True)
# Current JAX:                   0.0
# xlogy(p, p / q):              -0.9992007221626414
# p * log1p((p - q) / q):       -0.9999999999999997 (matches SciPy exactly)

Using jnp.where(abs(p - q) < 0.5 * q, p * lax.log1p((p - q) / q), xlogy(p, p / q)) resolves both issues cleanly.

hrideymarwah15 avatar Oct 10 '26 10:10 hrideymarwah15