diff --git a/autolens/analysis/analysis/dataset.py b/autolens/analysis/analysis/dataset.py index aab782af5..686d7cc3a 100644 --- a/autolens/analysis/analysis/dataset.py +++ b/autolens/analysis/analysis/dataset.py @@ -66,6 +66,7 @@ def __init__( raise_inversion_positions_likelihood_exception: bool = True, title_prefix: str = None, use_jax: bool = True, + setup=None, **kwargs, ): """ @@ -99,6 +100,16 @@ def __init__( be inferred, in which case an Exception is raised before the model-fit begins to inform the user of this. This exception is not raised if this input is False, allowing the user to perform the model-fit anyway. + 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: `None` (the 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 such as `"numba_cpu_sparse_fp64"`. It is resolved first in `modify_before_fit` by the + **PyAutoGalaxy** base class (see `autogalaxy.analysis.analysis.dataset.AnalysisDataset`). A setup is + not supported inside a factor graph, which does not call `modify_before_fit`: the likelihood raises + an `exc.SetupException` instead of fitting with the setup silently ignored. """ super().__init__( @@ -108,6 +119,7 @@ def __init__( settings=settings, title_prefix=title_prefix, use_jax=use_jax, + setup=setup, **kwargs, ) @@ -136,6 +148,10 @@ def modify_before_fit(self, paths: af.DirectoryPaths, model: af.Collection): This function: + - Resolves and applies the compute `setup` (via the **PyAutoGalaxy** base class, which does this first, + before the grids are preloaded), keeping the backend (`_use_jax`, and `_xp`, which derives from it) in + step with the resolved setup. + - Checks that the adapt-dataset is consistent with previous adapt-datasets if the model-fit is being resumed from a previous run. diff --git a/autolens/analysis/analysis/setup.py b/autolens/analysis/analysis/setup.py new file mode 100644 index 000000000..e635731c2 --- /dev/null +++ b/autolens/analysis/analysis/setup.py @@ -0,0 +1,195 @@ +""" +The compute `setup` of the lens analyses that have no dataset operator (point-source and weak lensing), +and the guard that stops a setup being silently ignored inside a factor graph. + +The imaging and interferometer analyses resolve their setup through the **PyAutoGalaxy** base class +(`autogalaxy.analysis.analysis.dataset.AnalysisDataset.resolve_setup`), which also applies it to the +dataset (attaching the sparse operator it names). `AnalysisPoint` and `AnalysisWeak` do not fit an +`aa.Imaging` / `aa.Interferometer`, so their setup has no operator to attach (operator `"na"` or +`"dense"`); `AnalysisSetupNoOperator` resolves and applies the rest of it (backend, threads, banner, +`files/setup.json`), reusing the helpers of `autogalaxy.analysis.setup_util`. + +`raise_if_setup_unresolved` is called at the top of every lens `log_likelihood_function`. A setup is +resolved in `modify_before_fit`, which a `FactorGraphModel` does not call on its factors, so a setup +given to an analysis fitted inside a factor graph would otherwise never be applied. +""" + +import logging +from typing import Optional, Tuple + +import autofit as af +import autoarray as aa + +from autogalaxy.analysis import setup_util + +from autolens import exc + +logger = logging.getLogger(__name__) + +logger.setLevel(level="INFO") + + +SETUP_UNRESOLVED_MESSAGE = """ +The {cls} was given `setup={setup_input!r}`, but the setup was never resolved, because +`modify_before_fit` was not called before the likelihood was evaluated. + +This happens when the analysis is fitted inside a factor graph (`af.FactorGraphModel` of +`af.AnalysisFactor`s): the factor graph does not call each factor's `modify_before_fit`, so the +setup would silently not be applied. Setups are not yet supported inside factor graphs (this is +planned for the PyAutoFit phase of the likelihood lifecycle, 5D). + +Instead, apply the setup to each dataset yourself and choose the backend explicitly, e.g. + + dataset = dataset.apply_setup("numba_cpu_sparse_fp64") + analysis = al.AnalysisImaging(dataset=dataset, use_jax=False) + +(`use_jax=True` for a `jax_*` setup), and do not pass `setup=` to the analysis. +""" + + +def raise_if_setup_unresolved(analysis): + """ + Raise an `exc.SetupException` when an analysis was given a `setup` that was never resolved. + + A setup is resolved in `modify_before_fit`, which a non-linear search calls before sampling. A + `FactorGraphModel` does not call it on its factors, so a factor given `setup=` would otherwise be + fitted with its constructor backend and the setup silently ignored. + + This is a cheap Python attribute check, safe under JAX tracing. It is called at the top of each + `log_likelihood_function`, outside the `raise_fit_exception` wrapper, so it stops the fit instead of + being turned into a resample. It is not called by `fit_from`, so visualization, results and the + aggregator are unaffected. + """ + setup_input = getattr(analysis, "setup_input", None) + + if setup_input is None or getattr(analysis, "setup", None) is not None: + return + + if isinstance(setup_input, aa.Setup): + setup_input = setup_input.setup_id + + raise exc.SetupException( + SETUP_UNRESOLVED_MESSAGE.format( + cls=type(analysis).__name__, setup_input=setup_input + ) + ) + + +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 + + +class AnalysisSetupNoOperator: + """ + Mixin resolving the compute `setup` of an analysis whose dataset has no operator to attach + (`AnalysisPoint`, `AnalysisWeak`). + + The subclass calls `_init_setup(setup)` in its constructor, `resolve_setup(model)` first in its + `modify_before_fit`, `save_setup(paths)` in its `save_attributes`, and implements `setup_key_from` + (the `(dataset_type, variant)` rule key of `aa.Setup.auto`). + """ + + def _init_setup(self, setup): + """ + Store the normalised `setup` input (`None`, `"auto"` or an `aa.Setup`, see + `setup_util.setup_input_from`); the resolved setup is set by `resolve_setup`. + """ + self.setup_input = setup_util.setup_input_from(setup) + self.setup = None + self.setup_chosen_by = None + + def setup_key_from(self, model: af.Collection) -> Tuple[str, str]: + """ + The `(dataset_type, variant)` rule key of `aa.Setup.auto` for this analysis and model. + """ + raise NotImplementedError + + 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 `setup_key_from(model)`; + `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); `_xp` follows, as it derives from `_use_jax`; + - pins the thread pools (`setup.apply_threads()`); + - is logged as the setup banner line and stored as `self.setup`. + + There is no dataset operator to attach or check. + """ + setup_input = getattr(self, "setup_input", None) + + if setup_input is None: + self._log_setup_auto_would_choose(model=model) + return + + environment = setup_environment() + + if setup_input == setup_util.SETUP_AUTO: + setup = aa.Setup.auto(*self.setup_key_from(model), environment=environment) + chosen_by = setup_util.chosen_by_from(setup=setup, auto=True) + else: + 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") + + 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, + ) + ) + + def _log_setup_auto_would_choose(self, model: af.Collection): + """ + Log one line reporting the setup `setup="auto"` would choose, applying nothing. + """ + try: + setup = aa.Setup.auto( + *self.setup_key_from(model), environment=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' + ) + + def save_setup(self, paths: af.DirectoryPaths): + """ + Write the resolved setup to `files/setup.json`, when a setup was resolved. + """ + setup: Optional[aa.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 + ), + ) diff --git a/autolens/exc.py b/autolens/exc.py index 05ca7c0f3..391e2ae40 100644 --- a/autolens/exc.py +++ b/autolens/exc.py @@ -64,3 +64,16 @@ class PointProfileMismatchException(Exception): absent dataset components (its long-standing name-pairing semantics), and profile/fit mismatches must never be silently skipped — they invalidate the composed model. """ + + +class SetupException(AnalysisException): + """ + Raised when the compute `setup` of an analysis cannot be honoured, for example when an analysis given + `setup=` is fitted inside a factor graph, where its `modify_before_fit` (which resolves and applies the + setup) is never called. + + Deliberately NOT a subclass of `af.exc.FitException`: it is a configuration error, so it must stop the + model-fit with a clear message rather than be swallowed into a resample on every likelihood call. + """ + + pass diff --git a/autolens/imaging/model/analysis.py b/autolens/imaging/model/analysis.py index 40111cdc4..4886474ea 100644 --- a/autolens/imaging/model/analysis.py +++ b/autolens/imaging/model/analysis.py @@ -21,6 +21,7 @@ from autonerves.fitsable import hdu_list_for_output_from from autolens.analysis.analysis.dataset import AnalysisDataset +from autolens.analysis.analysis.setup import raise_if_setup_unresolved from autolens.analysis.exceptions import raise_fit_exception from autolens.analysis.latent import LatentLens from autolens.imaging.model.result import ResultImaging @@ -52,6 +53,7 @@ def __init__( title_prefix: str = None, use_jax: bool = True, shared_preloads: bool = False, + setup=None, **kwargs, ): """ @@ -60,6 +62,10 @@ def __init__( Parameters ---------- + 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`. shared_preloads Opts this analysis into the cross-factor shared-state mechanism of a `FactorGraphModel` (see `shared_state_from`). Set this to `True` only when this analysis is one of many @@ -77,6 +83,7 @@ def __init__( raise_inversion_positions_likelihood_exception=raise_inversion_positions_likelihood_exception, title_prefix=title_prefix, use_jax=use_jax, + setup=setup, **kwargs, ) @@ -126,6 +133,8 @@ def log_likelihood_function(self, instance: af.ModelInstance, shared=None) -> fl The log likelihood indicating how well this model instance fitted the imaging data. """ + raise_if_setup_unresolved(analysis=self) + log_likelihood_penalty = self.log_likelihood_penalty_from( instance=instance, ) diff --git a/autolens/interferometer/model/analysis.py b/autolens/interferometer/model/analysis.py index b4e68c851..4fea4642c 100644 --- a/autolens/interferometer/model/analysis.py +++ b/autolens/interferometer/model/analysis.py @@ -24,6 +24,7 @@ from autogalaxy.interferometer.model.analysis import interferometer_hdu_list_from from autolens.analysis.analysis.dataset import AnalysisDataset +from autolens.analysis.analysis.setup import raise_if_setup_unresolved from autolens.analysis.exceptions import raise_fit_exception from autolens.analysis.positions import PositionsLH from autolens.interferometer.model.result import ResultInterferometer @@ -53,6 +54,7 @@ def __init__( title_prefix: str = None, use_jax: bool = True, shared_preloads: bool = False, + setup=None, **kwargs, ): """ @@ -95,6 +97,10 @@ 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. + 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`. shared_preloads Opts this analysis into the cross-factor shared-state mechanism of a `FactorGraphModel` (see `shared_state_from`). Set this to `True` only when this analysis is one of many datacube channels @@ -111,6 +117,7 @@ def __init__( raise_inversion_positions_likelihood_exception=raise_inversion_positions_likelihood_exception, title_prefix=title_prefix, use_jax=use_jax, + setup=setup, **kwargs, ) @@ -164,6 +171,8 @@ def log_likelihood_function(self, instance, shared=None): The log likelihood indicating how well this model instance fitted the interferometer data. """ + raise_if_setup_unresolved(analysis=self) + log_likelihood_penalty = self.log_likelihood_penalty_from( instance=instance, ) diff --git a/autolens/point/model/analysis.py b/autolens/point/model/analysis.py index 7a42d4c2b..057b7364b 100644 --- a/autolens/point/model/analysis.py +++ b/autolens/point/model/analysis.py @@ -27,6 +27,10 @@ from autogalaxy.analysis.analysis.analysis import Analysis as AgAnalysis from autolens.analysis.analysis.lens import AnalysisLens +from autolens.analysis.analysis.setup import ( + AnalysisSetupNoOperator, + raise_if_setup_unresolved, +) from autolens.analysis.exceptions import raise_fit_exception from autolens.point.fit.positions.image.pair_all import FitPositionsImagePairAllSolved from autolens.point.fit.dataset import FitPointDataset @@ -40,7 +44,7 @@ logger = logging.getLogger(__name__) -class AnalysisPoint(AgAnalysis, AnalysisLens): +class AnalysisPoint(AnalysisSetupNoOperator, AgAnalysis, AnalysisLens): Visualizer = VisualizerPoint Result = ResultPoint @@ -66,6 +70,7 @@ def __init__( use_jax: bool = True, fit_flux_cls=FitFluxes, fit_time_delays_cls=FitTimeDelays, + setup=None, **kwargs, ): """ @@ -112,6 +117,17 @@ 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: `None` (the default, nothing changes), `"auto"`, an `aa.Setup` + or a setup_id string such as `"jax_cpu_na_fp64"`. It is resolved in `modify_before_fit`. With + `"auto"` the rule key is `point_source_source/source_plane` when `fit_positions_cls` is a + source-plane fit (`FitPositionsSource` or a subclass) and `point_source_image/image_plane` otherwise + (see `setup_key_from`). A resolved setup sets the backend, pins the thread pools, is logged as a + banner line and is written to `files/setup.json`; a point dataset has no operator to attach. A setup + is not supported inside a factor graph: the likelihood raises an `exc.SetupException` instead. """ super().__init__(cosmology=cosmology, use_jax=use_jax, **kwargs) @@ -128,8 +144,44 @@ def __init__( self.fit_flux_cls = fit_flux_cls self.fit_time_delays_cls = fit_time_delays_cls self.title_prefix = title_prefix + self._init_setup(setup) self._check_solver_extent() + def setup_key_from(self, model: af.Collection = None): + """ + The `(dataset_type, variant)` rule key of `aa.Setup.auto` for this point-source analysis. + + The key follows the positions fit, which decides where the likelihood is evaluated: + + - `("point_source_source", "source_plane")` when `fit_positions_cls` is a source-plane fit + (`FitPositionsSource`, `FitPositionsSourceSolved` or any other subclass of `FitPositionsSource`), + which traces the observed positions to the source plane and needs no `PointSolver`. + - `("point_source_image", "image_plane")` otherwise: the image-plane pair fits + (`AbstractFitPositionsImagePair` subclasses), which solve for the model image positions with the + `PointSolver`, and any custom or absent positions fit. + + The model does not change the key (the rule table has one variant per point-source likelihood). + """ + from autolens.point.fit.positions.source.separations import FitPositionsSource + + fit_positions_cls = self.fit_positions_cls + + if isinstance(fit_positions_cls, type) and issubclass( + fit_positions_cls, FitPositionsSource + ): + return ("point_source_source", "source_plane") + + return ("point_source_image", "image_plane") + + def modify_before_fit(self, paths: af.DirectoryPaths, model: af.Collection): + """ + Called immediately before the non-linear search begins: resolves and applies the compute `setup` + (see `AnalysisSetupNoOperator.resolve_setup`), before any other preparation. + """ + self.resolve_setup(model=model) + + return super().modify_before_fit(paths=paths, model=model) + def _check_solver_extent(self): """Diagnose observed-position coverage once, outside likelihood tracing. @@ -239,6 +291,8 @@ def log_likelihood_function(self, instance): float The log likelihood indicating how well this model instance fitted the imaging data. """ + raise_if_setup_unresolved(analysis=self) + if self._use_jax: return self.fit_from(instance=instance).log_likelihood @@ -378,6 +432,7 @@ def save_attributes(self, paths: af.DirectoryPaths): For this analysis, it uses the `AnalysisDataset` object's method to output the following: - The dataset's point source dataset as a readable .json file. + - The resolved compute setup (`setup.json`), when a `setup` was given. It is common for these attributes to be loaded by many of the template aggregator functions given in the `aggregator` modules. For example, when using the database tools to perform a fit, the default behaviour is for @@ -394,3 +449,5 @@ def save_attributes(self, paths: af.DirectoryPaths): obj=self.dataset, file_path=paths._files_path / "dataset.json", ) + + self.save_setup(paths=paths) diff --git a/autolens/weak/model/analysis.py b/autolens/weak/model/analysis.py index dff3a61c0..682199d84 100644 --- a/autolens/weak/model/analysis.py +++ b/autolens/weak/model/analysis.py @@ -19,13 +19,17 @@ from autogalaxy.analysis.analysis.analysis import Analysis as AgAnalysis from autolens.analysis.analysis.lens import AnalysisLens +from autolens.analysis.analysis.setup import ( + AnalysisSetupNoOperator, + raise_if_setup_unresolved, +) from autolens.weak.dataset import WeakDataset from autolens.weak.fit import FitWeak from autolens.weak.model.result import ResultWeak from autolens.weak.model.visualizer import VisualizerWeak -class AnalysisWeak(AgAnalysis, AnalysisLens): +class AnalysisWeak(AnalysisSetupNoOperator, AgAnalysis, AnalysisLens): Visualizer = VisualizerWeak Result = ResultWeak @@ -35,6 +39,7 @@ def __init__( cosmology: ag.cosmo.LensingCosmology = None, title_prefix: str = None, use_jax: bool = False, + setup=None, **kwargs, ): """ @@ -65,6 +70,16 @@ 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: `None` (the default, nothing changes), `"auto"`, an `aa.Setup` + or a setup_id string such as `"jax_cpu_dense_fp64"`. It is resolved in `modify_before_fit`; with + `"auto"` the rule key is `weak/isothermal` (see `setup_key_from`). A resolved setup sets the backend, + pins the thread pools, is logged as a banner line and is written to `files/setup.json`; a shear + catalogue has no operator to attach. A setup is not supported inside a factor graph: the likelihood + raises an `exc.SetupException` instead. """ super().__init__(cosmology=cosmology, use_jax=use_jax, **kwargs) @@ -77,6 +92,25 @@ def __init__( self.title_prefix = title_prefix + self._init_setup(setup) + + def setup_key_from(self, model: af.Collection = None): + """ + The `(dataset_type, variant)` rule key of `aa.Setup.auto` for this weak-lensing analysis: + `("weak", "isothermal")`, the one weak-lensing likelihood the rule table designates so far. It is used + for every lens mass model; the setup decides only how the likelihood is computed, never the model. + """ + return ("weak", "isothermal") + + def modify_before_fit(self, paths: af.DirectoryPaths, model: af.Collection): + """ + Called immediately before the non-linear search begins: resolves and applies the compute `setup` + (see `AnalysisSetupNoOperator.resolve_setup`), before any other preparation. + """ + self.resolve_setup(model=model) + + return super().modify_before_fit(paths=paths, model=model) + def log_likelihood_function(self, instance): """ Given an instance of the model, where the model parameters are set via a non-linear search, fit the model @@ -106,6 +140,8 @@ def log_likelihood_function(self, instance): float The log likelihood indicating how well this model instance fitted the weak-lensing data. """ + raise_if_setup_unresolved(analysis=self) + return self.fit_from(instance=instance).log_likelihood def fit_from(self, instance) -> FitWeak: @@ -165,6 +201,7 @@ def save_attributes(self, paths: af.DirectoryPaths): For this analysis, it outputs the following: - The weak-lensing shear catalogue as a readable .json file. + - The resolved compute setup (`setup.json`), when a `setup` was given. It is common for these attributes to be loaded by many of the template aggregator functions given in the `aggregator` modules. For example, when using the database tools to perform a fit, the default behaviour is for @@ -181,3 +218,5 @@ def save_attributes(self, paths: af.DirectoryPaths): obj=self.dataset, file_path=paths._files_path / "dataset.json", ) + + self.save_setup(paths=paths) diff --git a/test_autolens/imaging/model/test_analysis_imaging_setup.py b/test_autolens/imaging/model/test_analysis_imaging_setup.py new file mode 100644 index 000000000..4adb7bf39 --- /dev/null +++ b/test_autolens/imaging/model/test_analysis_imaging_setup.py @@ -0,0 +1,318 @@ +""" +The compute `setup` of `al.AnalysisImaging` (likelihood lifecycle 5C-2): threading of the `setup=` +kwarg to the PyAutoGalaxy base class, `setup="auto"` resolution in `modify_before_fit`, the backend +(`_use_jax` / `_xp`) staying in step with the resolved setup, the factor-graph guard and the +operator / backend mismatch surfacing before sampling. +""" + +import copy +import json +import logging + +import numpy as np +import pytest + +import autofit as af +import autoarray as aa +import autolens as al + +from autonerves.environment import Environment + +from autolens import exc + + +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) + monkeypatch.delenv("PYAUTO_RAISE_ANALYSIS_EXCEPTIONS", raising=False) + + +def _detect(monkeypatch, environment): + monkeypatch.setattr(Environment, "detect", classmethod(lambda cls: environment)) + + +def _rectangular_model(): + pixelization = af.Model( + al.Pixelization, + mesh=al.mesh.RectangularUniform(shape=(3, 3)), + regularization=al.reg.Constant, + ) + return af.Collection( + galaxies=af.Collection( + lens=al.Galaxy(redshift=0.5, mass=al.mp.IsothermalSph(einstein_radius=1.0)), + source=af.Model(al.Galaxy, redshift=1.0, pixelization=pixelization), + ) + ) + + +def _light_model(): + return af.Collection( + galaxies=af.Collection( + lens=al.Galaxy(redshift=0.5, light=al.lp.Sersic(intensity=0.1)) + ) + ) + + +def _analysis(dataset, **kwargs): + return al.AnalysisImaging( + dataset=dataset, + raise_inversion_positions_likelihood_exception=False, + **kwargs, + ) + + +def test__setup_kwarg__threaded_to_galaxy_base(masked_imaging_7x7): + assert _analysis(masked_imaging_7x7).setup_input is None + assert _analysis(masked_imaging_7x7, setup="AUTO").setup_input == "auto" + + analysis = _analysis(masked_imaging_7x7, setup="numba_cpu_dense_fp64") + + assert isinstance(analysis.setup_input, aa.Setup) + assert analysis.setup_input.setup_id == "numba_cpu_dense_fp64" + assert analysis.setup is None + + with pytest.raises(ValueError): + _analysis(masked_imaging_7x7, setup="not_a_setup") + + +def test__setup_auto__cpu_many_core_rectangular__numba_sparse_operator__numpy_xp( + 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 = _analysis(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._xp is np + 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 len(banners) == 1 + assert banners[0].startswith("Setup: numba/cpu/sparse/fp64") + + +def test__setup_auto__a100_rectangular__jax_dense__jax_xp( + masked_imaging_7x7, monkeypatch +): + pytest.importorskip("jax") + import jax.numpy as jnp + + _detect(monkeypatch, A100) + + analysis = _analysis(masked_imaging_7x7, setup="auto", use_jax=False) + + assert analysis._xp is np + + analysis.modify_before_fit(paths=af.DirectoryPaths(), model=_rectangular_model()) + + assert analysis.setup.setup_id == "jax_gpu_dense_fp64" + assert analysis._use_jax is True + assert analysis._xp is jnp + assert analysis.dataset.sparse_operator is None + + +def test__modify_before_fit__resolves_setup_once(masked_imaging_7x7, monkeypatch): + _detect(monkeypatch, MANY_CORE) + + calls = {"n": 0} + + original = al.AnalysisImaging.resolve_setup + + def counting(self, model): + calls["n"] += 1 + return original(self, model=model) + + monkeypatch.setattr(al.AnalysisImaging, "resolve_setup", counting) + + analysis = _analysis(masked_imaging_7x7, setup="numba_cpu_dense_fp64") + analysis.modify_before_fit(paths=af.DirectoryPaths(), model=_light_model()) + + assert calls["n"] == 1 + assert analysis.setup.setup_id == "numba_cpu_dense_fp64" + + +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 = _analysis(masked_imaging_7x7, setup="auto", use_jax=True) + 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 + assert analysis._xp is np + + 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["setup_id"] == "numba_cpu_dense_fp64" + assert setup_dict["chosen_by"] == "PYAUTO_SETUP" + + +def test__no_setup__dataset_and_backend_unchanged( + masked_imaging_7x7, monkeypatch, tmp_path, caplog +): + _detect(monkeypatch, MANY_CORE) + + analysis = _analysis(masked_imaging_7x7, use_jax=False) + + with caplog.at_level(logging.INFO): + analysis.modify_before_fit( + paths=af.DirectoryPaths(), model=_rectangular_model() + ) + + assert analysis.dataset is masked_imaging_7x7 + assert analysis._use_jax is False + assert analysis.setup is None + + lines = [r.message for r in caplog.records if r.message.startswith("Setup: ")] + assert lines == [ + "Setup: auto would choose numba_cpu_sparse_fp64 (rule " + 'imaging-rectangular-standard-cpu-many-core); pass setup="auto" to use it' + ] + + paths = af.DirectoryPaths(name="no_setup", path_prefix=str(tmp_path)) + analysis.save_attributes(paths=paths) + + assert not (paths._files_path / "setup.json").exists() + + instance = _light_model().instance_from_unit_vector([]) + assert analysis.log_likelihood_function(instance=instance) == pytest.approx( + al.FitImaging( + dataset=masked_imaging_7x7, + tracer=analysis.tracer_via_instance_from(instance=instance), + ).figure_of_merit + ) + + +def test__explicit_setup__search_fit__setup_json_written(masked_imaging_7x7, monkeypatch): + _detect(monkeypatch, MANY_CORE) + + analysis = _analysis(masked_imaging_7x7, setup="numba_cpu_dense_fp64") + + search = al.m.MockSearch(name="test_search_lens_setup") + search.fit(model=_light_model(), analysis=analysis) + + with open(search.paths._files_path / "setup.json") as f: + setup_dict = json.load(f) + + assert setup_dict["setup_id"] == "numba_cpu_dense_fp64" + assert setup_dict["chosen_by"] == "explicit" + + +def test__factor_graph__setup_raises_setup_exception(masked_imaging_7x7): + factors = [ + af.AnalysisFactor( + prior_model=_light_model(), + analysis=_analysis(masked_imaging_7x7, setup="auto", use_jax=False), + ) + for _ in range(2) + ] + + factor_graph = af.FactorGraphModel(*factors) + instance = factor_graph.global_prior_model.instance_from_unit_vector([]) + + with pytest.raises(exc.SetupException, match="factor graph") as e: + factor_graph.log_likelihood_function(instance) + + assert not isinstance(e.value, af.exc.FitException) + assert "apply_setup" in str(e.value) + assert "use_jax" in str(e.value) + + +def test__factor_graph_guard__fit_from_unaffected(masked_imaging_7x7): + analysis = _analysis(masked_imaging_7x7, setup="auto", use_jax=False) + + instance = _light_model().instance_from_unit_vector([]) + + fit = analysis.fit_from(instance=instance) + + assert fit.figure_of_merit == pytest.approx( + al.FitImaging( + dataset=masked_imaging_7x7, + tracer=analysis.tracer_via_instance_from(instance=instance), + ).figure_of_merit + ) + + +def test__factor_graph__no_setup__unchanged(masked_imaging_7x7): + factors = [ + af.AnalysisFactor( + prior_model=_light_model(), + analysis=_analysis(masked_imaging_7x7, use_jax=False), + ) + for _ in range(2) + ] + + factor_graph = af.FactorGraphModel(*factors) + instance = factor_graph.global_prior_model.instance_from_unit_vector([]) + + assert np.isfinite(factor_graph.log_likelihood_function(instance)) + + +def test__mismatched_operator__numpy_path__raises_at_modify_before_fit( + masked_imaging_7x7, monkeypatch +): + """ + A jax sparse setup with JAX disabled runs the numpy path. A stale numba operator left on the dataset + (simulated by an `apply_setup` that records the setup without rebuilding the operator) is a mismatch, + which must raise an `InversionException` at `modify_before_fit` rather than be turned into a + `FitException` (a resample) on every likelihood call. + """ + pytest.importorskip("numba") + + monkeypatch.setenv("PYAUTO_DISABLE_JAX", "1") + _detect(monkeypatch, MANY_CORE) + + dataset = masked_imaging_7x7.apply_setup("numba_cpu_sparse_fp64") + + def apply_setup_keeping_operator(self, setup, **kwargs): + dataset_copy = copy.copy(self) + dataset_copy.setup = aa.Setup.from_setup_id(setup) if isinstance(setup, str) else setup + return dataset_copy + + monkeypatch.setattr(aa.Imaging, "apply_setup", apply_setup_keeping_operator) + + analysis = _analysis(dataset, setup="jax_cpu_sparse_fp64") + + with pytest.raises(aa.exc.InversionException, match="mismatch") as e: + analysis.modify_before_fit(paths=af.DirectoryPaths(), model=_rectangular_model()) + + assert not isinstance(e.value, af.exc.FitException) + assert analysis._use_jax is False diff --git a/test_autolens/interferometer/model/test_analysis_interferometer.py b/test_autolens/interferometer/model/test_analysis_interferometer.py index c8d68079c..58338d40b 100644 --- a/test_autolens/interferometer/model/test_analysis_interferometer.py +++ b/test_autolens/interferometer/model/test_analysis_interferometer.py @@ -397,3 +397,136 @@ 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 (likelihood lifecycle 5C-2) --------------------------------------------------- + +import numpy as np + +from autonerves.environment import Environment + + +def _setup_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(name="unset_setup_env") +def make_unset_setup_env(monkeypatch): + monkeypatch.delenv("PYAUTO_SETUP", raising=False) + monkeypatch.delenv("PYAUTO_DISABLE_JAX", raising=False) + monkeypatch.delenv("PYAUTO_RAISE_ANALYSIS_EXCEPTIONS", raising=False) + + +def _light_model(): + return af.Collection( + galaxies=af.Collection( + lens=al.Galaxy(redshift=0.5, light=al.lp.Sersic(intensity=0.1)) + ) + ) + + +def test__setup_kwarg__threaded_to_galaxy_base(interferometer_7, unset_setup_env): + assert ( + al.AnalysisInterferometer(dataset=interferometer_7).setup_input is None + ) + + analysis = al.AnalysisInterferometer( + dataset=interferometer_7, setup="auto", shared_preloads=False + ) + + assert analysis.setup_input == "auto" + assert analysis.setup is None + + +def test__setup_auto__a100_mge__jax_dense_nufft__jax_xp( + interferometer_7, unset_setup_env, monkeypatch +): + pytest.importorskip("jax") + import jax.numpy as jnp + + monkeypatch.setattr( + Environment, + "detect", + classmethod( + lambda cls: _setup_environment(gpu=True, gpu_name="NVIDIA A100-SXM4-80GB") + ), + ) + + model = af.Collection( + galaxies=af.Collection( + lens=af.Model(al.Galaxy, redshift=0.5, light=al.lp.Sersic) + ) + ) + + analysis = al.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._xp is jnp + assert isinstance(analysis.dataset.transformer, al.TransformerNUFFT) + + +def test__explicit_setup__numba__numpy_xp(interferometer_7, unset_setup_env, monkeypatch): + monkeypatch.setattr( + Environment, "detect", classmethod(lambda cls: _setup_environment(cores=64)) + ) + + analysis = al.AnalysisInterferometer( + dataset=interferometer_7, setup="numba_cpu_dense_fp64", use_jax=True + ) + analysis.modify_before_fit(paths=af.DirectoryPaths(), model=_light_model()) + + assert analysis.setup.setup_id == "numba_cpu_dense_fp64" + assert analysis.setup_chosen_by == "explicit" + assert analysis._use_jax is False + assert analysis._xp is np + + +def test__no_setup__interferometer_unchanged(interferometer_7, unset_setup_env, monkeypatch): + monkeypatch.setattr( + Environment, "detect", classmethod(lambda cls: _setup_environment(cores=64)) + ) + + analysis = al.AnalysisInterferometer(dataset=interferometer_7, use_jax=False) + analysis.modify_before_fit(paths=af.DirectoryPaths(), model=_light_model()) + + assert analysis.dataset is interferometer_7 + assert analysis._use_jax is False + assert analysis.setup is None + + +def test__factor_graph__setup_raises_setup_exception__interferometer( + interferometer_7, unset_setup_env +): + factor_graph = af.FactorGraphModel( + *[ + af.AnalysisFactor( + prior_model=_light_model(), + analysis=al.AnalysisInterferometer( + dataset=interferometer_7, + setup="numba_cpu_dense_fp64", + use_jax=False, + ), + ) + for _ in range(2) + ] + ) + instance = factor_graph.global_prior_model.instance_from_unit_vector([]) + + with pytest.raises(exc.SetupException, match="factor graph") as e: + factor_graph.log_likelihood_function(instance) + + assert not isinstance(e.value, af.exc.FitException) + assert "numba_cpu_dense_fp64" in str(e.value) diff --git a/test_autolens/point/model/test_analysis_point_setup.py b/test_autolens/point/model/test_analysis_point_setup.py new file mode 100644 index 000000000..46e320b01 --- /dev/null +++ b/test_autolens/point/model/test_analysis_point_setup.py @@ -0,0 +1,223 @@ +""" +The compute `setup` of `al.AnalysisPoint` (likelihood lifecycle 5C-2): the rule key follows the positions +fit (image plane or source plane), a resolved setup sets the backend, logs the banner and writes +`files/setup.json`, and a setup inside a factor graph raises instead of being silently ignored. +""" + +import json +import logging + +import numpy as np +import pytest + +import autofit as af +import autoarray as aa +import autolens as al + +from autonerves.environment import Environment + +from autolens import exc + + +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) + monkeypatch.delenv("PYAUTO_RAISE_ANALYSIS_EXCEPTIONS", raising=False) + + +def _detect(monkeypatch, environment): + monkeypatch.setattr(Environment, "detect", classmethod(lambda cls: environment)) + + +def _model(): + return af.Collection( + galaxies=af.Collection( + lens=al.Galaxy(redshift=0.5, point_0=al.ps.Point(centre=(0.0, 0.0))) + ) + ) + + +def _analysis(point_dataset, **kwargs): + solver = al.m.MockPointSolver(model_positions=point_dataset.positions) + return al.AnalysisPoint(dataset=point_dataset, solver=solver, **kwargs) + + +@pytest.mark.parametrize( + "fit_positions_cls, key", + [ + (al.FitPositionsImagePairAllSolved, ("point_source_image", "image_plane")), + (al.FitPositionsImagePairAll, ("point_source_image", "image_plane")), + (al.FitPositionsImagePairRepeat, ("point_source_image", "image_plane")), + (al.FitPositionsImagePair, ("point_source_image", "image_plane")), + (al.FitPositionsSource, ("point_source_source", "source_plane")), + (al.FitPositionsSourceSolved, ("point_source_source", "source_plane")), + (None, ("point_source_image", "image_plane")), + ], +) +def test__setup_key_from__follows_fit_positions_cls( + point_dataset, fit_positions_cls, key +): + analysis = _analysis(point_dataset, fit_positions_cls=fit_positions_cls) + + assert analysis.setup_key_from(model=_model()) == key + + +def test__setup_kwarg__stored(point_dataset): + assert _analysis(point_dataset).setup_input is None + assert _analysis(point_dataset, setup="auto").setup_input == "auto" + + analysis = _analysis(point_dataset, setup="jax_cpu_na_fp64") + + assert isinstance(analysis.setup_input, aa.Setup) + assert analysis.setup is None + + +def test__setup_auto__image_plane__jax_na__banner_and_setup_json( + point_dataset, monkeypatch, caplog, tmp_path +): + pytest.importorskip("jax") + import jax.numpy as jnp + + _detect(monkeypatch, MANY_CORE) + + analysis = _analysis(point_dataset, setup="auto", use_jax=False) + + with caplog.at_level(logging.INFO): + result = analysis.modify_before_fit(paths=af.DirectoryPaths(), model=_model()) + + assert result is analysis + assert analysis.setup.setup_id == "jax_cpu_na_fp64" + assert analysis.setup.rule_id == "point-source-image-image-plane-standard-cpu-many-core" + assert analysis.setup_chosen_by == "auto" + assert analysis._use_jax is True + assert analysis._xp is jnp + + banners = [r.message for r in caplog.records if r.message.startswith("Setup: ")] + assert banners == [ + "Setup: jax/cpu/na/fp64 (64 CPU cores) · rule " + "point-source-image-image-plane-standard-cpu-many-core · optimal (decision " + "point-source-image-image-plane-standard-cpu-many-core) · override: PYAUTO_SETUP" + ] + + paths = af.DirectoryPaths(name="point_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"] == "jax_cpu_na_fp64" + assert setup_dict["operator"] == "na" + assert setup_dict["rule_id"] == "point-source-image-image-plane-standard-cpu-many-core" + assert setup_dict["chosen_by"] == "auto" + + +def test__setup_auto__source_plane__a100__jax_gpu_na(point_dataset, monkeypatch): + _detect(monkeypatch, A100) + + analysis = _analysis( + point_dataset, setup="auto", fit_positions_cls=al.FitPositionsSource + ) + analysis.modify_before_fit(paths=af.DirectoryPaths(), model=_model()) + + assert analysis.setup.setup_id == "jax_gpu_na_fp64" + assert analysis.setup.rule_id == "point-source-source-source-plane-standard-gpu-a100" + assert analysis.setup.extrapolated is False + + +def test__setup_auto__disable_jax__numpy(point_dataset, monkeypatch): + _detect(monkeypatch, MANY_CORE) + monkeypatch.setenv("PYAUTO_DISABLE_JAX", "1") + + analysis = _analysis(point_dataset, setup="auto") + analysis.modify_before_fit(paths=af.DirectoryPaths(), model=_model()) + + assert analysis.setup.setup_id == "jax_cpu_na_fp64" + assert analysis._use_jax is False + assert analysis._xp is np + + +def test__setup_auto__pyauto_setup_env_wins(point_dataset, monkeypatch, tmp_path): + _detect(monkeypatch, A100) + monkeypatch.setenv("PYAUTO_SETUP", "numba_cpu_dense_fp64") + + analysis = _analysis(point_dataset, setup="auto", use_jax=True) + analysis.modify_before_fit(paths=af.DirectoryPaths(), model=_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="point_env", path_prefix=str(tmp_path)) + analysis.save_attributes(paths=paths) + + with open(paths._files_path / "setup.json") as f: + assert json.load(f)["chosen_by"] == "PYAUTO_SETUP" + + +def test__no_setup__unchanged__would_choose_logged( + point_dataset, monkeypatch, caplog, tmp_path +): + _detect(monkeypatch, MANY_CORE) + + analysis = _analysis( + point_dataset, fit_positions_cls=al.FitPositionsImagePairRepeat, use_jax=False + ) + + with caplog.at_level(logging.INFO): + analysis.modify_before_fit(paths=af.DirectoryPaths(), model=_model()) + + assert analysis.setup is None + assert analysis._use_jax is False + + lines = [r.message for r in caplog.records if r.message.startswith("Setup: ")] + assert lines == [ + "Setup: auto would choose jax_cpu_na_fp64 (rule " + 'point-source-image-image-plane-standard-cpu-many-core); pass setup="auto" to use it' + ] + + paths = af.DirectoryPaths(name="point_no_setup", path_prefix=str(tmp_path)) + analysis.save_attributes(paths=paths) + + assert (paths._files_path / "dataset.json").exists() + assert not (paths._files_path / "setup.json").exists() + + instance = _model().instance_from_unit_vector([]) + assert analysis.log_likelihood_function(instance=instance) == pytest.approx( + analysis.fit_from(instance=instance).log_likelihood + ) + + +def test__factor_graph__setup_raises_setup_exception(point_dataset): + factors = [ + af.AnalysisFactor( + prior_model=_model(), + analysis=_analysis(point_dataset, setup="auto", use_jax=False), + ) + ] + + factor_graph = af.FactorGraphModel(*factors) + instance = factor_graph.global_prior_model.instance_from_unit_vector([]) + + with pytest.raises(exc.SetupException, match="factor graph") as e: + factor_graph.log_likelihood_function(instance) + + assert not isinstance(e.value, af.exc.FitException) + assert "AnalysisPoint" in str(e.value) diff --git a/test_autolens/weak/test_analysis.py b/test_autolens/weak/test_analysis.py index 4f91414ec..806c9ef22 100644 --- a/test_autolens/weak/test_analysis.py +++ b/test_autolens/weak/test_analysis.py @@ -110,3 +110,125 @@ def test__save_attributes__dataset_json_round_trips(): ) os.remove(paths._files_path / "dataset.json") + + +# --- setup (likelihood lifecycle 5C-2) --------------------------------------------------- + +import json +import logging + +import pytest + +from autonerves.environment import Environment + +from autolens import exc + + +def _setup_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(name="detect_many_core") +def make_detect_many_core(monkeypatch): + monkeypatch.delenv("PYAUTO_SETUP", raising=False) + monkeypatch.delenv("PYAUTO_DISABLE_JAX", raising=False) + monkeypatch.setattr( + Environment, "detect", classmethod(lambda cls: _setup_environment(cores=64)) + ) + + +def test__setup_key_from__weak_isothermal(): + analysis = al.AnalysisWeak(dataset=_make_dataset()) + + assert analysis.setup_key_from(model=_lens_model()) == ("weak", "isothermal") + + +def test__setup_auto__weak_isothermal__jax_dense__banner_and_setup_json( + detect_many_core, caplog, tmp_path +): + pytest.importorskip("jax") + import jax.numpy as jnp + + analysis = al.AnalysisWeak(dataset=_make_dataset(), setup="auto") + + assert analysis._use_jax is False + + with caplog.at_level(logging.INFO): + analysis.modify_before_fit(paths=af.DirectoryPaths(), model=_lens_model()) + + assert analysis.setup.setup_id == "jax_cpu_dense_fp64" + assert analysis.setup.rule_id == "weak-isothermal-standard-cpu-many-core" + assert analysis._use_jax is True + assert analysis._xp is jnp + + banners = [r.message for r in caplog.records if r.message.startswith("Setup: ")] + assert len(banners) == 1 + assert banners[0].startswith("Setup: jax/cpu/dense/fp64 (64 CPU cores) · rule weak-isothermal") + + paths = af.DirectoryPaths(name="weak_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"] == "jax_cpu_dense_fp64" + assert setup_dict["decision_id"] == "weak-isothermal-standard-cpu-many-core" + assert setup_dict["chosen_by"] == "auto" + + +def test__setup_auto__pyauto_setup_env_wins__weak(detect_many_core, monkeypatch): + monkeypatch.setenv("PYAUTO_SETUP", "numba_cpu_dense_fp64") + + analysis = al.AnalysisWeak(dataset=_make_dataset(), setup="auto", use_jax=True) + analysis.modify_before_fit(paths=af.DirectoryPaths(), model=_lens_model()) + + assert analysis.setup.setup_id == "numba_cpu_dense_fp64" + assert analysis.setup_chosen_by == "PYAUTO_SETUP" + assert analysis._use_jax is False + assert analysis._xp is np + + +def test__no_setup__weak_unchanged(detect_many_core, caplog, tmp_path): + dataset = _make_dataset() + + analysis = al.AnalysisWeak(dataset=dataset) + + with caplog.at_level(logging.INFO): + analysis.modify_before_fit(paths=af.DirectoryPaths(), model=_lens_model()) + + assert analysis.setup is None + assert analysis._use_jax is False + assert analysis.dataset is dataset + + lines = [r.message for r in caplog.records if r.message.startswith("Setup: ")] + assert lines == [ + "Setup: auto would choose jax_cpu_dense_fp64 (rule " + 'weak-isothermal-standard-cpu-many-core); pass setup="auto" to use it' + ] + + paths = af.DirectoryPaths(name="weak_no_setup", path_prefix=str(tmp_path)) + analysis.save_attributes(paths=paths) + + assert not (paths._files_path / "setup.json").exists() + + +def test__factor_graph__setup_raises_setup_exception__weak(): + factor_graph = af.FactorGraphModel( + af.AnalysisFactor( + prior_model=_lens_model(), + analysis=al.AnalysisWeak(dataset=_make_dataset(), setup="auto"), + ) + ) + instance = factor_graph.global_prior_model.instance_from_unit_vector([]) + + with pytest.raises(exc.SetupException, match="factor graph"): + factor_graph.log_likelihood_function(instance)