diff --git a/autogalaxy/analysis/analysis/dataset.py b/autogalaxy/analysis/analysis/dataset.py index b3050c53..d83b7f6d 100644 --- a/autogalaxy/analysis/analysis/dataset.py +++ b/autogalaxy/analysis/analysis/dataset.py @@ -128,8 +128,18 @@ def modify_before_fit(self, paths: af.DirectoryPaths, model: af.Collection): self.resolve_setup(model=model, log_banner=False) - # Ensures preloaded in memory so repeated calls are fast + self._preload_grids() + super().modify_before_fit(paths=paths, model=model) + + self.log_setup_banner() + + return self + + def _preload_grids(self): + """ + Compute the dataset's grids once, before the fit, so repeated likelihood calls are fast. + """ self.dataset.grids.lp self.dataset.grids.lp.over_sampled self.dataset.grids.lp.over_sampler @@ -147,12 +157,6 @@ def modify_before_fit(self, paths: af.DirectoryPaths, model: af.Collection): self.dataset.grids.border_relocator - super().modify_before_fit(paths=paths, model=model) - - self.log_setup_banner() - - return self - @staticmethod def _setup_environment(): """ @@ -175,10 +179,30 @@ def _apply_resolved_setup(self, setup: aa.Setup): factory's check, so a mismatch raises an `InversionException` here rather than rejecting every sample. Called by `resolve_setup` (`AnalysisSetupMixin`) after `_use_jax` is set. """ + # The dataset as given, before any setup is applied, so `_undo_resolved_setup` can restore it. + if "_dataset_before_setup" not in self.__dict__: + self._dataset_before_setup = self.dataset + self.dataset = self.dataset.apply_setup(setup) setup_util.check_setup_consistency(dataset=self.dataset, use_jax=self._use_jax) + def _undo_resolved_setup(self): + """ + Restore the dataset as it was given, before `_apply_resolved_setup` attached the operator the + resolved setup named (`adopt_backend`, when a `FactorGraphModel` moves this analysis onto its shared + backend), check it against the new backend and preload its grids. + """ + original = self.__dict__.pop("_dataset_before_setup", None) + if original is None: + return + + self.dataset = original + + setup_util.check_setup_consistency(dataset=self.dataset, use_jax=self._use_jax) + + self._preload_grids() + @staticmethod def _save_dataset_fits(paths: af.AbstractPaths, hdu_list: HDUList) -> None: """Save the dataset for directory and database aggregators.""" diff --git a/autogalaxy/analysis/analysis/setup.py b/autogalaxy/analysis/analysis/setup.py index db3112d4..f38d7db8 100644 --- a/autogalaxy/analysis/analysis/setup.py +++ b/autogalaxy/analysis/analysis/setup.py @@ -58,6 +58,65 @@ def _init_setup(self, setup, setup_defaulted: bool = False): self.setup = None self.setup_chosen_by = None + @property + def setup_is_default(self) -> bool: + """ + Whether the setup of this analysis is the implicit default `setup="auto"` (neither `setup` nor + `use_jax` was passed), which a `FactorGraphModel` may replace by its shared backend + (`af.Analysis.setup_is_default`, `adopt_backend`). It stays `True` after `adopt_backend`, so a graph + that forwards `modify_before_fit` again treats the analysis the same way. + """ + return bool(getattr(self, "setup_defaulted", False)) + + def adopt_backend(self, use_jax: bool): + """ + Drop the default setup and run on the backend `use_jax` a `FactorGraphModel` chose for its factors + (`af.Analysis.adopt_backend`), because the factors' default setups disagree. + + The analysis moves to the manual opt-out path, as if constructed with `use_jax=use_jax`: the setup + input and resolved setup are cleared (no `files/setup.json` is written), the backend is `use_jax` + (falling back to NumPy when JAX is disabled or not installed) and anything the resolved setup applied + to the dataset, such as an operator, is undone (`_undo_resolved_setup`). One log line names the + backend and what `setup="auto"` had chosen for this analysis alone. Analyses whose setup the user + passed are never changed. + + Parameters + ---------- + use_jax + The backend of the factor graph: `True` for JAX. + """ + if not self.setup_is_default: + return + + previous = getattr(self, "setup", None) + + self.setup_input = None + self.setup = None + self.setup_chosen_by = None + self._setup_banner_lines = [] + + self._use_jax = setup_util.use_jax_from(use_jax) + + self._undo_resolved_setup() + + backend = "JAX" if self._use_jax else "numpy" + chose = ( + f'; setup="auto" chose {setup_util.setup_text_from(previous)} for it alone' + if previous is not None + else "" + ) + logger.info( + f"Compute setup: not set (the factor graph runs every factor left on the default setup on " + f"{backend}, as their default setups disagree{chose}; pass the same setup= to every " + f"factor to choose one)" + ) + + def _undo_resolved_setup(self): + """ + Undo what `_apply_resolved_setup` applied beyond the backend and threads, for `adopt_backend`. + The default does nothing. + """ + def setup_key_and_note_from( self, model: af.Collection ) -> Tuple[Tuple[str, str], Optional[str]]: diff --git a/test_autogalaxy/analysis/analysis/test_analysis_factor_graph_setup.py b/test_autogalaxy/analysis/analysis/test_analysis_factor_graph_setup.py new file mode 100644 index 00000000..5d61d962 --- /dev/null +++ b/test_autogalaxy/analysis/analysis/test_analysis_factor_graph_setup.py @@ -0,0 +1,201 @@ +""" +A `FactorGraphModel` of default-constructed analyses of different dataset types (e.g. imaging and +interferometer) resolves a different `setup="auto"` per factor. Factors whose setup was defaulted adopt +one shared backend (`adopt_backend`), so the graph fits without pins; explicit setups must still agree. +""" +import importlib.util +import logging + +import numpy as np +import pytest + +import autoarray as aa +import autofit as af +import autofit.graphical as g +import autogalaxy as ag + +from autofit import exc +from autonerves.environment import Environment + +MANY_CORE = Environment( + gpu=False, + gpu_name=None, + gpu_memory_gb=None, + cores=64, + ram_gb=None, + numba=True, + nufftax=True, + site="local", +) + +HAS_JAX = importlib.util.find_spec("jax") is not None + + +@pytest.fixture(name="many_core") +def make_many_core(monkeypatch): + monkeypatch.delenv("PYAUTO_SETUP", raising=False) + monkeypatch.delenv("PYAUTO_DISABLE_JAX", raising=False) + monkeypatch.setattr(Environment, "detect", classmethod(lambda cls: MANY_CORE)) + + +def _pixelized_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 _parametric_model(): + return af.Collection( + galaxies=af.Collection( + galaxy=af.Model(ag.Galaxy, redshift=0.5, light=ag.lp.Sersic) + ) + ) + + +def _graph(analysis_0, model_0, analysis_1, model_1, **kwargs): + return g.FactorGraphModel( + g.AnalysisFactor(model_0, analysis=analysis_0, name="factor_0"), + g.AnalysisFactor(model_1, analysis=analysis_1, name="factor_1"), + **kwargs, + ) + + +def _modify(graph, name): + return graph.modify_before_fit( + paths=af.DirectoryPaths(name=name), model=graph.global_prior_model + ) + + +def _sparse_operator(dataset): + return dataset.__dict__.get("sparse_operator") or getattr( + dataset, "_lazy_sparse_operator", None + ) + + +def test__default_imaging_and_interferometer__adopt_one_backend( + masked_imaging_7x7, interferometer_7, many_core, caplog +): + imaging = ag.AnalysisImaging(dataset=masked_imaging_7x7) + interferometer = ag.AnalysisInterferometer(dataset=interferometer_7) + + assert imaging.setup_is_default and interferometer.setup_is_default + + graph = _graph(imaging, _pixelized_model(), interferometer, _parametric_model()) + + with caplog.at_level(logging.INFO): + _modify(graph, "graph_default_mixed") + + analysis_0 = graph.model_factors[0].analysis + analysis_1 = graph.model_factors[1].analysis + + for analysis in (analysis_0, analysis_1): + assert analysis.setup is None + assert analysis.setup_input is None + assert analysis.setup_is_default + assert analysis.is_jax is HAS_JAX + + # The imaging auto setup (numba sparse) attached an operator; adopting the graph backend restores + # the dataset as given. + assert analysis_0.dataset is masked_imaging_7x7 + assert analysis_1.dataset is interferometer_7 + + assert graph.setup_ids() == {} + graph.check_setup_agreement() + graph.check_backend_agreement() + + notes = [r.message for r in caplog.records if "the factor graph runs" in r.message] + assert len(notes) == 2 + assert 'setup="auto" chose numba · CPU · sparse operator · fp64 for it alone' in notes[0] + + instance = graph.global_prior_model.instance_from_prior_medians() + log_likelihood = graph.log_likelihood_function(instance) + assert np.isfinite(float(log_likelihood)) + + +def test__graph_use_jax_false__pushes_numpy_down( + masked_imaging_7x7, interferometer_7, many_core +): + imaging = ag.AnalysisImaging(dataset=masked_imaging_7x7) + interferometer = ag.AnalysisInterferometer(dataset=interferometer_7) + + graph = _graph( + imaging, _parametric_model(), interferometer, _parametric_model(), use_jax=False + ) + _modify(graph, "graph_default_numpy") + + for factor in graph.model_factors: + assert factor.analysis.is_jax is False + assert factor.analysis.setup is None + + assert graph.is_jax is False + graph.check_backend_agreement() + + instance = graph.global_prior_model.instance_from_prior_medians() + assert np.isfinite(graph.log_likelihood_function(instance)) + + +def test__default_factor_follows_explicit_setup( + masked_imaging_7x7, interferometer_7, many_core +): + imaging = ag.AnalysisImaging( + dataset=masked_imaging_7x7, setup="numba_cpu_dense_fp64" + ) + interferometer = ag.AnalysisInterferometer(dataset=interferometer_7) + + graph = _graph(imaging, _parametric_model(), interferometer, _parametric_model()) + _modify(graph, "graph_explicit_lead") + + assert graph.model_factors[0].analysis.setup.setup_id == "numba_cpu_dense_fp64" + assert graph.model_factors[1].analysis.setup is None + assert graph.model_factors[1].analysis.is_jax is False + assert graph.setup_ids() == {"factor_0": "numba_cpu_dense_fp64"} + graph.check_backend_agreement() + + +def test__explicit_disagreeing_setups__still_raise( + masked_imaging_7x7, interferometer_7, many_core +): + imaging = ag.AnalysisImaging( + dataset=masked_imaging_7x7, setup="numba_cpu_dense_fp64" + ) + interferometer = ag.AnalysisInterferometer( + dataset=interferometer_7, setup="numba_cpu_sparse_fp64_wtilde" + ) + + graph = _graph(imaging, _parametric_model(), interferometer, _parametric_model()) + + with pytest.raises(exc.SearchException, match="setups passed explicitly"): + _modify(graph, "graph_explicit_bad") + + +def test__agreeing_default_setups__are_kept(masked_imaging_7x7, many_core): + graph = _graph( + ag.AnalysisImaging(dataset=masked_imaging_7x7), + _pixelized_model(), + ag.AnalysisImaging(dataset=masked_imaging_7x7), + _pixelized_model(), + ) + _modify(graph, "graph_default_agree") + + assert set(graph.setup_ids().values()) == {"numba_cpu_sparse_fp64"} + assert _sparse_operator(graph.model_factors[0].analysis.dataset) is not None + + +def test__adopt_backend__explicit_setup_is_never_changed(masked_imaging_7x7, many_core): + analysis = ag.AnalysisImaging( + dataset=masked_imaging_7x7, setup="numba_cpu_dense_fp64" + ) + analysis.modify_before_fit(paths=af.DirectoryPaths(), model=_parametric_model()) + + assert analysis.setup_is_default is False + analysis.adopt_backend(True) + + assert analysis.setup.setup_id == "numba_cpu_dense_fp64" + assert analysis.is_jax is False