From 2629933cc15d6197b6d6f5740dea55c0b3b93bd2 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 31 Aug 2026 19:15:53 +0000 Subject: [PATCH] fix: report step count and stop reason in the multi-start search.summary MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A MultiStartProdigy start_here.py run was reported as "stopping at 49 steps because iterations_per_quick_update=50". The search cannot stop at a quick-update boundary — the multi-start step loop never reads the cadence, and its only stop paths are the auto-convergence plateau (gated behind min_steps=100) and the n_steps ceiling. The 49 was search.summary's "Total Samples" line: 1 best + n_starts=48 per-start final points, a count fixed at construction that carries no step information, yet the summary's one prominent number — and the run's real length appeared nowhere. Label the gradient searches' sample count with its composition — only where the arithmetic actually holds: reloaded samples arrive with the weight-0 per-start rows pruned, and n_starts sits outside the search identifier, so on those paths the label would be self-contradictory and the count stays plain. Report Total Steps and Stop Reason beside it, and pin the non-interaction with an end-to-end regression: a MultiStartProdigy fit whose quick-update boundary falls mid-budget runs every one of its steps, and the cadence's current inertness is asserted so the change that wires real quick updates into the step loop must flip that assertion rather than inherit a vacuously green test. Refs #1553 Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_01RMc7X2QncxHM4GEC7b4K4P --- autofit/text/text_util.py | 35 ++++++ ...st_multi_start_quick_update_termination.py | 88 +++++++++++++++ test_autofit/text/test_text_util.py | 106 ++++++++++++++++++ 3 files changed, 229 insertions(+) create mode 100644 test_autofit/non_linear/search/mle/test_multi_start_quick_update_termination.py diff --git a/autofit/text/text_util.py b/autofit/text/text_util.py index 010a14ffc..84e854a97 100644 --- a/autofit/text/text_util.py +++ b/autofit/text/text_util.py @@ -223,6 +223,41 @@ def search_summary_from_samples(samples) -> [str]: n_value_nan = int(samples_info.get("n_value_nan_lane_steps", 0)) n_grad_nan = int(samples_info.get("n_grad_nan_lane_steps", 0)) + # For these searches ``Total Samples`` is 1 best + ``n_starts`` + # per-start final points — a count fixed at construction that carries + # no information about how long the search ran. As the summary's one + # prominent number it reads as a step count anyway: a 48-start run + # reports 49, one below a 50-step quick-update cadence, and was read + # as the search dying at its first quick-update boundary + # (PyAutoFit#1553). So the sample count is labelled with its + # composition and the run's real length is stated explicitly. + # + # The composition is asserted only where it actually holds. The + # per-start rows carry weight 0 and are pruned by the samples-weight + # threshold on write, so RELOADED samples (a completed fit re-run, the + # aggregator) arrive here with ``total_samples == 1``; and ``n_starts`` + # is outside the search identifier, so a re-run at a different + # ``n_starts`` reads a stored ``samples_info`` whose composition never + # matches. Printing "1 (1 best + 48 per-start final points)" on those + # paths would be self-contradictory — worse than the ambiguity this + # line exists to remove. + if ( + "n_starts" in samples_info + and samples.total_samples == int(samples_info["n_starts"]) + 1 + ): + line[0] = ( + f"Total Samples = {samples.total_samples} " + f"(1 best + {int(samples_info['n_starts'])} per-start final " + f"points; not a step count)\n" + ) + if "total_steps" in samples_info: + line.append(f"Total Steps = {int(samples_info['total_steps'])}\n") + # ``.get``: a ``search_internal`` written before auto-convergence + # existed carries no ``stop_reason``; a reason it never recorded is + # omitted rather than reported as ``None``. + if samples_info.get("stop_reason") is not None: + line.append(f"Stop Reason = {samples_info['stop_reason']}\n") + line.append(f"Resurrections = {int(samples_info.get('n_resurrections', 0))}\n") line.append(f"Value-NaN Lane-Steps = {n_value_nan}\n") line.append(f"Gradient-NaN Lane-Steps = {n_grad_nan}\n") diff --git a/test_autofit/non_linear/search/mle/test_multi_start_quick_update_termination.py b/test_autofit/non_linear/search/mle/test_multi_start_quick_update_termination.py new file mode 100644 index 000000000..f39e3ab0b --- /dev/null +++ b/test_autofit/non_linear/search/mle/test_multi_start_quick_update_termination.py @@ -0,0 +1,88 @@ +import importlib.util + +import pytest + +import autofit as af + +# The end-to-end test below runs the JAX-native multi-start step loop, which needs jax + optax +# (both ship via the `[optional]` extras). The Python-version matrix installs autofit without +# those extras, so skip there rather than fail with `No module named 'jax'`. +requires_jax = pytest.mark.skipif( + importlib.util.find_spec("jax") is None + or importlib.util.find_spec("optax") is None, + reason="requires jax + optax (installed via the [optional] extras; absent on the matrix env)", +) + + +class _QuickUpdateRecordingAnalysis(af.Analysis): + """ + A zero-centred Gaussian log-likelihood, written through ``self._xp`` so it + is JAX-traceable (and therefore differentiable) when built with + ``use_jax=True``. + + ``perform_quick_update`` records rather than raising ``NotImplementedError``, + so the assertions below stay valid whether or not the search wires quick + updates into its step loop (today it does not — see the ``EXEMPT`` entry in + ``test_quick_update_wiring.py``): fired or not, a quick update must never + END the search. + """ + + def __init__(self, **kwargs): + super().__init__(**kwargs) + self.quick_update_count = 0 + + def log_likelihood_function(self, instance): + xp = self._xp + values = xp.asarray([instance.one, instance.two]) + return -0.5 * xp.sum(values**2) + + def perform_quick_update(self, paths, instance): + self.quick_update_count += 1 + + +@requires_jax +def test__quick_update_mid_search_does_not_end_the_search(): + """ + Regression for PyAutoFit#1553: an ``imaging/start_here.py`` run using + ``MultiStartProdigy`` with ``iterations_per_quick_update=50`` was reported + as "stopping at 49 steps". The 49 was ``search.summary``'s + ``Total Samples`` line (1 best + ``n_starts=48`` per-start final points), + not a step count: the quick-update cadence must never terminate the step + loop, whose only stop paths are the auto-convergence plateau (gated behind + ``min_steps``) and the ``n_steps`` ceiling. + + Pinned end-to-end: a fit whose quick-update boundary (25) falls well + inside its budget (60) runs every one of its 60 steps. The convergence + check is turned off explicitly, so the ceiling is provably the ONLY thing + that can end this run, in any environment. + """ + model = af.Model(af.m.MockClassx2) + model.one = af.UniformPrior(lower_limit=-5.0, upper_limit=5.0) + model.two = af.UniformPrior(lower_limit=-5.0, upper_limit=5.0) + + search = af.MultiStartProdigy( + n_starts=4, + n_steps=60, + iterations_per_quick_update=25, + convergence=af.MultiStartGradientConvergence(check_for_convergence=False), + ) + + analysis = _QuickUpdateRecordingAnalysis(use_jax=True) + + result = search.fit(model=model, analysis=analysis) + + search_internal = result.search_internal + + assert int(search_internal["total_steps"]) == 60 + assert search_internal["stop_reason"] == "max_steps" + + # Today the cadence is INERT for this family: the search is an ``EXEMPT`` + # entry in ``test_quick_update_wiring.py`` (the traced ``fitness.call`` + # cannot count Python-side), so no quick update fires at all — asserted, + # so this test is sensitive to the knob's state rather than vacuously + # green. The change that wires real quick updates into the step loop MUST + # flip this to assert the updates FIRED (> 0) while keeping the two + # ceiling asserts above unchanged — that is the moment "a quick update + # mid-search does not end the search" is exercised for real, and a silent + # no-op (the PyAutoFit#1434 failure class) becomes a loud failure here. + assert analysis.quick_update_count == 0 diff --git a/test_autofit/text/test_text_util.py b/test_autofit/text/test_text_util.py index df405b53b..18bcf8348 100644 --- a/test_autofit/text/test_text_util.py +++ b/test_autofit/text/test_text_util.py @@ -186,6 +186,9 @@ def test__search_summary__nan_counters_absent_for_other_searches(model): assert "NaN" not in summary assert "Resurrections" not in summary assert "Lane-Step" not in summary + assert "Total Steps" not in summary + assert "Stop Reason" not in summary + assert "per-start" not in summary # The MCMC block it sits beside is untouched. assert "Total Accepted Samples = 2\n" in summary @@ -215,6 +218,109 @@ def test__search_summary__nan_rates_omitted_when_no_lane_steps_taken(model): assert "Rate" not in summary +def test__search_summary__step_count_and_stop_reason_reported(model): + """ + The gradient searches report how long the run actually was. Their + ``Total Samples`` is 1 best + ``n_starts`` per-start final points — fixed + at construction, no step information — yet as the summary's one prominent + number it reads as a step count: a 48-start run reports 49, one below a + 50-step quick-update cadence, and was read as the search dying at its + first quick-update boundary (PyAutoFit#1553). The sample count is + labelled with its composition and the step count / stop reason are + stated explicitly. + """ + # 1 best + 8 per-start final points, matching ``n_starts`` below — the + # composition label is only emitted where its arithmetic actually holds. + parameters = [[float(i), float(i)] for i in range(9)] + + samples = af.m.MockSamples( + model=model, + sample_list=af.Sample.from_lists( + parameter_lists=parameters, + log_likelihood_list=[1.0] + [0.0] * 8, + log_prior_list=[0.0] * 9, + weight_list=[1.0] + [0.0] * 8, + model=model, + ), + samples_info={ + "total_samples": 9, + "time": None, + "n_starts": 8, + "total_steps": 300, + "stop_reason": "max_steps", + "n_resurrections": 0, + "n_value_nan_lane_steps": 0, + "n_grad_nan_lane_steps": 0, + }, + ) + + summary = "".join(text_util.search_summary_from_samples(samples=samples)) + + assert ( + "Total Samples = 9 (1 best + 8 per-start final points; " + "not a step count)\n" in summary + ) + assert "Total Steps = 300\n" in summary + assert "Stop Reason = max_steps\n" in summary + + +def test__search_summary__composition_omitted_when_arithmetic_does_not_hold(model): + """ + The per-start rows carry weight 0 and are pruned by the samples-weight + threshold on write, so RELOADED samples (a completed fit re-run, the + aggregator) arrive with fewer rows than ``1 + n_starts``; and ``n_starts`` + is outside the search identifier, so a re-run at a different ``n_starts`` + reads a stored ``samples_info`` whose composition never matches. On those + paths the composition label would be self-contradictory, so the sample + count stays plain — the step count still reports. + """ + samples = _gradient_samples( + model=model, + samples_info={ + "total_samples": 9, + "time": None, + "n_starts": 8, + "total_steps": 300, + "stop_reason": "max_steps", + "n_resurrections": 0, + "n_value_nan_lane_steps": 0, + "n_grad_nan_lane_steps": 0, + }, + ) + + # ``total_samples`` is ``len(sample_list)`` — 2 in this mock, != 1 + 8. + summary = "".join(text_util.search_summary_from_samples(samples=samples)) + + assert "Total Samples = 2\n" in summary + assert "per-start" not in summary + assert "Total Steps = 300\n" in summary + + +def test__search_summary__stop_reason_omitted_when_never_written(model): + """ + A ``search_internal`` written before auto-convergence existed carries no + ``stop_reason``; a reason the run never recorded is omitted rather than + reported as ``None``. The step count still reports. + """ + samples = _gradient_samples( + model=model, + samples_info={ + "total_samples": 10, + "time": None, + "n_starts": 8, + "total_steps": 100, + "n_resurrections": 0, + "n_value_nan_lane_steps": 0, + "n_grad_nan_lane_steps": 0, + }, + ) + + summary = "".join(text_util.search_summary_from_samples(samples=samples)) + + assert "Total Steps = 100\n" in summary + assert "Stop Reason" not in summary + + def test__search_summary__clipper_none_emits_nothing(model): """ The default path must be untouched. A ``ClipperNone`` run reports no