From 32888ab5dc83083de3d80260e884a28eb7895710 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Tue, 24 Nov 2026 10:20:02 +0000 Subject: [PATCH 1/2] feat: apply_setup, inversion operator/backend check and Setup.apply_threads (5B-2) Imaging.apply_setup / Interferometer.apply_setup attach the operator or transformer an aa.Setup names; datasets store .setup and carry it through apply_mask / apply_noise_scaling / apply_over_sampling. The inversion factory raises InversionException on an operator/backend mismatch. Setup.apply_threads pins numba and threadpoolctl thread pools, safely inside multiprocessing workers. Part of #708 (likelihood-lifecycle phase 5B-2). Co-Authored-By: Claude Opus 5.5 --- autoarray/dataset/imaging/dataset.py | 157 ++++++++++++++- autoarray/dataset/interferometer/dataset.py | 128 ++++++++++++- autoarray/inversion/inversion/factory.py | 150 +++++++++++++++ autoarray/setup/setup.py | 132 +++++++++++++ .../dataset/imaging/test_dataset.py | 138 +++++++++++++ .../dataset/interferometer/test_dataset.py | 163 ++++++++++++++++ .../inversion/inversion/test_factory.py | 181 ++++++++++++++++++ test_autoarray/setup/test_setup.py | 149 ++++++++++++++ 8 files changed, 1186 insertions(+), 12 deletions(-) diff --git a/autoarray/dataset/imaging/dataset.py b/autoarray/dataset/imaging/dataset.py index 3ac1c7d8d..d125bb035 100644 --- a/autoarray/dataset/imaging/dataset.py +++ b/autoarray/dataset/imaging/dataset.py @@ -1,3 +1,4 @@ +import copy import logging import numpy as np from pathlib import Path @@ -12,6 +13,8 @@ from autoarray.operators.convolver import ConvolverState from autoarray.operators.convolver import Convolver from autoarray.mask.mask_2d import Mask2D +from autoarray.setup.setup import Setup +from autoarray.setup.setup import setup_from from autoarray import type as ty from autoarray import exc @@ -106,6 +109,7 @@ def __init__( use_normalized_psf: Optional[bool] = True, check_noise_map: bool = True, sparse_operator: Optional[ImagingSparseOperator] = None, + setup: Optional[Union[Setup, str]] = None, ): """ An imaging dataset, containing the image data, noise-map, PSF and associated quantities @@ -174,6 +178,10 @@ def __init__( The sparse linear algebra formalism of the linear algebra equations precomputes the convolution of every pair of masked noise-map values given the PSF (see `inversion.inversion_util`). Pass the `ImagingSparseOperator` object here to enable this linear algebra formalism for pixelized reconstructions. + setup + The compute setup (an `aa.Setup` or a setup_id string) this dataset is evaluated with, which is + stored and carried by `apply_mask`, `apply_noise_scaling` and `apply_over_sampling`. Passing it here + only records it; use `apply_setup()` to attach the operator it names. """ _validate_convolve_over_sample_size( @@ -287,6 +295,7 @@ def __init__( ) self.sparse_operator = sparse_operator + self.setup = setup_from(setup) @classmethod def from_fits( @@ -428,6 +437,11 @@ def apply_mask(self, mask: Mask2D) -> "Imaging": trimmed. An exception is raised if this is attempted. If you wish to apply a different mask, reload the dataset from .fits files. + A new mask invalidates any attached sparse operator. If the dataset has a `setup` (see + `apply_setup()`), the setup stays in effect: it is re-applied to the masked dataset, so the + operator it names is rebuilt for the new mask. Without a setup the operator is discarded + (with a warning). + Parameters ---------- mask @@ -469,9 +483,10 @@ def apply_mask(self, mask: Mask2D) -> "Imaging": values=self.over_sample_size_pixelization.native, mask=mask ) - _warn_sparse_operator_discarded( - sparse_operator=self.sparse_operator, method_name="apply_mask" - ) + if self.setup is None: + _warn_sparse_operator_discarded( + sparse_operator=self.sparse_operator, method_name="apply_mask" + ) dataset = Imaging( data=data, @@ -483,12 +498,16 @@ def apply_mask(self, mask: Mask2D) -> "Imaging": over_sample_size_pixelization=over_sample_size_pixelization, convolve_over_sample_size_lp=self.convolve_over_sample_size_lp, convolve_over_sample_size_pixelization=self.convolve_over_sample_size_pixelization, + setup=self.setup, ) logger.info( f"IMAGING - Data masked, contains a total of {mask.pixels_in_mask} image-pixels" ) + if self.setup is not None: + return dataset.apply_setup(setup=self.setup) + return dataset def apply_noise_scaling( @@ -521,6 +540,10 @@ def apply_noise_scaling( This function can only be applied before actual masking. + A changed noise-map invalidates any attached sparse operator. If the dataset has a `setup` + (see `apply_setup()`), the setup is re-applied to the returned dataset so the operator it names + is rebuilt for the new noise-map. Without a setup the operator is discarded (with a warning). + Parameters ---------- mask @@ -554,9 +577,10 @@ def apply_noise_scaling( noise_map = Array2D(values=noise_map, mask=self.data.mask) - _warn_sparse_operator_discarded( - sparse_operator=self.sparse_operator, method_name="apply_noise_scaling" - ) + if self.setup is None: + _warn_sparse_operator_discarded( + sparse_operator=self.sparse_operator, method_name="apply_noise_scaling" + ) dataset = Imaging( data=data, @@ -568,12 +592,16 @@ def apply_noise_scaling( convolve_over_sample_size_lp=self.convolve_over_sample_size_lp, convolve_over_sample_size_pixelization=self.convolve_over_sample_size_pixelization, check_noise_map=False, + setup=self.setup, ) logger.info( f"IMAGING - Data noise scaling applied, a total of {mask.pixels_in_mask} pixels were scaled to large noise values." ) + if self.setup is not None: + return dataset.apply_setup(setup=self.setup) + return dataset def apply_over_sampling( @@ -591,9 +619,10 @@ def apply_over_sampling( This function resets the cached properties so that the new over sampling is used in the grid and grid pixelization. - The `noise_covariance_matrix` and any attached `sparse_operator` are carried over, as neither depends on - the over sampling (the sparse operator depends only on the noise-map, PSF kernel and mask). This means - `apply_sparse_operator()` / `apply_sparse_operator_cpu()` may be called before or after this method. + The `noise_covariance_matrix`, any attached `sparse_operator` and the `setup` are carried over, as none + depends on the over sampling (the sparse operator depends only on the noise-map, PSF kernel and mask). This + means `apply_sparse_operator()` / `apply_sparse_operator_cpu()` / `apply_setup()` may be called before or + after this method. Parameters ---------- @@ -618,6 +647,7 @@ def apply_over_sampling( convolve_over_sample_size_pixelization=self.convolve_over_sample_size_pixelization, check_noise_map=False, sparse_operator=self.sparse_operator, + setup=self.setup, ) return dataset @@ -693,6 +723,7 @@ def apply_sparse_operator( convolve_over_sample_size_pixelization=self.convolve_over_sample_size_pixelization, check_noise_map=False, sparse_operator=sparse_operator, + setup=self.setup, ) def apply_sparse_operator_cpu( @@ -766,5 +797,113 @@ def apply_sparse_operator_cpu( convolve_over_sample_size_pixelization=self.convolve_over_sample_size_pixelization, check_noise_map=False, sparse_operator=sparse_operator, + setup=self.setup, + ) + + def _sparse_operator_matches(self, setup: Setup) -> bool: + """ + Whether the attached `sparse_operator` is the one `setup` names: a JAX + `ImagingSparseOperator` for a `jax` sparse setup, a numba `SparseLinAlgImagingNumba` + for a `numba` sparse setup, and no operator for any other operator token (`dense`, + `na`, ...). + """ + if setup.operator != "sparse": + return self.sparse_operator is None + + if setup.backend == "jax": + return isinstance(self.sparse_operator, ImagingSparseOperator) + + from autoarray.inversion.inversion.imaging_numba.inversion_imaging_numba_util import ( + SparseLinAlgImagingNumba, + ) + + return isinstance(self.sparse_operator, SparseLinAlgImagingNumba) + + def apply_setup( + self, + setup: Union[Setup, str], + batch_size: int = 128, + ) -> "Imaging": + """ + Apply a compute setup to the dataset, attaching the operator it names. + + - An operator `"sparse"` setup attaches the sparse linear algebra operator of its + backend: `apply_sparse_operator()` (an `ImagingSparseOperator`) for `backend="jax"` + and `apply_sparse_operator_cpu()` (a `SparseLinAlgImagingNumba`) for + `backend="numba"`. + - Any other operator (`"dense"`, `"na"`) attaches no operator, dropping an attached + one, so pixelized reconstructions use the mapping matrix formalism. + + The setup is stored as `dataset.setup` and carried by `apply_mask`, + `apply_noise_scaling` and `apply_over_sampling`; the first two rebuild the operator for + the new mask or noise-map. The inversion factory checks the operator against the setup + and the array backend, and raises on a mismatch. + + This method is idempotent: if the attached operator already matches the setup, no + operator is rebuilt (the dataset is returned as is, or as a shallow copy recording the + new setup when its provenance differs). + + The setup decides only how the likelihood is computed (backend, operator), never the + model (mesh, over-sampling, regularization). + + Parameters + ---------- + setup + The `aa.Setup`, or a setup_id string such as `"numba_cpu_sparse_fp64"`. + batch_size + The batch size of `apply_sparse_operator()`, used by a `jax` sparse setup. + + Returns + ------- + Imaging + The dataset with the setup applied. + + Raises + ------ + exc.DatasetException + If a sparse setup is applied to a dataset without a PSF, or names a backend with no + imaging sparse operator (`numpy`). + """ + setup = setup_from(setup) + + if self._sparse_operator_matches(setup=setup): + if self.setup == setup: + return self + dataset = copy.copy(self) + dataset.setup = setup + return dataset + + if setup.operator == "sparse": + if setup.backend not in ("jax", "numba"): + raise exc.DatasetException( + f"The setup {setup.setup_id!r} asks for the imaging sparse operator on the " + f"{setup.backend!r} backend, which has none: the imaging sparse operator is " + f"built for 'jax' (apply_sparse_operator) or 'numba' " + f"(apply_sparse_operator_cpu). Use a jax or numba setup, or a dense one." + ) + if self.psf is None: + raise exc.DatasetException( + f"The setup {setup.setup_id!r} asks for the imaging sparse operator, which " + f"precomputes PSF products, but this dataset has no PSF. Use a dense setup." + ) + + dataset = Imaging( + data=self.data, + noise_map=self.noise_map, + psf=self.psf, + noise_covariance_matrix=self.noise_covariance_matrix, + over_sample_size_lp=self.over_sample_size_lp, + over_sample_size_pixelization=self.over_sample_size_pixelization, + convolve_over_sample_size_lp=self.convolve_over_sample_size_lp, + convolve_over_sample_size_pixelization=self.convolve_over_sample_size_pixelization, + check_noise_map=False, + setup=setup, ) + if setup.operator != "sparse": + return dataset + + if setup.backend == "jax": + return dataset.apply_sparse_operator(batch_size=batch_size) + + return dataset.apply_sparse_operator_cpu() diff --git a/autoarray/dataset/interferometer/dataset.py b/autoarray/dataset/interferometer/dataset.py index 133e8ad34..0dbbe17f8 100644 --- a/autoarray/dataset/interferometer/dataset.py +++ b/autoarray/dataset/interferometer/dataset.py @@ -1,8 +1,9 @@ +import copy import dataclasses import logging import warnings import numpy as np -from typing import Optional, Tuple +from typing import Optional, Tuple, Union from autonerves.fitsable import ndarray_via_fits_from from autonerves import cached_property @@ -34,6 +35,8 @@ def disable_jax(): from autoarray.operators.transformer import TransformerDFT from autoarray.operators.transformer import TransformerNUFFT from autoarray.mask.mask_2d import Mask2D +from autoarray.setup.setup import Setup +from autoarray.setup.setup import setup_from from autoarray.structures.visibilities import Visibilities from autoarray.structures.visibilities import VisibilitiesNoiseMap @@ -58,6 +61,7 @@ def __init__( raise_error_dft_visibilities_limit: bool = True, sparse_terms: Optional["inversion_interferometer_util.SparseTerms"] = None, primary_beam=None, + setup: Optional[Union[Setup, str]] = None, ): """ An interferometer dataset, containing the visibilities data, noise-map, real-space msk, Fourier transformer and @@ -110,7 +114,8 @@ def __init__( raise_error_dft_visibilities_limit If `True`, an exception is raised if the dataset has more than 10,000 visibilities and `transformer_class=TransformerDFT`. The DFT is too slow for large datasets and `TransformerNUFFT` - should be used instead. Set to `False` to suppress this check. + should be used instead. Set to `False` to suppress this check. The check is not made when a `setup` + is given: the setup decides the transformer. sparse_terms The `SparseTerms` record the `sparse_operator` was accumulated from, if any (set by `from_stream`, `from_sparse_terms` and `apply_sparse_operator_from_chunks`). It @@ -127,6 +132,12 @@ def __init__( unmasked value of `P` is 0 (source pixels seen only there are unconstrained by the data and set by the regularization); no floor is applied. `None` (default) applies no primary beam. + setup + The compute setup (an `aa.Setup` or a setup_id string) this dataset is evaluated with, stored as + `dataset.setup` and carried by `apply_sparse_operator` and `apply_sparse_operator_from_chunks`. A + setup with `transformer="nufft"` replaces a `transformer_class` which is not a `TransformerNUFFT` + class with `TransformerNUFFT`, and any setup supersedes the >10,000-visibility DFT check. The sparse + operator a setup names is attached by `apply_setup()`, not here. Array-free datasets ------------------- @@ -138,6 +149,15 @@ def __init__( `exc.DatasetException` naming the missing input. """ self.real_space_mask = real_space_mask + self.setup = setup_from(setup) + + if ( + self.setup is not None + and self.setup.transformer == "nufft" + and isinstance(transformer_class, type) + and not issubclass(transformer_class, TransformerNUFFT) + ): + transformer_class = TransformerNUFFT super().__init__( data=data, @@ -194,7 +214,11 @@ def __init__( sparse_operator, primary_beam_slim=self.primary_beam_slim ) - if raise_error_dft_visibilities_limit and self.uv_wavelengths is not None: + if ( + raise_error_dft_visibilities_limit + and self.setup is None + and self.uv_wavelengths is not None + ): if ( self.uv_wavelengths.shape[0] > 10000 and transformer_class == TransformerDFT @@ -224,6 +248,7 @@ def from_fits( raise_error_dft_visibilities_limit: bool = True, primary_beam_path=None, primary_beam_hdu=0, + setup: Optional[Union[Setup, str]] = None, ): """ Load an interferometer dataset from multiple .fits files. @@ -272,6 +297,9 @@ def from_fits( primary beam. primary_beam_hdu The HDU index in the primary beam .fits file from which it is loaded. + setup + The compute setup recorded on the dataset (see `Interferometer`); it decides the transformer and + supersedes the >10,000-visibility DFT check. Call `apply_setup()` to attach its sparse operator. Returns ------- @@ -304,6 +332,7 @@ def from_fits( transformer_class=transformer_class, raise_error_dft_visibilities_limit=raise_error_dft_visibilities_limit, primary_beam=primary_beam, + setup=setup, ) @classmethod @@ -691,6 +720,7 @@ def apply_sparse_operator( uv_wavelengths=self.uv_wavelengths, transformer_class=lambda uv_wavelengths, real_space_mask: self.transformer, primary_beam=self.primary_beam, + setup=self.setup, ) pooling_record.log() @@ -790,6 +820,7 @@ def apply_sparse_operator( transformer_class=lambda uv_wavelengths, real_space_mask: self.transformer, sparse_operator=sparse_operator, primary_beam=self.primary_beam, + setup=self.setup, ) def apply_sparse_operator_from_chunks( @@ -959,8 +990,99 @@ def transformer_class(uv_wavelengths, real_space_mask): sparse_operator=sparse_operator, sparse_terms=terms, primary_beam=self.primary_beam, + setup=self.setup, ) + def apply_setup( + self, + setup: Union[Setup, str], + **sparse_operator_kwargs, + ) -> "Interferometer": + """ + Apply a compute setup to the dataset, attaching the transformer and operator it names. + + - A `transformer="nufft"` setup uses `TransformerNUFFT` (the dataset is rebuilt with it + if its transformer is not already one). Other transformer tokens (`"wtilde"`) keep the + dataset's transformer. + - An operator `"sparse"` setup attaches the `InterferometerSparseOperator` via + `apply_sparse_operator()`. One operator serves both backends: the inversion applies it + with its `xp`, so a `numba` setup takes the numba `direct_conv` route under NumPy + (where the route's cost model picks it) and a `jax` setup the JAX FFT route. The + operator is built with `apply_sparse_operator`'s default `use_jax=False` builder + (`finufft`, which imports no JAX), which computes the same operator for both. + - Any other operator (`"dense"`, `"na"`) attaches no sparse operator, dropping an + attached one. + + A setup supersedes the >10,000-visibility DFT check of the constructor: the setup + decides the transformer, so applying one never raises it. + + The setup is stored as `dataset.setup` and carried by `apply_sparse_operator` and + `apply_sparse_operator_from_chunks`. The inversion factory checks the operator against + the setup and the array backend, and raises on a mismatch. + + This method is idempotent: if the transformer and operator already match the setup, + nothing is rebuilt (the dataset is returned as is, or as a shallow copy recording the + new setup when its provenance differs). + + Parameters + ---------- + setup + The `aa.Setup`, or a setup_id string such as `"numba_cpu_sparse_fp64_wtilde"`. + sparse_operator_kwargs + Passed to `apply_sparse_operator()` when a sparse operator is built (e.g. + `batch_size`, `pool_noise_map=True`). + + Returns + ------- + Interferometer + The dataset with the setup applied. + """ + setup = setup_from(setup) + + needs_nufft = setup.transformer == "nufft" and not ( + self.transformer is None or isinstance(self.transformer, TransformerNUFFT) + ) + wants_sparse = setup.operator == "sparse" + has_sparse = self.sparse_operator is not None + + if not needs_nufft and wants_sparse == has_sparse: + if self.setup == setup: + return self + dataset = copy.copy(self) + dataset.setup = setup + return dataset + + self._require( + "apply_setup", + "data", + "noise_map", + "uv_wavelengths", + ) + + if needs_nufft: + transformer_class = TransformerNUFFT + else: + transformer_class = ( + lambda uv_wavelengths, real_space_mask: self.transformer + ) + + dataset = Interferometer( + real_space_mask=self.real_space_mask, + data=self.data, + noise_map=self.noise_map, + uv_wavelengths=self.uv_wavelengths, + transformer_class=transformer_class, + sparse_operator=self.sparse_operator if wants_sparse else None, + sparse_terms=self.sparse_terms if wants_sparse else None, + primary_beam=self.primary_beam, + setup=setup, + ) + + if wants_sparse and dataset.sparse_operator is None: + return dataset.apply_sparse_operator(**sparse_operator_kwargs) + + return dataset + def psf_precision_operator_from( self, chunk_k: int = 2048, diff --git a/autoarray/inversion/inversion/factory.py b/autoarray/inversion/inversion/factory.py index 9b310b56b..cfb8762f5 100644 --- a/autoarray/inversion/inversion/factory.py +++ b/autoarray/inversion/inversion/factory.py @@ -40,6 +40,9 @@ from autoarray.inversion.inversion.imaging.sparse import ( InversionImagingSparse, ) +from autoarray.inversion.inversion.imaging.inversion_imaging_util import ( + ImagingSparseOperator, +) from autoarray.settings import Settings from autoarray.structures.arrays.uniform_2d import Array2D @@ -96,6 +99,141 @@ def inversion_from( ) +def _setup_mismatch_exception(message: str, setup=None) -> exc.InversionException: + """ + The `InversionException` raised when a dataset's operator, its `setup` and the array + backend `xp` of an inversion disagree, ending with how to fix it. + """ + fix = ( + f"call `dataset = dataset.apply_setup({setup.setup_id!r})` so the attached operator " + f"matches the setup, or apply the setup whose backend you are running" + if setup is not None + else "call `dataset.apply_setup(setup)` with the setup you are running, or attach " + "the operator of the backend you are running" + ) + + return exc.InversionException( + f"Operator / setup / backend mismatch: {message}. The inversion refuses to silently " + f"take another linear algebra path. To fix this, {fix}." + ) + + +def _xp_name(xp) -> str: + return "numpy" if xp is np else getattr(xp, "__name__", str(xp)) + + +def _check_imaging_setup_consistency(dataset, xp, use_sparse_operator: bool): + """ + Raise an `InversionException` when an imaging dataset's sparse operator, its `setup` and + the array backend `xp` disagree, rather than silently taking another path. + + The mismatches are: + + - a numba `SparseLinAlgImagingNumba` operator used by an inversion running on JAX (it + has no JAX path); + - an operator of the wrong backend for `dataset.setup` (a JAX `ImagingSparseOperator` + under a `numba` setup, or a numba operator under a `jax` setup); + - a `sparse` setup with no sparse operator attached; + - a non-sparse (`dense`, `na`) setup with a sparse operator attached. + + A JAX `ImagingSparseOperator` used with `xp=np` is not a mismatch (it runs on NumPy, + e.g. for visualization after a JAX fit), nor is a numba operator on a func-list-only + inversion, which deliberately uses the mapping formalism and never touches it. + """ + sparse_operator = getattr(dataset, "sparse_operator", None) + setup = getattr(dataset, "setup", None) + + is_numba_operator = isinstance(sparse_operator, SparseLinAlgImagingNumba) + is_jax_operator = isinstance(sparse_operator, ImagingSparseOperator) + + if is_numba_operator and use_sparse_operator and xp is not np: + raise _setup_mismatch_exception( + f"the imaging dataset carries the numba sparse operator " + f"(SparseLinAlgImagingNumba, from apply_sparse_operator_cpu) but the inversion " + f"runs on {_xp_name(xp)!r}, and the numba operator has no JAX path" + + (f" (dataset.setup is {setup.setup_id!r})" if setup is not None else ""), + setup=setup, + ) + + if setup is None: + return + + if setup.operator == "sparse": + if sparse_operator is None: + raise _setup_mismatch_exception( + f"dataset.setup is {setup.setup_id!r} (operator 'sparse') but the imaging " + f"dataset has no sparse operator attached", + setup=setup, + ) + if setup.backend == "numba" and is_jax_operator: + raise _setup_mismatch_exception( + f"dataset.setup is {setup.setup_id!r} (backend 'numba') but the imaging " + f"dataset carries the JAX sparse operator (ImagingSparseOperator, from " + f"apply_sparse_operator)", + setup=setup, + ) + if setup.backend == "jax" and is_numba_operator: + raise _setup_mismatch_exception( + f"dataset.setup is {setup.setup_id!r} (backend 'jax') but the imaging " + f"dataset carries the numba sparse operator (SparseLinAlgImagingNumba, from " + f"apply_sparse_operator_cpu)", + setup=setup, + ) + elif sparse_operator is not None: + raise _setup_mismatch_exception( + f"dataset.setup is {setup.setup_id!r} (operator {setup.operator!r}) but the " + f"imaging dataset carries a sparse operator " + f"({type(sparse_operator).__name__})", + setup=setup, + ) + + +def _check_interferometer_setup_consistency(dataset, xp): + """ + Raise an `InversionException` when an interferometer dataset's sparse operator, its + `setup` and the array backend `xp` disagree, rather than silently taking another path. + + The interferometer has one `InterferometerSparseOperator` for both backends (the + inversion applies it with its `xp`), so the mismatches are: + + - a `numba` setup with an inversion running on JAX (which would silently take the JAX + FFT route instead of the numba one); + - a `sparse` setup with no sparse operator attached; + - a non-sparse (`dense`, `na`) setup with a sparse operator attached. + + A `jax` setup with `xp=np` is not a mismatch (the operator runs on NumPy, e.g. for + visualization after a JAX fit). + """ + setup = getattr(dataset, "setup", None) + + if setup is None: + return + + sparse_operator = getattr(dataset, "sparse_operator", None) + + if setup.backend == "numba" and xp is not np: + raise _setup_mismatch_exception( + f"dataset.setup is {setup.setup_id!r} (backend 'numba') but the interferometer " + f"inversion runs on {_xp_name(xp)!r}", + setup=setup, + ) + + if setup.operator == "sparse" and sparse_operator is None: + raise _setup_mismatch_exception( + f"dataset.setup is {setup.setup_id!r} (operator 'sparse') but the " + f"interferometer dataset has no sparse operator attached", + setup=setup, + ) + + if setup.operator != "sparse" and sparse_operator is not None: + raise _setup_mismatch_exception( + f"dataset.setup is {setup.setup_id!r} (operator {setup.operator!r}) but the " + f"interferometer dataset carries a sparse operator " + f"({type(sparse_operator).__name__})", + setup=setup, + ) + + def inversion_imaging_from( dataset, linear_obj_list: List[LinearObj], @@ -120,6 +258,9 @@ def inversion_imaging_from( This factory inspects the type of dataset input and settings of the inversion in order to create the appropriate inversion object. + Before routing, the dataset's sparse operator is checked against its `setup` and the array backend `xp`, and an + `InversionException` is raised on a mismatch (see `_check_imaging_setup_consistency`). + Parameters ---------- dataset @@ -147,6 +288,10 @@ def inversion_imaging_from( ): use_sparse_operator = False + _check_imaging_setup_consistency( + dataset=dataset, xp=xp, use_sparse_operator=use_sparse_operator + ) + if dataset.sparse_operator is not None and use_sparse_operator: if isinstance(dataset.sparse_operator, SparseLinAlgImagingNumba): @@ -209,6 +354,9 @@ def inversion_interferometer_from( This factory inspects the type of dataset input and settings of the inversion in order to create the appropriate inversion object. + Before routing, the dataset's sparse operator is checked against its `setup` and the array backend `xp`, and an + `InversionException` is raised on a mismatch (see `_check_interferometer_setup_consistency`). + Parameters ---------- dataset @@ -232,6 +380,8 @@ def inversion_interferometer_from( settings is not None and settings.interferometer_route == "matrix_free" ) + _check_interferometer_setup_consistency(dataset=dataset, xp=xp) + if dataset.sparse_operator is not None: # The matrix-free route is opt-in only. `InversionInterferometerMatrixFree` raises on diff --git a/autoarray/setup/setup.py b/autoarray/setup/setup.py index 18c883912..bf72fac9b 100644 --- a/autoarray/setup/setup.py +++ b/autoarray/setup/setup.py @@ -15,6 +15,7 @@ """ import functools +import logging import os from dataclasses import dataclass from pathlib import Path @@ -47,6 +48,29 @@ EXPLICIT_RULE_ID = f"explicit:{SETUP_ENV_VAR}" +logger = logging.getLogger(__name__) + + +def _default_thread_count() -> int: + """ + The thread count :meth:`Setup.apply_threads` uses when none is given: the + ``NUMBA_NUM_THREADS`` environment variable when it is a positive integer, else the + cores this process may use (``Environment.detect().cores``, i.e. + :func:`autonerves.environment.detect_cores`). + """ + value = os.environ.get("NUMBA_NUM_THREADS") + if value is not None: + try: + n = int(value) + if n > 0: + return n + except ValueError: + pass + + from autonerves.environment import detect_cores + + return detect_cores() + def _validate_token(name: str, value: Optional[str], allowed=None, optional=False): if value is None and optional: @@ -66,6 +90,26 @@ def _validate_token(name: str, value: Optional[str], allowed=None, optional=Fals ) +def setup_from(setup) -> Optional["Setup"]: + """ + A `Setup` from a `Setup`, a setup_id string (via :meth:`Setup.from_setup_id`) or + `None` (returned unchanged), as accepted by the datasets' `setup` inputs and + `apply_setup` methods. + + Raises + ------ + ValueError + If `setup` is neither a `Setup`, a setup_id string nor `None`. + """ + if setup is None or isinstance(setup, Setup): + return setup + if isinstance(setup, str): + return Setup.from_setup_id(setup) + raise ValueError( + f"A setup must be an aa.Setup or a setup_id string, got {setup!r}." + ) + + @functools.lru_cache(maxsize=None) def _load_rules(path: str = str(RULES_PATH)) -> Tuple[dict, ...]: """ @@ -209,6 +253,94 @@ def from_setup_id(cls, setup_id: str, **provenance) -> "Setup": **provenance, ) + def apply_threads(self, n: Optional[int] = None) -> Optional[int]: + """ + Pin the run-time thread pools of this process to ``n`` threads, and return the + thread count actually applied. + + This sets ``numba.set_num_threads(n)`` (``n`` clipped to + ``numba.config.NUMBA_NUM_THREADS``, the most threads numba may use in this + process) and, when ``threadpoolctl`` is installed, limits the BLAS / OpenMP + pools via ``threadpoolctl.threadpool_limits(n)`` (``OMP_NUM_THREADS`` does not + cap numba, and numba does not cap BLAS, so both are set). + + It is safe to call inside multiprocessing workers: it launches no ``prange`` + kernel, never raises (a failure is logged as a warning and the remaining pools + are still pinned) and is idempotent, so calling it once per worker and again in + the parent is harmless. In a process that may not launch numba parallel kernels + (a multiprocessing worker, see ``autoarray.numba_util.parallel_kernel_allowed``) + numba runs its serial kernels, so its thread count is left alone: setting it + would initialise a numba threading layer in the worker for nothing. Only the + BLAS / OpenMP pools are limited there. + + The setup does not choose the thread count; this is the per-process half of + applying a setup (the dataset half is ``dataset.apply_setup(setup)``). + + Parameters + ---------- + n + The number of threads. ``None`` takes the ``NUMBA_NUM_THREADS`` environment + variable when set, else the cores this process may use + (``Environment.detect().cores``). Values below 1 are raised to 1. + + Returns + ------- + The thread count applied: the numba thread count when it was set, else the + count given to ``threadpoolctl``; ``None`` if neither could be applied. + """ + try: + n = _default_thread_count() if n is None else int(n) + except Exception as e: # never raise inside a worker + logger.warning(f"Setup.apply_threads could not resolve a thread count: {e}") + return None + + n = max(1, n) + applied = None + + try: + from autoarray import numba_util + + numba_allowed = numba_util.parallel_kernel_allowed() + except Exception: + numba_allowed = False + + numba = None + + if numba_allowed: + try: + import numba + except ImportError: + numba = None + + if numba is not None: + try: + n_numba = min(n, int(numba.config.NUMBA_NUM_THREADS)) + if numba.get_num_threads() != n_numba: + numba.set_num_threads(n_numba) + applied = n_numba + except Exception as e: + logger.warning( + f"Setup.apply_threads could not set numba to {n} threads: {e}" + ) + + try: + import threadpoolctl + except ImportError: + threadpoolctl = None + + if threadpoolctl is not None: + try: + threadpoolctl.threadpool_limits(limits=n) + if applied is None: + applied = n + except Exception as e: + logger.warning( + f"Setup.apply_threads could not limit the BLAS / OpenMP thread " + f"pools to {n} threads: {e}" + ) + + return applied + @classmethod def auto( cls, diff --git a/test_autoarray/dataset/imaging/test_dataset.py b/test_autoarray/dataset/imaging/test_dataset.py index 4ecc9fe81..9e95cdcbb 100644 --- a/test_autoarray/dataset/imaging/test_dataset.py +++ b/test_autoarray/dataset/imaging/test_dataset.py @@ -600,3 +600,141 @@ def test__convolve_over_sample_size__sparse_operator_cpu_guard(): with pytest.raises(aa.exc.DatasetException): dataset.apply_sparse_operator_cpu() + + +def test__apply_setup__sparse_numba_and_jax_attach_their_operator(masked_imaging_7x7): + from autoarray.inversion.inversion.imaging_numba.inversion_imaging_numba_util import ( + SparseLinAlgImagingNumba, + ) + + dataset = masked_imaging_7x7.apply_setup(setup="numba_cpu_sparse_fp64") + + assert isinstance(dataset.sparse_operator, SparseLinAlgImagingNumba) + assert dataset.setup == aa.Setup.from_setup_id("numba_cpu_sparse_fp64") + + dataset = masked_imaging_7x7.apply_setup( + setup=aa.Setup.from_setup_id("jax_cpu_sparse_fp64") + ) + + assert isinstance(dataset.sparse_operator, aa.ImagingSparseOperator) + assert dataset.setup.setup_id == "jax_cpu_sparse_fp64" + + +def test__apply_setup__dense_attaches_no_operator_and_drops_one(masked_imaging_7x7): + dataset = masked_imaging_7x7.apply_sparse_operator_cpu().apply_setup( + setup="jax_gpu_dense_fp64" + ) + + assert dataset.sparse_operator is None + assert dataset.setup.setup_id == "jax_gpu_dense_fp64" + + dataset = masked_imaging_7x7.apply_setup(setup="jax_cpu_na_fp64") + + assert dataset.sparse_operator is None + + +def test__apply_setup__idempotent(masked_imaging_7x7): + dataset = masked_imaging_7x7.apply_setup(setup="numba_cpu_sparse_fp64") + + assert dataset.apply_setup(setup="numba_cpu_sparse_fp64") is dataset + + # A setup of the same tuple but other provenance reuses the operator. + setup_auto = aa.Setup.from_setup_id( + "numba_cpu_sparse_fp64", rule_id="pulse-decision" + ) + dataset_auto = dataset.apply_setup(setup=setup_auto) + + assert dataset_auto is not dataset + assert dataset_auto.setup == setup_auto + assert dataset_auto.sparse_operator is dataset.sparse_operator + + # An operator already attached by hand is reused. + dataset_cpu = masked_imaging_7x7.apply_sparse_operator_cpu() + + assert ( + dataset_cpu.apply_setup(setup="numba_cpu_sparse_fp64").sparse_operator + is dataset_cpu.sparse_operator + ) + + dataset_dense = masked_imaging_7x7.apply_setup(setup="jax_gpu_dense_fp64") + + assert dataset_dense.apply_setup(setup="jax_gpu_dense_fp64") is dataset_dense + + +def test__apply_setup__survives_apply_mask_noise_scaling_and_over_sampling( + imaging_7x7, mask_2d_7x7, caplog +): + from autoarray.inversion.inversion.imaging_numba.inversion_imaging_numba_util import ( + SparseLinAlgImagingNumba, + ) + + dataset = imaging_7x7.apply_setup(setup="numba_cpu_sparse_fp64") + + with caplog.at_level(logging.WARNING, logger="autoarray.dataset.imaging.dataset"): + masked = dataset.apply_mask(mask=mask_2d_7x7) + + # The operator is rebuilt for the new mask, silently. + assert "sparse operator" not in caplog.text + assert masked.setup == dataset.setup + assert isinstance(masked.sparse_operator, SparseLinAlgImagingNumba) + assert masked.sparse_operator is not dataset.sparse_operator + assert masked.sparse_operator.psf_precision_operator_sparse == pytest.approx( + masked.apply_sparse_operator_cpu().sparse_operator.psf_precision_operator_sparse, + 1.0e-8, + ) + + with caplog.at_level(logging.WARNING, logger="autoarray.dataset.imaging.dataset"): + scaled = masked.apply_noise_scaling(mask=mask_2d_7x7, noise_value=10.0) + + assert "sparse operator" not in caplog.text + assert scaled.setup == dataset.setup + assert isinstance(scaled.sparse_operator, SparseLinAlgImagingNumba) + assert scaled.sparse_operator is not masked.sparse_operator + + over_sampled = masked.apply_over_sampling(over_sample_size_lp=2) + + assert over_sampled.setup == dataset.setup + assert over_sampled.sparse_operator is masked.sparse_operator + + # A dense setup is carried and still attaches nothing. + dense = imaging_7x7.apply_setup(setup="jax_gpu_dense_fp64").apply_mask( + mask=mask_2d_7x7 + ) + + assert dense.setup.setup_id == "jax_gpu_dense_fp64" + assert dense.sparse_operator is None + + +def test__apply_setup__sparse_operator_builders_carry_setup(masked_imaging_7x7): + dataset = masked_imaging_7x7.apply_setup(setup="jax_gpu_dense_fp64") + + assert dataset.apply_sparse_operator_cpu().setup == dataset.setup + assert dataset.apply_sparse_operator().setup == dataset.setup + + +def test__apply_setup__invalid_inputs_raise(masked_imaging_7x7): + with pytest.raises(exc.DatasetException): + masked_imaging_7x7.apply_setup(setup="numpy_cpu_sparse_fp64") + + dataset_no_psf = aa.Imaging( + data=masked_imaging_7x7.data, + noise_map=masked_imaging_7x7.noise_map, + ) + + with pytest.raises(exc.DatasetException): + dataset_no_psf.apply_setup(setup="numba_cpu_sparse_fp64") + + with pytest.raises(ValueError): + masked_imaging_7x7.apply_setup(setup="cpu") + + +def test__setup__constructor_input_is_stored(masked_imaging_7x7): + dataset = aa.Imaging( + data=masked_imaging_7x7.data, + noise_map=masked_imaging_7x7.noise_map, + psf=masked_imaging_7x7.psf, + setup="jax_gpu_dense_fp64", + ) + + assert dataset.setup == aa.Setup.from_setup_id("jax_gpu_dense_fp64") + assert masked_imaging_7x7.setup is None diff --git a/test_autoarray/dataset/interferometer/test_dataset.py b/test_autoarray/dataset/interferometer/test_dataset.py index c12d0e799..b7041dc5a 100644 --- a/test_autoarray/dataset/interferometer/test_dataset.py +++ b/test_autoarray/dataset/interferometer/test_dataset.py @@ -1493,3 +1493,166 @@ def test__primary_beam__propagates_through_every_reconstruction_site( _assert_carries_primary_beam(dataset_cached, primary_beam.array) assert operator.primary_beam_slim is None + + +def _large_interferometer_inputs(n_visibilities=10_001): + data = aa.Visibilities(visibilities=np.ones(n_visibilities) + 1j) + noise_map = aa.VisibilitiesNoiseMap( + visibilities=np.ones(n_visibilities) + 1j * np.ones(n_visibilities) + ) + uv_wavelengths = ( + np.random.default_rng(seed=1).normal(size=(n_visibilities, 2)) * 1000.0 + ) + return data, noise_map, uv_wavelengths + + +def test__apply_setup__sparse_wtilde_attaches_operator_and_keeps_transformer( + interferometer_7, +): + for setup_id in ("numba_cpu_sparse_fp64_wtilde", "jax_gpu_sparse_fp64_wtilde"): + dataset = interferometer_7.apply_setup(setup=setup_id) + + assert isinstance(dataset.sparse_operator, aa.InterferometerSparseOperator) + assert type(dataset.transformer) is transformer.TransformerDFT + assert dataset.setup.setup_id == setup_id + + # The operator equals the one apply_sparse_operator builds. + dataset = interferometer_7.apply_setup(setup="numba_cpu_sparse_fp64_wtilde") + reference = interferometer_7.apply_sparse_operator() + + assert dataset.sparse_operator.dirty_image == pytest.approx( + reference.sparse_operator.dirty_image, 1.0e-8 + ) + + +def test__apply_setup__nufft_uses_nufft_transformer_and_drops_operator( + interferometer_7, +): + dataset = interferometer_7.apply_sparse_operator().apply_setup( + setup="jax_cpu_dense_fp64_nufft" + ) + + assert type(dataset.transformer) is transformer.TransformerNUFFT + assert dataset.sparse_operator is None + assert dataset.setup.setup_id == "jax_cpu_dense_fp64_nufft" + + +def test__apply_setup__idempotent(interferometer_7): + dataset = interferometer_7.apply_setup(setup="numba_cpu_sparse_fp64_wtilde") + + assert dataset.apply_setup(setup="numba_cpu_sparse_fp64_wtilde") is dataset + + setup_auto = aa.Setup.from_setup_id( + "numba_cpu_sparse_fp64_wtilde", rule_id="pulse-decision" + ) + dataset_auto = dataset.apply_setup(setup=setup_auto) + + assert dataset_auto.setup == setup_auto + assert dataset_auto.sparse_operator is dataset.sparse_operator + + dataset_nufft = interferometer_7.apply_setup(setup="jax_cpu_dense_fp64_nufft") + + assert dataset_nufft.apply_setup(setup="jax_cpu_dense_fp64_nufft") is dataset_nufft + + +def test__apply_setup__carried_by_apply_sparse_operator(interferometer_7): + dataset = interferometer_7.apply_setup(setup="jax_cpu_dense_fp64_nufft") + + assert dataset.apply_sparse_operator().setup == dataset.setup + assert ( + dataset.apply_sparse_operator(pool_noise_map=True).setup == dataset.setup + ) + + +def test__setup__supersedes_dft_visibilities_limit(mask_2d_7x7): + data, noise_map, uv_wavelengths = _large_interferometer_inputs() + + # Without a setup the guard is unchanged. + with pytest.raises(aa.exc.DatasetException): + aa.Interferometer( + data=data, + noise_map=noise_map, + uv_wavelengths=uv_wavelengths, + real_space_mask=mask_2d_7x7, + transformer_class=transformer.TransformerDFT, + ) + + # A nufft setup decides the transformer: NUFFT, not the DFT. + dataset = aa.Interferometer( + data=data, + noise_map=noise_map, + uv_wavelengths=uv_wavelengths, + real_space_mask=mask_2d_7x7, + transformer_class=transformer.TransformerDFT, + setup="jax_cpu_dense_fp64_nufft", + ) + + assert type(dataset.transformer) is transformer.TransformerNUFFT + + # Any setup supersedes the guard; a wtilde setup keeps the transformer it is given. + dataset = aa.Interferometer( + data=data, + noise_map=noise_map, + uv_wavelengths=uv_wavelengths, + real_space_mask=mask_2d_7x7, + transformer_class=transformer.TransformerDFT, + setup=aa.Setup.from_setup_id("numba_cpu_sparse_fp64_wtilde"), + ) + + assert type(dataset.transformer) is transformer.TransformerDFT + assert dataset.setup.setup_id == "numba_cpu_sparse_fp64_wtilde" + + # apply_setup on a large DFT dataset (built with the guard off) never raises it. + dataset = aa.Interferometer( + data=data, + noise_map=noise_map, + uv_wavelengths=uv_wavelengths, + real_space_mask=mask_2d_7x7, + transformer_class=transformer.TransformerDFT, + raise_error_dft_visibilities_limit=False, + ).apply_setup(setup="jax_cpu_dense_fp64_nufft") + + assert type(dataset.transformer) is transformer.TransformerNUFFT + + +def test__from_fits__setup_supersedes_dft_visibilities_limit(tmp_path, mask_2d_7x7): + from astropy.io import fits + + n_visibilities = 10_001 + paths = [] + for name in ("data", "noise_map", "uv_wavelengths"): + path = tmp_path / f"{name}.fits" + fits.PrimaryHDU(data=np.ones((n_visibilities, 2))).writeto(path) + paths.append(path) + + dataset = aa.Interferometer.from_fits( + data_path=paths[0], + noise_map_path=paths[1], + uv_wavelengths_path=paths[2], + real_space_mask=mask_2d_7x7, + transformer_class=transformer.TransformerDFT, + setup="jax_cpu_dense_fp64_nufft", + ) + + assert type(dataset.transformer) is transformer.TransformerNUFFT + assert dataset.setup.setup_id == "jax_cpu_dense_fp64_nufft" + + +def test__apply_setup__array_free_dataset(mask_2d_7x7, interferometer_7): + chunks = [ + ( + interferometer_7.uv_wavelengths, + interferometer_7.data.array, + interferometer_7.noise_map.array, + ) + ] + dataset = aa.Interferometer.from_stream(chunks, real_space_mask=mask_2d_7x7) + + # The operator it carries already matches a sparse setup. + dataset_sparse = dataset.apply_setup(setup="numba_cpu_sparse_fp64_wtilde") + + assert dataset_sparse.sparse_operator is dataset.sparse_operator + + # A dense setup needs the visibilities it does not have. + with pytest.raises(aa.exc.DatasetException): + dataset.apply_setup(setup="jax_cpu_dense_fp64_nufft") diff --git a/test_autoarray/inversion/inversion/test_factory.py b/test_autoarray/inversion/inversion/test_factory.py index 0d8a0b011..609bd15ab 100644 --- a/test_autoarray/inversion/inversion/test_factory.py +++ b/test_autoarray/inversion/inversion/test_factory.py @@ -8,6 +8,9 @@ from autoarray.inversion.inversion.imaging_numba.sparse import ( InversionImagingSparseNumba, ) +from autoarray.inversion.inversion.interferometer_numba.sparse import ( + InversionInterferometerSparseNumba, +) def test__inversion_imaging__via_linear_obj_func_list(masked_imaging_7x7_no_blur): @@ -985,3 +988,181 @@ def per_element(n): # A power of two is the cheapest per element of its size class. assert per_element(512) < per_element(510) + + +def _jnp(): + return pytest.importorskip("jax.numpy") + + +def test__setup_consistency__imaging_numba_operator_under_jax_raises( + masked_imaging_7x7_no_blur, rectangular_mapper_7x7_3x3 +): + jnp = _jnp() + + dataset = masked_imaging_7x7_no_blur.apply_sparse_operator_cpu() + + with pytest.raises(aa.exc.InversionException, match="SparseLinAlgImagingNumba"): + aa.Inversion( + dataset=dataset, linear_obj_list=[rectangular_mapper_7x7_3x3], xp=jnp + ) + + +def test__setup_consistency__imaging_jax_operator_under_numba_setup_raises( + masked_imaging_7x7_no_blur, rectangular_mapper_7x7_3x3 +): + dataset = masked_imaging_7x7_no_blur.apply_setup( + setup="numba_cpu_sparse_fp64" + ).apply_sparse_operator() + + with pytest.raises(aa.exc.InversionException, match="numba_cpu_sparse_fp64"): + aa.Inversion(dataset=dataset, linear_obj_list=[rectangular_mapper_7x7_3x3]) + + +def test__setup_consistency__imaging_numba_operator_under_jax_setup_raises( + masked_imaging_7x7_no_blur, rectangular_mapper_7x7_3x3 +): + dataset = masked_imaging_7x7_no_blur.apply_setup( + setup="jax_cpu_sparse_fp64" + ).apply_sparse_operator_cpu() + + with pytest.raises(aa.exc.InversionException, match="apply_setup"): + aa.Inversion(dataset=dataset, linear_obj_list=[rectangular_mapper_7x7_3x3]) + + +def test__setup_consistency__imaging_sparse_setup_without_operator_raises( + masked_imaging_7x7_no_blur, rectangular_mapper_7x7_3x3 +): + dataset = copy.copy( + masked_imaging_7x7_no_blur.apply_setup(setup="numba_cpu_sparse_fp64") + ) + dataset.sparse_operator = None + + with pytest.raises(aa.exc.InversionException, match="no sparse operator"): + aa.Inversion(dataset=dataset, linear_obj_list=[rectangular_mapper_7x7_3x3]) + + +def test__setup_consistency__imaging_dense_setup_with_operator_raises( + masked_imaging_7x7_no_blur, rectangular_mapper_7x7_3x3 +): + dataset = masked_imaging_7x7_no_blur.apply_setup( + setup="jax_gpu_dense_fp64" + ).apply_sparse_operator_cpu() + + with pytest.raises(aa.exc.InversionException, match="jax_gpu_dense_fp64"): + aa.Inversion(dataset=dataset, linear_obj_list=[rectangular_mapper_7x7_3x3]) + + +def test__setup_consistency__imaging_matched_setups_route_as_before( + masked_imaging_7x7_no_blur, rectangular_mapper_7x7_3x3 +): + inversion = aa.Inversion( + dataset=masked_imaging_7x7_no_blur.apply_setup(setup="numba_cpu_sparse_fp64"), + linear_obj_list=[rectangular_mapper_7x7_3x3], + ) + + assert isinstance(inversion, InversionImagingSparseNumba) + assert inversion.log_det_curvature_reg_matrix_term == pytest.approx( + 7.257175708246, 1.0e-4 + ) + + inversion = aa.Inversion( + dataset=masked_imaging_7x7_no_blur.apply_setup(setup="jax_gpu_dense_fp64"), + linear_obj_list=[rectangular_mapper_7x7_3x3], + ) + + assert isinstance(inversion, aa.InversionImagingMapping) + + # A JAX operator applied with NumPy (e.g. visualization after a JAX fit) is legitimate. + inversion = aa.Inversion( + dataset=masked_imaging_7x7_no_blur.apply_setup(setup="jax_cpu_sparse_fp64"), + linear_obj_list=[rectangular_mapper_7x7_3x3], + ) + + assert isinstance(inversion, aa.InversionImagingSparse) + + # A func-list-only inversion keeps the mapping formalism with a numba operator, + # even under JAX, since it never touches the operator. + jnp = _jnp() + + grid = aa.Grid2D.from_mask(mask=masked_imaging_7x7_no_blur.mask) + linear_obj = aa.m.MockLinearObjFuncList( + parameters=1, grid=grid, mapping_matrix=np.full(fill_value=0.5, shape=(9, 1)) + ) + + inversion = aa.Inversion( + dataset=masked_imaging_7x7_no_blur.apply_setup(setup="numba_cpu_sparse_fp64"), + linear_obj_list=[linear_obj], + xp=jnp, + ) + + assert isinstance(inversion, aa.InversionImagingMapping) + + +def test__setup_consistency__interferometer_numba_setup_under_jax_raises( + interferometer_7_no_fft, rectangular_mapper_7x7_3x3 +): + jnp = _jnp() + + dataset = interferometer_7_no_fft.apply_setup(setup="numba_cpu_sparse_fp64_wtilde") + + with pytest.raises(aa.exc.InversionException, match="backend 'numba'"): + aa.Inversion( + dataset=dataset, linear_obj_list=[rectangular_mapper_7x7_3x3], xp=jnp + ) + + +def test__setup_consistency__interferometer_sparse_setup_without_operator_raises( + interferometer_7_no_fft, rectangular_mapper_7x7_3x3 +): + dataset = copy.copy( + interferometer_7_no_fft.apply_setup(setup="numba_cpu_sparse_fp64_wtilde") + ) + dataset.sparse_operator = None + + with pytest.raises(aa.exc.InversionException, match="no sparse operator"): + aa.Inversion(dataset=dataset, linear_obj_list=[rectangular_mapper_7x7_3x3]) + + +def test__setup_consistency__interferometer_dense_setup_with_operator_raises( + interferometer_7_no_fft, rectangular_mapper_7x7_3x3 +): + dataset = interferometer_7_no_fft.apply_setup( + setup="jax_cpu_dense_fp64_nufft" + ).apply_sparse_operator() + + with pytest.raises(aa.exc.InversionException, match="jax_cpu_dense_fp64_nufft"): + aa.Inversion(dataset=dataset, linear_obj_list=[rectangular_mapper_7x7_3x3]) + + +def test__setup_consistency__interferometer_matched_setups_route_as_before( + interferometer_7_no_fft, rectangular_mapper_7x7_3x3 +): + inversion = aa.Inversion( + dataset=interferometer_7_no_fft.apply_setup( + setup="numba_cpu_sparse_fp64_wtilde" + ), + linear_obj_list=[rectangular_mapper_7x7_3x3], + ) + + assert isinstance( + inversion, (aa.InversionInterferometerSparse, InversionInterferometerSparseNumba) + ) + + inversion_mapping = aa.Inversion( + dataset=interferometer_7_no_fft, + linear_obj_list=[rectangular_mapper_7x7_3x3], + ) + + assert inversion.log_det_curvature_reg_matrix_term == pytest.approx( + inversion_mapping.log_det_curvature_reg_matrix_term, 1.0e-4 + ) + + # A jax setup applied with NumPy is legitimate. + inversion = aa.Inversion( + dataset=interferometer_7_no_fft.apply_setup(setup="jax_gpu_sparse_fp64_wtilde"), + linear_obj_list=[rectangular_mapper_7x7_3x3], + ) + + assert inversion.log_det_curvature_reg_matrix_term == pytest.approx( + inversion_mapping.log_det_curvature_reg_matrix_term, 1.0e-4 + ) diff --git a/test_autoarray/setup/test_setup.py b/test_autoarray/setup/test_setup.py index 08ea0418e..f76d2779c 100644 --- a/test_autoarray/setup/test_setup.py +++ b/test_autoarray/setup/test_setup.py @@ -348,3 +348,152 @@ def test__rule_table__parity_with_pulse(tmp_path): assert regenerated == RULES assert generate_rules.check(pulse, setup_py.RULES_PATH) + + +class _FakeNumba: + def __init__(self, max_threads=8, current=8, fail=False): + self.config = type("config", (), {"NUMBA_NUM_THREADS": max_threads}) + self.current = current + self.fail = fail + self.calls = [] + + def get_num_threads(self): + return self.current + + def set_num_threads(self, n): + if self.fail: + raise RuntimeError("numba refused") + self.calls.append(n) + self.current = n + + +class _FakeThreadpoolctl: + def __init__(self, fail=False): + self.fail = fail + self.calls = [] + + def threadpool_limits(self, limits): + if self.fail: + raise RuntimeError("threadpoolctl refused") + self.calls.append(limits) + + +def _patch_thread_modules(monkeypatch, numba=None, threadpoolctl=None): + import sys + + monkeypatch.setitem(sys.modules, "numba", numba) + monkeypatch.setitem(sys.modules, "threadpoolctl", threadpoolctl) + + +def test__apply_threads__sets_numba_and_threadpoolctl(monkeypatch): + numba = _FakeNumba(max_threads=8, current=8) + threadpoolctl = _FakeThreadpoolctl() + _patch_thread_modules(monkeypatch, numba=numba, threadpoolctl=threadpoolctl) + + setup = aa.Setup.from_setup_id("numba_cpu_sparse_fp64") + + assert setup.apply_threads(4) == 4 + assert numba.calls == [4] + assert threadpoolctl.calls == [4] + + # Idempotent: numba is not reset when already at the count. + assert setup.apply_threads(4) == 4 + assert numba.calls == [4] + + +def test__apply_threads__clips_to_numba_maximum_and_floors_at_one(monkeypatch): + numba = _FakeNumba(max_threads=8, current=8) + threadpoolctl = _FakeThreadpoolctl() + _patch_thread_modules(monkeypatch, numba=numba, threadpoolctl=threadpoolctl) + + setup = aa.Setup.from_setup_id("numba_cpu_sparse_fp64") + + assert setup.apply_threads(64) == 8 + assert threadpoolctl.calls == [64] + + assert setup.apply_threads(0) == 1 + assert numba.calls[-1] == 1 + + +def test__apply_threads__default_from_environment(monkeypatch): + numba = _FakeNumba(max_threads=16, current=16) + _patch_thread_modules(monkeypatch, numba=numba, threadpoolctl=None) + + setup = aa.Setup.from_setup_id("numba_cpu_sparse_fp64") + + monkeypatch.setenv("NUMBA_NUM_THREADS", "3") + assert setup.apply_threads() == 3 + + monkeypatch.delenv("NUMBA_NUM_THREADS") + monkeypatch.setattr("autonerves.environment.detect_cores", lambda: 5) + assert setup.apply_threads() == 5 + + +def test__apply_threads__threadpoolctl_missing(monkeypatch): + numba = _FakeNumba(max_threads=8, current=8) + _patch_thread_modules(monkeypatch, numba=numba, threadpoolctl=None) + + setup = aa.Setup.from_setup_id("numba_cpu_sparse_fp64") + + assert setup.apply_threads(2) == 2 + assert numba.calls == [2] + + +def test__apply_threads__never_raises(monkeypatch, caplog): + numba = _FakeNumba(max_threads=8, current=8, fail=True) + threadpoolctl = _FakeThreadpoolctl(fail=True) + _patch_thread_modules(monkeypatch, numba=numba, threadpoolctl=threadpoolctl) + + setup = aa.Setup.from_setup_id("numba_cpu_sparse_fp64") + + assert setup.apply_threads(2) is None + assert "numba" in caplog.text + assert "BLAS" in caplog.text + + # Without numba, the threadpoolctl count is returned. + _patch_thread_modules( + monkeypatch, numba=None, threadpoolctl=_FakeThreadpoolctl() + ) + assert setup.apply_threads(2) == 2 + + # An unparseable count is logged, not raised. + assert setup.apply_threads("many") is None + + +def test__apply_threads__real_numba(): + numba = pytest.importorskip("numba") + + setup = aa.Setup.from_setup_id("numba_cpu_sparse_fp64") + + previous = numba.get_num_threads() + try: + assert setup.apply_threads(1) == 1 + assert numba.get_num_threads() == 1 + finally: + numba.set_num_threads(previous) + + +def test__setup_from__accepts_setup_setup_id_or_none(): + setup = aa.Setup.from_setup_id("jax_gpu_dense_fp64") + + assert setup_py.setup_from(setup) is setup + assert setup_py.setup_from("jax_gpu_dense_fp64") == setup + assert setup_py.setup_from(None) is None + + with pytest.raises(ValueError): + setup_py.setup_from(3) + + +def test__apply_threads__worker_leaves_numba_alone(monkeypatch): + numba = _FakeNumba(max_threads=8, current=8) + threadpoolctl = _FakeThreadpoolctl() + _patch_thread_modules(monkeypatch, numba=numba, threadpoolctl=threadpoolctl) + monkeypatch.setattr( + "autoarray.numba_util.parallel_kernel_allowed", lambda: False + ) + + setup = aa.Setup.from_setup_id("numba_cpu_sparse_fp64") + + assert setup.apply_threads(2) == 2 + assert numba.calls == [] + assert threadpoolctl.calls == [2] From 3aebdb1945fb6f785c346ba2c83619ffeb761cbc Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Tue, 24 Nov 2026 10:46:35 +0000 Subject: [PATCH 2/2] test: skip the JAX parts of the 5B-2 setup tests when jax is absent The unittest-nojax leg failed on five new tests that build the JAX ImagingSparseOperator. Guard their JAX parts with pytest.importorskip, as other test modules do; the numba halves still run without jax. Co-Authored-By: Claude Opus 5.5 --- test_autoarray/dataset/imaging/test_dataset.py | 4 ++++ test_autoarray/inversion/inversion/test_factory.py | 6 ++++++ 2 files changed, 10 insertions(+) diff --git a/test_autoarray/dataset/imaging/test_dataset.py b/test_autoarray/dataset/imaging/test_dataset.py index 9e95cdcbb..b5fc1971c 100644 --- a/test_autoarray/dataset/imaging/test_dataset.py +++ b/test_autoarray/dataset/imaging/test_dataset.py @@ -612,6 +612,8 @@ def test__apply_setup__sparse_numba_and_jax_attach_their_operator(masked_imaging assert isinstance(dataset.sparse_operator, SparseLinAlgImagingNumba) assert dataset.setup == aa.Setup.from_setup_id("numba_cpu_sparse_fp64") + pytest.importorskip("jax") # the JAX ImagingSparseOperator needs jax + dataset = masked_imaging_7x7.apply_setup( setup=aa.Setup.from_setup_id("jax_cpu_sparse_fp64") ) @@ -706,6 +708,8 @@ def test__apply_setup__survives_apply_mask_noise_scaling_and_over_sampling( def test__apply_setup__sparse_operator_builders_carry_setup(masked_imaging_7x7): + pytest.importorskip("jax") # the JAX ImagingSparseOperator needs jax + dataset = masked_imaging_7x7.apply_setup(setup="jax_gpu_dense_fp64") assert dataset.apply_sparse_operator_cpu().setup == dataset.setup diff --git a/test_autoarray/inversion/inversion/test_factory.py b/test_autoarray/inversion/inversion/test_factory.py index 609bd15ab..e0f426b8d 100644 --- a/test_autoarray/inversion/inversion/test_factory.py +++ b/test_autoarray/inversion/inversion/test_factory.py @@ -1010,6 +1010,8 @@ def test__setup_consistency__imaging_numba_operator_under_jax_raises( def test__setup_consistency__imaging_jax_operator_under_numba_setup_raises( masked_imaging_7x7_no_blur, rectangular_mapper_7x7_3x3 ): + pytest.importorskip("jax") # the JAX ImagingSparseOperator needs jax + dataset = masked_imaging_7x7_no_blur.apply_setup( setup="numba_cpu_sparse_fp64" ).apply_sparse_operator() @@ -1021,6 +1023,8 @@ def test__setup_consistency__imaging_jax_operator_under_numba_setup_raises( def test__setup_consistency__imaging_numba_operator_under_jax_setup_raises( masked_imaging_7x7_no_blur, rectangular_mapper_7x7_3x3 ): + pytest.importorskip("jax") # the JAX ImagingSparseOperator needs jax + dataset = masked_imaging_7x7_no_blur.apply_setup( setup="jax_cpu_sparse_fp64" ).apply_sparse_operator_cpu() @@ -1072,6 +1076,8 @@ def test__setup_consistency__imaging_matched_setups_route_as_before( assert isinstance(inversion, aa.InversionImagingMapping) + pytest.importorskip("jax") # the JAX ImagingSparseOperator needs jax + # A JAX operator applied with NumPy (e.g. visualization after a JAX fit) is legitimate. inversion = aa.Inversion( dataset=masked_imaging_7x7_no_blur.apply_setup(setup="jax_cpu_sparse_fp64"),