From 44019f7f5f851b9151cb35f4715f8372a16b0b2c Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Wed, 25 Nov 2026 10:56:10 +0000 Subject: [PATCH] feat: automatic compute-setup header and concise Setup line Part of the concise automatic compute-setup banner (PyAutoLabs/PyAutoGalaxy#754): one header line stating the automatic CPU/GPU choice, aligned Setup / Parallel / Estimate lines printed together, and notices when the setup acts outside modeling. Shares branch feature/auto-setup-banner across PyAutoNerves, PyAutoArray, PyAutoFit, PyAutoGalaxy and PyAutoLens. Co-Authored-By: Claude Opus 5.5 --- autogalaxy/aggregator/agg_util.py | 8 +- autogalaxy/analysis/analysis/dataset.py | 8 +- autogalaxy/analysis/analysis/setup.py | 46 ++-- autogalaxy/analysis/setup_util.py | 205 +++++++++++++++--- .../aggregator/test_dataset_setup.py | 19 +- .../analysis/test_analysis_dataset.py | 190 +++++++++++++++- .../imaging/model/test_analysis_imaging.py | 6 +- 7 files changed, 417 insertions(+), 65 deletions(-) diff --git a/autogalaxy/aggregator/agg_util.py b/autogalaxy/aggregator/agg_util.py index f1687d9f..782ad505 100644 --- a/autogalaxy/aggregator/agg_util.py +++ b/autogalaxy/aggregator/agg_util.py @@ -250,6 +250,8 @@ def dataset_with_setup_from(fit: af.Fit, dataset): - a search with no ``setup.json`` (no ``setup`` was given) returns the dataset unchanged; - an array-free dataset (``dataset.data is None``, rebuilt by ``Interferometer.from_sparse_terms``) already carries its operator and is returned unchanged; + - on success one INFO line says so (`Compute setup: reapplied from the search's setup.json`; + ``apply_setup`` itself logs nothing); - if the setup cannot be applied here (e.g. a JAX sparse setup reloaded without JAX installed, or an unreadable file), one warning is logged and the dataset is returned unapplied. @@ -278,7 +280,7 @@ def dataset_with_setup_from(fit: af.Fit, dataset): setup_id = setup_dict.get("setup_id") if isinstance(setup_dict, dict) else setup_dict try: - return dataset.apply_setup(setup_id) + dataset = dataset.apply_setup(setup_id) except Exception as e: logger.warning( f"Aggregator: the search's compute setup {setup_id!r} could not be reapplied to the " @@ -286,3 +288,7 @@ def dataset_with_setup_from(fit: af.Fit, dataset): f"of it may take a different operator route from the search." ) return dataset + + logger.info(f"Compute setup: reapplied {setup_id} from the search's setup.json") + + return dataset diff --git a/autogalaxy/analysis/analysis/dataset.py b/autogalaxy/analysis/analysis/dataset.py index cafc84e0..a3c03b27 100644 --- a/autogalaxy/analysis/analysis/dataset.py +++ b/autogalaxy/analysis/analysis/dataset.py @@ -116,9 +116,11 @@ def modify_before_fit(self, paths: af.DirectoryPaths, model: af.Collection): """ # The setup is resolved first: applying it may rebuild the dataset, so the grids below are - # preloaded on the dataset the likelihood will use. + # preloaded on the dataset the likelihood will use. Its log lines are kept until the end, so + # anything the preloading warns comes before them and they sit with the fit's `Parallel:` / + # `Estimate:` lines. - self.resolve_setup(model=model) + self.resolve_setup(model=model, log_banner=False) # Ensures preloaded in memory so repeated calls are fast @@ -141,6 +143,8 @@ def modify_before_fit(self, paths: af.DirectoryPaths, model: af.Collection): super().modify_before_fit(paths=paths, model=model) + self.log_setup_banner() + return self @staticmethod diff --git a/autogalaxy/analysis/analysis/setup.py b/autogalaxy/analysis/analysis/setup.py index 69e9c015..c9c41e20 100644 --- a/autogalaxy/analysis/analysis/setup.py +++ b/autogalaxy/analysis/analysis/setup.py @@ -70,7 +70,7 @@ def _apply_resolved_setup(self, setup: aa.Setup): default does nothing. """ - def resolve_setup(self, model: af.Collection): + def resolve_setup(self, model: af.Collection, log_banner: bool = True): """ Resolve the `setup` input of the analysis against the model and apply it. @@ -87,17 +87,25 @@ def resolve_setup(self, model: af.Collection): the dataset and checks it against the backend, so a mismatch raises here rather than rejecting every sample); - pins the thread pools (`setup.apply_threads()`); - - is logged as the setup banner line and stored as `self.setup`. + - is logged as the header and `Setup:` lines (two records) and stored as `self.setup`. Parameters ---------- model The model fitted by the search, which decides the rule variant (e.g. pixelization mesh or MGE). + log_banner + Whether to log the setup lines now. `False` keeps them for `log_setup_banner`, so a caller that + does more work after resolving (e.g. `AnalysisDataset` preloading its grids, which can warn) logs + them last, next to the fit's `Parallel:` / `Estimate:` lines. """ setup_input = getattr(self, "setup_input", None) + self._setup_banner_lines = [] + if setup_input is None: self._log_setup_auto_would_choose(model=model) + if log_banner: + self.log_setup_banner() return note = None @@ -121,18 +129,31 @@ def resolve_setup(self, model: af.Collection): self.setup = setup self.setup_chosen_by = chosen_by - logger.info( - setup_util.setup_banner_from( - setup=setup, - chosen_by=chosen_by, - environment=environment, - note=note, - ) + # 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. + self._setup_banner_lines = setup_util.setup_banner_lines_from( + setup=setup, + chosen_by=chosen_by, + environment=environment, + note=note, ) + if log_banner: + self.log_setup_banner() + + def log_setup_banner(self): + """ + Log the setup lines `resolve_setup` prepared (the header and `Setup:` line, or the one "not set" + line), each as its own record, once. + """ + for line in getattr(self, "_setup_banner_lines", None) or []: + logger.info(line) + self._setup_banner_lines = [] + def _log_setup_auto_would_choose(self, model: af.Collection): """ - Log one line reporting the setup `setup="auto"` would choose, applying nothing. + Prepare the one line reporting the setup `setup="auto"` would choose (logged by + `log_setup_banner`), applying nothing. """ try: key, _ = self.setup_key_and_note_from(model) @@ -143,10 +164,7 @@ def _log_setup_auto_would_choose(self, model: af.Collection): ) return - logger.info( - f"Setup: auto would choose {setup.setup_id} (rule {setup.rule_id}); " - f'pass setup="auto" to use it' - ) + self._setup_banner_lines = [setup_util.setup_not_set_line_from(setup)] def save_setup(self, paths: af.DirectoryPaths): """ diff --git a/autogalaxy/analysis/setup_util.py b/autogalaxy/analysis/setup_util.py index 8dbb096f..2bc54865 100644 --- a/autogalaxy/analysis/setup_util.py +++ b/autogalaxy/analysis/setup_util.py @@ -14,8 +14,10 @@ `use_jax` (honouring `PYAUTO_DISABLE_JAX` and a missing JAX install). - `check_setup_consistency`: run the inversion factory's operator / setup / backend check once, outside the likelihood, so a mismatch raises before sampling. -- `setup_banner_from` / `setup_dict_from`: the banner line logged at fit start and the - contents of `files/setup.json`. +- `setup_header_from` / `setup_banner_from` / `setup_dict_from`: the header and `Setup:` + lines logged at fit start, and the contents of `files/setup.json`. +- `setup_text_from`: the readable setup (`numba · CPU · sparse operator · fp64`) those + lines, the "not set" line and the aggregator notice share. - `setup_environment`: the detected hardware `aa.Setup.auto` chooses for. The resolution itself is `autogalaxy.analysis.analysis.setup.AnalysisSetupMixin`, shared by every @@ -33,7 +35,16 @@ import autoarray as aa -from autoarray.setup.setup import EXPLICIT_RULE_ID, Setup, rules, setup_from +from autoarray.setup.setup import ( + EXPLICIT_RULE_ID, + GPU_A100_NAME, + HARDWARE_CLASS_CPU, + HARDWARE_CLASS_GPU, + MANY_CORE_MIN_CORES, + Setup, + rules, + setup_from, +) logger = logging.getLogger(__name__) @@ -299,8 +310,8 @@ def chosen_by_from(setup: Setup, auto: bool) -> str: def hardware_description_from(setup: Setup, environment=None) -> Optional[str]: """ - A short description of the hardware a setup runs on, for the banner: the GPU name for - a GPU setup, the core count for a CPU setup, or `None` if unknown. + A short description of the hardware a setup runs on: the GPU name for a GPU setup, + the core count for a CPU setup, or `None` if unknown. """ if environment is None: return None @@ -310,6 +321,117 @@ def hardware_description_from(setup: Setup, environment=None) -> Optional[str]: return f"{cores} CPU cores" if cores else None +_BACKEND_TEXT = {"numba": "numba", "jax": "JAX", "numpy": "numpy"} +_OPERATOR_TEXT = {"sparse": "sparse operator", "dense": "dense", "na": "no operator"} +_PRECISION_TEXT = {"mp": "mixed precision"} +_TRANSFORMER_TEXT = {"wtilde": "w-tilde", "nufft": "NUFFT", "dft": "DFT"} + +# The `Setup:` / `Parallel:` / `Estimate:` labels of the fit-start block share one width. +LABEL_WIDTH = len("Parallel: ") + + +def setup_text_from(setup: Setup) -> str: + """ + The setup tuple in readable tokens, e.g. `numba · CPU · sparse operator · fp64` or + `numba · CPU · sparse operator · fp64 · w-tilde`. + """ + tokens = [ + _BACKEND_TEXT.get(setup.backend, setup.backend), + setup.device.upper(), + _OPERATOR_TEXT.get(setup.operator, f"{setup.operator} operator"), + _PRECISION_TEXT.get(setup.precision, setup.precision), + ] + if setup.transformer is not None: + tokens.append(_TRANSFORMER_TEXT.get(setup.transformer, setup.transformer)) + return " · ".join(tokens) + + +def rule_likelihood_from(setup: Setup) -> Optional[str]: + """ + The `/` likelihood of the rule that chose a setup (looked up + by its `decision_id` in the rule table), or `None` when it was not chosen by a rule. + """ + decision_id = setup.decision_id or setup.rule_id + if not decision_id or decision_id == EXPLICIT_RULE_ID: + return None + for row in rules(): + if row.get("decision_id") == decision_id: + return row["likelihood"] + return None + + +def _intended_hardware_class(environment) -> str: + """ + The hardware class `aa.Setup.auto` aimed for: `gpu_a100` when `PYAUTO_SETUP=gpu`, or + when it is unset / `auto` and a GPU is detected; otherwise `cpu_many_core`. + """ + value = (os.environ.get("PYAUTO_SETUP") or "auto").strip().lower() + if value == "gpu": + return HARDWARE_CLASS_GPU + if value == "cpu": + return HARDWARE_CLASS_CPU + return HARDWARE_CLASS_GPU if getattr(environment, "gpu", False) else HARDWARE_CLASS_CPU + + +_CLASS_TEXT = {HARDWARE_CLASS_CPU: "CPU", HARDWARE_CLASS_GPU: "GPU"} + + +def extrapolated_reason_from(setup: Setup, environment=None) -> Optional[str]: + """ + Why an automatically chosen setup is marked extrapolated (`None` when it is not): + + - a CPU rule on fewer than `MANY_CORE_MIN_CORES` cores: + `8 cores, rules measured on ≥16-core nodes`; + - an A100 rule on another GPU: `, rules measured on A100`, or on a machine + with no GPU: `no GPU detected, rules measured on A100`; + - no rule for the intended hardware class: + `no GPU rule for this likelihood, the CPU rule is used`. + """ + if not setup.extrapolated: + return None + + if environment is not None and setup.hardware_class is not None: + intended = _intended_hardware_class(environment) + if intended != setup.hardware_class: + return ( + f"no {_CLASS_TEXT.get(intended, intended)} rule for this likelihood, " + f"the {_CLASS_TEXT.get(setup.hardware_class, setup.hardware_class)} " + f"rule is used" + ) + + if setup.hardware_class == HARDWARE_CLASS_GPU: + if environment is None: + return f"rules measured on {GPU_A100_NAME}" + gpu_name = getattr(environment, "gpu_name", None) + if not getattr(environment, "gpu", False): + return f"no GPU detected, rules measured on {GPU_A100_NAME}" + return f"{gpu_name or 'GPU'}, rules measured on {GPU_A100_NAME}" + + cores = getattr(environment, "cores", None) if environment is not None else None + measured = f"rules measured on ≥{MANY_CORE_MIN_CORES}-core nodes" + return f"{cores} cores, {measured}" if cores else measured + + +def setup_header_from(setup: Setup, chosen_by: str) -> str: + """ + The header line logged before the `Setup:` line at fit start, saying how the setup + was chosen: + + - `"auto"`: `Automatic compute setup (CPU/GPU choice from setup="auto"; override with + PYAUTO_SETUP or setup=...):` + - `"PYAUTO_SETUP"`: `Compute setup (set by PYAUTO_SETUP=):` + - `"explicit"`: `Compute setup (set explicitly by setup=...):` + """ + if chosen_by == CHOSEN_BY_AUTO: + return ( + 'Automatic compute setup (CPU/GPU choice from setup="auto"; ' + "override with PYAUTO_SETUP or setup=...):" + ) + if chosen_by == CHOSEN_BY_ENV: + return f"Compute setup (set by PYAUTO_SETUP={setup.setup_id}):" + return "Compute setup (set explicitly by setup=...):" + + def setup_banner_from( setup: Setup, chosen_by: str, @@ -317,37 +439,66 @@ def setup_banner_from( note: Optional[str] = None, ) -> str: """ - The setup banner line logged at fit start, e.g. + The `Setup:` line logged at fit start (after `setup_header_from`), e.g. - `Setup: jax/gpu/dense/fp64 (NVIDIA A100-SXM4-80GB) · rule imaging-rectangular-standard-gpu-a100 · - optimal (decision imaging-rectangular-standard-gpu-a100) · override: PYAUTO_SETUP` - """ - tokens = [setup.backend, setup.device, setup.operator, setup.precision] - if setup.transformer is not None: - tokens.append(setup.transformer) + `Setup: numba · CPU · sparse operator · fp64 (rule imaging/rectangular · + extrapolated: 8 cores, rules measured on ≥16-core nodes)` - line = f"Setup: {'/'.join(tokens)}" - - hardware = hardware_description_from(setup=setup, environment=environment) - if hardware: - line += f" ({hardware})" + An automatically chosen setup names its rule (`/`) and, when + 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. + """ + line = f"{'Setup:':<{LABEL_WIDTH}}{setup_text_from(setup)}" + details = [] if chosen_by == CHOSEN_BY_AUTO: - line += f" · rule {setup.rule_id}" - quality = "extrapolated" if setup.extrapolated else "optimal" - line += f" · {quality} (decision {setup.decision_id})" - line += " · override: PYAUTO_SETUP" - elif chosen_by == CHOSEN_BY_ENV: - line += " · rule explicit (PYAUTO_SETUP)" - else: - line += " · rule explicit (setup passed to the analysis)" - + likelihood = rule_likelihood_from(setup) + details.append(f"rule {likelihood or setup.rule_id}") + reason = extrapolated_reason_from(setup=setup, environment=environment) + if reason: + details.append(f"extrapolated: {reason}") if note: - line += f" · {note}" + details.append(note) + + if details: + line += f" ({' · '.join(details)})" return line +def setup_banner_lines_from( + setup: Setup, + chosen_by: str, + environment=None, + note: Optional[str] = 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). + """ + return [ + setup_header_from(setup=setup, chosen_by=chosen_by), + setup_banner_from( + setup=setup, chosen_by=chosen_by, environment=environment, note=note + ), + ] + + +def setup_not_set_line_from(setup: Setup) -> str: + """ + The one line logged when an analysis has no `setup`, e.g. + + `Compute setup: not set (auto would choose numba · CPU · sparse operator · fp64; + pass setup="auto")` + """ + return ( + f"Compute setup: not set (auto would choose {setup_text_from(setup)}; " + f'pass setup="auto")' + ) + + def setup_dict_from(setup: Setup, chosen_by: str) -> dict: """ The contents of `files/setup.json`: the setup_id, the setup tuple, its provenance and diff --git a/test_autogalaxy/aggregator/test_dataset_setup.py b/test_autogalaxy/aggregator/test_dataset_setup.py index a540de16..691d84dd 100644 --- a/test_autogalaxy/aggregator/test_dataset_setup.py +++ b/test_autogalaxy/aggregator/test_dataset_setup.py @@ -58,16 +58,22 @@ def test__imaging_from__no_setup_json__reloads_unchanged(masked_imaging_7x7, mon assert (dataset.data.array == masked_imaging_7x7.data.array).all() -def test__imaging_from__setup_json__reapplied(masked_imaging_7x7, monkeypatch): +def test__imaging_from__setup_json__reapplied(masked_imaging_7x7, monkeypatch, caplog): pytest.importorskip("numba") hdu_list = _imaging_hdu_list_from(masked_imaging_7x7, monkeypatch) - dataset = _imaging_from( - fit=_fake_fit( - {"dataset": hdu_list, "setup": _setup_dict("numba_cpu_sparse_fp64")} - ) - )[0] + with caplog.at_level(logging.INFO, logger=agg_util.__name__): + dataset = _imaging_from( + fit=_fake_fit( + {"dataset": hdu_list, "setup": _setup_dict("numba_cpu_sparse_fp64")} + ) + )[0] + + notices = [r.message for r in caplog.records if r.name == agg_util.__name__] + assert notices == [ + "Compute setup: reapplied numba_cpu_sparse_fp64 from the search's setup.json" + ] assert dataset.setup.setup_id == "numba_cpu_sparse_fp64" assert dataset.sparse_operator is not None @@ -106,6 +112,7 @@ def raise_(self, setup, **kwargs): warnings = [r for r in caplog.records if r.levelno == logging.WARNING] assert len(warnings) == 1 + assert not [r for r in caplog.records if r.message.startswith("Compute setup: reapplied")] assert "jax_cpu_sparse_fp64" in warnings[0].message assert "no JAX here" in warnings[0].message diff --git a/test_autogalaxy/analysis/analysis/test_analysis_dataset.py b/test_autogalaxy/analysis/analysis/test_analysis_dataset.py index 8c2f563e..fc215ad2 100644 --- a/test_autogalaxy/analysis/analysis/test_analysis_dataset.py +++ b/test_autogalaxy/analysis/analysis/test_analysis_dataset.py @@ -340,9 +340,11 @@ def test__no_setup__dataset_and_backend_unchanged__would_choose_logged( would_choose = [r.message for r in caplog.records if "auto would choose" in r.message] assert would_choose == [ - "Setup: auto would choose numba_cpu_sparse_fp64 " - "(rule imaging-rectangular-standard-cpu-many-core); pass setup=\"auto\" to use it" + "Compute setup: not set (auto would choose numba · CPU · sparse operator · fp64; " + 'pass setup="auto")' ] + # Nothing else of the setup block is logged when no setup was given. + assert not [r for r in caplog.records if r.message.startswith(("Setup:", "Automatic"))] def test__no_setup__save_attributes_writes_no_setup_json( @@ -404,16 +406,13 @@ def test__setup_banner_from(): environment=_environment(gpu=True, gpu_name="NVIDIA A100-SXM4-80GB"), ) - assert banner == ( - "Setup: jax/gpu/dense/fp64 (NVIDIA A100-SXM4-80GB) · rule " - "imaging-rectangular-standard-gpu-a100 · optimal (decision " - "imaging-rectangular-standard-gpu-a100) · override: PYAUTO_SETUP" - ) + assert banner == "Setup: JAX · GPU · dense · fp64 (rule imaging/rectangular)" extrapolated = aa.Setup.from_setup_id( "numba_cpu_sparse_fp64_wtilde", - rule_id="r", - decision_id="r", + rule_id="interferometer-rectangular-standard-cpu-many-core", + hardware_class="cpu_many_core", + decision_id="interferometer-rectangular-standard-cpu-many-core", extrapolated=True, ) @@ -421,5 +420,174 @@ def test__setup_banner_from(): setup=extrapolated, chosen_by="auto", environment=_environment(cores=8) ) - assert banner.startswith("Setup: numba/cpu/sparse/fp64/wtilde (8 CPU cores)") - assert "extrapolated (decision r)" in banner + assert banner == ( + "Setup: numba · CPU · sparse operator · fp64 · w-tilde " + "(rule interferometer/rectangular · extrapolated: 8 cores, rules measured on " + "≥16-core nodes)" + ) + + +def test__setup_banner_from__extrapolated_reasons(monkeypatch): + monkeypatch.delenv("PYAUTO_SETUP", raising=False) + + gpu_setup = aa.Setup.from_setup_id( + "jax_gpu_dense_fp64", + rule_id="imaging-rectangular-standard-gpu-a100", + hardware_class="gpu_a100", + decision_id="imaging-rectangular-standard-gpu-a100", + extrapolated=True, + ) + + banner = setup_util.setup_banner_from( + setup=gpu_setup, + chosen_by="auto", + environment=_environment(gpu=True, gpu_name="NVIDIA RTX 2060"), + ) + + assert banner == ( + "Setup: JAX · GPU · dense · fp64 (rule imaging/rectangular · " + "extrapolated: NVIDIA RTX 2060, rules measured on A100)" + ) + + # PYAUTO_SETUP=gpu on a machine with no GPU. + monkeypatch.setenv("PYAUTO_SETUP", "gpu") + banner = setup_util.setup_banner_from( + setup=gpu_setup, chosen_by="auto", environment=_environment(cores=8) + ) + assert banner.endswith("(rule imaging/rectangular · extrapolated: no GPU detected, " + "rules measured on A100)") + monkeypatch.delenv("PYAUTO_SETUP") + + # A GPU machine whose likelihood has only a CPU rule. + cpu_only = aa.Setup.from_setup_id( + "numba_cpu_sparse_fp64", + rule_id="datacube-delaunay-standard-cpu-many-core", + hardware_class="cpu_many_core", + decision_id="datacube-delaunay-standard-cpu-many-core", + extrapolated=True, + ) + banner = setup_util.setup_banner_from( + setup=cpu_only, + chosen_by="auto", + environment=_environment(gpu=True, gpu_name="NVIDIA A100-SXM4-80GB"), + ) + assert banner.endswith( + "(rule datacube/delaunay · extrapolated: no GPU rule for this likelihood, " + "the CPU rule is used)" + ) + + # Not extrapolated: no clause; a note is appended inside the parentheses. + optimal = aa.Setup.from_setup_id( + "numba_cpu_sparse_fp64", + rule_id="imaging-rectangular-standard-cpu-many-core", + hardware_class="cpu_many_core", + decision_id="imaging-rectangular-standard-cpu-many-core", + extrapolated=False, + ) + banner = setup_util.setup_banner_from( + setup=optimal, + chosen_by="auto", + environment=_environment(cores=64), + note="no rule for imaging/delaunay_nn, using the nearest rule imaging/rectangular", + ) + assert banner == ( + "Setup: numba · CPU · sparse operator · fp64 (rule imaging/rectangular · " + "no rule for imaging/delaunay_nn, using the nearest rule imaging/rectangular)" + ) + + +def test__setup_header_from__auto_explicit_and_env(): + setup = aa.Setup.from_setup_id("numba_cpu_sparse_fp64") + + assert setup_util.setup_header_from(setup=setup, chosen_by="auto") == ( + 'Automatic compute setup (CPU/GPU choice from setup="auto"; override with ' + "PYAUTO_SETUP or setup=...):" + ) + assert setup_util.setup_header_from(setup=setup, chosen_by="explicit") == ( + "Compute setup (set explicitly by setup=...):" + ) + assert setup_util.setup_header_from(setup=setup, chosen_by="PYAUTO_SETUP") == ( + "Compute setup (set by PYAUTO_SETUP=numba_cpu_sparse_fp64):" + ) + + # Explicit and PYAUTO_SETUP setups name no rule. + assert setup_util.setup_banner_from(setup=setup, chosen_by="explicit") == ( + "Setup: numba · CPU · sparse operator · fp64" + ) + + +def test__setup_text_from__readable_tokens(): + text = setup_util.setup_text_from + + assert text(aa.Setup.from_setup_id("jax_cpu_na_fp64")) == "JAX · CPU · no operator · fp64" + assert text(aa.Setup.from_setup_id("numpy_cpu_dense_mp")) == ( + "numpy · CPU · dense · mixed precision" + ) + assert text(aa.Setup.from_setup_id("jax_gpu_sparse_fp32_nufft")) == ( + "JAX · GPU · sparse operator · fp32 · NUFFT" + ) + + +def _setup_block(caplog): + messages = [r.message for r in caplog.records] + start = next( + i for i, m in enumerate(messages) if "ompute setup (" in m + ) + return messages[start : start + 2] + + +def test__setup_header_and_line__logged_consecutively__auto_explicit_env( + masked_imaging_7x7, many_core, caplog, monkeypatch +): + model = _model_with_mesh(ag.mesh.RectangularUniform(shape=(3, 3))) + + 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=model) + assert _setup_block(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() + + analysis = ag.AnalysisImaging( + dataset=masked_imaging_7x7, setup="numba_cpu_dense_fp64", use_jax=False + ) + with caplog.at_level(logging.INFO): + analysis.modify_before_fit(paths=af.DirectoryPaths(), model=model) + assert _setup_block(caplog) == [ + "Compute setup (set explicitly by setup=...):", + "Setup: numba · CPU · dense · fp64", + ] + caplog.clear() + + monkeypatch.setenv("PYAUTO_SETUP", "numba_cpu_dense_fp64") + 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=model) + assert _setup_block(caplog) == [ + "Compute setup (set by PYAUTO_SETUP=numba_cpu_dense_fp64):", + "Setup: numba · CPU · dense · fp64", + ] + + +def test__resolve_setup__log_banner_false__lines_kept_for_log_setup_banner( + masked_imaging_7x7, many_core, caplog +): + model = _model_with_mesh(ag.mesh.RectangularUniform(shape=(3, 3))) + + analysis = ag.AnalysisImaging(dataset=masked_imaging_7x7, setup="auto", use_jax=False) + + with caplog.at_level(logging.INFO): + analysis.resolve_setup(model=model, log_banner=False) + + assert not [r for r in caplog.records if "ompute setup" in r.message] + + with caplog.at_level(logging.INFO): + analysis.log_setup_banner() + analysis.log_setup_banner() # logged once only + + 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 diff --git a/test_autogalaxy/imaging/model/test_analysis_imaging.py b/test_autogalaxy/imaging/model/test_analysis_imaging.py index 11440af3..43e8a831 100644 --- a/test_autogalaxy/imaging/model/test_analysis_imaging.py +++ b/test_autogalaxy/imaging/model/test_analysis_imaging.py @@ -206,12 +206,10 @@ def test__setup_auto__cpu_many_core_rectangular__numba_sparse_operator( assert analysis.dataset.setup == analysis.setup assert isinstance(analysis.dataset.sparse_operator, SparseLinAlgImagingNumba) - banners = [r.message for r in caplog.records if r.message.startswith("Setup: ")] + banners = [r.message for r in caplog.records if r.message.startswith("Setup:")] assert banners == [ - "Setup: numba/cpu/sparse/fp64 (64 CPU cores) · rule " - "imaging-rectangular-standard-cpu-many-core · optimal (decision " - "imaging-rectangular-standard-cpu-many-core) · override: PYAUTO_SETUP" + "Setup: numba · CPU · sparse operator · fp64 (rule imaging/rectangular)" ]