BUG: Bernoulli(logit_p=...) has a nan gradient once logit_p is large, although logp is finite
Describe the issue:
With logit_p, Bernoulli.dist builds p = sigmoid(logit_p), and logp uses log1p(-p) for an
observed 0. The value is fine, but the gradient is nan once 1 - p rounds to 0, from about
logit_p = 37. An observed 1 with a very negative logit is fine, since it goes through log(p).
NegativeBinomial.logp already spells this log(1 - p), because the sigmoid stabilization rewrites
don't recognize log1p(-p), and pymc-devs/pytensor#2328 teaches them to. I checked that PR out: it
fixes the observed-variable case below, but not pm.logp(pm.Bernoulli.dist(logit_p=...), data)
inside a Potential, which stays nan. Spelling it log(1 - p) in Bernoulli.logp fixes both.
I ran into it on two posteriordb posteriors whose PyMC
implementations use Bernoulli(logit_p=...), irt_2pl and
lsat: at points a little away from the default initial point, 16 of
144 and 94 of 1006 terms of compile_dlogp are nan while logp is finite.
Reproducible code example:
import numpy as np
import pymc as pm
with pm.Model() as m:
pm.Bernoulli("y", logit_p=pm.Normal("z"), observed=[0])
print(m.compile_logp()({"z": np.array(40.0)})) # -840.91..., finite
print(m.compile_dlogp()({"z": np.array(40.0)})) # [nan]; the exact value is -41
with pm.Model() as m:
z = pm.Normal("z")
pm.Potential("ll", pm.logp(pm.Bernoulli.dist(logit_p=z), np.array([0])).sum())
print(m.compile_dlogp()({"z": np.array(40.0)})) # [nan], also with pytensor#2328PyMC version information: PyMC 6.3.2 and main (3f3b108), PyTensor 3.3.2 and main (5b55f5c); also PyMC 5.28.5 / PyTensor 2.38.3. Python 3.13 and 3.11, macOS arm64, pip.
Context for the issue: I've opened a PR with the one-line change and a test: #8458. Happy to change or close it if you'd rather fix this another way.
Source: pymc-devs/pymc