diff --git a/autolens/analysis/analysis/dataset.py b/autolens/analysis/analysis/dataset.py index 824a56cec..992a157f9 100644 --- a/autolens/analysis/analysis/dataset.py +++ b/autolens/analysis/analysis/dataset.py @@ -108,9 +108,10 @@ def __init__( The compute setup of the likelihood: `None` (the 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 such as `"numba_cpu_sparse_fp64"`. It is resolved first in `modify_before_fit` by the - **PyAutoGalaxy** base class (see `autogalaxy.analysis.analysis.dataset.AnalysisDataset`). A setup is - not supported inside a factor graph, which does not call `modify_before_fit`: the likelihood raises - an `exc.SetupException` instead of fitting with the setup silently ignored. + **PyAutoGalaxy** base class (see `autogalaxy.analysis.analysis.dataset.AnalysisDataset`), or before + the fit by `prepare_for_model(model)` (e.g. via `print_vram_use(model=...)`). Evaluating the + likelihood before the setup is resolved raises an `exc.SetupException` instead of fitting with the + setup silently ignored. """ super().__init__( diff --git a/autolens/analysis/analysis/setup.py b/autolens/analysis/analysis/setup.py index 839a9db4e..d5c92f668 100644 --- a/autolens/analysis/analysis/setup.py +++ b/autolens/analysis/analysis/setup.py @@ -1,6 +1,6 @@ """ The compute `setup` of the lens analyses that have no dataset operator (point-source and weak lensing), -and the guard that stops a setup being silently ignored inside a factor graph. +and the guard that stops a likelihood being evaluated before its setup has been resolved. The imaging and interferometer analyses resolve their setup through the **PyAutoGalaxy** base class (`autogalaxy.analysis.analysis.dataset.AnalysisDataset.resolve_setup`), which also applies it to the @@ -10,9 +10,11 @@ `files/setup.json`) through PyAutoGalaxy's shared `AnalysisSetupMixin` (`autogalaxy.analysis.analysis.setup`). -`raise_if_setup_unresolved` is called at the top of every lens `log_likelihood_function`. A setup is -resolved in `modify_before_fit`, which a `FactorGraphModel` does not call on its factors, so a setup -given to an analysis fitted inside a factor graph would otherwise never be applied. +`raise_if_setup_unresolved` is called at the top of every lens `log_likelihood_function`. A setup +resolves when the fit starts (`modify_before_fit`, which a search calls on the analysis and a +`FactorGraphModel` forwards to each factor) or on a pre-fit call that receives a model +(`analysis.prepare_for_model(model)`, called by e.g. `print_vram_use(model=...)`). A likelihood evaluated +before either would otherwise run with the constructor backend and the setup silently ignored. """ import logging @@ -32,15 +34,17 @@ SETUP_UNRESOLVED_MESSAGE = """ -The {cls} was given `setup={setup_input!r}`, but the setup was never resolved, because -`modify_before_fit` was not called before the likelihood was evaluated. +The {cls} was given `setup={setup_input!r}`, but its likelihood was evaluated before the setup was +resolved. -This happens when the analysis is fitted inside a factor graph (`af.FactorGraphModel` of -`af.AnalysisFactor`s): the factor graph does not call each factor's `modify_before_fit`, so the -setup would silently not be applied. Setups are not yet supported inside factor graphs (this is -planned for the PyAutoFit phase of the likelihood lifecycle, 5D). +The setup resolves when the fit starts (`search.fit` calls `modify_before_fit`, which a factor graph +forwards to each factor's analysis) or on a pre-fit call that receives a model, e.g. +`analysis.print_vram_use(model=model, batch_size=...)`. The likelihood was evaluated before the fit +started and before either. -Instead, apply the setup to each dataset yourself and choose the backend explicitly, e.g. +Call `analysis.prepare_for_model(model)` first (it resolves the setup from the model you will fit), +or run the fit. Alternatively, apply the setup to the dataset yourself and choose the backend +explicitly, e.g. dataset = dataset.apply_setup("numba_cpu_sparse_fp64") analysis = al.AnalysisImaging(dataset=dataset, use_jax=False) @@ -53,9 +57,10 @@ def raise_if_setup_unresolved(analysis): """ Raise an `exc.SetupException` when an analysis was given a `setup` that was never resolved. - A setup is resolved in `modify_before_fit`, which a non-linear search calls before sampling. A - `FactorGraphModel` does not call it on its factors, so a factor given `setup=` would otherwise be - fitted with its constructor backend and the setup silently ignored. + A setup is resolved in `modify_before_fit`, which a non-linear search calls before sampling (and a + `FactorGraphModel` forwards to each factor), or by `prepare_for_model(model)` on pre-fit calls that + receive a model (e.g. `print_vram_use`). A likelihood evaluated before either would otherwise use the + constructor backend with the setup silently ignored. This is a cheap Python attribute check, safe under JAX tracing. It is called at the top of each `log_likelihood_function`, outside the `raise_fit_exception` wrapper, so it stops the fit instead of diff --git a/autolens/analysis/runtime_estimate.py b/autolens/analysis/runtime_estimate.py index 395ef85f2..bae994801 100644 --- a/autolens/analysis/runtime_estimate.py +++ b/autolens/analysis/runtime_estimate.py @@ -40,7 +40,6 @@ import yaml import autoarray as aa -from autoarray.setup.setup import setup_from from autolens.analysis import wall_model @@ -146,6 +145,45 @@ class RuntimeEstimate: expected_evals_band: Optional[Tuple[int, int]] = None band_across: Optional[str] = None supported_search: bool = True + has_profiling_cell: bool = True + fallback_reason: Optional[str] = None + + @classmethod + def no_profiling_cell( + cls, + setup_id: str, + backend: Optional[str], + number_of_cores: int, + search=None, + fallback_reason: Optional[str] = None, + ) -> "RuntimeEstimate": + """ + The estimate of a setup the run-time table has no row for (e.g. `numba_cpu_dense_fp64`): every + number is `None` and `line()` reads `Estimate: no estimate for (no profiling cell)`. + + `fallback_reason` (e.g. `"JAX disabled"`) marks a `jax` setup that runs on numpy instead: the + table has rows for the JAX designation only, so the fit that actually runs is not priced, and + `line()` says why. + """ + return cls( + ms_per_eval=None, + record_id=None, + instrument=None, + matched_by="none", + expected_evals=None, + evals_model="none", + parallel_efficiency=None, + number_of_cores=number_of_cores, + wall_seconds=None, + wall_band=None, + calibrated=False, + note="no profiling cell", + setup_id=setup_id, + backend=backend, + search_name=None if search is None else type(search).__name__, + has_profiling_cell=False, + fallback_reason=fallback_reason, + ) def line(self) -> str: """ @@ -158,8 +196,21 @@ def line(self) -> str: fit has `1 worker (JAX)` in place of `η`; an uncalibrated estimate ends its details with `uncalibrated (held-out 0.2–0.5×)`; a search other than Nautilus reads `Estimate: none for Emcee (the run-time model covers Nautilus only) (697 ms/eval, hst cell)`. - The worker count is not repeated (the fit's `Parallel:` line reports it). + The worker count is not repeated (the fit's `Parallel:` line reports it). A setup with no row in + the run-time table reads `Estimate: no estimate for numba_cpu_dense_fp64 (no profiling cell)`. """ + if not self.has_profiling_cell and self.fallback_reason is not None: + return _estimate_line( + f"no estimate for {self.setup_id} (designated JAX; {self.fallback_reason}, " + f"the numpy fallback has no profiling cell)", + [], + ) + + if not self.has_profiling_cell: + return _estimate_line( + f"no estimate for {self.setup_id} (no profiling cell)", [] + ) + details = [] if self.ms_per_eval_band is not None: @@ -478,12 +529,67 @@ def matched_rows_for( return candidates, matched, matched_by +def _rule_key_from(dataset, model, likelihood: Optional[str]) -> Tuple[str, str]: + """ + The `(dataset_type, variant)` rule key of `aa.Setup.auto` for `setup="auto"`: the one the analyses + use (`autogalaxy.analysis.setup_util.setup_key_and_note_from` for imaging and interferometer, + `weak/isothermal` for weak lensing), or the `likelihood` the caller gives. + + Raises + ------ + ValueError + When the key cannot be worked out (a point dataset needs `likelihood=`, as its rule depends on + the analysis's positions fit). + """ + if likelihood is not None: + dataset_type, _, variant = likelihood.partition("/") + return dataset_type, variant + + dataset_type = dataset_type_from(dataset) + + if dataset_type in ("imaging", "interferometer"): + from autogalaxy.analysis import setup_util + + key, _ = setup_util.setup_key_and_note_from(dataset=dataset, model=model) + return key + + if dataset_type == "weak": + return "weak", "isothermal" + + raise ValueError( + "setup='auto' cannot work out the setup rule for this dataset" + + ( + ": a point dataset's rule depends on its positions fit, so pass likelihood=" + "'point_source_image/image_plane' or 'point_source_source/source_plane'." + if dataset_type == POINT_DATASET_TYPE + else f" ({type(dataset).__name__}); pass likelihood='/'." + ) + ) + + +def resolve_setup_from(dataset, model, setup, likelihood: Optional[str] = None): + """ + The compute setup of `estimate_runtime`: `None`, an `aa.Setup` or setup_id string as given, or for + `"auto"` the setup a fit's `setup="auto"` resolves to, `aa.Setup.auto` with the analyses' rule key + (`_rule_key_from`) on the detected hardware (`PYAUTO_SETUP` overrides it, as in a fit). + """ + from autogalaxy.analysis import setup_util + + setup = setup_util.setup_input_from(setup) + + if setup != setup_util.SETUP_AUTO: + return setup + + key = _rule_key_from(dataset=dataset, model=model, likelihood=likelihood) + return aa.Setup.auto(*key, environment=setup_util.setup_environment()) + + def estimate_runtime( dataset, model, search, setup, - number_of_cores: int = 1, + number_of_cores=1, likelihood: Optional[str] = None, ) -> Optional[RuntimeEstimate]: """ @@ -501,9 +607,13 @@ def estimate_runtime( The non-linear search: only `af.Nautilus` gets an estimate (its `n_live`); any other search gets an estimate whose line says there is none. setup - The compute setup, an `al.Setup` or a setup_id string (e.g. `"numba_cpu_sparse_fp64"`). + The compute setup: an `al.Setup`, a setup_id string (e.g. `"numba_cpu_sparse_fp64"`) or `"auto"`, + resolved as a fit's `setup="auto"` is (`aa.Setup.auto` with the analyses' rule key for the dataset + and model on the detected hardware; `PYAUTO_SETUP` overrides it). number_of_cores - The worker count of the fit. For a numba setup the per-call is divided by + The worker count of the fit, an int or `"auto"` (resolved as a fit resolves it, by PyAutoFit's + `resolve_number_of_cores`: 1 for a JAX backend, else the detected cores capped by the matched row's + `cpus_per_eval` / `peak_rss_gb`). For a numba setup the per-call is divided by `cores * efficiency(cores)`; a JAX setup runs one worker and uses its per-call as is. likelihood The `/` likelihood, when the caller knows it (the analyses pass their setup @@ -511,9 +621,12 @@ def estimate_runtime( Returns ------- - A `RuntimeEstimate`, or `None` when there is no setup or the table has no row for it. + A `RuntimeEstimate`, or `None` when there is no setup. A setup the table has no row for gives an + estimate whose `line()` reads `no estimate for (no profiling cell)`. """ - setup = setup_from(setup) + setup = resolve_setup_from( + dataset=dataset, model=model, setup=setup, likelihood=likelihood + ) if setup is None: return None @@ -527,12 +640,37 @@ def estimate_runtime( likelihood=likelihood, rows=table["rows"], ) - if not candidates: - return None backend = setup.backend - is_jax = backend == "jax" - cores = 1 if is_jax else max(1, int(number_of_cores or 1)) + cores = _number_of_cores_from( + number_of_cores=number_of_cores, + setup=setup, + resources=resources_per_eval_from(matched, matched_by), + ) + + from autogalaxy.analysis import setup_util + + # A `jax` setup run on numpy (`PYAUTO_DISABLE_JAX=1` or JAX not installed) is not what the JAX + # rows measured, so it is not priced by them (the `Setup:` line reports the same fallback). + fallback_reason = setup_util.jax_fallback_reason_from( + setup=setup, use_jax=setup_util.use_jax_from(backend == "jax") + ) + if fallback_reason is not None: + return RuntimeEstimate.no_profiling_cell( + setup_id=setup.setup_id, + backend="numpy", + number_of_cores=cores, + search=search, + fallback_reason=fallback_reason, + ) + + if not candidates: + return RuntimeEstimate.no_profiling_cell( + setup_id=setup.setup_id, + backend=backend, + number_of_cores=cores, + search=search, + ) efficiency = ( wall_model.parallel_efficiency(cores, curve=curve) @@ -617,6 +755,39 @@ def estimate_runtime( return estimate +def _number_of_cores_from(number_of_cores, setup: aa.Setup, resources: Optional[dict]) -> int: + """ + The worker count `estimate_runtime` prices a fit by: 1 for a setup whose backend resolves to JAX + (after `PYAUTO_DISABLE_JAX` and a missing JAX install, as in a fit), else the request, with `"auto"` + resolved by PyAutoFit's `resolve_number_of_cores` exactly as a fit resolves it (the detected cores, + capped by the matched row's `cpus_per_eval` / `peak_rss_gb`). + """ + from types import SimpleNamespace + + from autofit.non_linear.parallel.pool import resolve_number_of_cores + from autofit.non_linear.parallel.resources import is_auto + from autogalaxy.analysis import setup_util + + is_jax = setup_util.use_jax_from(setup.backend == "jax") + + if is_auto(number_of_cores): + # A stand-in analysis carrying what `resolve_number_of_cores` duck-types: the setup and the + # matched row's resources. + analysis = SimpleNamespace( + setup=setup, is_jax=is_jax, resources_per_eval=lambda: resources + ) + return resolve_number_of_cores( + requested=number_of_cores, + analysis=analysis, + is_jax=is_jax, + where="estimate_runtime", + ).number_of_cores + + if is_jax: + return 1 + return max(1, int(number_of_cores or 1)) + + def resources_per_eval_from(rows: List[dict], matched_by: str) -> Optional[dict]: """ `{"cpus_per_eval", "peak_rss_gb"}` of the matched row, or for a band the largest of each across the @@ -699,7 +870,11 @@ def runtime_estimate(self, search, model=None, number_of_cores=1) -> Optional[st except Exception as e: logger.debug(f"Run-time estimate failed and was ignored: {e!r}") return None - return None if estimate is None else estimate.line() + # A setup with no profiling cell logs nothing at fit time (as before); only a direct + # `al.estimate_runtime` call reports "no estimate for (no profiling cell)". + if estimate is None or not estimate.has_profiling_cell: + return None + return estimate.line() def resources_per_eval(self) -> Optional[dict]: """ @@ -710,6 +885,9 @@ def resources_per_eval(self) -> Optional[dict]: setup = getattr(self, "setup", None) if setup is None: return None + # A `jax` setup run on numpy is not what the JAX rows measured (see `estimate_runtime`). + if setup.backend == "jax" and not self.is_jax: + return None model = getattr(self, "_runtime_estimate_model", None) _, matched, matched_by = matched_rows_for( dataset=getattr(self, "dataset", None), diff --git a/autolens/exc.py b/autolens/exc.py index 391e2ae40..56b33f27e 100644 --- a/autolens/exc.py +++ b/autolens/exc.py @@ -68,9 +68,9 @@ class PointProfileMismatchException(Exception): class SetupException(AnalysisException): """ - Raised when the compute `setup` of an analysis cannot be honoured, for example when an analysis given - `setup=` is fitted inside a factor graph, where its `modify_before_fit` (which resolves and applies the - setup) is never called. + Raised when the compute `setup` of an analysis cannot be honoured, for example when the likelihood of an + analysis given `setup=` is evaluated before the setup was resolved (by `modify_before_fit` when the fit + starts, or by `prepare_for_model(model)` before it). Deliberately NOT a subclass of `af.exc.FitException`: it is a configuration error, so it must stop the model-fit with a clear message rather than be swallowed into a resample on every likelihood call. diff --git a/autolens/point/model/analysis.py b/autolens/point/model/analysis.py index 182de1089..68ee3edb4 100644 --- a/autolens/point/model/analysis.py +++ b/autolens/point/model/analysis.py @@ -129,8 +129,9 @@ def __init__( `"auto"` the rule key is `point_source_source/source_plane` when `fit_positions_cls` is a source-plane fit (`FitPositionsSource` or a subclass) and `point_source_image/image_plane` otherwise (see `setup_key_from`). A resolved setup sets the backend, pins the thread pools, is logged as a - banner line and is written to `files/setup.json`; a point dataset has no operator to attach. A setup - is not supported inside a factor graph: the likelihood raises an `exc.SetupException` instead. + banner line and is written to `files/setup.json`; a point dataset has no operator to attach. + Evaluating the likelihood before the setup is resolved (by the fit or `prepare_for_model(model)`) + raises an `exc.SetupException`. """ super().__init__(cosmology=cosmology, use_jax=use_jax, **kwargs) diff --git a/autolens/weak/model/analysis.py b/autolens/weak/model/analysis.py index 21102e9c4..0dd10e96b 100644 --- a/autolens/weak/model/analysis.py +++ b/autolens/weak/model/analysis.py @@ -81,8 +81,8 @@ def __init__( or a setup_id string such as `"jax_cpu_dense_fp64"`. It is resolved in `modify_before_fit`; with `"auto"` the rule key is `weak/isothermal` (see `setup_key_from`). A resolved setup sets the backend, pins the thread pools, is logged as a banner line and is written to `files/setup.json`; a shear - catalogue has no operator to attach. A setup is not supported inside a factor graph: the likelihood - raises an `exc.SetupException` instead. + catalogue has no operator to attach. Evaluating the likelihood before the setup is resolved (by the + fit or `prepare_for_model(model)`) raises an `exc.SetupException`. """ super().__init__(cosmology=cosmology, use_jax=use_jax, **kwargs) diff --git a/test_autolens/analysis/test_runtime_estimate.py b/test_autolens/analysis/test_runtime_estimate.py index b5ab6ed47..0aa1e7153 100644 --- a/test_autolens/analysis/test_runtime_estimate.py +++ b/test_autolens/analysis/test_runtime_estimate.py @@ -5,6 +5,7 @@ `resources_per_eval`). """ +import importlib.util import logging import re from types import SimpleNamespace @@ -25,6 +26,25 @@ def unset_setup_env(monkeypatch): monkeypatch.delenv("PYAUTO_DISABLE_JAX", raising=False) +_real_find_spec = importlib.util.find_spec + + +@pytest.fixture(autouse=True) +def jax_installed(monkeypatch): + """ + Price JAX setups as if JAX were installed, so these tests behave the same on the no-JAX CI leg. + A JAX setup on a machine without JAX runs on numpy and is not priced by the JAX rows + (`test__jax_setup_with_jax_not_installed__not_priced_by_jax_rows` covers that). + """ + monkeypatch.setattr( + importlib.util, + "find_spec", + lambda name, *args, **kwargs: ( + object() if name == "jax" else _real_find_spec(name, *args, **kwargs) + ), + ) + + class Nautilus: """A Nautilus-like search: only its name and `n_live` matter to the estimator.""" @@ -254,24 +274,139 @@ def test__weak__single__uncalibrated(): assert estimate.note == "uncalibrated (held-out 0.2–0.5×)" -def test__no_setup__or_no_row__none(): +def test__no_setup__none__no_row__no_profiling_cell_line(): assert ( al.estimate_runtime( dataset=None, model=None, search=Nautilus(), setup=None ) is None ) - assert ( + + estimate = al.estimate_runtime( + dataset=None, + model=None, + search=Nautilus(), + setup="numba_cpu_dense_fp32", + likelihood="imaging/rectangular", + ) + + assert estimate.has_profiling_cell is False + assert estimate.wall_seconds is None + assert estimate.ms_per_eval is None + assert estimate.line() == ( + "Estimate: no estimate for numba_cpu_dense_fp32 (no profiling cell)" + ) + + +def _many_core(monkeypatch, cores=64, gpu=False): + from autonerves.environment import Environment + + environment = Environment( + gpu=gpu, + gpu_name="NVIDIA A100-SXM4-80GB" if gpu else None, + gpu_memory_gb=None, + cores=cores, + ram_gb=None, + numba=True, + nufftax=True, + site="local", + ) + monkeypatch.setattr(Environment, "detect", classmethod(lambda cls: environment)) + + +def test__setup_auto__resolves_as_the_analysis_does(masked_imaging_7x7, monkeypatch): + from autogalaxy.analysis import setup_util + + _many_core(monkeypatch) + + model = _rectangular_model() + + estimate = al.estimate_runtime( + dataset=masked_imaging_7x7, model=model, search=Nautilus(), setup="auto" + ) + + key, _ = setup_util.setup_key_and_note_from(dataset=masked_imaging_7x7, model=model) + expected = al.Setup.auto(*key, environment=setup_util.setup_environment()) + + assert estimate.setup_id == expected.setup_id + + analysis = al.AnalysisImaging(dataset=masked_imaging_7x7, setup="auto", use_jax=False) + analysis.resolve_setup(model=model, log_banner=False) + + assert estimate.setup_id == analysis.setup.setup_id + + +def test__setup_auto__pyauto_setup_overrides(masked_imaging_7x7, monkeypatch): + _many_core(monkeypatch) + monkeypatch.setenv("PYAUTO_SETUP", "numba_cpu_dense_fp64") + + estimate = al.estimate_runtime( + dataset=masked_imaging_7x7, + model=_rectangular_model(), + search=Nautilus(), + setup="auto", + ) + + assert estimate.setup_id == "numba_cpu_dense_fp64" + assert estimate.line() == ( + "Estimate: no estimate for numba_cpu_dense_fp64 (no profiling cell)" + ) + + +def test__setup_auto__point_dataset_needs_likelihood(point_dataset, monkeypatch): + _many_core(monkeypatch) + + with pytest.raises(ValueError, match="likelihood="): al.estimate_runtime( - dataset=None, - model=None, - search=Nautilus(), - setup="numba_cpu_dense_fp32", - likelihood="imaging/rectangular", + dataset=point_dataset, model=None, search=Nautilus(), setup="auto" ) - is None + + +def test__number_of_cores_auto__jax_is_one_worker(): + estimate = al.estimate_runtime( + dataset=_sized_imaging(_row(setup_id="jax_gpu_dense_fp64")["n_pixels_masked"]), + model=_rectangular_model(), + search=Nautilus(), + setup="jax_gpu_dense_fp64", + number_of_cores="auto", + likelihood=_row(setup_id="jax_gpu_dense_fp64")["likelihood"], + ) + + assert estimate.number_of_cores == 1 + + +def test__number_of_cores_auto__numba_resolved_as_a_fit(monkeypatch): + from autofit.non_linear.parallel import pool + + monkeypatch.setattr(pool, "detected_cores", lambda: 12) + + row = _row(setup_id="numba_cpu_sparse_fp64", likelihood="imaging/rectangular") + + estimate = al.estimate_runtime( + dataset=_sized_imaging(row["n_pixels_masked"]), + model=_rectangular_model(), + search=Nautilus(), + setup="numba_cpu_sparse_fp64", + number_of_cores="auto", + likelihood="imaging/rectangular", ) + resources = re_mod.resources_per_eval_from([row], "size") + expected = pool.resolve_number_of_cores( + "auto", + analysis=SimpleNamespace(resources_per_eval=lambda: resources), + is_jax=False, + ).number_of_cores + + assert estimate.number_of_cores == expected + assert 1 <= estimate.number_of_cores <= 12 + + +def test__analysis__no_profiling_cell__fit_time_estimate_stays_silent(masked_imaging_7x7): + analysis = _imaging_analysis(masked_imaging_7x7, "numba_cpu_dense_fp32") + + assert analysis.runtime_estimate(search=Nautilus(), model=_rectangular_model()) is None + # Heuristic, efficiency and line @@ -599,3 +734,51 @@ def test__hook__auto_cores_capped_by_peak_rss(masked_imaging_7x7, monkeypatch): assert resolution.number_of_cores == 9 # floor(10 / 1.024) assert resolution.reason == "memory" + + +def test__jax_setup_with_jax_disabled__not_priced_by_jax_rows(monkeypatch): + monkeypatch.setenv("PYAUTO_DISABLE_JAX", "1") + + estimate = al.estimate_runtime( + dataset=_sized_imaging(_row(setup_id="jax_gpu_dense_fp64")["n_pixels_masked"]), + model=_rectangular_model(), + search=Nautilus(), + setup="jax_gpu_dense_fp64", + number_of_cores=4, + likelihood=_row(setup_id="jax_gpu_dense_fp64")["likelihood"], + ) + + assert estimate.has_profiling_cell is False + assert estimate.backend == "numpy" + assert estimate.number_of_cores == 4 + assert estimate.wall_seconds is None + assert estimate.line() == ( + "Estimate: no estimate for jax_gpu_dense_fp64 (designated JAX; JAX disabled, " + "the numpy fallback has no profiling cell)" + ) + + +def test__jax_setup_with_jax_not_installed__not_priced_by_jax_rows(monkeypatch): + monkeypatch.setattr( + importlib.util, + "find_spec", + lambda name, *args, **kwargs: ( + None if name == "jax" else _real_find_spec(name, *args, **kwargs) + ), + ) + + with pytest.warns(UserWarning, match="JAX is not installed"): + estimate = al.estimate_runtime( + dataset=_sized_imaging(_row(setup_id="jax_gpu_dense_fp64")["n_pixels_masked"]), + model=_rectangular_model(), + search=Nautilus(), + setup="jax_gpu_dense_fp64", + likelihood=_row(setup_id="jax_gpu_dense_fp64")["likelihood"], + ) + + assert estimate.has_profiling_cell is False + assert estimate.backend == "numpy" + assert estimate.line() == ( + "Estimate: no estimate for jax_gpu_dense_fp64 (designated JAX; JAX not installed, " + "the numpy fallback has no profiling cell)" + ) diff --git a/test_autolens/imaging/model/test_analysis_imaging_setup.py b/test_autolens/imaging/model/test_analysis_imaging_setup.py index 8635a38fc..740d78cb1 100644 --- a/test_autolens/imaging/model/test_analysis_imaging_setup.py +++ b/test_autolens/imaging/model/test_analysis_imaging_setup.py @@ -249,7 +249,7 @@ def test__factor_graph__setup_raises_setup_exception(masked_imaging_7x7): factor_graph = af.FactorGraphModel(*factors) instance = factor_graph.global_prior_model.instance_from_unit_vector([]) - with pytest.raises(exc.SetupException, match="factor graph") as e: + with pytest.raises(exc.SetupException, match="evaluated before the setup") as e: factor_graph.log_likelihood_function(instance) assert not isinstance(e.value, af.exc.FitException) diff --git a/test_autolens/interferometer/model/test_analysis_interferometer.py b/test_autolens/interferometer/model/test_analysis_interferometer.py index 58338d40b..50e6d3c78 100644 --- a/test_autolens/interferometer/model/test_analysis_interferometer.py +++ b/test_autolens/interferometer/model/test_analysis_interferometer.py @@ -525,7 +525,7 @@ def test__factor_graph__setup_raises_setup_exception__interferometer( ) instance = factor_graph.global_prior_model.instance_from_unit_vector([]) - with pytest.raises(exc.SetupException, match="factor graph") as e: + with pytest.raises(exc.SetupException, match="evaluated before the setup") as e: factor_graph.log_likelihood_function(instance) assert not isinstance(e.value, af.exc.FitException) diff --git a/test_autolens/point/model/test_analysis_point_setup.py b/test_autolens/point/model/test_analysis_point_setup.py index 0672a03a4..b9615b0aa 100644 --- a/test_autolens/point/model/test_analysis_point_setup.py +++ b/test_autolens/point/model/test_analysis_point_setup.py @@ -1,7 +1,7 @@ """ The compute `setup` of `al.AnalysisPoint` (likelihood lifecycle 5C-2): the rule key follows the positions fit (image plane or source plane), a resolved setup sets the backend, logs the banner and writes -`files/setup.json`, and a setup inside a factor graph raises instead of being silently ignored. +`files/setup.json`, and a likelihood evaluated before the setup resolves raises instead of ignoring it. """ import json @@ -214,7 +214,7 @@ def test__factor_graph__setup_raises_setup_exception(point_dataset): factor_graph = af.FactorGraphModel(*factors) instance = factor_graph.global_prior_model.instance_from_unit_vector([]) - with pytest.raises(exc.SetupException, match="factor graph") as e: + with pytest.raises(exc.SetupException, match="evaluated before the setup") as e: factor_graph.log_likelihood_function(instance) assert not isinstance(e.value, af.exc.FitException) diff --git a/test_autolens/weak/test_analysis.py b/test_autolens/weak/test_analysis.py index 7306932df..cd3d96ae9 100644 --- a/test_autolens/weak/test_analysis.py +++ b/test_autolens/weak/test_analysis.py @@ -228,5 +228,5 @@ def test__factor_graph__setup_raises_setup_exception__weak(): ) instance = factor_graph.global_prior_model.instance_from_unit_vector([]) - with pytest.raises(exc.SetupException, match="factor graph"): + with pytest.raises(exc.SetupException, match="evaluated before the setup"): factor_graph.log_likelihood_function(instance)