From 7edd5955f5bd3610e41b1984b3495c3b63ec9b4d Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Sun, 22 Nov 2026 19:13:10 +0000 Subject: [PATCH 1/4] Bound Nautilus sampling by an optional wall-clock budget --- autofit/exc.py | 14 +++ .../non_linear/search/nest/nautilus/search.py | 99 +++++++++++++------ .../non_linear/search/nest/test_nautilus.py | 98 ++++++++++++++++-- 3 files changed, 175 insertions(+), 36 deletions(-) diff --git a/autofit/exc.py b/autofit/exc.py index a814ba124..71c3efbfe 100644 --- a/autofit/exc.py +++ b/autofit/exc.py @@ -62,6 +62,20 @@ class SearchException(Exception): pass +class SearchBudgetExceeded(SearchException): + """A search reached its budget before it produced any posterior samples.""" + + def __init__(self, termination_reason: str): + super().__init__(termination_reason) + self.termination_reason = termination_reason + + def __str__(self): + return ( + f"The search reached its {self.termination_reason} budget " + "without posterior samples." + ) + + class ProjectionException(ValueError): """ Raised when an importance-weighted message projection diff --git a/autofit/non_linear/search/nest/nautilus/search.py b/autofit/non_linear/search/nest/nautilus/search.py index 2408b215c..16a9176d9 100644 --- a/autofit/non_linear/search/nest/nautilus/search.py +++ b/autofit/non_linear/search/nest/nautilus/search.py @@ -1,5 +1,6 @@ from __future__ import annotations +import math import multiprocessing import numpy as np import logging @@ -7,6 +8,7 @@ import sys from contextlib import contextmanager, nullcontext from pathlib import Path +from time import monotonic from typing import Dict, Optional, Tuple, TYPE_CHECKING @@ -346,6 +348,7 @@ def __init__( session: Optional[sa.orm.Session] = None, use_jax_vmap: Optional[bool] = None, checkpoint: bool = True, + timeout: Optional[float] = None, **kwargs, ): """ @@ -382,6 +385,13 @@ def __init__( Number of likelihood evaluations performed at each step. n_like_max Maximum number of likelihood evaluations before stopping. + timeout + Optional positive wall-clock budget in seconds across the sampling + loop, including intervening full updates. Nautilus checks it between + batches, so in-flight work can finish after the deadline. If a budget + stops the search early, the samples record the ``termination_reason``. + If there are no posterior samples, the fit raises + ``SearchBudgetExceeded`` with the same reason. f_live Maximum fraction of evidence in the live set before terminating. n_eff @@ -444,6 +454,11 @@ def __init__( self.n_shell = n_shell self.n_eff = n_eff self.n_like_max = n_like_max + if timeout is not None and (not math.isfinite(timeout) or timeout <= 0): + raise ValueError( + "Nautilus timeout must be a finite positive number of seconds." + ) + self.timeout = timeout self.discard_exploration = discard_exploration self.verbose = verbose @@ -810,7 +825,9 @@ def call_search(self, search_internal, model, analysis, fitness, update=None): the log likelihood the search maximizes. """ - finished = False + timeout = getattr(self, "timeout", None) + deadline = monotonic() + timeout if timeout is not None else None + termination_reason = None minimum_iterations_per_full_updates = 3 * self.n_live @@ -834,9 +851,16 @@ def call_search(self, search_internal, model, analysis, fitness, update=None): """ ) - while not finished: - - iterations, total_iterations = self.iterations_from( + while True: + run_options = {} + if deadline is not None: + remaining = deadline - monotonic() + if remaining <= 0: + termination_reason = "timeout" + break + run_options["timeout"] = remaining + + iterations, calls_before_run = self.iterations_from( search_internal=search_internal, iterations_per_full_update=iterations_per_full_update, ) @@ -848,33 +872,38 @@ def call_search(self, search_internal, model, analysis, fitness, update=None): discard_exploration=self.discard_exploration, verbose=self.verbose, n_like_max=iterations, + **run_options, ) - - iterations_after_run = self.iterations_from(search_internal=search_internal)[1] - - if ( - converged - or total_iterations == iterations_after_run - or ( - self.n_like_max is not None - and iterations_after_run >= self.n_like_max - ) + calls_after_run = search_internal.n_like + + if converged: + break + if self.n_like_max is not None and calls_after_run >= self.n_like_max: + termination_reason = "n_like_max" + break + if deadline is not None and ( + calls_after_run < iterations or monotonic() >= deadline ): - finished = True - - if not finished: - - if update is not None: - update(search_internal) - else: - self.perform_update( - model=model, - analysis=analysis, - during_analysis=True, - fitness=fitness, - search_internal=search_internal - ) + # Nautilus returns False only for a likelihood or time limit. + # Below the chunk's likelihood limit it stopped on its timeout. + termination_reason = "timeout" + break + if calls_before_run == calls_after_run: + break + + if update is not None: + update(search_internal) + else: + self.perform_update( + model=model, + analysis=analysis, + during_analysis=True, + fitness=fitness, + search_internal=search_internal, + ) + # Keep the outcome with the sampler through archival and sample conversion. + search_internal._autofit_termination_reason = termination_reason return search_internal def progress(self, search_internal) -> Optional[Dict]: @@ -941,13 +970,17 @@ def iterations_from( return iterations, total_iterations def samples_info_from(self, search_internal=None): - return { + info = { "log_evidence": search_internal.log_z, "total_samples": int(search_internal.n_like), "total_accepted_samples": int(search_internal.n_like), "time": self.timer.time if self.timer else None, "number_live_points": int(search_internal.n_live), } + termination_reason = getattr(search_internal, "_autofit_termination_reason", None) + if termination_reason is not None: + info["termination_reason"] = termination_reason + return info def raw_samples_from(self, model, search_internal): """ @@ -961,7 +994,15 @@ def raw_samples_from(self, model, search_internal): search_internal The nautilus sampler. """ + termination_reason = getattr(search_internal, "_autofit_termination_reason", None) + if termination_reason is not None and search_internal.n_like == 0: + # Nautilus can reach its timeout before its first batch. + raise exc.SearchBudgetExceeded(termination_reason) + parameters, log_weights, log_likelihoods = search_internal.posterior() + if termination_reason is not None and len(parameters) == 0: + # For example, discard_exploration can exclude every point collected. + raise exc.SearchBudgetExceeded(termination_reason) return RawSamples( parameters=parameters, diff --git a/test_autofit/non_linear/search/nest/test_nautilus.py b/test_autofit/non_linear/search/nest/test_nautilus.py index b3ee0ef1a..ae4702dcc 100644 --- a/test_autofit/non_linear/search/nest/test_nautilus.py +++ b/test_autofit/non_linear/search/nest/test_nautilus.py @@ -1,9 +1,11 @@ import importlib.util +import json import numpy as np import pytest import autofit as af +from autonerves.conf import with_config pytestmark = pytest.mark.filterwarnings("ignore::FutureWarning") @@ -18,17 +20,18 @@ @pytest.mark.parametrize( - "steps, limit, expected_budgets, expected_updates", + "steps, limit, expected_budgets, expected_updates, reason", [ - ([(40, True)], None, [300], 0), - ([(320, False), (360, True)], None, [300, 620], 1), - ([(320, False), (640, False)], 600, [300, 600], 1), - ([(300, False)], 300, [300], 0), - ([(0, False)], None, [300], 0), + ([(40, True)], None, [300], 0, None), + ([(320, False), (360, True)], None, [300, 620], 1, None), + ([(320, False), (640, False)], 600, [300, 600], 1, "n_like_max"), + ([(300, False)], 300, [300], 0, "n_like_max"), + ([(300, True)], 300, [300], 0, None), + ([(0, False)], None, [300], 0, None), ], ) def test__completion_and_likelihood_budgets( - monkeypatch, steps, limit, expected_budgets, expected_updates + monkeypatch, steps, limit, expected_budgets, expected_updates, reason ): """Convergence ends immediately; incomplete chunks advance by real calls.""" search = af.Nautilus( @@ -40,11 +43,14 @@ def test__completion_and_likelihood_budgets( class Sampler: n_like = 0 + n_live = 10 + log_z = 0.0 def __init__(self): self.budgets = [] def run(self, **kwargs): + assert "timeout" not in kwargs self.budgets.append(kwargs["n_like_max"]) self.n_like, converged = steps[len(self.budgets) - 1] return converged @@ -54,11 +60,89 @@ def posterior(self): sampler = Sampler() assert search.call_search(sampler, None, None, None) is sampler + assert search.samples_info_from(sampler).get("termination_reason") == reason assert sampler.budgets == expected_budgets assert len(updates) == expected_updates assert all(update["during_analysis"] for update in updates) +@pytest.mark.parametrize( + "update_duration, expected_timeouts", [(2.0, [10.0, 5.0]), (7.0, [10.0])] +) +def test__timeout_uses_one_deadline_across_chunks( + monkeypatch, update_duration, expected_timeouts +): + from autofit.non_linear.search.nest.nautilus import search as nautilus_search + + elapsed = 0.0 + monkeypatch.setattr(nautilus_search, "monotonic", lambda: elapsed) + search = af.Nautilus( + name="timeout", n_live=10, iterations_per_full_update=300, timeout=10 + ) + timeouts = [] + + class Sampler: + n_like = 0 + n_live = 10 + log_z = 0.0 + + def run(self, *, timeout, n_like_max, **kwargs): + nonlocal elapsed + timeouts.append(timeout) + if len(timeouts) == 1: + self.n_like = n_like_max + elapsed += 3.0 + else: + self.n_like += 20 + elapsed += timeout + return False + + def update(sampler): + nonlocal elapsed + elapsed += update_duration + + sampler = search.call_search(Sampler(), None, None, None, update=update) + assert timeouts == expected_timeouts + assert search.samples_info_from(sampler)["termination_reason"] == "timeout" + + +@requires_nautilus +@with_config("general", "output", "samples_to_csv", value=True) +@pytest.mark.parametrize("batches, force_x1_cpu", [(0, False), (1, False), (1, True)]) +def test__real_timeout_returns_or_reports_empty_posterior( + tmp_path, monkeypatch, batches, force_x1_cpu +): + import nautilus.sampler + from autofit.conf import instance + + monkeypatch.delenv("PYAUTO_TEST_MODE", raising=False) + monkeypatch.setattr(instance, "output_path", str(tmp_path)) + # The real sampler reads time() at entry and before each batch. + clock = iter([0.0] * (1 + batches) + [100.0]) + monkeypatch.setattr(nautilus.sampler, "time", lambda: next(clock)) + + search = af.Nautilus( + name="timeout_fit", + timeout=10, + n_live=20, + n_batch=10, + seed=1, + verbose=False, + force_x1_cpu=force_x1_cpu, + ) + fit_args = dict(model=_vector_model(2), analysis=_VectorGaussianAnalysis(2)) + if batches == 0: + with pytest.raises(af.exc.SearchBudgetExceeded) as error: + search.fit(**fit_args) + assert error.value.termination_reason == "timeout" + else: + result = search.fit(**fit_args) + assert result.samples.samples_info["termination_reason"] == "timeout" + assert result.samples.samples_info["total_samples"] == 10 + info_file = search.paths.open_result() / "files" / "samples_info.json" + assert json.loads(info_file.read_text())["termination_reason"] == "timeout" + + @pytest.mark.parametrize("limit", [None, float("inf"), 100]) def test__null_paths_likelihood_budget(limit): from types import SimpleNamespace From 37b0eae06a6a6ec8390d437cc696225897e2b7ae Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Sun, 22 Nov 2026 19:17:21 +0000 Subject: [PATCH 2/4] Unfreeze models after an empty search budget stop --- autofit/non_linear/search/abstract_search.py | 21 ++++++++++++------- .../non_linear/search/nest/test_nautilus.py | 2 ++ 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/autofit/non_linear/search/abstract_search.py b/autofit/non_linear/search/abstract_search.py index 6a9b4947e..c33f28e92 100644 --- a/autofit/non_linear/search/abstract_search.py +++ b/autofit/non_linear/search/abstract_search.py @@ -11,6 +11,7 @@ from autofit.database.sqlalchemy_ import sa from autofit.non_linear.result import Result +from autofit.exc import SearchBudgetExceeded from autofit.graphical import FactorApproximation, MeanField from autofit.graphical.utils import Status from autofit.graphical.expectation_propagation import ( @@ -438,13 +439,19 @@ def start_resume_fit(self, analysis: Analysis, model: AbstractPriorModel) -> Res if hasattr(fitness, "shutdown_quick_update"): fitness.shutdown_quick_update() - samples = self.perform_update( - model=model, - analysis=analysis, - search_internal=search_internal, - fitness=fitness, - during_analysis=False, - ) + try: + samples = self.perform_update( + model=model, + analysis=analysis, + search_internal=search_internal, + fitness=fitness, + during_analysis=False, + ) + except SearchBudgetExceeded: + # Finalization normally unfreezes the model. A caller can recover + # from a budget stop without samples and reuse this model. + model.unfreeze() + raise samples_summary = None diff --git a/test_autofit/non_linear/search/nest/test_nautilus.py b/test_autofit/non_linear/search/nest/test_nautilus.py index ae4702dcc..2b12f7d50 100644 --- a/test_autofit/non_linear/search/nest/test_nautilus.py +++ b/test_autofit/non_linear/search/nest/test_nautilus.py @@ -135,6 +135,8 @@ def test__real_timeout_returns_or_reports_empty_posterior( with pytest.raises(af.exc.SearchBudgetExceeded) as error: search.fit(**fit_args) assert error.value.termination_reason == "timeout" + assert not search.paths.is_complete + fit_args["model"].x0 = af.UniformPrior(lower_limit=0.0, upper_limit=2.0) else: result = search.fit(**fit_args) assert result.samples.samples_info["termination_reason"] == "timeout" From 81a84485a6cdd203ece5b5815266a9717f790b89 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Sun, 22 Nov 2026 19:22:38 +0000 Subject: [PATCH 3/4] Record the Nautilus timeout and capped metadata in conformance tests --- test_autofit/non_linear/search/conformance_roster.py | 1 + test_autofit/non_linear/search/test_conformance_backend.py | 5 ++++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/test_autofit/non_linear/search/conformance_roster.py b/test_autofit/non_linear/search/conformance_roster.py index d02f69666..577c91951 100644 --- a/test_autofit/non_linear/search/conformance_roster.py +++ b/test_autofit/non_linear/search/conformance_roster.py @@ -498,6 +498,7 @@ class Golden: "n_update", "seed", "split_threshold", + "timeout", "use_jax_vmap", "vectorized", "verbose", diff --git a/test_autofit/non_linear/search/test_conformance_backend.py b/test_autofit/non_linear/search/test_conformance_backend.py index 4664d71ef..096b58c95 100644 --- a/test_autofit/non_linear/search/test_conformance_backend.py +++ b/test_autofit/non_linear/search/test_conformance_backend.py @@ -221,7 +221,8 @@ }, "DynestyStatic": _DYNESTY_NAUTILUS_KEYS, "DynestyDynamic": _DYNESTY_NAUTILUS_KEYS, - "Nautilus": _DYNESTY_NAUTILUS_KEYS, + # The reduced-budget fixture stops Nautilus at n_like_max=1. + "Nautilus": _DYNESTY_NAUTILUS_KEYS | {"termination_reason"}, "NSS": _DYNESTY_NAUTILUS_KEYS | { "log_evidence_error", @@ -610,6 +611,8 @@ def test_samples_info_key_set(entry, backend_run): assert FAMILY_SAMPLES_INFO_CORE[entry.family] <= keys assert keys == SAMPLES_INFO_KEYS[entry.name] + if entry.name == "Nautilus": + assert backend_run(entry).samples_info["termination_reason"] == "n_like_max" @pytest.mark.parametrize( From 936b073d4a1daf6720b54445a97a3d51172b05aa Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Sun, 22 Nov 2026 19:23:38 +0000 Subject: [PATCH 4/4] Keep the search lifecycle description within its module budget --- autofit/non_linear/search/abstract_search.py | 14 ++++---------- 1 file changed, 4 insertions(+), 10 deletions(-) diff --git a/autofit/non_linear/search/abstract_search.py b/autofit/non_linear/search/abstract_search.py index c33f28e92..caa60da6c 100644 --- a/autofit/non_linear/search/abstract_search.py +++ b/autofit/non_linear/search/abstract_search.py @@ -392,16 +392,10 @@ def pre_fit_output( @configure_handler def start_resume_fit(self, analysis: Analysis, model: AbstractPriorModel) -> Result: - """ - Start a non-linear search from scratch, or resume one which was previously - terminated mid-way through (from the samples it left off at), and return its - ``Result``. - - When the search completes a `.completed` file is output, so a rerun is not - repeated and loads its results via `result_via_completed_fit`; results are also - output to the `files` folder via the analysis' `save_results`. Under - ``PYAUTO_TEST_MODE>=2`` the backend is bypassed (``TestModeBypass``); both - paths end in ``finalize_result``. + """Run or resume the search and return its result. + + Both the real backend and the test-mode bypass finish in `finalize_result`. + Only successful finalization writes `.completed` for subsequent reuse. """ if self.paths.has_timer: self.timer.start()