diff --git a/autofit/non_linear/analysis/analysis.py b/autofit/non_linear/analysis/analysis.py index 0b6fb55ae..03de38ac3 100644 --- a/autofit/non_linear/analysis/analysis.py +++ b/autofit/non_linear/analysis/analysis.py @@ -307,6 +307,17 @@ def modify_before_fit(self, paths: AbstractPaths, model: AbstractPriorModel): """ return self + def prepare_for_model(self, model: AbstractPriorModel): + """ + Let this analysis finish any model-dependent setup before its likelihood is used + outside a fit, e.g. by ``print_vram_use`` or ``batched_memory_bytes``. + + A fit does this in ``modify_before_fit``; this hook is the pre-fit equivalent for + calls that are handed a model. The default does nothing. A PyAutoGalaxy / + PyAutoLens analysis built with ``setup="auto"`` overrides it to resolve its + compute setup (and therefore its backend) from ``model``. + """ + def modify_model(self, model): return model @@ -418,6 +429,9 @@ def batched_memory_bytes(self, model, batch_size: int, gradient: bool = False): The projected bytes, or ``None`` when this analysis is not on the JAX path (nothing to measure). """ + # As in `print_vram_use`: resolve any model-dependent backend first. + self.prepare_for_model(model) + if not self.is_jax: return None @@ -468,6 +482,11 @@ def print_vram_use(self, model, batch_size : int, gradient: bool = False) -> str """ from autofit.non_linear.test_mode import skip_fit_output + # The backend may depend on the model (e.g. a `setup="auto"` analysis), so let + # the analysis resolve it before `is_jax` is read. Done before the test-mode + # skip so a script behaves the same (setup resolved, banner logged) either way. + self.prepare_for_model(model) + if skip_fit_output(): return diff --git a/autofit/non_linear/analysis/model_analysis.py b/autofit/non_linear/analysis/model_analysis.py index 379fa72a1..ff4564c21 100644 --- a/autofit/non_linear/analysis/model_analysis.py +++ b/autofit/non_linear/analysis/model_analysis.py @@ -42,6 +42,63 @@ def gradient_mode(self) -> str: """ return self.analysis.gradient_mode + def modify_before_fit(self, paths: AbstractPaths, model: AbstractPriorModel): + """ + Forward ``modify_before_fit`` to the wrapped analysis, rebind this wrapper to the + analysis it returns and refresh the wrapper's backend from it. + + The base ``Analysis.modify_before_fit`` (which returns ``self``) would otherwise + shadow ``__getattr__`` forwarding, so the wrapped analysis's own + ``modify_before_fit`` (e.g. a PyAutoGalaxy / PyAutoLens ``setup="auto"`` + resolution) would never run. + + The wrapped analysis receives this wrapper's own ``self.model``, not the + search's ``model``: the wrapper evaluates the wrapped likelihood on instances of + ``self.model`` (see ``Analysis.with_model``), so that is the model whose + structure any model-dependent setup must be resolved from. The rebinding mirrors + ``AnalysisFactor.modify_before_fit`` / ``rebind_analysis``. + + Returns + ------- + This wrapper, its wrapped analysis now the modified one. + """ + self._rebind(self.analysis.modify_before_fit(paths=paths, model=self.model)) + return self + + def modify_after_fit(self, paths: AbstractPaths, model: AbstractPriorModel, result): + """ + Forward ``modify_after_fit`` to the wrapped analysis with this wrapper's own + ``self.model`` (as ``modify_before_fit`` does), rebinding to the analysis it + returns. + + Returns + ------- + This wrapper. + """ + self._rebind( + self.analysis.modify_after_fit(paths=paths, model=self.model, result=result) + ) + return self + + def prepare_for_model(self, model: AbstractPriorModel): + """ + Forward ``Analysis.prepare_for_model`` to the wrapped analysis with this + wrapper's own ``self.model`` (the model its likelihood is evaluated on), then + refresh the wrapper's backend, which the wrapped analysis may only now know. + """ + self.analysis.prepare_for_model(self.model) + self._use_jax = self.analysis.is_jax + + def _rebind(self, analysis: Optional[Analysis]): + """ + Point this wrapper at ``analysis`` (when not ``None``) and refresh its + ``is_jax`` from it, so the wrapper and the analysis it wraps never disagree + about the backend once the wrapped analysis has resolved its setup. + """ + if analysis is not None: + self.analysis = analysis + self._use_jax = self.analysis.is_jax + def __getattr__(self, item): if item in ("__getstate__", "__setstate__"): raise AttributeError(item) diff --git a/test_autofit/analysis/test_model_analysis_forwarding.py b/test_autofit/analysis/test_model_analysis_forwarding.py new file mode 100644 index 000000000..d938b4840 --- /dev/null +++ b/test_autofit/analysis/test_model_analysis_forwarding.py @@ -0,0 +1,140 @@ +""" +``ModelAnalysis`` (``analysis.with_model(model)``) forwards the pre-fit hooks to the +analysis it wraps: ``modify_before_fit`` (rebinding to the analysis returned and +refreshing ``is_jax``), ``modify_after_fit`` and ``prepare_for_model``, each with the +wrapper's own model. Also inside an ``AnalysisFactor``. +""" + +import pytest + +import autofit as af +import autofit.graphical as g +from autofit.non_linear.analysis.model_analysis import ModelAnalysis +from autofit.non_linear.paths.null import NullPaths + +pytestmark = pytest.mark.filterwarnings("ignore::FutureWarning") + + +class ResolvingAnalysis(af.Analysis): + """ + Stands in for a ``setup="auto"`` analysis: its backend is only known once + ``modify_before_fit`` / ``prepare_for_model`` has seen a model. + """ + + def __init__(self, return_new=False): + super().__init__(use_jax=False) + self.return_new = return_new + self.before_models = [] + self.prepared_models = [] + self.after_models = [] + + def log_likelihood_function(self, instance): + return 0.0 + + def _resolve(self): + # Flip the backend flag directly so the test needs no JAX install. + self._use_jax = True + + def modify_before_fit(self, paths, model): + self.before_models.append(model) + if self.return_new: + new = ResolvingAnalysis() + new._resolve() + new.before_models = self.before_models + return new + self._resolve() + return self + + def prepare_for_model(self, model): + self.prepared_models.append(model) + self._resolve() + + def modify_after_fit(self, paths, model, result): + self.after_models.append(model) + return self + + +@pytest.fixture(name="explicit_model") +def make_explicit_model(): + return af.Model(af.ex.Gaussian) + + +@pytest.fixture(name="search_model") +def make_search_model(): + return af.Collection(gaussian=af.Model(af.ex.Gaussian)) + + +def test_modify_before_fit_is_forwarded_and_returns_the_wrapper( + explicit_model, search_model +): + inner = ResolvingAnalysis() + wrapper = inner.with_model(explicit_model) + assert wrapper.is_jax is False + + returned = wrapper.modify_before_fit(paths=NullPaths(), model=search_model) + + assert returned is wrapper + assert isinstance(returned, ModelAnalysis) + # The wrapped analysis sees the model its likelihood is evaluated on. + assert inner.before_models == [explicit_model] + assert wrapper.analysis is inner + assert wrapper.is_jax is True + + +def test_modify_before_fit_rebinds_to_a_new_inner_analysis(explicit_model): + inner = ResolvingAnalysis(return_new=True) + wrapper = inner.with_model(explicit_model) + + returned = wrapper.modify_before_fit(paths=NullPaths(), model=explicit_model) + + assert returned is wrapper + assert wrapper.analysis is not inner + assert isinstance(wrapper.analysis, ResolvingAnalysis) + assert wrapper.is_jax is True + + +def test_prepare_for_model_is_forwarded_with_the_wrapper_model( + explicit_model, search_model +): + inner = ResolvingAnalysis() + wrapper = inner.with_model(explicit_model) + + wrapper.prepare_for_model(search_model) + + assert inner.prepared_models == [explicit_model] + assert wrapper.is_jax is True + + +def test_modify_after_fit_is_forwarded(explicit_model): + inner = ResolvingAnalysis() + wrapper = inner.with_model(explicit_model) + + returned = wrapper.modify_after_fit( + paths=NullPaths(), model=explicit_model, result=None + ) + + assert returned is wrapper + assert inner.after_models == [explicit_model] + + +def test_base_prepare_for_model_is_a_no_op(explicit_model): + analysis = af.Analysis() + assert analysis.prepare_for_model(explicit_model) is None + assert analysis.is_jax is False + + +def test_analysis_factor_over_a_model_analysis_resolves_the_inner_analysis( + explicit_model, +): + inner = ResolvingAnalysis(return_new=True) + wrapper = inner.with_model(explicit_model) + factor = g.AnalysisFactor(explicit_model, analysis=wrapper, name="f0") + + returned = factor.modify_before_fit(paths=NullPaths(), model=explicit_model) + + assert returned is factor + # The factor keeps the (same) wrapper, whose inner analysis is the new one. + assert factor.analysis is wrapper + assert wrapper.analysis is not inner + assert inner.before_models == [explicit_model] + assert factor.is_jax is True