Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
136 changes: 130 additions & 6 deletions autofit/graphical/declarative/collection.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,8 +153,14 @@ def modify_before_fit(self, paths: AbstractPaths, model):
fitted ``model`` (which may carry replacement priors, e.g. in a grid-search
cell), else the factor's ``prior_model``. ``AnalysisFactor.modify_before_fit``
rebinds both of the factor's analysis references to the object returned.
Hierarchical factors carry no analysis and are skipped. The factors must then
agree on their resolved setup (``check_setup_agreement``).
Hierarchical factors carry no analysis and are skipped.

Factors whose setup is the implicit default (``setup_is_default``, e.g. a
PyAutoGalaxy / PyAutoLens analysis built with neither ``setup`` nor ``use_jax``)
then adopt one shared backend when their default setups disagree
(``adopt_shared_backend``), so a graph mixing dataset types fits without pins.
The factors must then agree on their resolved setup (``check_setup_agreement``);
setups the user passed are never changed, so disagreeing explicit setups raise.

Returns
-------
Expand All @@ -167,9 +173,123 @@ def modify_before_fit(self, paths: AbstractPaths, model):
child_paths = paths.for_sub_analysis(analysis_name=f"analyses/analysis_{i}")
factor.modify_before_fit(child_paths, self._factor_model(model, i, factor))

self.adopt_shared_backend()
self.check_setup_agreement()
return self

def _setup_factors(self) -> List:
"""
The factors that may carry a compute setup: analysis factors and nested graphs
(the flattened factors, so a ``HierarchicalFactor``'s generated factors, which
have no analysis, report no default setup).
"""
return [
factor
for factor in self._flat_factors()
if isinstance(factor, (AnalysisFactor, FactorGraphModel))
]

@property
def setup_is_default(self) -> bool:
"""
Whether this graph, as a factor of an enclosing graph, has only default setups:
``True`` when at least one of its factors has a default setup and none has a
setup the user passed.
"""
ids = self.setup_ids()
factors = self._setup_factors()
defaulted = [factor for factor in factors if factor.setup_is_default]
explicit = [
factor
for factor in factors
if factor.name in ids and not factor.setup_is_default
]
return bool(defaulted) and not explicit

def adopt_backend(self, use_jax: bool):
"""
Move every factor of this graph with a default setup onto ``use_jax``
(``Analysis.adopt_backend``), when this graph is a factor of an enclosing graph.
"""
for factor in self._setup_factors():
if factor.setup_is_default:
factor.adopt_backend(use_jax)

def _shared_backend(self, explicit_factors) -> Optional[bool]:
"""
The backend factors with a default setup adopt: the graph's explicit ``use_jax``
when one was given, else the backend of the factors the user configured (an
explicit ``setup=`` or ``use_jax=``), else JAX, unless JAX is disabled
(``PYAUTO_DISABLE_JAX=1``) or not installed. ``None`` when the configured
factors disagree on their backend (``check_backend_agreement`` then raises).
"""
explicit = self.__dict__.get("_explicit_use_jax")
if explicit is not None:
return bool(explicit)
if explicit_factors:
backends = {bool(factor.is_jax) for factor in explicit_factors}
return backends.pop() if len(backends) == 1 else None

import importlib.util
import os

if os.environ.get("PYAUTO_DISABLE_JAX") == "1":
return False
return importlib.util.find_spec("jax") is not None

def adopt_shared_backend(self) -> Optional[bool]:
"""
Put every factor whose compute setup is the implicit default on one shared
backend, when the factors would otherwise disagree.

Each factor resolves its own setup (``modify_before_fit``), so a graph mixing
dataset types (e.g. imaging and interferometer, or imaging and a point source)
resolves a different default setup per factor, which a whole-graph fit cannot
run. When the resolved setups disagree, or a factor with a default setup runs on
a different backend from the graph's ``use_jax`` or from the factors the user
configured, every factor with a default setup (``setup_is_default``) drops it
and runs with no setup on the shared backend (``adopt_backend``, see
``_shared_backend``). Factors the user configured (``setup=`` or ``use_jax=``)
are never changed: when their setups or backends disagree with one another
nothing is adopted and ``check_setup_agreement`` / ``check_backend_agreement``
raise.

Returns
-------
The backend adopted (``True`` for JAX), or ``None`` when nothing changed.
"""
factors = self._setup_factors()
defaulted = [factor for factor in factors if factor.setup_is_default]
if not defaulted:
return None

configured = [factor for factor in factors if not factor.setup_is_default]

ids = self.setup_ids()
configured_ids = {ids[f.name] for f in configured if f.name in ids}
if len(configured_ids) > 1:
return None

use_jax = self._shared_backend(explicit_factors=configured)
if use_jax is None:
return None

backend_is_set = (
self.__dict__.get("_explicit_use_jax") is not None or bool(configured)
)
setups_disagree = len(set(ids.values())) > 1
backends_disagree = backend_is_set and any(
bool(factor.is_jax) != use_jax for factor in defaulted
)

