diff --git a/autogalaxy/abstract_fit.py b/autogalaxy/abstract_fit.py index 90716aa7..4b6af8a2 100644 --- a/autogalaxy/abstract_fit.py +++ b/autogalaxy/abstract_fit.py @@ -85,10 +85,11 @@ def sparse_operator(self) -> Optional[aa.ImagingSparseOperator]: - an operator attached to the dataset (by `apply_setup` / `apply_sparse_operator`) is returned whatever the fit, so a fit whose light is entirely linear (linear light profiles, MGE) keeps using it, as before; - - otherwise, with the lazy sparse operator policy on (`aa.Settings(lazy_sparse_operator="auto")`), + - otherwise, with the lazy sparse operator policy on (`aa.Settings(lazy_sparse_operator="auto")`, + the default), a fit with a pixelization (`total_mappers > 0`) on NumPy gets the operator the dataset builds on first use and caches; a fit without a pixelization, or a JAX fit, never triggers a build; - - with the policy off (the default) it is the attached operator or `None`, exactly as before. + - with the policy off (`lazy_sparse_operator="off"`) it is the attached operator or `None`. A dataset without `sparse_operator_for` (e.g. a duck-typed dataset) falls back to its `sparse_operator`. diff --git a/autogalaxy/analysis/analysis/dataset.py b/autogalaxy/analysis/analysis/dataset.py index a3c03b27..b3050c53 100644 --- a/autogalaxy/analysis/analysis/dataset.py +++ b/autogalaxy/analysis/analysis/dataset.py @@ -38,8 +38,8 @@ def __init__( cosmology: LensingCosmology = None, settings: aa.Settings = None, title_prefix: str = None, - use_jax: bool = True, - setup=None, + use_jax: Optional[bool] = None, + setup=setup_util.SETUP_DEFAULT, **kwargs, ): """ @@ -65,29 +65,35 @@ def __init__( 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. + Whether the likelihood is evaluated with JAX. Passing it with no `setup` opts out of `setup="auto"`: + the backend is `use_jax`, as with `setup=None`. With a `setup` it is only the backend before the + setup is resolved, which then sets the backend. 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 + The compute setup of the likelihood (backend, device, operator, precision, transformer): `"auto"`, + `None`, 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). + - `"auto"` (the default when neither `setup` nor `use_jax` is passed): `aa.Setup.auto` chooses the + designated setup for the likelihood and hardware (`PYAUTO_SETUP=` overrides it). + - `None`, or an explicit `use_jax` with no `setup`: the manual opt-out; nothing changes and one log + line reports what `"auto"` would choose. - 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`. """ + setup, use_jax, setup_defaulted = setup_util.setup_and_use_jax_from( + setup=setup, use_jax=use_jax + ) + super().__init__( cosmology=cosmology, use_jax=use_jax, **kwargs, ) - self._init_setup(setup) + self._init_setup(setup, setup_defaulted=setup_defaulted) self.dataset = dataset self.adapt_images = adapt_images diff --git a/autogalaxy/analysis/analysis/setup.py b/autogalaxy/analysis/analysis/setup.py index 32515df3..db3112d4 100644 --- a/autogalaxy/analysis/analysis/setup.py +++ b/autogalaxy/analysis/analysis/setup.py @@ -45,12 +45,16 @@ class AnalysisSetupMixin: changes its dataset. """ - def _init_setup(self, setup): + def _init_setup(self, setup, setup_defaulted: bool = False): """ 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`. + + `setup_defaulted` records that the input is the implicit default `"auto"` (neither `setup` nor + `use_jax` was passed, see `setup_util.setup_and_use_jax_from`). """ self.setup_input = setup_util.setup_input_from(setup) + self.setup_defaulted = bool(setup_defaulted) and self.setup_input is not None self.setup = None self.setup_chosen_by = None @@ -90,12 +94,13 @@ def resolve_setup(self, model: af.Collection, log_banner: bool = True): """ 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 no `setup` input (`setup=None`, or an explicit `use_jax` with no `setup`) 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 analysis and - model (`setup_key_and_note_from`); `PYAUTO_SETUP=` overrides it. An explicit `aa.Setup` - or setup_id is used as given. The resolved setup then: + model (`setup_key_and_note_from`); `PYAUTO_SETUP=` overrides it. When `"auto"` is the + implicit default and no setup can be chosen (e.g. no rule for the dataset), a warning is logged and + the constructor backend is kept. 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); @@ -134,8 +139,19 @@ def resolve_setup(self, model: af.Collection, log_banner: bool = True): environment = setup_util.setup_environment() if setup_input == setup_util.SETUP_AUTO: - key, note = self.setup_key_and_note_from(model) - setup = aa.Setup.auto(*key, environment=environment) + try: + key, note = self.setup_key_and_note_from(model) + setup = aa.Setup.auto(*key, environment=environment) + except Exception as e: + if not getattr(self, "setup_defaulted", False): + raise + # The default `"auto"` never stops a fit that ran before it was the default: when no + # setup can be chosen, the analysis keeps its constructor backend (as `setup=None`). + logger.warning( + f"Setup: setup='auto' (the default) could not choose a setup ({e}); the fit " + f"runs with the constructor backend (use_jax={bool(self._use_jax)})." + ) + return chosen_by = setup_util.chosen_by_from(setup=setup, auto=True) else: setup = setup_input diff --git a/autogalaxy/analysis/setup_util.py b/autogalaxy/analysis/setup_util.py index e7eb554b..62e6ea92 100644 --- a/autogalaxy/analysis/setup_util.py +++ b/autogalaxy/analysis/setup_util.py @@ -7,6 +7,8 @@ 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_DEFAULT` / `setup_and_use_jax_from`: the default `setup` of an analysis and the precedence + between `setup` and `use_jax` (an explicit `use_jax` with no `setup` opts out of `"auto"`). - `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`. @@ -50,6 +52,58 @@ SETUP_AUTO = "auto" + +class _SetupDefault(str): + """ + The default `setup` of the analyses: a `str` equal to `"auto"` (so it reads as `setup="auto"` in + signatures and help), told apart from an explicit `setup="auto"` by identity (`is SETUP_DEFAULT`). + """ + + def __reduce__(self): + return (_setup_default, ()) + + +def _setup_default(): + return SETUP_DEFAULT + + +SETUP_DEFAULT = _SetupDefault(SETUP_AUTO) + + +def setup_and_use_jax_from( + setup, use_jax: Optional[bool], default_use_jax: bool = True +) -> Tuple[Union[None, str, Setup], bool, bool]: + """ + The `setup` and `use_jax` an analysis is constructed with, after the precedence between them. + + - `setup` passed (an `aa.Setup`, a setup_id string, `"auto"` or `None`): it is used as given. + `setup=None` is the manual opt-out: the backend is `use_jax`. + - `setup` not passed and `use_jax` passed (`True` / `False`): the manual opt-out, as `setup=None`. + - Neither passed: `setup="auto"`. + + A `use_jax` of `None` becomes `default_use_jax`, the backend the analysis used before `"auto"` was the + default (`False` for `AnalysisWeak`, `True` for the others). For the default `"auto"` it is `True` only + when JAX is installed, so a JAX-free install does not warn about a backend nobody asked for; the + resolved setup sets the backend at fit start. + + Returns + ------- + `(setup, use_jax, setup_defaulted)`: the setup input (with the default replaced by the plain + `"auto"`), the constructor backend passed to `af.Analysis.__init__` (a `bool`) and whether the setup is + the implicit default (an unresolved default setup does not stop a pre-fit likelihood evaluation, see + `autolens.analysis.analysis.setup.raise_if_setup_unresolved`). + """ + if setup is not SETUP_DEFAULT: + return setup, default_use_jax if use_jax is None else bool(use_jax), False + + if use_jax is not None: + return None, bool(use_jax), False + + if default_use_jax: + default_use_jax = importlib.util.find_spec("jax") is not None + + return SETUP_AUTO, default_use_jax, True + CHOSEN_BY_AUTO = "auto" CHOSEN_BY_EXPLICIT = "explicit" CHOSEN_BY_ENV = "PYAUTO_SETUP" diff --git a/autogalaxy/imaging/model/analysis.py b/autogalaxy/imaging/model/analysis.py index 32f416ce..a7b37491 100644 --- a/autogalaxy/imaging/model/analysis.py +++ b/autogalaxy/imaging/model/analysis.py @@ -21,6 +21,7 @@ from autonerves.fitsable import hdu_list_for_output_from +from autogalaxy.analysis import setup_util from autogalaxy.analysis.adapt_images.adapt_images import AdaptImages from autogalaxy.analysis.analysis.dataset import AnalysisDataset from autogalaxy.cosmology.model import LensingCosmology @@ -45,8 +46,8 @@ def __init__( cosmology: LensingCosmology = None, settings: aa.Settings = None, title_prefix: str = None, - use_jax: bool = True, - setup=None, + use_jax: Optional[bool] = None, + setup=setup_util.SETUP_DEFAULT, **kwargs, ): """ @@ -79,11 +80,12 @@ def __init__( 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`. + Whether the likelihood is evaluated with JAX. Passing it with no `setup` opts out of `"auto"` (the + manual backend, as `setup=None`); with a `setup`, the resolved setup sets the backend. 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`. + The compute setup of the likelihood: `"auto"` (the default: the designated setup for the likelihood + and hardware, chosen at fit start from the model), `None` (the manual opt-out, backend `use_jax`), + an `aa.Setup` or a setup_id string. See `AnalysisDataset`. """ super().__init__( dataset=dataset, diff --git a/autogalaxy/interferometer/model/analysis.py b/autogalaxy/interferometer/model/analysis.py index 87086bb0..cf21a74b 100644 --- a/autogalaxy/interferometer/model/analysis.py +++ b/autogalaxy/interferometer/model/analysis.py @@ -20,6 +20,7 @@ import autofit as af import autoarray as aa +from autogalaxy.analysis import setup_util from autogalaxy.analysis.adapt_images.adapt_images import AdaptImages from autogalaxy.analysis.analysis.dataset import AnalysisDataset from autogalaxy.cosmology.model import LensingCosmology @@ -271,8 +272,8 @@ def __init__( cosmology: LensingCosmology = None, settings: aa.Settings = None, title_prefix: str = None, - use_jax: bool = True, - setup=None, + use_jax: Optional[bool] = None, + setup=setup_util.SETUP_DEFAULT, **kwargs, ): """ @@ -305,11 +306,12 @@ def __init__( 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`. + Whether the likelihood is evaluated with JAX. Passing it with no `setup` opts out of `"auto"` (the + manual backend, as `setup=None`); with a `setup`, the resolved setup sets the backend. 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`. + The compute setup of the likelihood: `"auto"` (the default: the designated setup for the likelihood + and hardware, chosen at fit start from the model), `None` (the manual opt-out, backend `use_jax`), + an `aa.Setup` or a setup_id string. See `AnalysisDataset`. """ super().__init__( dataset=dataset, diff --git a/test_autogalaxy/analysis/analysis/test_analysis_dataset.py b/test_autogalaxy/analysis/analysis/test_analysis_dataset.py index 08a252d6..8e9594f4 100644 --- a/test_autogalaxy/analysis/analysis/test_analysis_dataset.py +++ b/test_autogalaxy/analysis/analysis/test_analysis_dataset.py @@ -735,3 +735,113 @@ def test__disable_jax__setup_and_parallel_lines_report_numpy( assert resolution.is_jax is False assert resolution.reason != "jax" assert "JAX" not in resolution.banner + + +# The default `setup="auto"` and its opt-outs (likelihood-lifecycle R6). + + +def test__default__neither_setup_nor_use_jax__auto_resolved_at_fit_start( + masked_imaging_7x7, many_core, caplog +): + analysis = ag.AnalysisImaging(dataset=masked_imaging_7x7) + + assert analysis.setup_input == "auto" + assert analysis.setup_defaulted is True + assert analysis.setup is None + + with caplog.at_level(logging.INFO): + analysis.modify_before_fit( + paths=af.DirectoryPaths(), + model=_model_with_mesh(ag.mesh.RectangularUniform(shape=(3, 3))), + ) + + assert analysis.setup.setup_id == "numba_cpu_sparse_fp64" + assert analysis.setup_chosen_by == "auto" + assert analysis._use_jax is False + assert analysis.dataset.sparse_operator is not None + assert _setup_block(caplog)[0].startswith("Automatic compute setup (") + + +def test__default__explicit_use_jax_false_opts_out( + masked_imaging_7x7, many_core, caplog +): + analysis = ag.AnalysisImaging(dataset=masked_imaging_7x7, use_jax=False) + + assert analysis.setup_input is None + assert analysis.setup_defaulted is False + + with caplog.at_level(logging.INFO): + analysis.modify_before_fit( + paths=af.DirectoryPaths(), + model=_model_with_mesh(ag.mesh.RectangularUniform(shape=(3, 3))), + ) + + assert analysis.setup is None + assert analysis._use_jax is False + assert analysis.dataset is masked_imaging_7x7 + assert [r.message for r in caplog.records if "auto would choose" in r.message] + assert not [r for r in caplog.records if r.message.startswith("Automatic")] + + +def test__default__explicit_setup_none_opts_out_with_old_default_backend( + masked_imaging_7x7, +): + import importlib.util + + analysis = ag.AnalysisImaging(dataset=masked_imaging_7x7, setup=None) + + assert analysis.setup_input is None + assert analysis.setup_defaulted is False + assert analysis._use_jax is (importlib.util.find_spec("jax") is not None) + + +def test__default__explicit_setup_wins_over_use_jax(masked_imaging_7x7): + analysis = ag.AnalysisImaging( + dataset=masked_imaging_7x7, setup="auto", use_jax=False + ) + + assert analysis.setup_input == "auto" + assert analysis.setup_defaulted is False + + +def test__default__no_rule__falls_back_to_constructor_backend( + masked_imaging_7x7, many_core, monkeypatch, caplog +): + def raise_key(self, model): + raise ValueError("no rule") + + monkeypatch.setattr(ag.AnalysisImaging, "setup_key_and_note_from", raise_key) + + analysis = ag.AnalysisImaging(dataset=masked_imaging_7x7) + + with caplog.at_level(logging.WARNING): + analysis.resolve_setup(model=_parametric_model()) + + assert analysis.setup is None + assert any("could not choose a setup" in r.message for r in caplog.records) + + # An explicit `setup="auto"` still raises. + analysis = ag.AnalysisImaging(dataset=masked_imaging_7x7, setup="auto") + + with pytest.raises(ValueError, match="no rule"): + analysis.resolve_setup(model=_parametric_model()) + + +def test__default__sentinel_reads_as_auto_and_pickles(): + import inspect + import pickle + + default = inspect.signature(ag.AnalysisImaging.__init__).parameters["setup"].default + + assert default == "auto" + assert default is setup_util.SETUP_DEFAULT + assert pickle.loads(pickle.dumps(default)) is setup_util.SETUP_DEFAULT + + +def test__default__analysis_pickles(masked_imaging_7x7): + import pickle + + analysis = pickle.loads(pickle.dumps(ag.AnalysisImaging(dataset=masked_imaging_7x7))) + + assert analysis.setup_input == "auto" + assert analysis.setup_defaulted is True diff --git a/test_autogalaxy/imaging/test_fit_imaging.py b/test_autogalaxy/imaging/test_fit_imaging.py index 5837884c..5215c024 100644 --- a/test_autogalaxy/imaging/test_fit_imaging.py +++ b/test_autogalaxy/imaging/test_fit_imaging.py @@ -847,6 +847,7 @@ def test__galaxy_image_dicts__add_ordinary_and_linear_light(masked_imaging_7x7): # The lazy sparse operator (`dataset.sparse_operator_for`) reached through `fit.sparse_operator`. LAZY_ON = aa.Settings(lazy_sparse_operator="auto") +LAZY_OFF = aa.Settings(lazy_sparse_operator="off") @pytest.fixture(name="no_ambient_setup") @@ -874,7 +875,9 @@ def test__sparse_operator__lazy_policy_on__matches_dense_built_once_and_reused( galaxies = _pixelization_galaxies() - fit_dense = ag.FitImaging(dataset=masked_imaging_7x7, galaxies=galaxies) + fit_dense = ag.FitImaging( + dataset=masked_imaging_7x7, galaxies=galaxies, settings=LAZY_OFF + ) assert fit_dense.sparse_operator is None assert isinstance(fit_dense.inversion, aa.InversionImagingMapping) @@ -1010,3 +1013,24 @@ def test__sparse_operator__linear_light_only__attached_operator_unchanged( assert fit.figure_of_merit == pytest.approx( fit_dense.figure_of_merit, rel=1.0e-6 ) + + +def test__sparse_operator__lazy_policy_default_auto__numpy_pixelized_fit_builds_lazily( + masked_imaging_7x7, no_ambient_setup +): + pytest.importorskip("numba") + + masked_imaging_7x7._lazy_sparse_operator = None + + fit = ag.FitImaging(dataset=masked_imaging_7x7, galaxies=_pixelization_galaxies()) + + assert aa.Settings().lazy_sparse_operator == "auto" + assert fit.sparse_operator is not None + assert masked_imaging_7x7.sparse_operator is None + assert masked_imaging_7x7._lazy_sparse_operator is fit.sparse_operator + + fit_dense = ag.FitImaging( + dataset=masked_imaging_7x7, galaxies=_pixelization_galaxies(), settings=LAZY_OFF + ) + + assert fit.figure_of_merit == pytest.approx(fit_dense.figure_of_merit, rel=1.0e-8) diff --git a/test_autogalaxy/interferometer/test_fit_interferometer.py b/test_autogalaxy/interferometer/test_fit_interferometer.py index eaeed586..81c32501 100644 --- a/test_autogalaxy/interferometer/test_fit_interferometer.py +++ b/test_autogalaxy/interferometer/test_fit_interferometer.py @@ -4,6 +4,9 @@ import autoarray as aa import autogalaxy as ag +# The dense mapping-matrix reference fits switch the lazy sparse operator (on by default) off. +LAZY_OFF = aa.Settings(lazy_sparse_operator="off") + def test__model_visibilities__real_component__correct_value(interferometer_7): g0 = ag.Galaxy(redshift=0.5, bulge=ag.m.MockLightProfile(image_2d=np.ones(9))) @@ -513,7 +516,7 @@ def test__model_visibilities_of_galaxies_list__matches_galaxy_model_visibilities def _assert_sparse_fit_matches_dense(dataset, dataset_sparse, galaxies): - fit = ag.FitInterferometer(dataset=dataset, galaxies=galaxies) + fit = ag.FitInterferometer(dataset=dataset, galaxies=galaxies, settings=LAZY_OFF) fit_sparse = ag.FitInterferometer(dataset=dataset_sparse, galaxies=galaxies) assert isinstance(fit.inversion, aa.InversionInterferometerMapping) @@ -786,7 +789,9 @@ def test__fit_figure_of_merit__sparse_operator__pixelization_only__data_term_sca ) # The dense fit's inversion already carries its data, so it is returned unchanged. - fit = ag.FitInterferometer(dataset=interferometer_7, galaxies=galaxies) + fit = ag.FitInterferometer( + dataset=interferometer_7, galaxies=galaxies, settings=LAZY_OFF + ) assert fit.inversion_with_data is fit.inversion @@ -985,7 +990,7 @@ def _assert_array_free_fit_matches_dense(dataset, dataset_array_free, galaxies): The fit on the array-free dataset reproduces the in-memory dense fit (which forms and subtracts the light profile visibilities `F i_p`) at rel 1e-8, without ever forming visibilities. """ - fit = ag.FitInterferometer(dataset=dataset, galaxies=galaxies) + fit = ag.FitInterferometer(dataset=dataset, galaxies=galaxies, settings=LAZY_OFF) fit_array_free = ag.FitInterferometer(dataset=dataset_array_free, galaxies=galaxies) assert fit_array_free._uses_precomputed_data_term @@ -1708,7 +1713,9 @@ def test__sparse_operator__lazy_policy_off__dense_and_nothing_built( interferometer_7, no_ambient_setup ): fit = ag.FitInterferometer( - dataset=interferometer_7, galaxies=_pixelization_only_galaxies() + dataset=interferometer_7, + galaxies=_pixelization_only_galaxies(), + settings=LAZY_OFF, ) assert fit.sparse_operator is None @@ -1723,7 +1730,9 @@ def test__sparse_operator__lazy_policy_on__pixelization_only__matches_dense_buil galaxies = _pixelization_only_galaxies() - fit_dense = ag.FitInterferometer(dataset=interferometer_7, galaxies=galaxies) + fit_dense = ag.FitInterferometer( + dataset=interferometer_7, galaxies=galaxies, settings=LAZY_OFF + ) fit = ag.FitInterferometer( dataset=interferometer_7, galaxies=galaxies, settings=LAZY_ON @@ -1759,7 +1768,9 @@ def test__sparse_operator__lazy_policy_on__pixelization_and_light_profile__dirty galaxies = _pixelization_and_light_profile_galaxies() - fit_dense = ag.FitInterferometer(dataset=interferometer_7, galaxies=galaxies) + fit_dense = ag.FitInterferometer( + dataset=interferometer_7, galaxies=galaxies, settings=LAZY_OFF + ) fit = ag.FitInterferometer( dataset=interferometer_7, galaxies=galaxies, settings=LAZY_ON