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
20 changes: 13 additions & 7 deletions autofit/mapper/prior/_erf_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,23 +12,29 @@
"""

import numpy as np
from scipy.special import ndtr as _np_ndtr
from scipy.special import ndtri as _np_ndtri


def _norm_cdf(z, xp):
"""Standard-normal CDF (== ``scipy.stats.norm.cdf(z)`` to ULPs)."""
"""Standard-normal CDF (== ``scipy.stats.norm.cdf(z)`` to ULPs).

The NumPy branch uses the module-level ``scipy.special.ndtr`` binding, so the
hot EP message maths pays no per-call import lookup.
"""
if xp is np:
from scipy.special import ndtr
else:
from jax.scipy.special import ndtr
return _np_ndtr(z)
from jax.scipy.special import ndtr

return ndtr(z)


def _norm_ppf(p, xp):
"""Standard-normal PPF (== ``scipy.stats.norm.ppf(p)`` to ULPs)."""
if xp is np:
from scipy.special import ndtri
else:
from jax.scipy.special import ndtri
return _np_ndtri(p)
from jax.scipy.special import ndtri

return ndtri(p)


Expand Down
17 changes: 10 additions & 7 deletions autofit/messages/truncated_normal.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,14 +50,16 @@ def log_partition(self, xp=np) -> float:
float
The log-partition (log of the normalizing constant).
"""
from scipy.stats import norm
from autofit.mapper.prior._erf_helpers import _norm_cdf

# 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
Z = norm.cdf(b) - norm.cdf(a)
# `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
return gaussian + log_Z

Expand Down Expand Up @@ -340,15 +342,16 @@ def kl(self, dist : "TruncatedNormalMessage") -> float:
if (self.lower_limit != dist.lower_limit) or (self.upper_limit != dist.upper_limit):
raise ValueError("KL divergence between truncated Gaussians with different support is not implemented.")

from scipy.stats import norm, truncnorm
from scipy.stats import truncnorm
from autofit.mapper.prior._erf_helpers import _norm_cdf

a_p = (self.lower_limit - self.mean) / self.sigma
b_p = (self.upper_limit - self.mean) / self.sigma
a_q = (self.lower_limit - dist.mean) / dist.sigma
b_q = (self.upper_limit - dist.mean) / dist.sigma

log_Z_p = np.log(norm.cdf(b_p) - norm.cdf(a_p))
log_Z_q = np.log(norm.cdf(b_q) - norm.cdf(a_q))
log_Z_p = np.log(_norm_cdf(b_p, np) - _norm_cdf(a_p, np))
log_Z_q = np.log(_norm_cdf(b_q, np) - _norm_cdf(a_q, np))

