From 3333c1a3597143dab0ec28c7613ed3000226fbe6 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Tue, 24 Nov 2026 20:52:34 +0000 Subject: [PATCH] feat: runtime_estimate hook after the Parallel banner (5E-2) resolve_fit_parallel takes the model and, after the Parallel: banner, asks a duck-typed analysis.runtime_estimate(search, model, number_of_cores) for a one-line estimate, logging it and recording estimate_line in files/parallel.json. A missing, raising or empty hook never affects a fit. Part of PyAutoLabs/PyAutoLens#887 (likelihood-lifecycle phase 5E-2). Co-Authored-By: Claude Opus 5.5 --- autofit/non_linear/search/abstract_search.py | 2 +- autofit/non_linear/search/runtime.py | 45 ++++++++- .../non_linear/test_number_of_cores_auto.py | 92 +++++++++++++++++++ 3 files changed, 135 insertions(+), 4 deletions(-) diff --git a/autofit/non_linear/search/abstract_search.py b/autofit/non_linear/search/abstract_search.py index 29467bdb9..57f8d25f3 100644 --- a/autofit/non_linear/search/abstract_search.py +++ b/autofit/non_linear/search/abstract_search.py @@ -317,7 +317,7 @@ def _fit_and_output(self, model, analysis, info=None): model.freeze() analysis = analysis.modify_before_fit(paths=self.paths, model=model) model.unfreeze() - resolve_fit_parallel(self, analysis) + resolve_fit_parallel(self, analysis, model=model) if not skip_fit_output(): self.pre_fit_output(analysis=analysis, model=model, info=info) diff --git a/autofit/non_linear/search/runtime.py b/autofit/non_linear/search/runtime.py index 926c8dff8..5721d529a 100644 --- a/autofit/non_linear/search/runtime.py +++ b/autofit/non_linear/search/runtime.py @@ -268,7 +268,7 @@ def log_fit_start(search, analysis): logger.info(search.quick_update_message) -def resolve_fit_parallel(search, analysis): +def resolve_fit_parallel(search, analysis, model=None): """ Resolve a fit's worker count once ``modify_before_fit`` has resolved the analysis's compute setup (``autofit.non_linear.parallel.pool.resolve_number_of_cores``: @@ -281,6 +281,12 @@ def resolve_fit_parallel(search, analysis): ``"auto"`` request gets its thread warning here, for the resolved count. Writes ``files/parallel.json`` unless the fit is already complete (a completed fit keeps the record of the run that produced it). + + After the banner, an analysis that defines ``runtime_estimate(search, model, + number_of_cores)`` (duck-typed; PyAutoLens implements it) is asked for a one-line + run-time estimate, which is logged and recorded as ``estimate_line`` in + ``files/parallel.json``. The hook is advisory: an analysis without it, a hook + returning anything but a non-empty string, or a hook that raises never affects the fit. """ from autofit.non_linear.parallel.pool import resolve_number_of_cores from autofit.non_linear.parallel.resources import is_auto @@ -294,18 +300,51 @@ def resolve_fit_parallel(search, analysis): search._parallel_resolution = resolution search._parallel_summary = resolution.summary - getattr(search, "logger", logger).info(resolution.banner) + search_logger = getattr(search, "logger", logger) + search_logger.info(resolution.banner) + + estimate_line = runtime_estimate_line( + search=search, + analysis=analysis, + model=model, + number_of_cores=resolution.number_of_cores, + ) + if estimate_line is not None: + search_logger.info(estimate_line) if is_auto(resolution.requested): warn_if_threads_unpinned(resolution.number_of_cores) paths = getattr(search, "paths", None) if paths is not None and not paths.is_complete: - paths.save_json("parallel", resolution.to_dict()) + record = resolution.to_dict() + record["estimate_line"] = estimate_line + paths.save_json("parallel", record) return resolution +def runtime_estimate_line(search, analysis, model, number_of_cores): + """ + The one-line run-time estimate an analysis gives for this fit, or ``None``. + + Calls ``analysis.runtime_estimate(search=..., model=..., number_of_cores=...)`` when + the analysis defines it. Only a non-empty string is used; any exception is logged at + debug level and ignored, so an estimate can never stop or change a fit. + """ + hook = getattr(analysis, "runtime_estimate", None) + if not callable(hook): + return None + try: + line = hook(search=search, model=model, number_of_cores=number_of_cores) + except Exception as e: + logger.debug(f"runtime_estimate failed and was ignored: {e!r}") + return None + if isinstance(line, str) and line.strip(): + return line.strip() + return None + + def fit_pools(search, analysis): """ The fit's ``PoolFactory``, built on the resolution ``resolve_fit_parallel`` made diff --git a/test_autofit/non_linear/test_number_of_cores_auto.py b/test_autofit/non_linear/test_number_of_cores_auto.py index 1ab7ba2a0..1b39eee30 100644 --- a/test_autofit/non_linear/test_number_of_cores_auto.py +++ b/test_autofit/non_linear/test_number_of_cores_auto.py @@ -363,6 +363,7 @@ def test_fit_logs_one_banner_after_modify_before_fit_and_writes_parallel_json( "detected_cores": 64, "available_memory_gb": None, "setup_id": "numba_cpu_sparse_fp64", + "estimate_line": None, } assert search_json["arguments"]["number_of_cores"] == "auto" @@ -381,3 +382,94 @@ def test_fit_banner_for_jax_auto(monkeypatch, caplog, tmp_path): assert [r.getMessage() for r in _banner_records(caplog)] == [ "Parallel: 1 worker (requested auto; JAX analyses run single-process)" ] + + +# ------------------------------------------------- runtime_estimate hook (5E-2) + + +class _EstimateAnalysis(_SetupAnalysis): + """An analysis with a duck-typed ``runtime_estimate`` hook that records its call.""" + + def __init__(self, *args, line="Estimate: ~2 ms/eval", raises=False, **kwargs): + super().__init__(*args, **kwargs) + self.line = line + self.raises = raises + self.calls = [] + + def runtime_estimate(self, search, model, number_of_cores): + self.calls.append((search, model, number_of_cores)) + if self.raises: + raise RuntimeError("no estimate data") + return self.line + + +def _fit_with(analysis, tmp_path, monkeypatch, caplog, name): + monkeypatch.setenv("PYAUTO_TEST_MODE", "2") + search = af.Emcee(name=name, path_prefix=str(tmp_path), number_of_cores="auto") + model = af.Model(af.ex.Gaussian) + with caplog.at_level(logging.INFO): + search.fit(model=model, analysis=analysis) + with zipfile.ZipFile(search.paths._zip_path) as archive: + record = json.loads(archive.read("files/parallel.json")) + messages = [r.getMessage() for r in caplog.records] + return search, model, record, messages + + +def test_runtime_estimate_hook_is_logged_after_the_banner_and_recorded( + monkeypatch, caplog, tmp_path +): + analysis = _EstimateAnalysis(data=np.ones(10), noise_map=np.ones(10)) + search, model, record, messages = _fit_with( + analysis, tmp_path, monkeypatch, caplog, "estimate_hook" + ) + + banner = next(i for i, m in enumerate(messages) if m.startswith("Parallel:")) + assert messages[banner + 1] == "Estimate: ~2 ms/eval" + assert record["estimate_line"] == "Estimate: ~2 ms/eval" + + assert len(analysis.calls) == 1 + called_search, called_model, called_cores = analysis.calls[0] + assert called_search is search + assert called_model.prior_count == model.prior_count + assert called_cores == 64 + + +def test_runtime_estimate_hook_that_raises_is_ignored(monkeypatch, caplog, tmp_path): + analysis = _EstimateAnalysis( + data=np.ones(10), noise_map=np.ones(10), raises=True + ) + _, _, record, messages = _fit_with( + analysis, tmp_path, monkeypatch, caplog, "estimate_raises" + ) + + assert record["estimate_line"] is None + assert not [m for m in messages if m.startswith("Estimate:")] + assert len([m for m in messages if m.startswith("Parallel:")]) == 1 + + +@pytest.mark.parametrize("line", [None, "", " ", 42]) +def test_runtime_estimate_hook_non_string_or_empty_is_ignored(line): + from autofit.non_linear.search.runtime import runtime_estimate_line + + class _Analysis: + def runtime_estimate(self, search, model, number_of_cores): + return line + + assert ( + runtime_estimate_line( + search=None, analysis=_Analysis(), model=None, number_of_cores=1 + ) + is None + ) + + +def test_runtime_estimate_line_without_hook_is_none(): + from autofit.non_linear.search.runtime import runtime_estimate_line + + assert ( + runtime_estimate_line( + search=None, analysis=object(), model=None, number_of_cores=4 + ) + is None + ) +