jax icon indicating copy to clipboard operation
jax copied to clipboard

jax.scipy.stats.poisson.entropy returns NaN gradients for large mu (and small mu in float32)

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

Description

Description

jax.grad(jax.scipy.stats.poisson.entropy) returns NaN for mu >= ~88 and mu <= ~0.39 in float32 (and mu >= ~713 in float64), although the forward value is correct. The out-of-regime branches of the jnp.where switch underflow the pmf to 0, where entr's derivative -log(p) - 1 is infinite, and inf * 0 in the chain rule makes the selected branch's gradient NaN.

Steps to reproduce

import jax, jax.numpy as jnp
from jax.scipy.stats import poisson
print(jax.grad(poisson.entropy)(jnp.float32(150.0)))   # nan
print(jax.grad(poisson.entropy)(jnp.float32(5.0)))     # 0.1046673

Expected

Finite gradients wherever the entropy is finite (d/dmu H ~ 1/(2 mu) for large mu).

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 Sep 25 '26 03:09 the-Shallow

#38651

jakevdp avatar Sep 25 '26 12:09 jakevdp

Confirming the root cause and tested fix locally:

Root Cause

  1. Underflow to zero in summation regimes: In _entropy_small_mu and _entropy_medium_mu, for larger $k$ (e.g. $k \ge 20$ when $\mu = 0.1$), pmf(k, mu, 0) underflows to 0.0. While entr(0.0) = 0.0, the derivative d/dp entr(0) = -log(0) - 1 = +inf. In the chain rule, d/dmu entr(pmf) = (+inf) * (d pmf / d mu) = (+inf) * 0.0 = NaN.
  2. Regime branch leakage: When $\mu \ge 100$, the unselected branch _entropy_small_mu(mu) evaluates pmf(k, 150, 0), where exp(-150) = 0.0 in float32 for all $k$, immediately poisoning the unselected branch with NaNs that propagate through jnp.where.

Fix

  1. In _entropy_small_mu and _entropy_medium_mu, guard entr using safe masked probabilities:
mask = (k < upper_bounds[None, :]) & (probs > 0)
safe_probs = jnp.where(mask, probs, 1.0)
entr_vals = jnp.where(mask, entr(safe_probs), 0.0)
return jnp.sum(entr_vals, axis=0)
  1. In poisson.entropy, clamp mu_flat to the valid domain of each regime before evaluating the branches:
mu_small = jnp.clip(mu_flat, 1e-4, 9.9)
mu_medium = jnp.clip(mu_flat, 10.0, 99.9)
mu_large = jnp.maximum(mu_flat, 100.0)

Verified locally on CPU across $\mu \in [0.05, 500.0]$ in both float32 and float64:

  • $\mu = 0.1$: grad = 2.3705 (matches SciPy finite-difference 2.3700).
  • $\mu = 150.0$: grad = 0.003337 (matches asymptotic 1 / (2 mu) + 1 / (12 mu^2) = 0.0033370).

hrideymarwah15 avatar Oct 10 '26 10:10 hrideymarwah15