if not (setups_disagree or backends_disagree):
return None

for factor in defaulted:
factor.adopt_backend(use_jax)

return use_jax

def _factor_model(self, model, index: int, factor):
"""
The model of factor ``index`` within the fitted graph ``model``, or the factor's
Expand Down Expand Up @@ -203,8 +323,9 @@ def check_setup_agreement(self):

A whole-graph fit evaluates every factor in one process, so every factor that
has a setup must have resolved the same one (factors without a setup are
ignored). Called at the end of ``modify_before_fit`` and by the runtime gates
beside ``check_backend_agreement``.
ignored). Called at the end of ``modify_before_fit`` (after factors with a
default setup have adopted a shared backend, ``adopt_shared_backend``) and by
the runtime gates beside ``check_backend_agreement``.
"""
ids = self.setup_ids()
if len(set(ids.values())) <= 1:
Expand All @@ -222,8 +343,11 @@ def check_setup_agreement(self):
f"The FactorGraphModel {self.name} is fitted as one analysis, but its "
f"factors resolved different compute setups ({listing}). Whole-graph "
f"fitting evaluates every factor in one process, so every factor must use "
f"the same setup: build every factor's analysis with the same setup= (or "
f"none, so each resolves the default)."
f"the same setup. Factors left on the default setup (neither setup= nor "
f"use_jax= passed) adopt one shared backend automatically; setups passed "
f"explicitly are never changed, so build every factor's analysis with the "
f"same setup=, or pass none so the graph chooses the backend "
f"(FactorGraphModel(use_jax=...) sets it)."
)

@property
Expand Down
16 changes: 16 additions & 0 deletions autofit/graphical/declarative/factor/analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,22 @@ def rebind_analysis(self, analysis: Analysis):
if isinstance(factor, FactorCallable):
factor.analysis = analysis

@property
def setup_is_default(self) -> bool:
"""
Whether the wrapped analysis's compute setup is the implicit default
(``Analysis.setup_is_default``).
"""
return self.analysis.setup_is_default

def adopt_backend(self, use_jax: bool):
"""
Forward ``adopt_backend`` to the wrapped analysis (``Analysis.adopt_backend``),
which ``FactorGraphModel.modify_before_fit`` calls on factors whose default setups
disagree.
"""
self.analysis.adopt_backend(use_jax)

@property
def is_jax(self) -> bool:
"""
Expand Down
25 changes: 25 additions & 0 deletions autofit/non_linear/analysis/analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,31 @@ def prepare_for_model(self, model: AbstractPriorModel):
compute setup (and therefore its backend) from ``model``.
"""

@property
def setup_is_default(self) -> bool:
"""
Whether this analysis's compute setup is the implicit default, chosen without the user
passing one (a PyAutoGalaxy / PyAutoLens analysis constructed with neither ``setup`` nor
``use_jax`` resolves ``setup="auto"``).

A ``FactorGraphModel`` fitted as one analysis may move such a factor onto the graph's
shared backend (``adopt_backend``) when the factors' default setups disagree; a setup the
user passed is never changed. The default, ``False``, is for analyses with no setup.
"""
return False

def adopt_backend(self, use_jax: bool):
"""
Move this analysis onto the backend ``use_jax`` chosen for it by a ``FactorGraphModel``
whose factors resolved different default compute setups (see ``setup_is_default``).

Called by ``FactorGraphModel.modify_before_fit`` after forwarding ``modify_before_fit`` to
every factor, only on factors whose ``setup_is_default`` is ``True``. An analysis that
resolves a default setup overrides it to drop that setup and run with no setup on
``use_jax`` (a PyAutoGalaxy / PyAutoLens analysis undoes any dataset operator the setup
attached). The default does nothing.
"""

def modify_model(self, model):
return model

Expand Down
16 changes: 16 additions & 0 deletions autofit/non_linear/analysis/model_analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,22 @@ def prepare_for_model(self, model: AbstractPriorModel):
self.analysis.prepare_for_model(self.model)
self._use_jax = self.analysis.is_jax

@property
def setup_is_default(self) -> bool:
"""
The wrapped analysis's ``setup_is_default`` (the base ``Analysis`` property would
otherwise shadow ``__getattr__`` forwarding).
"""
return self.analysis.setup_is_default

def adopt_backend(self, use_jax: bool):
"""
Forward ``adopt_backend`` to the wrapped analysis, then refresh this wrapper's
backend from it.
"""
self.analysis.adopt_backend(use_jax)
self._use_jax = self.analysis.is_jax

