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
5 changes: 3 additions & 2 deletions autogalaxy/abstract_fit.py
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down
26 changes: 16 additions & 10 deletions autogalaxy/analysis/analysis/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
):
"""
Expand All @@ -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=<setup_id>` 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=<setup_id>` 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
Expand Down
30 changes: 23 additions & 7 deletions autogalaxy/analysis/analysis/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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=<setup_id>` 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=<setup_id>` 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);
Expand Down Expand Up @@ -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
Expand Down
54 changes: 54 additions & 0 deletions autogalaxy/analysis/setup_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down Expand Up @@ -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"
Expand Down
14 changes: 8 additions & 6 deletions autogalaxy/imaging/model/analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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,
):
"""
Expand Down Expand Up @@ -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,
Expand Down
14 changes: 8 additions & 6 deletions autogalaxy/interferometer/model/analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
):
"""
Expand Down Expand Up @@ -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,
Expand Down
110 changes: 110 additions & 0 deletions test_autogalaxy/analysis/analysis/test_analysis_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Loading
Loading