From 451d60ab883281391d3de0a81b705eb46b497f62 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Wed, 25 Nov 2026 16:21:24 +0000 Subject: [PATCH] feat: resolve setup before pre-fit use, idempotent banner, JAX-fallback Setup line Part of PyAutoLabs/PyAutoGalaxy#756. Co-Authored-By: Claude Opus 5.5 --- autogalaxy/analysis/analysis/setup.py | 35 +++++ autogalaxy/analysis/setup_util.py | 55 ++++++- .../analysis/test_analysis_dataset.py | 144 ++++++++++++++++++ 3 files changed, 228 insertions(+), 6 deletions(-) diff --git a/autogalaxy/analysis/analysis/setup.py b/autogalaxy/analysis/analysis/setup.py index c9c41e20..32515df3 100644 --- a/autogalaxy/analysis/analysis/setup.py +++ b/autogalaxy/analysis/analysis/setup.py @@ -70,6 +70,22 @@ def _apply_resolved_setup(self, setup: aa.Setup): default does nothing. """ + def prepare_for_model(self, model: af.Collection): + """ + Resolve the setup from `model` before the fit starts, when the analysis has a `setup` input + that is not yet resolved (`af.Analysis.prepare_for_model`). + + Pre-fit likelihood use, such as `print_vram_use(model=...)`, calls this so a `setup="auto"` + analysis knows its backend before its likelihood is evaluated. The banner is logged now; the + `modify_before_fit` of a later fit with the same model re-applies the same setup without + logging it again (see `resolve_setup`). + """ + if getattr(self, "setup_input", None) is None: + return + if getattr(self, "setup", None) is not None: + return + self.resolve_setup(model=model) + def resolve_setup(self, model: af.Collection, log_banner: bool = True): """ Resolve the `setup` input of the analysis against the model and apply it. @@ -89,6 +105,11 @@ def resolve_setup(self, model: af.Collection, log_banner: bool = True): - pins the thread pools (`setup.apply_threads()`); - is logged as the header and `Setup:` lines (two records) and stored as `self.setup`. + It is safe to call more than once (e.g. by `prepare_for_model` before the fit and by + `modify_before_fit` when it starts): the setup is re-resolved and re-applied each time, but when + it is the one already resolved (same `setup_id`, chosen the same way) the banner is not logged a + second time. A different setup is applied and logged. + Parameters ---------- model @@ -120,8 +141,16 @@ def resolve_setup(self, model: af.Collection, log_banner: bool = True): setup = setup_input chosen_by = setup_util.chosen_by_from(setup=setup, auto=False) + previous = getattr(self, "setup", None) + already_logged = ( + previous is not None + and previous.setup_id == setup.setup_id + and getattr(self, "setup_chosen_by", None) == chosen_by + ) + self._use_jax = setup_util.use_jax_from(setup.backend == "jax") + # `apply_setup` is idempotent, so re-applying the same setup rebuilds nothing. self._apply_resolved_setup(setup) setup.apply_threads() @@ -129,13 +158,19 @@ def resolve_setup(self, model: af.Collection, log_banner: bool = True): self.setup = setup self.setup_chosen_by = chosen_by + if already_logged: + return + # The header and `Setup:` line are logged after the operator build and checks above (or # later still, by `log_setup_banner`), so they sit with the fit's `Parallel:` / `Estimate:` lines. + # They report the backend that runs (`_use_jax`), which differs from the designated one when + # JAX is disabled or not installed. self._setup_banner_lines = setup_util.setup_banner_lines_from( setup=setup, chosen_by=chosen_by, environment=environment, note=note, + use_jax=self._use_jax, ) if log_banner: diff --git a/autogalaxy/analysis/setup_util.py b/autogalaxy/analysis/setup_util.py index 2bc54865..e7eb554b 100644 --- a/autogalaxy/analysis/setup_util.py +++ b/autogalaxy/analysis/setup_util.py @@ -330,14 +330,39 @@ def hardware_description_from(setup: Setup, environment=None) -> Optional[str]: LABEL_WIDTH = len("Parallel: ") -def setup_text_from(setup: Setup) -> str: +def jax_fallback_reason_from(setup: Setup, use_jax: Optional[bool] = None) -> Optional[str]: + """ + Why a setup designating the `jax` backend runs on numpy instead (`None` when it does not): + `"JAX disabled"` under `PYAUTO_DISABLE_JAX=1`, else `"JAX not installed"`. + + `use_jax` is the resolved backend of the analysis (`use_jax_from`); `None` means "as + designated", so there is no fallback. + """ + if use_jax is None or use_jax or setup.backend != "jax": + return None + if os.environ.get("PYAUTO_DISABLE_JAX") == "1": + return "JAX disabled" + return "JAX not installed" + + +def setup_text_from(setup: Setup, use_jax: Optional[bool] = None) -> str: """ The setup tuple in readable tokens, e.g. `numba · CPU · sparse operator · fp64` or `numba · CPU · sparse operator · fp64 · w-tilde`. + + `use_jax` is the backend the analysis actually resolved (`use_jax_from`). When the setup + designates `jax` but `use_jax` is `False` (`PYAUTO_DISABLE_JAX=1` or JAX not installed), + the text reports what runs, `numpy · CPU`, not the designation. `None` (the default) + reports the setup as designated. """ + if jax_fallback_reason_from(setup=setup, use_jax=use_jax) is not None: + backend, device = "numpy", "cpu" + else: + backend, device = setup.backend, setup.device + tokens = [ - _BACKEND_TEXT.get(setup.backend, setup.backend), - setup.device.upper(), + _BACKEND_TEXT.get(backend, backend), + device.upper(), _OPERATOR_TEXT.get(setup.operator, f"{setup.operator} operator"), _PRECISION_TEXT.get(setup.precision, setup.precision), ] @@ -437,6 +462,7 @@ def setup_banner_from( chosen_by: str, environment=None, note: Optional[str] = None, + use_jax: Optional[bool] = None, ) -> str: """ The `Setup:` line logged at fit start (after `setup_header_from`), e.g. @@ -448,8 +474,13 @@ def setup_banner_from( extrapolated, why (`extrapolated_reason_from`); `note` (e.g. that a fallback rule was used) is appended inside the parentheses. An explicit or `PYAUTO_SETUP` setup has only the note, if any. + + `use_jax` is the backend the analysis resolved (`use_jax_from`). When a `jax` setup + falls back to numpy, the line reports what runs and names the designation and why, e.g. + + `Setup: numpy · CPU · dense · fp64 (rule imaging/mge · designated JAX; JAX disabled)` """ - line = f"{'Setup:':<{LABEL_WIDTH}}{setup_text_from(setup)}" + line = f"{'Setup:':<{LABEL_WIDTH}}{setup_text_from(setup, use_jax=use_jax)}" details = [] if chosen_by == CHOSEN_BY_AUTO: @@ -458,6 +489,12 @@ def setup_banner_from( reason = extrapolated_reason_from(setup=setup, environment=environment) if reason: details.append(f"extrapolated: {reason}") + fallback = jax_fallback_reason_from(setup=setup, use_jax=use_jax) + if fallback: + designated = _BACKEND_TEXT.get(setup.backend, setup.backend) + if setup.device != "cpu": + designated += f" on {setup.device.upper()}" + details.append(f"designated {designated}; {fallback}") if note: details.append(note) @@ -472,16 +509,22 @@ def setup_banner_lines_from( chosen_by: str, environment=None, note: Optional[str] = None, + use_jax: Optional[bool] = None, ) -> list: """ The header and `Setup:` lines logged at fit start, as two lines logged as two consecutive records (so each carries the log prefix and the labels align with the - `Parallel:` / `Estimate:` lines that follow). + `Parallel:` / `Estimate:` lines that follow). `use_jax` is the resolved backend (see + `setup_banner_from`). """ return [ setup_header_from(setup=setup, chosen_by=chosen_by), setup_banner_from( - setup=setup, chosen_by=chosen_by, environment=environment, note=note + setup=setup, + chosen_by=chosen_by, + environment=environment, + note=note, + use_jax=use_jax, ), ] diff --git a/test_autogalaxy/analysis/analysis/test_analysis_dataset.py b/test_autogalaxy/analysis/analysis/test_analysis_dataset.py index fc215ad2..08a252d6 100644 --- a/test_autogalaxy/analysis/analysis/test_analysis_dataset.py +++ b/test_autogalaxy/analysis/analysis/test_analysis_dataset.py @@ -591,3 +591,147 @@ def test__resolve_setup__log_banner_false__lines_kept_for_log_setup_banner( messages = [r.message for r in caplog.records] assert len([m for m in messages if m.startswith("Automatic compute setup (")]) == 1 assert len([m for m in messages if m.startswith("Setup:")]) == 1 + + +def _setup_lines(caplog): + return [ + r.message + for r in caplog.records + if r.message.startswith(("Automatic compute setup (", "Setup:")) + ] + + +def test__print_vram_use__resolves_auto_setup_and_logs_banner_once( + masked_imaging_7x7, many_core, caplog, monkeypatch, capsys +): + monkeypatch.delenv("PYAUTO_SKIP_FIT_OUTPUT", raising=False) + + model = _model_with_mesh(ag.mesh.RectangularUniform(shape=(3, 3))) + + analysis = ag.AnalysisImaging(dataset=masked_imaging_7x7, setup="auto", use_jax=True) + + assert analysis.setup is None + + with caplog.at_level(logging.INFO): + analysis.print_vram_use(model=model, batch_size=2) + + # Resolved from the model before `is_jax` was read: a numba CPU setup, so no VRAM. + assert analysis.setup.setup_id == "numba_cpu_sparse_fp64" + assert analysis.is_jax is False + assert "use_jax=False" in capsys.readouterr().out + assert _setup_lines(caplog) == [ + 'Automatic compute setup (CPU/GPU choice from setup="auto"; override with ' + "PYAUTO_SETUP or setup=...):", + "Setup: numba · CPU · sparse operator · fp64 (rule imaging/rectangular)", + ] + caplog.clear() + + # The fit then re-applies the same setup without logging it again. + with caplog.at_level(logging.INFO): + analysis.modify_before_fit(paths=af.DirectoryPaths(), model=model) + + assert analysis.setup.setup_id == "numba_cpu_sparse_fp64" + assert analysis.dataset.setup.setup_id == "numba_cpu_sparse_fp64" + assert _setup_lines(caplog) == [] + + +def test__prepare_for_model__no_setup_input_is_a_no_op(masked_imaging_7x7, many_core): + analysis = ag.AnalysisImaging(dataset=masked_imaging_7x7, use_jax=False) + + analysis.prepare_for_model(_parametric_model()) + + assert analysis.setup is None + assert analysis.dataset is masked_imaging_7x7 + + +def test__resolve_setup__different_setup_is_logged_again( + masked_imaging_7x7, many_core, caplog +): + analysis = ag.AnalysisImaging(dataset=masked_imaging_7x7, setup="auto", use_jax=False) + + analysis.prepare_for_model(_model_with_mesh(ag.mesh.RectangularUniform(shape=(3, 3)))) + assert analysis.setup.setup_id == "numba_cpu_sparse_fp64" + caplog.clear() + + with caplog.at_level(logging.INFO): + analysis.modify_before_fit(paths=af.DirectoryPaths(), model=_parametric_model()) + + assert analysis.setup.setup_id == "jax_cpu_dense_fp64" + assert len([m for m in _setup_lines(caplog) if m.startswith("Setup:")]) == 1 + + +def test__model_analysis__modify_before_fit_resolves_inner_setup( + masked_imaging_7x7, many_core +): + model = _model_with_mesh(ag.mesh.RectangularUniform(shape=(3, 3))) + + analysis = ag.AnalysisImaging(dataset=masked_imaging_7x7, setup="auto", use_jax=True) + wrapper = analysis.with_model(model) + + returned = wrapper.modify_before_fit(paths=af.DirectoryPaths(), model=model) + + assert returned is wrapper + assert wrapper.analysis.setup.setup_id == "numba_cpu_sparse_fp64" + assert wrapper.is_jax is False + + +@pytest.mark.parametrize( + "disable, reason", [(True, "JAX disabled"), (False, "JAX not installed")] +) +def test__setup_banner_from__jax_fallback_reports_numpy(monkeypatch, disable, reason): + if disable: + monkeypatch.setenv("PYAUTO_DISABLE_JAX", "1") + else: + monkeypatch.delenv("PYAUTO_DISABLE_JAX", raising=False) + + setup = aa.Setup.from_setup_id( + "jax_gpu_dense_fp64", + rule_id="imaging-mge-standard-gpu-a100", + hardware_class="gpu_a100", + decision_id="imaging-mge-standard-gpu-a100", + extrapolated=False, + ) + + banner = setup_util.setup_banner_from( + setup=setup, + chosen_by="auto", + environment=_environment(gpu=True, gpu_name="NVIDIA A100-SXM4-80GB"), + use_jax=False, + ) + + assert banner == ( + "Setup: numpy · CPU · dense · fp64 " + f"(rule imaging/mge · designated JAX on GPU; {reason})" + ) + + # As designated when the backend resolved to JAX, or is not given. + assert setup_util.setup_banner_from( + setup=setup, chosen_by="explicit", use_jax=True + ) == "Setup: JAX · GPU · dense · fp64" + assert setup_util.setup_text_from(setup) == "JAX · GPU · dense · fp64" + + +def test__disable_jax__setup_and_parallel_lines_report_numpy( + masked_imaging_7x7, many_core, caplog, monkeypatch +): + from autofit.non_linear.parallel.pool import resolve_number_of_cores + + monkeypatch.setenv("PYAUTO_DISABLE_JAX", "1") + + analysis = ag.AnalysisImaging(dataset=masked_imaging_7x7, setup="auto", use_jax=False) + + with caplog.at_level(logging.INFO): + analysis.modify_before_fit(paths=af.DirectoryPaths(), model=_parametric_model()) + + assert analysis.setup.setup_id == "jax_cpu_dense_fp64" + assert analysis.is_jax is False + assert _setup_lines(caplog)[-1] == ( + "Setup: numpy · CPU · dense · fp64 " + "(rule imaging/mge · designated JAX; JAX disabled)" + ) + + resolution = resolve_number_of_cores(requested="auto", analysis=analysis) + + assert resolution.is_jax is False + assert resolution.reason != "jax" + assert "JAX" not in resolution.banner