def _rebind(self, analysis: Optional[Analysis]):
"""
Point this wrapper at ``analysis`` (when not ``None``) and refresh its
Expand Down
132 changes: 132 additions & 0 deletions test_autofit/graphical/test_factor_graph_setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,3 +181,135 @@ def modify_before_fit(self, paths, model):
assert banners == [
"Parallel: 8 workers (auto: detected cores)"
]


class _DefaultAnalysis(af.Analysis):
"""
Resolves a default setup (`setup_is_default`) in `modify_before_fit`, whose backend
follows the setup_id prefix, and records `adopt_backend` calls.
"""

def __init__(self, setup_id, default=True):
super().__init__(use_jax=False)
self._setup_id = setup_id
self._default = default
self.setup = None
self.adopted = []

@property
def setup_is_default(self):
return self._default

def adopt_backend(self, use_jax):
self.adopted.append(use_jax)
self.setup = None
self._use_jax = use_jax

def log_likelihood_function(self, instance):
return 0.0

def modify_before_fit(self, paths, model):
if not self.adopted:
self.setup = _Setup(self._setup_id)
self._use_jax = self._setup_id.startswith("jax")
return self


def _modify(graph, name):
return graph.modify_before_fit(paths=af.DirectoryPaths(name=name), model=None)


def test_base_analysis_has_no_default_setup_and_adopt_is_a_no_op():
analysis = _Analysis()
assert analysis.setup_is_default is False
analysis.adopt_backend(True)
assert analysis.is_jax is False


def test_disagreeing_default_setups_adopt_one_backend(monkeypatch):
monkeypatch.delenv("PYAUTO_DISABLE_JAX", raising=False)
a = _DefaultAnalysis("numba_cpu_sparse_fp64")
b = _DefaultAnalysis("jax_cpu_dense_fp64_nufft")
graph = g.FactorGraphModel(_factor(a, "a"), _factor(b, "b"))

_modify(graph, "graph_default_mixed")

import importlib.util

expected = importlib.util.find_spec("jax") is not None
assert a.adopted == [expected] and b.adopted == [expected]
assert graph.setup_ids() == {}
assert graph.factors_disagreeing_on_backend() == []
graph.check_setup_agreement()


def test_agreeing_default_setups_are_kept():
a = _DefaultAnalysis("numba_cpu_sparse_fp64")
b = _DefaultAnalysis("numba_cpu_sparse_fp64")
graph = g.FactorGraphModel(_factor(a, "a"), _factor(b, "b"))

_modify(graph, "graph_default_agree")

assert a.adopted == [] and b.adopted == []
assert setup_id_of(graph) == "numba_cpu_sparse_fp64"


def test_graph_use_jax_false_pushes_numpy_down_to_default_factors():
a = _DefaultAnalysis("numba_cpu_sparse_fp64")
b = _DefaultAnalysis("jax_cpu_dense_fp64_nufft")
graph = g.FactorGraphModel(_factor(a, "a"), _factor(b, "b"), use_jax=False)

_modify(graph, "graph_default_numpy")

assert a.adopted == [False] and b.adopted == [False]
assert graph.is_jax is False
graph.check_backend_agreement()


def test_graph_use_jax_pushes_down_even_when_default_setups_agree():
a = _DefaultAnalysis("jax_cpu_dense_fp64")
b = _DefaultAnalysis("jax_cpu_dense_fp64")
graph = g.FactorGraphModel(_factor(a, "a"), _factor(b, "b"), use_jax=False)

_modify(graph, "graph_default_agree_numpy")

assert a.adopted == [False] and b.adopted == [False]
graph.check_backend_agreement()


def test_default_factors_follow_an_explicit_setup():
explicit = _DefaultAnalysis("numba_cpu_sparse_fp64", default=False)
default = _DefaultAnalysis("jax_cpu_dense_fp64_nufft")
graph = g.FactorGraphModel(_factor(explicit, "a"), _factor(default, "b"))

_modify(graph, "graph_explicit_lead")

assert explicit.adopted == []
assert default.adopted == [False]
assert graph.setup_ids() == {"a": "numba_cpu_sparse_fp64"}


def test_disagreeing_explicit_setups_still_raise():
a = _DefaultAnalysis("numba_cpu_sparse_fp64", default=False)
b = _DefaultAnalysis("jax_cpu_dense_fp64", default=False)
c = _DefaultAnalysis("jax_cpu_dense_fp64_nufft")
graph = g.FactorGraphModel(_factor(a, "a"), _factor(b, "b"), _factor(c, "c"))

with pytest.raises(exc.SearchException, match="setups passed explicitly"):
_modify(graph, "graph_explicit_bad")

assert a.adopted == [] and b.adopted == [] and c.adopted == []


def test_model_analysis_forwards_default_setup_and_adopt_backend():
from autofit.non_linear.analysis.model_analysis import ModelAnalysis

inner = _DefaultAnalysis("jax_cpu_dense_fp64")
inner._use_jax = True
wrapper = ModelAnalysis(analysis=inner, model=af.Model(af.ex.Gaussian))

assert wrapper.setup_is_default is True
wrapper.adopt_backend(False)

assert inner.adopted == [False]
assert wrapper.is_jax is False
Loading