From 4d351b72b021a3c925b500ead529cb3426242c89 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Tue, 24 Nov 2026 11:43:58 +0000 Subject: [PATCH] feat: setup="auto" (opt-in), setup.json and setup banner in the dataset analyses (5C-1) AnalysisImaging / AnalysisInterferometer accept setup=None|"auto"|aa.Setup| "". modify_before_fit resolves it from the dataset and model (pixelization mesh or MGE), sets the backend, applies it to the dataset, runs the operator/backend consistency check outside the likelihood, pins threads, logs a banner and writes files/setup.json. Without setup= nothing changes beyond one "auto would choose" log line (ruling R6). Part of PyAutoLabs/PyAutoLens#881 (likelihood-lifecycle phase 5C-1). Co-Authored-By: Claude Opus 5.5 --- autogalaxy/analysis/analysis/dataset.py | 133 +++++++ autogalaxy/analysis/setup_util.py | 352 ++++++++++++++++++ autogalaxy/imaging/model/analysis.py | 8 + autogalaxy/interferometer/model/analysis.py | 8 + .../analysis/test_analysis_dataset.py | 303 +++++++++++++++ .../imaging/model/test_analysis_imaging.py | 218 +++++++++++ .../model/test_analysis_interferometer.py | 100 +++++ 7 files changed, 1122 insertions(+) create mode 100644 autogalaxy/analysis/setup_util.py diff --git a/autogalaxy/analysis/analysis/dataset.py b/autogalaxy/analysis/analysis/dataset.py index b692aeb96..fddd9772f 100644 --- a/autogalaxy/analysis/analysis/dataset.py +++ b/autogalaxy/analysis/analysis/dataset.py @@ -13,6 +13,7 @@ from autogalaxy.cosmology.model import LensingCosmology from autogalaxy.analysis.analysis.analysis import Analysis from autogalaxy.analysis.result import ResultDataset +from autogalaxy.analysis import setup_util logger = logging.getLogger(__name__) @@ -37,6 +38,7 @@ def __init__( settings: aa.Settings = None, title_prefix: str = None, use_jax: bool = True, + setup=None, **kwargs, ): """ @@ -61,6 +63,22 @@ def __init__( title_prefix A string that is added before the title of all figures output by visualization, for example to put the name of the dataset and galaxy in the title. + use_jax + Whether the likelihood is evaluated with JAX. It is honoured as given when `setup` is `None`; a + resolved `setup` sets the backend instead. + setup + The compute setup of the likelihood (backend, device, operator, precision, transformer): `None`, + `"auto"`, an `aa.Setup` or a setup_id string such as `"numba_cpu_sparse_fp64"`. It is resolved in + `modify_before_fit`, because the rule key needs the model (pixelization mesh or MGE): + + - `None` (the default): nothing changes; one log line reports what `"auto"` would choose. + - `"auto"`: `aa.Setup.auto` chooses the designated setup for the likelihood and hardware + (`PYAUTO_SETUP=` overrides it). + - An `aa.Setup` or setup_id string: that setup is used as given. + + A resolved setup sets the analysis backend, is applied to the dataset (`dataset.apply_setup`), + checked for an operator / backend mismatch, pins the thread pools, is logged as a banner line and + is written to `files/setup.json`. """ super().__init__( cosmology=cosmology, @@ -68,6 +86,10 @@ def __init__( **kwargs, ) + self.setup_input = setup_util.setup_input_from(setup) + self.setup = None + self.setup_chosen_by = None + self.dataset = dataset self.adapt_images = adapt_images @@ -94,6 +116,11 @@ def modify_before_fit(self, paths: af.DirectoryPaths, model: af.Collection): the imaging data. """ + # The setup is resolved first: applying it may rebuild the dataset, so the grids below are + # preloaded on the dataset the likelihood will use. + + self.resolve_setup(model=model) + # Ensures preloaded in memory so repeated calls are fast self.dataset.grids.lp @@ -117,6 +144,101 @@ def modify_before_fit(self, paths: af.DirectoryPaths, model: af.Collection): return self + @staticmethod + def _setup_environment(): + """ + The detected hardware (`autonerves.environment.Environment`), or `None` if detection fails. + """ + try: + from autonerves.environment import Environment + + return Environment.detect() + except Exception as e: + logger.debug(f"Setup: hardware detection failed: {e}") + return None + + def resolve_setup(self, model: af.Collection): + """ + Resolve the `setup` input of the analysis against the model and apply it. + + With no `setup` input nothing changes: one log line reports what `setup="auto"` would choose (any + error working that out is ignored). + + With `setup="auto"` the setup is chosen by `aa.Setup.auto` from the rule key of the dataset and + model (see `setup_util.setup_key_from`); `PYAUTO_SETUP=` overrides it. An explicit + `aa.Setup` or setup_id is used as given. The resolved setup then: + + - sets the analysis backend (`_use_jax = setup.backend == "jax"`, falling back to numpy when JAX is + disabled or not installed, as `af.Analysis` does); + - is applied to the dataset (`dataset.apply_setup`), which attaches the operator it names; + - is checked against the dataset operator and backend with the inversion factory's check, so a + mismatch raises an `InversionException` 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`. + + Parameters + ---------- + model + The model fitted by the search, which decides the rule variant (pixelization mesh or MGE). + """ + setup_input = getattr(self, "setup_input", None) + + if setup_input is None: + self._log_setup_auto_would_choose(model=model) + return + + note = None + + if setup_input == setup_util.SETUP_AUTO: + environment = self._setup_environment() + key, note = setup_util.setup_key_and_note_from( + dataset=self.dataset, model=model + ) + setup = aa.Setup.auto(*key, environment=environment) + chosen_by = setup_util.chosen_by_from(setup=setup, auto=True) + else: + environment = self._setup_environment() + setup = setup_input + chosen_by = setup_util.chosen_by_from(setup=setup, auto=False) + + self._use_jax = setup_util.use_jax_from(setup.backend == "jax") + + self.dataset = self.dataset.apply_setup(setup) + + setup_util.check_setup_consistency(dataset=self.dataset, use_jax=self._use_jax) + + setup.apply_threads() + + 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, + ) + ) + + def _log_setup_auto_would_choose(self, model: af.Collection): + """ + Log one line reporting the setup `setup="auto"` would choose, applying nothing. + """ + try: + key, _ = setup_util.setup_key_and_note_from( + dataset=self.dataset, model=model + ) + setup = aa.Setup.auto(*key, environment=self._setup_environment()) + except Exception as e: + logger.debug(f"Setup: could not work out what setup='auto' would choose: {e}") + return + + logger.info( + f"Setup: auto would choose {setup.setup_id} (rule {setup.rule_id}); " + f'pass setup="auto" to use it' + ) + @staticmethod def _save_dataset_fits(paths: af.AbstractPaths, hdu_list: HDUList) -> None: """Save the dataset for directory and database aggregators.""" @@ -144,6 +266,7 @@ def save_attributes(self, paths: af.DirectoryPaths): - The settings associated with the inversion. - The settings associated with the pixelization. - The Cosmology. + - The resolved compute setup (`setup.json`), when a `setup` was given. The dataset itself is output as `dataset.fits` to the `image` folder by the `save_attributes` method of each dataset-specific subclass (e.g. `AnalysisImaging`), with the mask in its `PrimaryHDU`. @@ -173,6 +296,16 @@ def save_attributes(self, paths: af.DirectoryPaths): object_dict=to_dict(self.cosmology), ) + setup = getattr(self, "setup", None) + + if setup is not None: + paths.save_json( + name="setup", + object_dict=setup_util.setup_dict_from( + setup=setup, chosen_by=self.setup_chosen_by + ), + ) + def save_results(self, paths: af.DirectoryPaths, result: ResultDataset): """ At the end of a model-fit, this routine saves attributes of the `Analysis` object to the `files` diff --git a/autogalaxy/analysis/setup_util.py b/autogalaxy/analysis/setup_util.py new file mode 100644 index 000000000..01c96d743 --- /dev/null +++ b/autogalaxy/analysis/setup_util.py @@ -0,0 +1,352 @@ +""" +Helpers that wire the compute `aa.Setup` of a likelihood into the dataset analyses. + +A dataset analysis (`AnalysisImaging`, `AnalysisInterferometer`) accepts +`setup=None | "auto" | aa.Setup | ""`. The setup is resolved in +`AnalysisDataset.modify_before_fit`, because the rule key of `aa.Setup.auto` needs the +model: a pixelized source (and its mesh) and a parametric / MGE fit have different +designated setups. This module holds the pieces that resolution needs: + +- `setup_input_from`: normalise the `setup` input of an analysis. +- `setup_key_from`: map a dataset and a model to the `(dataset_type, variant)` rule key of + `aa.Setup.auto`. +- `use_jax_from`: resolve a requested backend the way `af.Analysis.__init__` resolves + `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`. + +The setup decides only how the likelihood is computed (backend, device, operator, +precision, transformer, threads), never the model. +""" + +import importlib.util +import logging +import os +import warnings +from typing import Optional, Tuple, Union + +import autoarray as aa + +from autoarray.setup.setup import EXPLICIT_RULE_ID, Setup, rules, setup_from + +logger = logging.getLogger(__name__) + +SETUP_AUTO = "auto" + +CHOSEN_BY_AUTO = "auto" +CHOSEN_BY_EXPLICIT = "explicit" +CHOSEN_BY_ENV = "PYAUTO_SETUP" + +VARIANT_MGE = "mge" +VARIANT_RECTANGULAR = "rectangular" +VARIANT_DELAUNAY = "delaunay" +VARIANT_DELAUNAY_NN = "delaunay_nn" + +# When the rule table has no row for a pixelized variant of a dataset type (e.g. +# `interferometer/delaunay_nn`), the nearest variant with a row is used instead. +_VARIANT_FALLBACKS = { + VARIANT_DELAUNAY_NN: (VARIANT_DELAUNAY, VARIANT_RECTANGULAR), + VARIANT_DELAUNAY: (VARIANT_RECTANGULAR,), + VARIANT_RECTANGULAR: (VARIANT_DELAUNAY,), + VARIANT_MGE: (), +} + +# When a model has several pixelizations, the most expensive mesh decides the variant. +_VARIANT_PRIORITY = (VARIANT_DELAUNAY_NN, VARIANT_DELAUNAY, VARIANT_RECTANGULAR) + + +def setup_input_from(setup) -> Union[None, str, Setup]: + """ + Normalise the `setup` input of a dataset analysis. + + Returns `None`, the sentinel string `"auto"` (any case), or an `aa.Setup` (an `aa.Setup` + unchanged, or the setup a setup_id string names, via `setup_from`). + + Raises + ------ + ValueError + If `setup` is not `None`, `"auto"`, an `aa.Setup` or a valid setup_id string. + """ + if isinstance(setup, str) and setup.strip().lower() == SETUP_AUTO: + return SETUP_AUTO + return setup_from(setup) + + +def dataset_type_from(dataset) -> str: + """ + The `dataset_type` of the setup rule key for a dataset: `"imaging"` or + `"interferometer"`. + + Raises + ------ + ValueError + If the dataset is neither an `aa.Imaging` nor an `aa.Interferometer`. + """ + if isinstance(dataset, aa.Imaging): + return "imaging" + if isinstance(dataset, aa.Interferometer): + return "interferometer" + raise ValueError( + f"A setup can only be chosen automatically for an aa.Imaging or " + f"aa.Interferometer dataset, got {type(dataset).__name__}." + ) + + +def mesh_variant_from(mesh_cls: type) -> str: + """ + The setup rule variant of a pixelization mesh class. + + - `DelaunayNN` (Sibson natural-neighbour interpolation) -> `"delaunay_nn"`. + - `Delaunay` and its other subclasses (e.g. the k-nearest-neighbour meshes) -> + `"delaunay"`. + - The rectangular meshes (`RectangularRTUAdaptDensity` and its subclasses) -> + `"rectangular"`. + + Any other mesh is treated as `"delaunay"`, the general irregular-mesh rule. + """ + from autoarray.inversion.mesh.mesh.delaunay import Delaunay + from autoarray.inversion.mesh.mesh.delaunay_nn import DelaunayNN + from autoarray.inversion.mesh.mesh.rectangular_rtu_adapt_density import ( + RectangularRTUAdaptDensity, + ) + + if issubclass(mesh_cls, DelaunayNN): + return VARIANT_DELAUNAY_NN + if issubclass(mesh_cls, Delaunay): + return VARIANT_DELAUNAY + if issubclass(mesh_cls, RectangularRTUAdaptDensity): + return VARIANT_RECTANGULAR + return VARIANT_DELAUNAY + + +def mesh_classes_from(model) -> list: + """ + The pixelization mesh classes in a model, found as `af.Model` components (free or + fixed) and as instances anywhere in the model tree. + """ + classes = [] + + if hasattr(model, "models_with_type"): + classes += [ + m.cls + for m in model.models_with_type( + aa.AbstractMesh, include_zero_dimension=True + ) + ] + + if hasattr(model, "attribute_tuples_with_type"): + classes += [ + type(value) + for _, value in model.attribute_tuples_with_type( + aa.AbstractMesh, ignore_children=False + ) + ] + elif isinstance(model, aa.AbstractMesh): + classes.append(type(model)) + + return classes + + +def variant_from_model(model) -> str: + """ + The setup rule variant of a model: the variant of its pixelization mesh, or `"mge"` + when it has no pixelization (parametric light profiles, linear light profiles, MGE). + + When the model has several pixelizations the most expensive mesh decides the variant + (`delaunay_nn`, then `delaunay`, then `rectangular`). + """ + variants = {mesh_variant_from(cls) for cls in mesh_classes_from(model)} + + for variant in _VARIANT_PRIORITY: + if variant in variants: + return variant + + return VARIANT_MGE + + +def _known_likelihoods(regime: str = "standard") -> set: + return {row["likelihood"] for row in rules() if row["regime"] == regime} + + +def setup_key_and_note_from( + dataset, model, regime: str = "standard" +) -> Tuple[Tuple[str, str], Optional[str]]: + """ + The `(dataset_type, variant)` rule key of `aa.Setup.auto` for a dataset and model, + plus a note when the model's variant has no rule for the dataset type and the nearest + variant with one was used (`None` otherwise). + + Raises + ------ + ValueError + If the dataset type is not supported, or neither the variant nor any fallback has + a rule. + """ + dataset_type = dataset_type_from(dataset) + variant = variant_from_model(model) + + known = _known_likelihoods(regime=regime) + + if f"{dataset_type}/{variant}" in known: + return (dataset_type, variant), None + + for fallback in _VARIANT_FALLBACKS.get(variant, ()): + if f"{dataset_type}/{fallback}" in known: + note = ( + f"no rule for {dataset_type}/{variant}, " + f"using the nearest rule {dataset_type}/{fallback}" + ) + return (dataset_type, fallback), note + + raise ValueError( + f"No setup rule for likelihood {dataset_type}/{variant} in regime {regime!r}, " + f"and no fallback variant has one. Known likelihoods: {sorted(known)}." + ) + + +def setup_key_from(dataset, model, regime: str = "standard") -> Tuple[str, str]: + """ + The `(dataset_type, variant)` rule key of `aa.Setup.auto` for a dataset and model. + + `dataset_type` is `"imaging"` for an `aa.Imaging` and `"interferometer"` for an + `aa.Interferometer`. `variant` comes from the model's pixelization mesh + (`"rectangular"`, `"delaunay"`, `"delaunay_nn"`), or is `"mge"` when the model has no + pixelization. A variant with no rule for the dataset type falls back to the nearest one + that has a rule (see `setup_key_and_note_from`). + """ + return setup_key_and_note_from(dataset=dataset, model=model, regime=regime)[0] + + +def use_jax_from(use_jax: bool) -> bool: + """ + Resolve a requested JAX backend exactly as `af.Analysis.__init__` resolves `use_jax`: + `False` when `PYAUTO_DISABLE_JAX=1`, and `False` with a warning when JAX is requested + but not installed. + """ + if os.environ.get("PYAUTO_DISABLE_JAX") == "1": + return False + + if use_jax and importlib.util.find_spec("jax") is None: + warnings.warn( + "The setup asks for the 'jax' backend but JAX is not installed. Falling back " + "to numpy: the fit will run, without JAX acceleration.", + UserWarning, + stacklevel=2, + ) + return False + + return bool(use_jax) + + +def check_setup_consistency(dataset, use_jax: bool): + """ + Run the inversion factory's operator / setup / backend check on a dataset once, outside + the likelihood, so a mismatch raises an `InversionException` now instead of every sample + being rejected mid-search. + + The check is the one `inversion_imaging_from` / `inversion_interferometer_from` run + before routing; it reads only `dataset.sparse_operator`, `dataset.setup` and the array + backend, so nothing heavy is built. + """ + import numpy as np + + from autoarray.inversion.inversion import factory + + if use_jax: + import jax.numpy as jnp + + xp = jnp + else: + xp = np + + if isinstance(dataset, aa.Imaging): + factory._check_imaging_setup_consistency( + dataset=dataset, xp=xp, use_sparse_operator=True + ) + elif isinstance(dataset, aa.Interferometer): + factory._check_interferometer_setup_consistency(dataset=dataset, xp=xp) + + +def chosen_by_from(setup: Setup, auto: bool) -> str: + """ + How a resolved setup was chosen: `"PYAUTO_SETUP"` when it came from the environment + variable, `"auto"` when `aa.Setup.auto` chose it from the rule table, else + `"explicit"`. + """ + if setup.rule_id == EXPLICIT_RULE_ID: + return CHOSEN_BY_ENV + return CHOSEN_BY_AUTO if auto else CHOSEN_BY_EXPLICIT + + +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. + """ + if environment is None: + return None + if setup.device == "gpu": + return getattr(environment, "gpu_name", None) or "GPU" + cores = getattr(environment, "cores", None) + return f"{cores} CPU cores" if cores else None + + +def setup_banner_from( + setup: Setup, + chosen_by: str, + environment=None, + note: Optional[str] = None, +) -> str: + """ + The setup banner line logged at fit start, 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) + + line = f"Setup: {'/'.join(tokens)}" + + hardware = hardware_description_from(setup=setup, environment=environment) + if hardware: + line += f" ({hardware})" + + 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)" + + if note: + line += f" · {note}" + + return line + + +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 + how it was chosen. + """ + return { + "setup_id": setup.setup_id, + "backend": setup.backend, + "device": setup.device, + "operator": setup.operator, + "precision": setup.precision, + "transformer": setup.transformer, + "rule_id": setup.rule_id, + "regime": setup.regime, + "hardware_class": setup.hardware_class, + "decision_id": setup.decision_id, + "extrapolated": setup.extrapolated, + "chosen_by": chosen_by, + } diff --git a/autogalaxy/imaging/model/analysis.py b/autogalaxy/imaging/model/analysis.py index 1694e4da9..32f416ce1 100644 --- a/autogalaxy/imaging/model/analysis.py +++ b/autogalaxy/imaging/model/analysis.py @@ -46,6 +46,7 @@ def __init__( settings: aa.Settings = None, title_prefix: str = None, use_jax: bool = True, + setup=None, **kwargs, ): """ @@ -77,6 +78,12 @@ def __init__( title_prefix A string that is added before the title of all figures output by visualization, for example to put the name of the dataset and galaxy in the title. + use_jax + Whether the likelihood is evaluated with JAX; honoured as given when `setup` is `None`. + setup + The compute setup of the likelihood: `None` (default, nothing changes), `"auto"` (the designated + setup for the likelihood and hardware, chosen at fit start from the model), an `aa.Setup` or a + setup_id string. See `AnalysisDataset`. """ super().__init__( dataset=dataset, @@ -85,6 +92,7 @@ def __init__( settings=settings, title_prefix=title_prefix, use_jax=use_jax, + setup=setup, **kwargs, ) diff --git a/autogalaxy/interferometer/model/analysis.py b/autogalaxy/interferometer/model/analysis.py index 88d5b38cc..87086bb00 100644 --- a/autogalaxy/interferometer/model/analysis.py +++ b/autogalaxy/interferometer/model/analysis.py @@ -272,6 +272,7 @@ def __init__( settings: aa.Settings = None, title_prefix: str = None, use_jax: bool = True, + setup=None, **kwargs, ): """ @@ -303,6 +304,12 @@ def __init__( title_prefix A string that is added before the title of all figures output by visualization, for example to put the name of the dataset and galaxy in the title. + use_jax + Whether the likelihood is evaluated with JAX; honoured as given when `setup` is `None`. + setup + The compute setup of the likelihood: `None` (default, nothing changes), `"auto"` (the designated + setup for the likelihood and hardware, chosen at fit start from the model), an `aa.Setup` or a + setup_id string. See `AnalysisDataset`. """ super().__init__( dataset=dataset, @@ -311,6 +318,7 @@ def __init__( settings=settings, title_prefix=title_prefix, use_jax=use_jax, + setup=setup, **kwargs, ) diff --git a/test_autogalaxy/analysis/analysis/test_analysis_dataset.py b/test_autogalaxy/analysis/analysis/test_analysis_dataset.py index 733ed8922..8c2f563e0 100644 --- a/test_autogalaxy/analysis/analysis/test_analysis_dataset.py +++ b/test_autogalaxy/analysis/analysis/test_analysis_dataset.py @@ -120,3 +120,306 @@ def test__save_results__galaxies_failure_never_kills_the_fit( ) assert not (paths._files_path / "galaxies.json").exists() + + +# --- setup="auto" (likelihood lifecycle 5C) --------------------------------------------- + +import json +import logging + +import autoarray as aa + +from autonerves.environment import Environment + +from autogalaxy.analysis import setup_util + + +def _environment(gpu=False, gpu_name=None, cores=64): + return Environment( + gpu=gpu, + gpu_name=gpu_name, + gpu_memory_gb=None, + cores=cores, + ram_gb=None, + numba=True, + nufftax=True, + site="local", + ) + + +MANY_CORE = _environment(cores=64) + + +@pytest.fixture(name="many_core") +def make_many_core(monkeypatch): + monkeypatch.delenv("PYAUTO_SETUP", raising=False) + monkeypatch.setattr(Environment, "detect", classmethod(lambda cls: MANY_CORE)) + + +def _model_with_mesh(mesh): + pixelization = af.Model(ag.Pixelization, mesh=mesh, regularization=ag.reg.Constant) + return af.Collection( + galaxies=af.Collection( + source=af.Model(ag.Galaxy, redshift=1.0, pixelization=pixelization) + ) + ) + + +def _parametric_model(): + return af.Collection( + galaxies=af.Collection( + galaxy=af.Model(ag.Galaxy, redshift=0.5, light=ag.lp.Sersic) + ) + ) + + +@pytest.mark.parametrize( + "mesh, variant", + [ + (af.Model(ag.mesh.RectangularUniform, shape=(3, 3)), "rectangular"), + (ag.mesh.RectangularUniform(shape=(3, 3)), "rectangular"), + (af.Model(ag.mesh.RectangularRTUAdaptImage), "rectangular"), + (af.Model(ag.mesh.RectangularBilinearAdaptDensity), "rectangular"), + (af.Model(ag.mesh.Delaunay, pixels=20), "delaunay"), + (ag.mesh.Delaunay(pixels=20), "delaunay"), + (af.Model(ag.mesh.KNearestNeighbor, pixels=20), "delaunay"), + (af.Model(ag.mesh.DelaunayNN, pixels=20), "delaunay_nn"), + (ag.mesh.DelaunayNN(pixels=20), "delaunay_nn"), + ], +) +def test__setup_key_from__imaging_mesh_variants(masked_imaging_7x7, mesh, variant): + model = _model_with_mesh(mesh) + + assert setup_util.setup_key_from(masked_imaging_7x7, model) == ("imaging", variant) + + +def test__setup_key_from__pixelization_instance_in_galaxy_instance(masked_imaging_7x7): + pixelization = ag.Pixelization( + mesh=ag.mesh.DelaunayNN(pixels=20), regularization=ag.reg.Constant() + ) + model = af.Collection( + galaxies=af.Collection( + source=ag.Galaxy(redshift=1.0, pixelization=pixelization) + ) + ) + + assert setup_util.setup_key_from(masked_imaging_7x7, model) == ( + "imaging", + "delaunay_nn", + ) + + +def test__setup_key_from__no_pixelization_is_mge(masked_imaging_7x7): + assert setup_util.setup_key_from(masked_imaging_7x7, _parametric_model()) == ( + "imaging", + "mge", + ) + + basis = af.Model( + ag.lp_basis.Basis, + profile_list=[af.Model(ag.lp_linear.Gaussian) for _ in range(3)], + ) + model = af.Collection( + galaxies=af.Collection(galaxy=af.Model(ag.Galaxy, redshift=0.5, bulge=basis)) + ) + + assert setup_util.setup_key_from(masked_imaging_7x7, model) == ("imaging", "mge") + + +def test__setup_key_from__several_meshes__most_expensive_wins(masked_imaging_7x7): + model = af.Collection( + galaxies=af.Collection( + source_0=af.Model( + ag.Galaxy, + redshift=1.0, + pixelization=af.Model( + ag.Pixelization, + mesh=ag.mesh.RectangularUniform(shape=(3, 3)), + regularization=ag.reg.Constant, + ), + ), + source_1=af.Model( + ag.Galaxy, + redshift=1.0, + pixelization=af.Model( + ag.Pixelization, + mesh=ag.mesh.Delaunay(pixels=20), + regularization=ag.reg.Constant, + ), + ), + ) + ) + + assert setup_util.setup_key_from(masked_imaging_7x7, model) == ( + "imaging", + "delaunay", + ) + + +def test__setup_key_from__interferometer__missing_variant_falls_back(interferometer_7): + model = _model_with_mesh(af.Model(ag.mesh.DelaunayNN, pixels=20)) + + key, note = setup_util.setup_key_and_note_from(interferometer_7, model) + + assert key == ("interferometer", "delaunay") + assert "interferometer/delaunay_nn" in note + + assert setup_util.setup_key_from(interferometer_7, _parametric_model()) == ( + "interferometer", + "mge", + ) + + +def test__setup_key_from__unsupported_dataset_raises(): + with pytest.raises(ValueError, match="Imaging or aa.Interferometer"): + setup_util.setup_key_from(object(), _parametric_model()) + + +def test__setup_input_from(): + assert setup_util.setup_input_from(None) is None + assert setup_util.setup_input_from("auto") == "auto" + assert setup_util.setup_input_from(" AUTO ") == "auto" + + setup = setup_util.setup_input_from("numba_cpu_sparse_fp64") + + assert isinstance(setup, aa.Setup) + assert setup.setup_id == "numba_cpu_sparse_fp64" + + explicit = aa.Setup.from_setup_id("jax_gpu_dense_fp64") + + assert setup_util.setup_input_from(explicit) is explicit + + with pytest.raises(ValueError): + setup_util.setup_input_from("not_a_setup") + + +def test__analysis__stores_setup_input(masked_imaging_7x7): + analysis = ag.AnalysisImaging(dataset=masked_imaging_7x7, use_jax=False) + + assert analysis.setup_input is None + assert analysis.setup is None + + analysis = ag.AnalysisImaging( + dataset=masked_imaging_7x7, setup="auto", use_jax=False + ) + + assert analysis.setup_input == "auto" + + analysis = ag.AnalysisImaging( + dataset=masked_imaging_7x7, setup="numba_cpu_dense_fp64", use_jax=False + ) + + assert analysis.setup_input == aa.Setup.from_setup_id("numba_cpu_dense_fp64") + + +def test__use_jax_from__disable_jax_env(monkeypatch): + monkeypatch.setenv("PYAUTO_DISABLE_JAX", "1") + + assert setup_util.use_jax_from(True) is False + + monkeypatch.delenv("PYAUTO_DISABLE_JAX") + + assert setup_util.use_jax_from(False) is False + + +def test__no_setup__dataset_and_backend_unchanged__would_choose_logged( + masked_imaging_7x7, many_core, caplog +): + model = _model_with_mesh(ag.mesh.RectangularUniform(shape=(3, 3))) + + analysis = ag.AnalysisImaging(dataset=masked_imaging_7x7, use_jax=False) + + with caplog.at_level(logging.INFO): + analysis.modify_before_fit(paths=af.DirectoryPaths(), model=model) + + assert analysis.dataset is masked_imaging_7x7 + assert analysis.dataset.setup is None + assert analysis._use_jax is False + assert analysis.setup is None + + 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" + ] + + +def test__no_setup__save_attributes_writes_no_setup_json( + masked_imaging_7x7, tmp_path +): + analysis = ag.AnalysisImaging(dataset=masked_imaging_7x7, use_jax=False) + + paths = af.DirectoryPaths(name="no_setup", path_prefix=str(tmp_path)) + analysis.save_attributes(paths=paths) + + assert (paths._files_path / "settings.json").exists() + assert not (paths._files_path / "setup.json").exists() + + +def test__explicit_setup__save_attributes_writes_setup_json( + masked_imaging_7x7, many_core, tmp_path +): + analysis = ag.AnalysisImaging( + dataset=masked_imaging_7x7, setup="numba_cpu_dense_fp64", use_jax=True + ) + analysis.modify_before_fit( + paths=af.DirectoryPaths(), model=_parametric_model() + ) + + paths = af.DirectoryPaths(name="explicit_setup", path_prefix=str(tmp_path)) + analysis.save_attributes(paths=paths) + + with open(paths._files_path / "setup.json") as f: + setup_dict = json.load(f) + + assert setup_dict == { + "setup_id": "numba_cpu_dense_fp64", + "backend": "numba", + "device": "cpu", + "operator": "dense", + "precision": "fp64", + "transformer": None, + "rule_id": None, + "regime": "standard", + "hardware_class": None, + "decision_id": None, + "extrapolated": False, + "chosen_by": "explicit", + } + + +def test__setup_banner_from(): + 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=False, + ) + + banner = setup_util.setup_banner_from( + setup=setup, + chosen_by="auto", + 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" + ) + + extrapolated = aa.Setup.from_setup_id( + "numba_cpu_sparse_fp64_wtilde", + rule_id="r", + decision_id="r", + extrapolated=True, + ) + + banner = setup_util.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 diff --git a/test_autogalaxy/imaging/model/test_analysis_imaging.py b/test_autogalaxy/imaging/model/test_analysis_imaging.py index 925c9f8bd..11440af36 100644 --- a/test_autogalaxy/imaging/model/test_analysis_imaging.py +++ b/test_autogalaxy/imaging/model/test_analysis_imaging.py @@ -116,3 +116,221 @@ def test__save_attributes__registers_dataset_fits_in_database(masked_imaging_7x7 np.testing.assert_array_equal( database_dataset.psf.kernel.array, directory_dataset.psf.kernel.array ) + + +# --- setup="auto" (likelihood lifecycle 5C) --------------------------------------------- + +import json +import logging + +import pytest + +import autoarray as aa + +from autonerves.environment import Environment + + +def _environment(gpu=False, gpu_name=None, cores=64): + return Environment( + gpu=gpu, + gpu_name=gpu_name, + gpu_memory_gb=None, + cores=cores, + ram_gb=None, + numba=True, + nufftax=True, + site="local", + ) + + +MANY_CORE = _environment(cores=64) +A100 = _environment(gpu=True, gpu_name="NVIDIA A100-SXM4-80GB") + + +@pytest.fixture(autouse=True) +def unset_setup_env(monkeypatch): + monkeypatch.delenv("PYAUTO_SETUP", raising=False) + monkeypatch.delenv("PYAUTO_DISABLE_JAX", raising=False) + + +def _detect(monkeypatch, environment): + monkeypatch.setattr(Environment, "detect", classmethod(lambda cls: environment)) + + +def _rectangular_model(): + pixelization = af.Model( + ag.Pixelization, + mesh=ag.mesh.RectangularUniform(shape=(3, 3)), + regularization=ag.reg.Constant, + ) + return af.Collection( + galaxies=af.Collection( + source=af.Model(ag.Galaxy, redshift=1.0, pixelization=pixelization) + ) + ) + + +def _mge_model(): + basis = af.Model( + ag.lp_basis.Basis, + profile_list=[af.Model(ag.lp_linear.Gaussian) for _ in range(3)], + ) + return af.Collection( + galaxies=af.Collection(galaxy=af.Model(ag.Galaxy, redshift=0.5, bulge=basis)) + ) + + +def test__setup_auto__cpu_many_core_rectangular__numba_sparse_operator( + masked_imaging_7x7, monkeypatch, caplog +): + pytest.importorskip("numba") + from autoarray.inversion.inversion.imaging_numba.inversion_imaging_numba_util import ( + SparseLinAlgImagingNumba, + ) + + _detect(monkeypatch, MANY_CORE) + + analysis = ag.AnalysisImaging( + dataset=masked_imaging_7x7, setup="auto", use_jax=True + ) + + with caplog.at_level(logging.INFO): + result = analysis.modify_before_fit( + paths=af.DirectoryPaths(), model=_rectangular_model() + ) + + assert result is analysis + assert analysis.setup.setup_id == "numba_cpu_sparse_fp64" + assert analysis.setup_chosen_by == "auto" + assert analysis._use_jax is False + 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: ")] + + 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" + ] + + +def test__setup_auto__gpu_rectangular__jax_dense_no_operator( + masked_imaging_7x7, monkeypatch +): + pytest.importorskip("jax") + + _detect(monkeypatch, A100) + + analysis = ag.AnalysisImaging( + dataset=masked_imaging_7x7, setup="auto", use_jax=False + ) + analysis.modify_before_fit(paths=af.DirectoryPaths(), model=_rectangular_model()) + + assert analysis.setup.setup_id == "jax_gpu_dense_fp64" + assert analysis.setup.extrapolated is False + assert analysis._use_jax is True + assert analysis.dataset.sparse_operator is None + + +def test__setup_auto__cpu_mge__jax_dense(masked_imaging_7x7, monkeypatch): + pytest.importorskip("jax") + + _detect(monkeypatch, MANY_CORE) + + analysis = ag.AnalysisImaging( + dataset=masked_imaging_7x7, setup="auto", use_jax=False + ) + analysis.modify_before_fit(paths=af.DirectoryPaths(), model=_mge_model()) + + assert analysis.setup.setup_id == "jax_cpu_dense_fp64" + assert analysis._use_jax is True + assert analysis.dataset.sparse_operator is None + + +def test__setup_auto__disable_jax_falls_back_to_numpy(masked_imaging_7x7, monkeypatch): + _detect(monkeypatch, A100) + monkeypatch.setenv("PYAUTO_DISABLE_JAX", "1") + + analysis = ag.AnalysisImaging(dataset=masked_imaging_7x7, setup="auto") + analysis.modify_before_fit(paths=af.DirectoryPaths(), model=_rectangular_model()) + + assert analysis.setup.setup_id == "jax_gpu_dense_fp64" + assert analysis._use_jax is False + + +def test__setup_auto__pyauto_setup_env_wins(masked_imaging_7x7, monkeypatch, tmp_path): + _detect(monkeypatch, A100) + monkeypatch.setenv("PYAUTO_SETUP", "numba_cpu_dense_fp64") + + analysis = ag.AnalysisImaging(dataset=masked_imaging_7x7, setup="auto") + analysis.modify_before_fit(paths=af.DirectoryPaths(), model=_rectangular_model()) + + assert analysis.setup.setup_id == "numba_cpu_dense_fp64" + assert analysis.setup_chosen_by == "PYAUTO_SETUP" + assert analysis._use_jax is False + + paths = af.DirectoryPaths(name="pyauto_setup", path_prefix=str(tmp_path)) + analysis.save_attributes(paths=paths) + + with open(paths._files_path / "setup.json") as f: + setup_dict = json.load(f) + + assert setup_dict["chosen_by"] == "PYAUTO_SETUP" + assert setup_dict["rule_id"] == "explicit:PYAUTO_SETUP" + assert setup_dict["setup_id"] == "numba_cpu_dense_fp64" + + +def test__explicit_setup__wins_over_pyauto_setup_env(masked_imaging_7x7, monkeypatch): + _detect(monkeypatch, MANY_CORE) + monkeypatch.setenv("PYAUTO_SETUP", "jax_cpu_dense_fp64") + + setup = aa.Setup.from_setup_id("numba_cpu_dense_fp64") + + analysis = ag.AnalysisImaging( + dataset=masked_imaging_7x7, setup=setup, use_jax=True + ) + analysis.modify_before_fit(paths=af.DirectoryPaths(), model=_mge_model()) + + assert analysis.setup is setup + assert analysis.setup_chosen_by == "explicit" + assert analysis._use_jax is False + + +def test__setup_auto__setup_json_written_by_search(masked_imaging_7x7, monkeypatch): + pytest.importorskip("jax") + + _detect(monkeypatch, MANY_CORE) + + model = af.Collection(galaxies=af.Collection(galaxy_0=ag.Galaxy(redshift=0.5))) + + analysis = ag.AnalysisImaging( + dataset=masked_imaging_7x7, setup="auto", use_jax=False + ) + + search = ag.m.MockSearch(name="test_search_setup_auto") + search.fit(model=model, analysis=analysis) + + with open(search.paths._files_path / "setup.json") as f: + setup_dict = json.load(f) + + assert setup_dict["setup_id"] == "jax_cpu_dense_fp64" + assert setup_dict["rule_id"] == "imaging-mge-standard-cpu-many-core" + assert setup_dict["decision_id"] == "imaging-mge-standard-cpu-many-core" + assert setup_dict["hardware_class"] == "cpu_many_core" + assert setup_dict["extrapolated"] is False + assert setup_dict["chosen_by"] == "auto" + + +def test__check_setup_consistency__numba_operator_under_jax_raises(masked_imaging_7x7): + pytest.importorskip("jax") + pytest.importorskip("numba") + + from autogalaxy.analysis import setup_util + + dataset = masked_imaging_7x7.apply_setup("numba_cpu_sparse_fp64") + + setup_util.check_setup_consistency(dataset=dataset, use_jax=False) + + with pytest.raises(aa.exc.InversionException, match="mismatch"): + setup_util.check_setup_consistency(dataset=dataset, use_jax=True) diff --git a/test_autogalaxy/interferometer/model/test_analysis_interferometer.py b/test_autogalaxy/interferometer/model/test_analysis_interferometer.py index d5db8083b..f863e3a8b 100644 --- a/test_autogalaxy/interferometer/model/test_analysis_interferometer.py +++ b/test_autogalaxy/interferometer/model/test_analysis_interferometer.py @@ -1039,3 +1039,103 @@ def test__save_attributes__registers_dataset_fits_in_database( database_dataset.uv_wavelengths, directory_dataset.uv_wavelengths ) assert type(database_dataset.transformer) is type(directory_dataset.transformer) + + +# --- setup="auto" (likelihood lifecycle 5C) --------------------------------------------- + +import pytest + +from autonerves.environment import Environment + + +def _environment(gpu=False, gpu_name=None, cores=64): + return Environment( + gpu=gpu, + gpu_name=gpu_name, + gpu_memory_gb=None, + cores=cores, + ram_gb=None, + numba=True, + nufftax=True, + site="local", + ) + + +@pytest.fixture(autouse=True) +def unset_setup_env(monkeypatch): + monkeypatch.delenv("PYAUTO_SETUP", raising=False) + monkeypatch.delenv("PYAUTO_DISABLE_JAX", raising=False) + + +def _rectangular_model(): + pixelization = af.Model( + ag.Pixelization, + mesh=ag.mesh.RectangularUniform(shape=(3, 3)), + regularization=ag.reg.Constant, + ) + return af.Collection( + galaxies=af.Collection( + source=af.Model(ag.Galaxy, redshift=1.0, pixelization=pixelization) + ) + ) + + +def test__setup_auto__cpu_many_core_rectangular__numba_wtilde_sparse_operator( + interferometer_7, monkeypatch +): + pytest.importorskip("finufft") + + monkeypatch.setattr( + Environment, "detect", classmethod(lambda cls: _environment(cores=64)) + ) + + analysis = ag.AnalysisInterferometer( + dataset=interferometer_7, setup="auto", use_jax=True + ) + analysis.modify_before_fit(paths=af.DirectoryPaths(), model=_rectangular_model()) + + assert analysis.setup.setup_id == "numba_cpu_sparse_fp64_wtilde" + assert analysis._use_jax is False + assert analysis.dataset.sparse_operator is not None + assert analysis.dataset.setup == analysis.setup + + +def test__setup_auto__gpu_mge__jax_dense_nufft(interferometer_7, monkeypatch): + pytest.importorskip("jax") + + monkeypatch.setattr( + Environment, + "detect", + classmethod( + lambda cls: _environment(gpu=True, gpu_name="NVIDIA A100-SXM4-80GB") + ), + ) + + model = af.Collection( + galaxies=af.Collection( + galaxy=af.Model(ag.Galaxy, redshift=0.5, light=ag.lp.Sersic) + ) + ) + + analysis = ag.AnalysisInterferometer( + dataset=interferometer_7, setup="auto", use_jax=False + ) + analysis.modify_before_fit(paths=af.DirectoryPaths(), model=model) + + assert analysis.setup.setup_id == "jax_gpu_dense_fp64_nufft" + assert analysis._use_jax is True + assert analysis.dataset.sparse_operator is None + assert isinstance(analysis.dataset.transformer, ag.TransformerNUFFT) + + +def test__no_setup__dataset_unchanged(interferometer_7, monkeypatch): + monkeypatch.setattr( + Environment, "detect", classmethod(lambda cls: _environment(cores=64)) + ) + + analysis = ag.AnalysisInterferometer(dataset=interferometer_7, use_jax=False) + analysis.modify_before_fit(paths=af.DirectoryPaths(), model=_rectangular_model()) + + assert analysis.dataset is interferometer_7 + assert analysis._use_jax is False + assert analysis.setup is None