jax.scipy.stats.poisson.entropy returns NaN gradients for large mu (and small mu in float32)
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
#38651
Confirming the root cause and tested fix locally:
Root Cause
- Underflow to zero in summation regimes: In
_entropy_small_muand_entropy_medium_mu, for larger $k$ (e.g. $k \ge 20$ when $\mu = 0.1$),pmf(k, mu, 0)underflows to0.0. Whileentr(0.0) = 0.0, the derivatived/dp entr(0) = -log(0) - 1 = +inf. In the chain rule,d/dmu entr(pmf) = (+inf) * (d pmf / d mu) = (+inf) * 0.0 = NaN. - Regime branch leakage: When $\mu \ge 100$, the unselected branch
_entropy_small_mu(mu)evaluatespmf(k, 150, 0), whereexp(-150) = 0.0in float32 for all $k$, immediately poisoning the unselected branch with NaNs that propagate throughjnp.where.
Fix
- In
_entropy_small_muand_entropy_medium_mu, guardentrusing 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)
- In
poisson.entropy, clampmu_flatto 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-difference2.3700). - $\mu = 150.0$:
grad = 0.003337(matches asymptotic1 / (2 mu) + 1 / (12 mu^2) = 0.0033370).