From 0e2c09748d64b4545228f16caee8f29758d523db Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Thu, 24 Sep 2026 16:47:32 +0200 Subject: [PATCH 1/2] fix(dynesty): recognise a converged first pass as finished (#1642) run_search_internal only treated a pass as final when it added zero likelihood calls, so every converged dynesty search ran an intermediate perform_update, a checkpoint restore and a second no-op run_nested. dynesty's per-run call counter resets on each run_nested and stops on the budget only once it is strictly above maxcall, while sum(results.ncall) grows by at least that counter. A pass that added no more calls than the budget it was handed therefore stopped on dynesty's own criterion. The finish test is now: NullPaths; global maxcall reached; dynesty stopped under budget; legacy no-progress. Finite iterations_per_full_update cadences still loop through perform_update. Co-Authored-By: Claude Fable 5.1 --- .../search/nest/dynesty/search/abstract.py | 40 +++-- .../non_linear/search/nest/test_dynesty.py | 162 ++++++++++++++++++ 2 files changed, 190 insertions(+), 12 deletions(-) diff --git a/autofit/non_linear/search/nest/dynesty/search/abstract.py b/autofit/non_linear/search/nest/dynesty/search/abstract.py index 6f8605152..8a3d99f7d 100644 --- a/autofit/non_linear/search/nest/dynesty/search/abstract.py +++ b/autofit/non_linear/search/nest/dynesty/search/abstract.py @@ -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( @@ -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: """ diff --git a/test_autofit/non_linear/search/nest/test_dynesty.py b/test_autofit/non_linear/search/nest/test_dynesty.py index 94d5cc58b..86f72372a 100644 --- a/test_autofit/non_linear/search/nest/test_dynesty.py +++ b/test_autofit/non_linear/search/nest/test_dynesty.py @@ -103,3 +103,165 @@ def no_fork_context(*args, **kwargs): ) search.fit(model=model, analysis=analysis) + + +class _FakeRunSampler: + """ + A stand-in for a dynesty sampler whose `run_nested` appends a fixed number of + likelihood calls per run to `results.ncall`, mirroring how dynesty's + `sum(results.ncall)` grows across successive `run_nested` calls. + """ + + def __init__(self, calls_per_run): + self.calls_per_run = list(calls_per_run) + self.results = MockDynestyResults( + samples=None, logl=None, logwt=None, ncall=[], logz=None, nlive=None + ) + self.maxcalls = [] + + def run_nested(self, maxcall, **kwargs): + self.maxcalls.append(maxcall) + self.results.ncall.append(self.calls_per_run.pop(0)) + + +def _search_with_directory_paths(name, **kwargs): + search = af.DynestyStatic(nlive=20, number_of_cores=1, silence=True, **kwargs) + search.paths = af.DirectoryPaths(name=name) + return search + + +def test__run_search_internal__converged_first_pass_is_finished(): + """ + Under the default `iterations_per_full_update` (1e99) dynesty stops on its own + convergence criterion, far inside the budget it was handed, so the first pass is + finished: no second `perform_update` + checkpoint restore + no-op `run_nested`. + """ + search = _search_with_directory_paths("dynesty_converged_first_pass") + sampler = _FakeRunSampler(calls_per_run=[1641]) + + assert search.run_search_internal(search_internal=sampler) is True + assert len(sampler.maxcalls) == 1 + + +def test__run_search_internal__chunk_limited_pass_is_not_finished(): + """ + With a finite cadence dynesty's per-run counter stops only once it is strictly + above `maxcall`, so a pass that consumed more calls than its budget was cut by + the budget, not by convergence, and the search must loop again. + """ + search = _search_with_directory_paths( + "dynesty_chunk_limited", iterations_per_full_update=50 + ) + sampler = _FakeRunSampler(calls_per_run=[51]) + + assert search.run_search_internal(search_internal=sampler) is False + assert sampler.maxcalls == [50] + + +def test__run_search_internal__global_maxcall_is_finished(): + """ + Reaching the search's global `maxcall` finishes the search even though the pass + overran its budget. + """ + search = _search_with_directory_paths("dynesty_global_maxcall", maxcall=100) + sampler = _FakeRunSampler(calls_per_run=[120]) + + assert search.run_search_internal(search_internal=sampler) is True + assert sampler.maxcalls == [100] + + +def test__fit__finite_cadence_loops_through_intermediate_updates(monkeypatch): + """ + A finite `iterations_per_full_update` still chunks the run: two budget-limited + passes (60 calls each against a budget of 50) followed by a converged pass (30 + calls) give three `run_nested` calls and two intermediate `perform_update`s. + """ + search = _search_with_directory_paths( + "dynesty_finite_cadence", iterations_per_full_update=50 + ) + sampler = _FakeRunSampler(calls_per_run=[60, 60, 30]) + + monkeypatch.setattr( + search, "search_internal_from", lambda *args, **kwargs: sampler + ) + + updates = [] + monkeypatch.setattr( + search, + "perform_update", + lambda *args, **kwargs: updates.append(kwargs.get("during_analysis")), + ) + + model = af.Model(af.ex.Gaussian) + analysis = af.ex.Analysis(data=np.full(10, 1.0), noise_map=np.full(10, 1.0)) + + search._fit(model=model, analysis=analysis) + + assert sampler.maxcalls == [50, 50, 50] + assert updates == [True, True] + + +@pytest.mark.parametrize( + "search_cls, kwargs", + [ + (af.DynestyStatic, {"nlive": 20}), + (af.DynestyDynamic, {"nlive_init": 20, "maxiter": 400}), + ], +) +def test__fit__real_dynesty_converges_in_a_single_run_nested( + search_cls, kwargs, monkeypatch +): + """ + A real dynesty fit under the default update cadence calls `run_nested` exactly + once and performs no `during_analysis=True` update: the converged first pass is + recognised as finished (#1642). Before the fix every search ran a second, no-op + `run_nested` after an intermediate `perform_update` and a checkpoint restore. + """ + import dynesty.sampler + import dynesty.dynamicsampler + from autofit.non_linear.search.abstract_search import NonLinearSearch + + monkeypatch.delenv("PYAUTO_TEST_MODE", raising=False) + + calls = [] + + for cls in (dynesty.sampler.Sampler, dynesty.dynamicsampler.DynamicSampler): + original = cls.run_nested + + def counted(self, *args, _original=original, **kw): + calls.append(type(self).__name__) + return _original(self, *args, **kw) + + monkeypatch.setattr(cls, "run_nested", counted) + + updates = [] + original_perform_update = NonLinearSearch.perform_update + + def recorded(self, *args, **kw): + updates.append(kw.get("during_analysis")) + return original_perform_update(self, *args, **kw) + + monkeypatch.setattr(NonLinearSearch, "perform_update", recorded) + + model = af.Model(af.ex.Gaussian) + model.normalization = 1.0 + model.sigma = 5.0 + model.centre = af.UniformPrior(lower_limit=0.0, upper_limit=100.0) + + xvalues = np.arange(100.0) + data = af.ex.Gaussian(centre=50.0, normalization=1.0, sigma=5.0).model_data_from( + xvalues + ) + analysis = af.ex.Analysis(data=data, noise_map=np.full(100, 0.1)) + + search = search_cls( + name=f"dynesty_single_run_nested_{search_cls.__name__}", + number_of_cores=1, + silence=True, + **kwargs, + ) + + search.fit(model=model, analysis=analysis) + + assert len(calls) == 1 + assert True not in updates From 16789050aeeaf69d73765b9df315ccbcea02c154 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Thu, 24 Sep 2026 16:53:15 +0200 Subject: [PATCH 2/2] perf(ep): ndtr in truncated-normal message maths; skip disabled quick updates (#1642) - TruncatedNormalMessage.log_partition / kl / _normal_gradient_hessian_from use scipy.special.ndtr via _erf_helpers._norm_cdf instead of scipy.stats.norm.cdf: the same Cephes routine without the rv_continuous wrapper, bit-identical (test__ndtr_swap_bit_identical, incl. infinite limits). truncnorm.stats is untouched. _erf_helpers binds ndtr/ndtri once at module level for NumPy. - Fitness.manage_quick_update returns before any bookkeeping when iterations_per_quick_update is None or >= ITERATIONS_NEVER (the packaged 1e99 default); ITERATIONS_NEVER moves to fitness.py and is re-exported from abstract_search.py for existing importers. Co-Authored-By: Claude Fable 5.1 --- autofit/mapper/prior/_erf_helpers.py | 20 +++-- autofit/messages/truncated_normal.py | 17 ++-- autofit/non_linear/fitness.py | 16 +++- autofit/non_linear/search/abstract_search.py | 10 +-- .../messages/test_truncated_normal.py | 83 +++++++++++++++++++ .../test_quick_update_parameter_types.py | 14 ++++ 6 files changed, 138 insertions(+), 22 deletions(-) diff --git a/autofit/mapper/prior/_erf_helpers.py b/autofit/mapper/prior/_erf_helpers.py index b07fd2bad..1b5b8098c 100644 --- a/autofit/mapper/prior/_erf_helpers.py +++ b/autofit/mapper/prior/_erf_helpers.py @@ -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) diff --git a/autofit/messages/truncated_normal.py b/autofit/messages/truncated_normal.py index 2a1701b94..a396464f3 100644 --- a/autofit/messages/truncated_normal.py +++ b/autofit/messages/truncated_normal.py @@ -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 @@ -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). @@ -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) diff --git a/autofit/non_linear/fitness.py b/autofit/non_linear/fitness.py index 67ade0295..42452e13e 100644 --- a/autofit/non_linear/fitness.py +++ b/autofit/non_linear/fitness.py @@ -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(): @@ -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: diff --git a/autofit/non_linear/search/abstract_search.py b/autofit/non_linear/search/abstract_search.py index 6cfdc5276..da687d9d5 100644 --- a/autofit/non_linear/search/abstract_search.py +++ b/autofit/non_linear/search/abstract_search.py @@ -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 @@ -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 diff --git a/test_autofit/messages/test_truncated_normal.py b/test_autofit/messages/test_truncated_normal.py index cd02fdd5d..923cd6f21 100644 --- a/test_autofit/messages/test_truncated_normal.py +++ b/test_autofit/messages/test_truncated_normal.py @@ -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)) diff --git a/test_autofit/non_linear/test_quick_update_parameter_types.py b/test_autofit/non_linear/test_quick_update_parameter_types.py index 24b165a3d..3d5b87eab 100644 --- a/test_autofit/non_linear/test_quick_update_parameter_types.py +++ b/test_autofit/non_linear/test_quick_update_parameter_types.py @@ -71,3 +71,17 @@ def test__no_update_body_runs_when_the_cadence_is_not_reached(): fitness.manage_quick_update(parameters=[50.0, 25.0, 10.0], log_likelihood=-10.0) assert fitness.quick_update_count == 1 + + +@pytest.mark.parametrize("cadence", [1e99, 1e100]) +def test__disabled_cadence_returns_before_any_bookkeeping(cadence): + # The packaged 1e99 default (and anything at or above `ITERATIONS_NEVER`) + # disables quick updates, so the per-likelihood-call bookkeeping is skipped + # entirely (#1642): no count, no running maximum, no render. + fitness = _fitness(iterations_per_quick_update=cadence) + + fitness.manage_quick_update(parameters=[50.0, 25.0, 10.0], log_likelihood=-10.0) + + assert fitness.quick_update_count == 0 + assert fitness.quick_update_max_lh_parameters is None + assert fitness.paths.results == []