Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 17 additions & 5 deletions autofit/messages/truncated_normal.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,17 +50,29 @@ def log_partition(self, xp=np) -> float:
float
The log-partition (log of the normalizing constant).
"""
from autofit.mapper.prior._erf_helpers import _norm_cdf
if xp is np:
from scipy.special import log_ndtr
else:
from jax.scipy.special import log_ndtr

# Untruncated Gaussian log-partition — see NormalMessage.log_partition.
gaussian = (self.mean ** 2) / (2 * self.sigma ** 2) + xp.log(self.sigma)

a = (self.lower_limit - self.mean) / self.sigma
b = (self.upper_limit - self.mean) / self.sigma
# `scipy.special.ndtr` is the routine `scipy.stats.norm.cdf` wraps: bit-identical,
# without the `rv_continuous` argument-checking overhead.
Z = _norm_cdf(b, np) - _norm_cdf(a, np)
log_Z = xp.log(Z) if Z > 0 else -xp.inf
# Reflect upper-tail intervals so their CDFs stay distinguishable.
upper_tail = a > 0
log_upper = log_ndtr(xp.where(upper_tail, -a, b))
log_lower = log_ndtr(xp.where(upper_tail, -b, a))

# Mask zero mass before subtracting to avoid inf - inf and log(0).
positive_mass = log_upper > log_lower
difference = xp.where(positive_mass, log_lower, -xp.inf) - xp.where(
positive_mass, log_upper, 0.0
)
log_Z = xp.where(
positive_mass, log_upper + xp.log(-xp.expm1(difference)), -xp.inf
)
return gaussian + log_Z

log_base_measure = -0.5 * np.log(2 * np.pi)
Expand Down
41 changes: 20 additions & 21 deletions test_autofit/graphical/functionality/test_evidence_nonfinite.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,7 @@
"""
A non-finite term in the EP log evidence is reported by name, not summed (PyAutoFit#1713).

On the analytic_gaussian ensemble (seeds 25 and 172, default ``projection="mode"``)
one member of a ``HierarchicalFactor`` sends the parent scatter a truncated-normal
message centred thousands of sigma below its support (mean -7374, sigma 384 on
[0, 100]). Its truncation mass ``Phi(b) - Phi(a)`` evaluates to ``1 - 1 = 0``, so its
log-partition is ``-inf``: the scatter's variable evidence is ``+inf``, every adjacent
factor term is ``-inf``, and ``EPMeanField.log_evidence`` added them, emitting numpy's
``invalid value encountered in add`` once per evaluation and returning NaN. The
posteriors are unaffected; only the evidence readout is.

The fixture below is that state in miniature: two factors share ``x``, one message is
the production message.
"""EP evidence reports non-finite terms by name (PyAutoFit#1713).

The degenerate fixture injects the non-finite log-partition that triggered the
reporting bug. The production tail message now has a finite normalizer.
"""

import logging
Expand Down Expand Up @@ -41,18 +31,21 @@ def _degenerate(x):
return -x


def make_approx(x, bad_mean=-7374.0, bad_sigma=384.0):
class NonfinitePartitionMessage(TruncatedNormalMessage):
def log_partition(self, xp=np):
return -xp.inf


def make_approx(x, mean, sigma, message_type=TruncatedNormalMessage):
ok_factor = g.Factor(_ok, x, name="f_ok")
degenerate_factor = g.Factor(_degenerate, x, name="f_degenerate")
ok = TruncatedNormalMessage(mean=10.0, sigma=5.0, lower_limit=0.0, upper_limit=100.0)
bad = TruncatedNormalMessage(
mean=bad_mean, sigma=bad_sigma, lower_limit=0.0, upper_limit=100.0
)
other = message_type(mean=mean, sigma=sigma, lower_limit=0.0, upper_limit=100.0)
return g.EPMeanField(
factor_graph=g.FactorGraph([ok_factor, degenerate_factor]),
factor_mean_field={
ok_factor: g.MeanField({x: ok}),
degenerate_factor: g.MeanField({x: bad}),
degenerate_factor: g.MeanField({x: other}),
},
)

Expand All @@ -64,12 +57,18 @@ def make_x():

@pytest.fixture(name="degenerate")
def make_degenerate(x):
return make_approx(x)
return make_approx(x, -7374.18, 384.36, NonfinitePartitionMessage)


@pytest.fixture(name="healthy")
def make_healthy(x):
return make_approx(x, bad_mean=20.0, bad_sigma=8.0)
return make_approx(x, 20.0, 8.0)


def test_tail_message_has_finite_evidence(x):
approximation = make_approx(x, -7374.18, 384.36)
assert np.isfinite(approximation.log_evidence)
assert approximation.nonfinite_evidence_terms == {}


def test_log_evidence_nan_without_runtime_warning(degenerate):
Expand Down
33 changes: 32 additions & 1 deletion test_autofit/mapper/prior/test_priors_messages_fixes_1331.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import numpy as np
import pytest
from scipy import integrate
from scipy.special import log_ndtr
from scipy.stats import norm

import autofit as af
Expand Down Expand Up @@ -53,7 +54,37 @@ def test__truncated_message_log_partition_normalises_pdf():
a = (m.lower_limit - m.mean) / m.sigma
b = (m.upper_limit - m.mean) / m.sigma
expected = (m.mean ** 2) / (2 * m.sigma ** 2) + np.log(m.sigma) + np.log(norm.cdf(b) - norm.cdf(a))
assert float(m.log_partition()) == pytest.approx(expected, rel=1e-9)
assert float(m.log_partition()) == pytest.approx(expected, abs=1e-12, rel=0)


@pytest.mark.parametrize(
("lower", "upper"),
[(-1.0, 2.0), (-np.inf, 2.0), (-1.0, np.inf), (-np.inf, np.inf)],
)
def test_truncated_message_log_partition_matches_direct_cdf(lower, upper):
mean, sigma = 0.5, 1.2
message = TruncatedNormalMessage(mean, sigma, lower, upper)
a, b = (lower - mean) / sigma, (upper - mean) / sigma
expected = (mean / sigma) ** 2 / 2 + np.log(sigma) + np.log(
norm.cdf(b) - norm.cdf(a)
)

assert message.log_partition() == pytest.approx(expected, abs=1e-12, rel=0)


@pytest.mark.parametrize(
("mean", "lower", "upper"),
[(-7374.18, 0.0, 100.0), (7374.18, -100.0, 0.0)],
)
def test_truncated_message_log_partition_in_both_tails(mean, lower, upper):
sigma = 384.36
message = TruncatedNormalMessage(mean, sigma, lower, upper)
log_near = log_ndtr(-abs(mean) / sigma)
log_far = log_ndtr(-(abs(mean) + 100.0) / sigma)
log_mass = log_near + np.log1p(-np.exp(log_far - log_near))
expected = (mean / sigma) ** 2 / 2 + np.log(sigma) + log_mass

assert message.log_partition() == pytest.approx(expected, abs=1e-9, rel=0)


# --- #10: FixedMessage.logpdf returns a fresh array (no aliased class-level cache) ---
Expand Down
16 changes: 16 additions & 0 deletions test_autofit/messages/test_jax_trace.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,22 @@
jnp = pytest.importorskip("jax.numpy")


def test_truncated_message_log_partition_is_jittable_in_both_tails():
message = TruncatedNormalMessage(
mean=np.array([-7374.18, 7474.18]),
sigma=384.36,
lower_limit=0.0,
upper_limit=100.0,
)
actual = jax.jit(lambda: message.log_partition(xp=jnp))()

assert np.isfinite(actual).all()
tolerance = 1e-9 if jax.config.jax_enable_x64 else 1e-4
np.testing.assert_allclose(
np.asarray(actual), message.log_partition(), atol=tolerance, rtol=0
)


MESSAGE_ARRAY_CASES = [
pytest.param(
lambda value, xp: NormalMessage.calc_natural_parameters(
Expand Down
9 changes: 2 additions & 7 deletions test_autofit/messages/test_truncated_normal.py
Original file line number Diff line number Diff line change
Expand Up @@ -313,10 +313,10 @@ def test__old_three_tuple_pickle_payload_still_loads():

def test__ndtr_swap_bit_identical():
"""
The truncated-normal message maths uses `scipy.special.ndtr` (via
The truncated-normal KL and gradient use `scipy.special.ndtr` (via
`_erf_helpers._norm_cdf`) instead of `scipy.stats.norm.cdf` (#1642): the same
Cephes routine without the `rv_continuous` wrapper. The swap must be bit
identical, including infinite truncation limits, for `log_partition`, `kl` and
identical, including infinite truncation limits, for `kl` and
`_normal_gradient_hessian_from`, each checked against a reference evaluated with
`scipy.stats.norm.cdf` directly.
"""
Expand All @@ -337,11 +337,6 @@ def test__ndtr_swap_bit_identical():

Z = norm.cdf(b) - norm.cdf(a)
log_Z = np.log(Z) if Z > 0 else -np.inf
expected_log_partition = (
mean**2 / (2 * sigma**2) + np.log(sigma) + log_Z
)
assert message.log_partition() == expected_log_partition

x = np.array([lower + 1e-3 if np.isfinite(lower) else mean - sigma, mean])
logl, grad, hess = message._normal_gradient_hessian_from(mean, sigma, x)
deltax = x - mean
Expand Down
Loading