From 1cd4a5b857535f465782f2ce3b3442e40c2b4f39 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Thu, 24 Sep 2026 17:28:51 +0200 Subject: [PATCH] perf(ep): EP factor searches skip per-search visuals by default (#1642) New config key `general.yaml -> output -> visualize_ep_factor_searches` (default false). Under expectation propagation, `NonLinearSearch.optimise` now turns off each factor search's per-search visuals (analysis.visualize / visualize_combined and plot_results) and draws before-fit visuals only on the first search of each factor. Samples, summaries and the EP optimiser's own output (graph.info, graph.png, ep_history.csv) are unchanged. Set the key true to restore the previous behaviour. - NonLinearSearch: class-level `_visualize_fit` / `_visualize_before_fit` switches, set around `self.fit` in `optimise` and reset in `finally`; `pre_fit_output` gates before-fit visuals on them. - SearchUpdater: `visualization_enabled` flag; `visualize()` is a no-op when False. `_updater` propagates `_visualize_fit` on every access. - The key is read with `.get(..., False)` so user configs that predate it keep working. Users lose per-factor model_fit/corner images by default under EP (intended). Co-Authored-By: Claude Fable 5.1 --- autofit/config/general.yaml | 1 + autofit/non_linear/search/abstract_search.py | 38 ++++- autofit/non_linear/search/updater.py | 10 ++ .../test_ep_factor_search_visuals.py | 157 ++++++++++++++++++ .../non_linear/search/test_updater.py | 32 ++++ 5 files changed, 236 insertions(+), 2 deletions(-) create mode 100644 test_autofit/graphical/test_ep_factor_search_visuals.py diff --git a/autofit/config/general.yaml b/autofit/config/general.yaml index a854e2a90..07743f094 100644 --- a/autofit/config/general.yaml +++ b/autofit/config/general.yaml @@ -22,6 +22,7 @@ output: search_internal : false # If True, the search internal folder which contains a saved state of the non-linear search is delete, saving on hard-disk space. samples_to_csv: true # If True, non-linear search samples are written to a .csv file. unconverged_sample_size : 100 # If outputting results of an unconverged search, the number of samples used to estimate the median PDF values and errors. + visualize_ep_factor_searches: false # Expectation propagation only. If True, every EP factor search draws its own per-search visuals (e.g. corner plots, model-fit images) and redraws its before-fit visuals. If False, only the first search of each factor draws before-fit visuals and no factor search draws per-search visuals (samples and summaries are still written; the EP optimiser's own graph.png / ep_history output is unaffected). parallel: warn_environment_variables: true # If True, a warning is displayed when the search's number of CPU > 1 and enviromment variables related to threading are also > 1. profiling: diff --git a/autofit/non_linear/search/abstract_search.py b/autofit/non_linear/search/abstract_search.py index da687d9d5..b24a9ac81 100644 --- a/autofit/non_linear/search/abstract_search.py +++ b/autofit/non_linear/search/abstract_search.py @@ -136,6 +136,14 @@ def decorated(self, *args, **kwargs): class NonLinearSearch(AbstractFactorOptimiser, ABC): + # Visualization switches toggled per factor search by ``optimise`` (EP), + # governed by ``general.yaml -> output -> visualize_ep_factor_searches``. + # Class-level (not set in ``__init__``) so search doubles that skip + # ``__init__`` (e.g. the regression suite's ``StaticSearch``) still have + # them. Outside EP both are always True. + _visualize_fit = True + _visualize_before_fit = True + def __init__( self, name: Optional[str] = None, @@ -430,7 +438,28 @@ def optimise( is_flat=True, ) - result = self.fit(model=model, analysis=analysis) + # EP re-enters the same factor search once per EP step. By default only + # the first search of each factor draws its before-fit visuals and no + # factor search draws per-search visuals (corner plots, model-fit + # images): at small per-factor fits the plotting dominates the wall + # time and the images are overwritten every step anyway. Samples and + # summaries are still written, and the EP optimiser's own visuals + # (graph.png, ep_history) are unaffected. `.get` with a default so user + # configs that predate the key keep working. + visualize_ep_factor_searches = bool( + conf.instance["general"]["output"].get( + "visualize_ep_factor_searches", False + ) + ) + + self._visualize_fit = visualize_ep_factor_searches + self._visualize_before_fit = visualize_ep_factor_searches or number == 0 + + try: + result = self.fit(model=model, analysis=analysis) + finally: + self._visualize_fit = True + self._visualize_before_fit = True # Record the sampler's log-evidence of this tilted-distribution fit on # the projected mean field — the per-factor Ẑₐ that README §5 documents @@ -755,7 +784,9 @@ def pre_fit_output( ) analysis.save_attributes(paths=self.paths) - if analysis.should_visualize(paths=self.paths): + if self._visualize_before_fit and analysis.should_visualize( + paths=self.paths + ): analysis.visualize_before_fit( paths=self.paths, model=model, @@ -1469,6 +1500,9 @@ def _updater(self): disable_output=self.disable_output, iterations_per_full_update=self.iterations_per_full_update, ) + # Re-applied on every access: ``optimise`` toggles ``_visualize_fit`` + # per EP factor search, and the cached updater must follow it. + self._search_updater.visualization_enabled = self._visualize_fit return self._search_updater def perform_update( diff --git a/autofit/non_linear/search/updater.py b/autofit/non_linear/search/updater.py index 560abb8f5..fe71bb12f 100644 --- a/autofit/non_linear/search/updater.py +++ b/autofit/non_linear/search/updater.py @@ -47,6 +47,7 @@ def __init__( samples_from_func: Callable[[AbstractPriorModel, ...], Samples], disable_output: bool, iterations_per_full_update: float, + visualization_enabled: bool = True, ): self._paths = paths self._timer = timer @@ -56,6 +57,10 @@ def __init__( self._disable_output = disable_output self._iterations_per_full_update = iterations_per_full_update self._iterations = 0 + # When False, ``visualize`` is a no-op (analysis visuals and the + # search's ``plot_results``). Set per factor search by EP; see + # ``general.yaml -> output -> visualize_ep_factor_searches``. + self.visualization_enabled = visualization_enabled @property def iterations(self) -> int: @@ -138,7 +143,12 @@ def visualize( Delegates to the analysis object for model-specific plots and to the search's ``plot_results`` for search-specific plots. + + Returns immediately when ``visualization_enabled`` is False. """ + if not self.visualization_enabled: + return + self._logger.debug("Visualizing") paths = paths_override or self._paths diff --git a/test_autofit/graphical/test_ep_factor_search_visuals.py b/test_autofit/graphical/test_ep_factor_search_visuals.py new file mode 100644 index 000000000..c5e42c2db --- /dev/null +++ b/test_autofit/graphical/test_ep_factor_search_visuals.py @@ -0,0 +1,157 @@ +""" +EP factor searches skip their per-search visuals by default (PyAutoFit #1642). + +Expectation propagation re-enters the same factor search once per factor per EP +step. At the small per-factor fits EP is built on, a search's own visuals +(`analysis.visualize`, the corner / fit plots of `plot_results`) dominated the +wall time, and each step overwrote the previous step's images anyway. + +`general.yaml -> output -> visualize_ep_factor_searches` (default False) now +governs them: off, only the first search of each factor draws its before-fit +visuals and no factor search draws per-search visuals; on, the old behaviour. +Samples, summaries and the EP optimiser's own output (`graph.info`, +`graph.png`, `ep_history.csv`) are written either way. +""" + +import numpy as np +import pytest + +from autonerves import conf + +import autofit as af + +pytestmark = [ + pytest.mark.filterwarnings("ignore::FutureWarning"), + pytest.mark.filterwarnings("ignore::RuntimeWarning"), +] + + +# Module level (not local classes / closures) so the analysis pickles with the +# dynesty checkpoint. +CALLS = [] +PLOT_CALLS = [] + + +class RecordingVisualizer(af.Visualizer): + @staticmethod + def visualize_before_fit(analysis, paths, model): + CALLS.append(("visualize_before_fit", paths.analysis_name)) + + @staticmethod + def visualize(analysis, paths, instance, during_analysis): + CALLS.append(("visualize", paths.analysis_name)) + + +class RecordingAnalysis(af.ex.Analysis): + Visualizer = RecordingVisualizer + + +def _run_ep(tmp_path, monkeypatch): + """ + Two AnalysisFactors sharing a centre, each fitted by a named DynestyStatic, + two EP steps. + + Returns the recorded Visualizer calls, the recorded `plot_results` calls + and the EP output path. + """ + CALLS.clear() + PLOT_CALLS.clear() + + def recording_plot_results(self, samples): + PLOT_CALLS.append(self.paths.analysis_name) + + monkeypatch.setattr(af.DynestyStatic, "plot_results", recording_plot_results) + + x = np.arange(50) + centre = af.GaussianPrior(mean=25.0, sigma=10.0) + + # One search object shared by both factors, as a user would build it; the + # prior factors fall back to the Laplace default optimiser. + search = af.DynestyStatic( + name="ep_visuals", nlive=20, maxcall=200, number_of_cores=1 + ) + + factors = [] + for i in range(2): + data = af.ex.Gaussian(centre=25.0, normalization=10.0, sigma=5.0).model_data_from( + xvalues=x + ) + model = af.Model( + af.ex.Gaussian, + centre=centre, + normalization=af.GaussianPrior(mean=10.0, sigma=5.0), + sigma=af.GaussianPrior(mean=5.0, sigma=2.0), + ) + factors.append( + af.AnalysisFactor( + model, + analysis=RecordingAnalysis(data=data, noise_map=np.ones(50)), + name=f"factor_{i}", + optimiser=search, + ) + ) + + factor_graph = af.FactorGraphModel(*factors) + + paths = af.DirectoryPaths(name="ep_factor_search_visuals", path_prefix=str(tmp_path)) + + factor_graph.optimise( + af.LaplaceOptimiser(), + paths=paths, + ep_history=af.EPHistory(kl_tol=None), + max_steps=2, + ) + + return list(CALLS), list(PLOT_CALLS), paths.output_path + + +def test__default__factor_searches_skip_per_search_visuals(tmp_path, monkeypatch): + calls, plot_calls, output_path = _run_ep(tmp_path, monkeypatch) + + assert [c for c in calls if c[0] == "visualize"] == [] + assert plot_calls == [] + + # Before-fit visuals once per factor: only its first search draws them. + before = sorted(c[1] for c in calls if c[0] == "visualize_before_fit") + assert before == ["factor_0/optimization_0", "factor_1/optimization_0"] + + # The EP optimiser's own output is untouched. + assert (output_path / "graph.info").exists() + assert (output_path / "graph.png").exists() + assert (output_path / "ep_history.csv").exists() + + +def test__key_on__factor_searches_draw_per_search_visuals(tmp_path, monkeypatch): + output = conf.instance["general"]["output"] + original = output.get("visualize_ep_factor_searches", False) + output["visualize_ep_factor_searches"] = True + try: + calls, plot_calls, _ = _run_ep(tmp_path, monkeypatch) + finally: + output["visualize_ep_factor_searches"] = original + + visualized = {c[1] for c in calls if c[0] == "visualize"} + assert visualized == { + "factor_0/optimization_0", + "factor_0/optimization_1", + "factor_1/optimization_0", + "factor_1/optimization_1", + } + assert len(plot_calls) == 4 + + before = sorted(c[1] for c in calls if c[0] == "visualize_before_fit") + assert before == [ + "factor_0/optimization_0", + "factor_0/optimization_1", + "factor_1/optimization_0", + "factor_1/optimization_1", + ] + + +def test__visualize_switches_reset_after_optimise(tmp_path, monkeypatch): + """`optimise` restores the switches, so the search behaves normally afterwards.""" + _run_ep(tmp_path, monkeypatch) + + search = af.DynestyStatic(name="after", number_of_cores=1) + assert search._visualize_fit is True + assert search._visualize_before_fit is True diff --git a/test_autofit/non_linear/search/test_updater.py b/test_autofit/non_linear/search/test_updater.py index afa15c518..a905eb0a5 100644 --- a/test_autofit/non_linear/search/test_updater.py +++ b/test_autofit/non_linear/search/test_updater.py @@ -203,3 +203,35 @@ def test__save_samples__writes_samples_csv_when_the_best_point_is_rejected( assert instance is None assert (paths._files_path / "samples.csv").exists() assert (paths._files_path / "samples_summary.json").exists() + + +def test__visualize__disabled_skips_all(): + """ + With ``visualization_enabled=False`` (EP factor searches, #1642) neither the + analysis visuals nor the search's ``plot_results`` run, and no samples are + loaded for plotting. + """ + updater = SearchUpdater( + paths=MagicMock(), + timer=MagicMock(), + search_logger=logging.getLogger("test_updater"), + plot_results_func=MagicMock(), + samples_from_func=MagicMock(), + disable_output=False, + iterations_per_full_update=1.0, + visualization_enabled=False, + ) + analysis = MagicMock() + + updater.visualize( + model=MagicMock(), + analysis=analysis, + during_analysis=False, + samples_summary=MagicMock(), + ) + + analysis.should_visualize.assert_not_called() + analysis.visualize.assert_not_called() + analysis.visualize_combined.assert_not_called() + updater._samples_from.assert_not_called() + updater._plot_results.assert_not_called()