# Truncated mean and variance of p (scipy returns them for the
# standardised bounds with loc/scale applied).
Expand Down Expand Up @@ -419,11 +422,11 @@ def _normal_gradient_hessian_from(
sigma: Union[float, np.ndarray],
x: np.ndarray,
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
from scipy.stats import norm
from autofit.mapper.prior._erf_helpers import _norm_cdf

a = (self.lower_limit - mean) / sigma
b = (self.upper_limit - mean) / sigma
Z = norm.cdf(b) - norm.cdf(a)
Z = _norm_cdf(b, np) - _norm_cdf(a, np)
log_Z = np.log(Z) if Z > 0 else -np.inf

shape = np.shape(x)
Expand Down
16 changes: 15 additions & 1 deletion autofit/non_linear/fitness.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,13 @@
from autofit.non_linear.paths.abstract import AbstractPaths
from autofit.non_linear.analysis import Analysis

#: Iteration cadences at or above this mean "never". The packaged config default
#: for both ``iterations_per_quick_update`` and ``iterations_per_full_update`` is
#: the inf-like ``1e99`` sentinel documented on ``_steps_until_full_update`` --
#: kept as a float so ``search.json`` stores a readable ``1e99`` rather than a
#: 99-digit integer. Compared against a threshold rather than ``1e99`` exactly so
#: a hand-set ``1e100`` in a workspace config reads as "never" too.
ITERATIONS_NEVER = 1e90


def get_timeout_seconds():
Expand Down Expand Up @@ -649,7 +656,14 @@ def manage_quick_update(self, parameters, log_likelihood):
not detailed science-quality outputs.
"""

if self.iterations_per_quick_update is None:
# Quick updates disabled (the packaged 1e99 default): return before any
# per-call bookkeeping. The running max / count only ever feed the quick
# update body, which can never fire at this cadence, and this method is
# called once per likelihood evaluation.
if (
self.iterations_per_quick_update is None
or self.iterations_per_quick_update >= ITERATIONS_NEVER
):
return

try:
Expand Down
10 changes: 3 additions & 7 deletions autofit/non_linear/search/abstract_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@
from autofit.mapper.model import ModelInstance
from autofit.non_linear.initializer import Initializer
from autofit.non_linear.fitness import Fitness
# `ITERATIONS_NEVER` is defined in `fitness.py` (so `Fitness.manage_quick_update` can
# use it) and re-exported here for existing importers, e.g. `multi_start_gradient`.
from autofit.non_linear.fitness import ITERATIONS_NEVER # noqa: F401
from autofit.non_linear.parallel import SneakyPool, SneakierPool, fork_context
from autofit.non_linear.paths.abstract import AbstractPaths
from autofit.non_linear.paths.database import DatabasePaths
Expand All @@ -57,13 +60,6 @@

logger = logging.getLogger(__name__)

#: Iteration cadences at or above this mean "never". The packaged config default
#: for both ``iterations_per_quick_update`` and ``iterations_per_full_update`` is
#: the inf-like ``1e99`` sentinel documented on ``_steps_until_full_update`` --
#: kept as a float so ``search.json`` stores a readable ``1e99`` rather than a
#: 99-digit integer. Compared against a threshold rather than ``1e99`` exactly so
#: a hand-set ``1e100`` in a workspace config reads as "never" too.
ITERATIONS_NEVER = 1e90

# A reduced test-mode fit needs a valid representative instance for result
# construction and search chaining. Keep fallback sampling bounded so an
Expand Down
40 changes: 28 additions & 12 deletions autofit/non_linear/search/nest/dynesty/search/abstract.py
Original file line number Diff line number Diff line change
Expand Up @@ -416,21 +416,34 @@ def run_search_internal(
"""
Run the Dynesty sampler, which could be either the static of dynamic sampler.

The number of iterations which the sampler runs from depends on the `maxcall` input. Due to on-to-fly updates
via `perform_update` the number of remaining iterations compared to `maxcall` is tracked between every
`run_nested` call, and whether or not the sampler is finished is returned at the end of this function.

A second finish criteria is used, which occurs when the dynesty run performs zero likelihood updates (because
the sampling accrording to Dynesty's termination criteria is complete).
The sampler is handed a budget of `iterations` likelihood calls (`maxcall`), which is either
`iterations_per_full_update` (so on-the-fly output via `perform_update` happens between chunks) or the
calls remaining under the search's global `maxcall`. Whether the search is finished is returned, using
these criteria in order:

1. No output paths (`NullPaths`): there are no on-the-fly updates, so one pass is always final.
2. The global `maxcall` has been reached.
3. Dynesty stopped itself inside the budget. Dynesty's per-run call counter resets on every
`run_nested` call and it stops on the budget only once that counter is *strictly above* `maxcall`,
while `sum(results.ncall)` grows by at least that counter. So a pass that added no more calls than
its budget stopped on dynesty's own termination criterion (`dlogz`, `maxiter`, ...) and is
converged. Under the default `iterations_per_full_update` (1e99) every converged run is therefore
finished in a single pass, with no intermediate `perform_update`, checkpoint restore or second
no-op `run_nested`.
4. Legacy criterion: the pass performed no new likelihood calls (e.g. re-running an already converged
sampler restored from its checkpoint).

A pass that overran its budget (a finite `iterations_per_full_update` chunk) is not finished, so the
search loops through `perform_update` and runs the next chunk.

Parameters
----------
sampler
search_internal
The Dynesty sampler (static or dynamic) which is run and performs nested sampling.

Returns
-------

True if the search is finished, False if another `run_nested` chunk is required.
"""

iterations, total_iterations = self.iterations_from(
Expand All @@ -453,10 +466,13 @@ def run_search_internal(
if isinstance(self.paths, NullPaths):
return True

return (
total_iterations == iterations_after_run
or total_iterations == self.maxcall
)
if self.maxcall is not None and iterations_after_run >= self.maxcall:
return True

if iterations > 0 and iterations_after_run - total_iterations <= iterations:
return True

return bool(total_iterations == iterations_after_run)

def write_uses_pool(self, uses_pool: bool) -> str:
"""
Expand Down
83 changes: 83 additions & 0 deletions test_autofit/messages/test_truncated_normal.py
Original file line number Diff line number Diff line change
Expand Up @@ -294,3 +294,86 @@ def test__old_three_tuple_pickle_payload_still_loads():

result = TruncatedNormalMessage._reconstruct((10.0, 5.0), 0.0, 7)
assert (result.lower_limit, result.upper_limit) == (-np.inf, np.inf)


_NDTR_GRID = [
(mean, sigma, lower, upper)
for mean in (-3.0, 0.0, 0.7, 50.0)
for sigma in (0.05, 1.0, 20.0)
for lower, upper in (
(-np.inf, np.inf),
(-np.inf, 0.5),
(-1.0, np.inf),
(-1.0, 0.5),
(0.0, 100.0),
(-40.0, -39.0),
)
]


def test__ndtr_swap_bit_identical():
"""
The truncated-normal message maths uses `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
`_normal_gradient_hessian_from`, each checked against a reference evaluated with
`scipy.stats.norm.cdf` directly.
"""
from scipy.stats import truncnorm
from autofit.mapper.prior._erf_helpers import _norm_cdf

for mean, sigma, lower, upper in _NDTR_GRID:
a = (lower - mean) / sigma
b = (upper - mean) / sigma

# The primitive itself: exact equality, 0 ulp.
assert _norm_cdf(a, np) == norm.cdf(a)
assert _norm_cdf(b, np) == norm.cdf(b)

message = TruncatedNormalMessage(
mean=mean, sigma=sigma, lower_limit=lower, upper_limit=upper
)

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
expected_logl = (
message.log_base_measure
+ 0.5 * (deltax * -(sigma**-2)) * deltax
- np.log(sigma)
- log_Z
)
in_bounds = (x >= lower) & (x <= upper)
expected_logl = np.where(in_bounds, expected_logl, -np.inf)
np.testing.assert_array_equal(logl, expected_logl)

if not Z > 0:
continue

other = TruncatedNormalMessage(
mean=mean + 0.3 * sigma,
sigma=1.5 * sigma,
lower_limit=lower,
upper_limit=upper,
)
a_q = (lower - other.mean) / other.sigma
b_q = (upper - other.mean) / other.sigma
log_Z_q = np.log(norm.cdf(b_q) - norm.cdf(a_q))
m_p, V_p = truncnorm.stats(a, b, loc=mean, scale=sigma, moments="mv")
e_zp2 = (V_p + (m_p - mean) ** 2) / sigma**2
e_zq2 = (V_p + (m_p - other.mean) ** 2) / other.sigma**2
expected_kl = (
np.log(other.sigma / sigma)
+ (log_Z_q - log_Z)
+ 0.5 * (e_zq2 - e_zp2)
)
kl = message.kl(other)
assert kl == expected_kl or (np.isnan(kl) and np.isnan(expected_kl))
Loading
Loading