From 56c25cc8db4e8e6056b98900592a73d92d59a428 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Tue, 24 Nov 2026 13:33:55 +0000 Subject: [PATCH] feat: lazy, size-gated sparse operator on the dataset (5B-3) Imaging.sparse_operator_for / Interferometer.sparse_operator_for return the attached operator, else (policy on) build the designated sparse operator once and cache it on the real dataset: numba for imaging, NUFFT w-tilde for interferometer (chunked above a 1e6-visibility budget). Never built under JAX, inside multiprocessing workers, with an explicit dense setup or without a pixelization; real != imaginary noise skips with a one-time warning and never pools. Policy general.yaml inversion: lazy_sparse_operator (default "off") or PYAUTO_SETUP=auto. Closes #711 (likelihood-lifecycle phase 5B-3). Co-Authored-By: Claude Opus 5.5 --- autoarray/config/general.yaml | 2 + autoarray/dataset/abstract/dataset.py | 4 + autoarray/dataset/imaging/dataset.py | 105 +++- autoarray/dataset/interferometer/dataset.py | 137 +++++ autoarray/dataset/lazy_operator.py | 186 +++++++ autoarray/settings.py | 39 ++ .../inversion/inversion/test_lazy_operator.py | 471 ++++++++++++++++++ 7 files changed, 942 insertions(+), 2 deletions(-) create mode 100644 autoarray/dataset/lazy_operator.py create mode 100644 test_autoarray/inversion/inversion/test_lazy_operator.py diff --git a/autoarray/config/general.yaml b/autoarray/config/general.yaml index df2bc5502..781576325 100644 --- a/autoarray/config/general.yaml +++ b/autoarray/config/general.yaml @@ -21,6 +21,8 @@ inversion: interferometer_numba_nnz_per_source_max: null # How a NumPy (xp=np) single-mapper interferometer inversion chooses between the numba `direct_conv` curvature path (InversionInterferometerSparseNumba) and the FFT one (InversionInterferometerSparse). null (default) = cost model: predicts both routes' single-thread time from source pixels S, total mapping non-zeros and the extent rectangle (FFT ~ S x rfft2+irfft2 cost of the padded (2ny,2nx) extent, direct_conv ~ nnz x ny x nx) and picks the faster; calibrated on autolens_profiling#226 and the Aris 512x512 mask (PyAutoArray#628). A positive value is a hard gate in mean non-zeros per source column (mapper.pix_sizes_for_sub_slim_index.sum() / mapper.params): numba at or below it, FFT above (the pre-#628 behaviour, default was 60.0). Set 0 to disable the numba path entirely. interferometer_route: null # Force the interferometer curvature route for benchmarking: null (default) routes by interferometer_numba_nnz_per_source_max; "fft" always uses the FFT route; "numba" uses the numba direct_conv route whenever it can represent the inversion (NumPy, one mapper, no linear functions, no over-sampling), overriding the gate and the 0 kill switch. "matrix_free" uses InversionInterferometerMatrixFree, which never forms the dense curvature or regularization matrix (PCG / interior-point solve, stochastic Lanczos log-det); it needs NumPy, one RectangularUniform mapper with MaternSparse regularization, no linear functions and (positive-only) use_edge_zeroed_pixels false, raises on anything else, and has no dense attributes such as reconstruction_noise_map (PyAutoArray#657). interferometer_direct_conv_symmetric_max_work_fraction: 0.7 # When the serial (numba parallel: false) direct_conv curvature route runs, use the symmetric row-restricted kernel (curvature_direct_conv_symmetric: source columns ranked by their top extent row, each convolving only the extent rows later-ranked columns span and only each row's mask x-range, then a mirror pass) when its geometry work fraction (its convolution work / the full kernel's) is at or below this value. Same F to round-off (computed entries bit-identical). Synthetic Aris-512 geometry (compact columns): f ~0.41, 1.81-1.90x single-thread on RAL; Aris's real 512 Delaunay mesh (multiply imaged, tall columns): f ~0.51, ~1.46x measured (PyAutoArray#635). The route cost model scales t_dc by min(1, 1.32 x work fraction), so the kernel wins below f ~0.76; 0.7 keeps a predicted gain >= 1.08x. Set 0 to always use the full kernel. The parallel kernel is unaffected. + lazy_sparse_operator: "off" # Whether a dataset builds its sparse operator lazily on the first NumPy pixelized fit that needs one, when none is attached (Imaging/Interferometer.sparse_operator_for). "off" (default this release): nothing is built and such fits take the dense mapping-matrix route, as before. "auto": the numba sparse operator (imaging) or the NUFFT w-tilde operator (interferometer) is built once, cached privately on the dataset and reused; never under JAX, inside a multiprocessing worker, with an explicit dense setup, or (interferometer) when the real and imaginary noise differ. PYAUTO_SETUP=auto also turns it on. Modeling applies its setup eagerly before forking and does not rely on this. + lazy_sparse_operator_visibility_budget: null # The visibility count above which the lazy interferometer build accumulates the operator chunk by chunk (apply_sparse_operator_from_chunks) instead of in one shot, bounding the NUFFT spreader buffer (~K x nspread^2 complex128: ~3 GB at 1e6 visibilities, ~15 GB at 5e6). null = 1e6. numba: use_numba: true # If True, use numba-accelerated mapper and Sibson interpolation paths when eligible. cache: true # If True, cache numba compiled functions on disk. diff --git a/autoarray/dataset/abstract/dataset.py b/autoarray/dataset/abstract/dataset.py index fd58d8eb8..8534ade79 100644 --- a/autoarray/dataset/abstract/dataset.py +++ b/autoarray/dataset/abstract/dataset.py @@ -264,6 +264,10 @@ def trimmed_after_convolution_from(self, kernel_shape) -> "AbstractDataset": """ dataset = copy.copy(self) + # A lazily built sparse operator (see `Imaging.sparse_operator_for`) describes the + # untrimmed mask, so it is not carried. + dataset._lazy_sparse_operator = None + dataset.data = dataset.data.trimmed_after_convolution_from( kernel_shape=kernel_shape ) diff --git a/autoarray/dataset/imaging/dataset.py b/autoarray/dataset/imaging/dataset.py index d125bb035..c34627850 100644 --- a/autoarray/dataset/imaging/dataset.py +++ b/autoarray/dataset/imaging/dataset.py @@ -1,5 +1,6 @@ import copy import logging +import time import numpy as np from pathlib import Path from typing import Optional, Union @@ -297,6 +298,10 @@ def __init__( self.sparse_operator = sparse_operator self.setup = setup_from(setup) + # The operator `sparse_operator_for` built lazily, if any; private, so it never changes + # what an attached `sparse_operator` means. + self._lazy_sparse_operator = None + @classmethod def from_fits( cls, @@ -619,8 +624,8 @@ 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`, 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 + The `noise_covariance_matrix`, any attached `sparse_operator`, the `setup` and any lazily built sparse + operator (see `sparse_operator_for()`) 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. @@ -650,6 +655,8 @@ def apply_over_sampling( setup=self.setup, ) + dataset._lazy_sparse_operator = getattr(self, "_lazy_sparse_operator", None) + return dataset def apply_sparse_operator( @@ -800,6 +807,99 @@ def apply_sparse_operator_cpu( setup=self.setup, ) + def sparse_operator_for(self, xp=np, needs_operator: bool = True, settings=None): + """ + The sparse operator a fit of this dataset should use: the attached `sparse_operator` if + there is one, otherwise (with the lazy policy on) the numba `SparseLinAlgImagingNumba` + operator, built once on first use and cached privately on this dataset. + + This lets calculations outside a model-fit -- a plain `FitImaging(dataset, ...)`, an + aggregator reload, `analysis.fit_from(...)` before a search -- use the sparse operator + modeling attaches eagerly (via `apply_setup()`), instead of the slow, memory-heavy dense + mapping-matrix route. The policy is off by default (see + `autoarray.dataset.lazy_operator.lazy_sparse_operator_enabled`), in which case this + returns the attached operator or `None`, exactly as before. + + Nothing is built, and `None` is returned, when `needs_operator` is False, the policy is + off, `xp` is not NumPy or the noise-map is a JAX tracer, or the dataset has an explicit + non-sparse (e.g. dense) setup. Inside a multiprocessing worker a cached operator is + returned but none is built (workers inherit the parent's cache, as PyAutoFit evaluates one + likelihood before forking). The build is also skipped when the dataset has no PSF, the PSF + is oversampled (`convolve_over_sample_size > 1`, which `apply_sparse_operator_cpu()` + rejects) or numba is not installed. + + The cache is carried by `apply_over_sampling()` and dropped by `apply_mask()`, + `apply_noise_scaling()` and `apply_setup()`, which change the mask or noise-map or attach + their own operator. + + Parameters + ---------- + xp + The array module of the fit (`numpy` or `jax.numpy`). + needs_operator + Whether the fit has a pixelization, i.e. would use a sparse operator at all (False + for, e.g., an MGE-only fit). + settings + The `Settings` of the fit, whose `lazy_sparse_operator` decides the policy; `None` + reads the config. + + Returns + ------- + The attached or lazily built sparse operator, or `None`. + """ + if self.sparse_operator is not None: + return self.sparse_operator + + from autoarray.dataset import lazy_operator + + reason = lazy_operator.lazy_build_blocked_reason( + dataset=self, xp=xp, needs_operator=needs_operator, settings=settings + ) + + if reason is not None: + return None + + # `getattr`: a dataset unpickled from before this attribute existed has none. + cached = getattr(self, "_lazy_sparse_operator", None) + + if cached is not None: + return cached + + if lazy_operator.in_worker_process(): + return None + + if self.psf is None: + logger.debug( + "INVERSION - lazy sparse operator skipped: the dataset has no PSF." + ) + return None + + if self.psf.convolve_over_sample_size > 1: + logger.debug( + "INVERSION - lazy sparse operator skipped: the PSF is oversampled " + "(convolve_over_sample_size > 1)." + ) + return None + + try: + import numba # noqa: F401 + except ModuleNotFoundError: + logger.debug( + "INVERSION - lazy sparse operator skipped: numba is not installed." + ) + return None + + start = time.perf_counter() + + self._lazy_sparse_operator = self.apply_sparse_operator_cpu().sparse_operator + + logger.info( + f"INVERSION - built numba sparse operator ({self.mask.pixels_in_mask} pixels) " + f"in {time.perf_counter() - start:.2f} s" + ) + + return self._lazy_sparse_operator + def _sparse_operator_matches(self, setup: Setup) -> bool: """ Whether the attached `sparse_operator` is the one `setup` names: a JAX @@ -871,6 +971,7 @@ def apply_setup( return self dataset = copy.copy(self) dataset.setup = setup + dataset._lazy_sparse_operator = None return dataset if setup.operator == "sparse": diff --git a/autoarray/dataset/interferometer/dataset.py b/autoarray/dataset/interferometer/dataset.py index 0dbbe17f8..1c38c5087 100644 --- a/autoarray/dataset/interferometer/dataset.py +++ b/autoarray/dataset/interferometer/dataset.py @@ -1,6 +1,7 @@ import copy import dataclasses import logging +import time import warnings import numpy as np from typing import Optional, Tuple, Union @@ -208,6 +209,12 @@ class with `TransformerNUFFT`, and any setup supersedes the >10,000-visibility D self.sparse_operator = sparse_operator self.sparse_terms = sparse_terms + # The operator `sparse_operator_for` built lazily, if any, and whether it has warned that + # the real and imaginary noise differ; private, so they never change what an attached + # `sparse_operator` means. + self._lazy_sparse_operator = None + self._lazy_sparse_operator_noise_warned = False + if sparse_operator is not None and self.primary_beam_slim is not None: if getattr(sparse_operator, "primary_beam_slim", None) is None: self.sparse_operator = dataclasses.replace( @@ -1050,6 +1057,7 @@ def apply_setup( return self dataset = copy.copy(self) dataset.setup = setup + dataset._lazy_sparse_operator = None return dataset self._require( @@ -1083,6 +1091,135 @@ def apply_setup( return dataset + def _lazy_chunks(self, chunk_visibilities: int): + """ + This dataset's own visibilities as `(uv_wavelengths, data, noise_map)` chunks of at most + `chunk_visibilities` visibilities, in the form `apply_sparse_operator_from_chunks` + expects (complex `(K,)` data and noise-map). Together they are exactly this dataset's + visibilities, so the accumulated operator is self-consistent with the retained arrays. + """ + uv_wavelengths = np.asarray(self.uv_wavelengths) + data = np.asarray(self.data.array, dtype=np.complex128) + noise_map = np.asarray(self.noise_map.array, dtype=np.complex128) + + for start in range(0, uv_wavelengths.shape[0], chunk_visibilities): + stop = start + chunk_visibilities + yield uv_wavelengths[start:stop], data[start:stop], noise_map[start:stop] + + def sparse_operator_for(self, xp=np, needs_operator: bool = True, settings=None): + """ + The sparse operator a fit of this dataset should use: the attached `sparse_operator` if + there is one, otherwise (with the lazy policy on) the `InterferometerSparseOperator` + (w-tilde) built by the NUFFT builder, once on first use and cached privately on this + dataset. + + This lets calculations outside a model-fit -- a plain `FitInterferometer(dataset, ...)`, + an aggregator reload, `analysis.fit_from(...)` before a search -- use the sparse operator + modeling attaches eagerly (via `apply_setup()`), instead of the slow, memory-heavy dense + mapping-matrix route. The policy is off by default (see + `autoarray.dataset.lazy_operator.lazy_sparse_operator_enabled`), in which case this + returns the attached operator or `None`, exactly as before. + + The build uses this dataset's own data and noise-map, as `apply_sparse_operator()` does + (`method="nufft"`, `use_jax=False`, so it never imports JAX). Above the visibility budget + (`lazy_operator.visibility_budget()`, 1e6 by default) it accumulates the same operator + chunk by chunk via `apply_sparse_operator_from_chunks`, bounding the NUFFT spreader's + gather buffer (~K x nspread^2 complex128: ~3 GB at 1e6 visibilities, ~15 GB at 5e6). + + Nothing is built, and `None` is returned, when `needs_operator` is False, the policy is + off, `xp` is not NumPy or the noise-map is a JAX tracer, or the dataset has an explicit + non-sparse (e.g. dense) setup. Inside a multiprocessing worker a cached operator is + returned but none is built (workers inherit the parent's cache, as PyAutoFit evaluates one + likelihood before forking). If the real and imaginary noise of any visibility differ the + build is skipped with a one-time warning: the sparse operator assumes they are equal, and + the noise-map is never pooled silently (use `apply_sparse_operator(pool_noise_map=True)` + explicitly to pool it). An array-free dataset (no visibilities or transformer) is skipped. + + Parameters + ---------- + xp + The array module of the fit (`numpy` or `jax.numpy`). + needs_operator + Whether the fit has a pixelization, i.e. would use a sparse operator at all (False + for, e.g., an MGE-only fit). + settings + The `Settings` of the fit, whose `lazy_sparse_operator` decides the policy; `None` + reads the config. + + Returns + ------- + The attached or lazily built sparse operator, or `None`. + """ + if self.sparse_operator is not None: + return self.sparse_operator + + from autoarray.dataset import lazy_operator + + reason = lazy_operator.lazy_build_blocked_reason( + dataset=self, xp=xp, needs_operator=needs_operator, settings=settings + ) + + if reason is not None: + return None + + # `getattr`: a dataset unpickled from before this attribute existed has none. + cached = getattr(self, "_lazy_sparse_operator", None) + + if cached is not None: + return cached + + if lazy_operator.in_worker_process(): + return None + + if ( + self.data is None + or self.noise_map is None + or self.uv_wavelengths is None + or self.transformer is None + ): + logger.debug( + "INVERSION - lazy sparse operator skipped: the dataset is array-free." + ) + return None + + try: + inversion_interferometer_util.check_noise_map_real_imag_equal( + self.noise_map + ) + except exc.DatasetException: + if not getattr(self, "_lazy_sparse_operator_noise_warned", False): + self._lazy_sparse_operator_noise_warned = True + warnings.warn( + "The real and imaginary noise of this Interferometer's visibilities differ, " + "so no sparse operator is built lazily (it assumes they are equal) and fits " + "take the dense mapping route. The noise-map is never pooled silently: to use " + "the sparse operator, attach it explicitly with " + "`dataset.apply_sparse_operator(pool_noise_map=True)`." + ) + return None + + n_vis = self.uv_wavelengths.shape[0] + chunked = n_vis > lazy_operator.visibility_budget() + + start = time.perf_counter() + + if chunked: + dataset = self.apply_sparse_operator_from_chunks( + self._lazy_chunks(chunk_visibilities=lazy_operator.CHUNK_VISIBILITIES) + ) + else: + dataset = self.apply_sparse_operator() + + self._lazy_sparse_operator = dataset.sparse_operator + + logger.info( + f"INVERSION - built NUFFT w-tilde sparse operator ({n_vis} visibilities, " + f"{self.real_space_mask.pixels_in_mask} pixels" + f"{', chunked' if chunked else ''}) in {time.perf_counter() - start:.2f} s" + ) + + return self._lazy_sparse_operator + def psf_precision_operator_from( self, chunk_k: int = 2048, diff --git a/autoarray/dataset/lazy_operator.py b/autoarray/dataset/lazy_operator.py new file mode 100644 index 000000000..6564ab9ec --- /dev/null +++ b/autoarray/dataset/lazy_operator.py @@ -0,0 +1,186 @@ +""" +The policy and gates of the lazy sparse operator (`Imaging.sparse_operator_for`, +`Interferometer.sparse_operator_for`). + +Modeling applies its compute setup eagerly, before a search forks its workers, so a model-fit +always has the sparse operator it needs attached to its dataset. Calculations outside a search do +not: a plain `FitImaging(dataset, tracer)`, an aggregator reload or `analysis.fit_from(...)` before +a search take the dense mapping-matrix route on CPU, which is slow and whose memory grows as +n_image x n_source. With the policy on, a dataset without an attached operator builds the one its +NumPy pixelized fits need on first use, caches it privately and reuses it. + +The hook is on the real dataset rather than the inversion factory: every fit wraps its data in a +fresh `DatasetInterface` with no setup and no back-reference, so a factory-side cache would be lost +after every fit. + +This module holds what both dataset types share: the policy (`lazy_sparse_operator_enabled`), the +gates under which nothing is ever built (`lazy_build_blocked_reason`, `in_worker_process`) and the +interferometer visibility budget (`visibility_budget`). +""" + +import logging +import os +import sys +from typing import Optional + +from autonerves import conf + +logger = logging.getLogger(__name__) + +# The visibility count above which the lazy interferometer build accumulates the operator chunk by +# chunk (`apply_sparse_operator_from_chunks`) instead of in one shot. The unchunked NUFFT +# spreader's gather buffer is ~K x nspread^2 complex128 (~3 GB at 1e6 visibilities, ~15 GB at 5e6; +# see `nufft_precision_operator_from`), whereas the stored operator is extent-sized. Overridden by +# `general.yaml` `inversion: lazy_sparse_operator_visibility_budget`. +VISIBILITY_BUDGET = 1_000_000 + +# The number of visibilities per chunk of the chunked lazy build (~0.8 GB of spreader buffer at +# `eps = 1e-12`). +CHUNK_VISIBILITIES = 2**18 + + +def lazy_sparse_operator_enabled(settings=None) -> bool: + """ + Whether the lazy sparse operator policy is on. + + - An explicit `Settings(lazy_sparse_operator=...)` decides on its own (``"auto"`` on, ``"off"`` + off), so a script can switch the lazy build off whatever the environment says. + - Otherwise the policy is on if `general.yaml` `inversion: lazy_sparse_operator` is ``"auto"``, + or the environment variable `PYAUTO_SETUP` is set to ``auto`` (parsed by + `autonerves.environment.parse_setup_intent`). An unset or empty `PYAUTO_SETUP` does not turn + it on: the default is off this release. + + Parameters + ---------- + settings + The `Settings` of the fit, if any; `None` reads the config. + """ + from autoarray.settings import Settings + + settings = settings if settings is not None else Settings() + + if settings._lazy_sparse_operator is not None: + return settings.lazy_sparse_operator == "auto" + + if settings.lazy_sparse_operator == "auto": + return True + + return _pyauto_setup_is_auto() + + +def _pyauto_setup_is_auto() -> bool: + """ + Whether `PYAUTO_SETUP` is explicitly set to ``auto``. An invalid value is left for + `Setup.auto` to report; here it simply does not turn the policy on. + """ + from autonerves.environment import SETUP_ENV_VAR, parse_setup_intent + + value = os.environ.get(SETUP_ENV_VAR) + + if value is None or not value.strip(): + return False + + try: + return parse_setup_intent(value) == "auto" + except ValueError: + return False + + +def visibility_budget() -> int: + """ + The visibility count above which the lazy interferometer build is chunked: the config value + `inversion: lazy_sparse_operator_visibility_budget` when set (not `null`), else + `VISIBILITY_BUDGET`. + """ + try: + value = conf.instance["general"]["inversion"][ + "lazy_sparse_operator_visibility_budget" + ] + except KeyError: + value = None + + if value is None: + return VISIBILITY_BUDGET + + return int(value) + + +def is_jax_tracer(array) -> bool: + """ + Whether `array` (or the raw array an autoarray structure wraps) is a JAX tracer, i.e. the call + is inside `jax.jit` / `jax.grad` / `jax.vmap`. JAX is only consulted when it is already + imported, so this never imports it. + """ + if "jax" not in sys.modules: + return False + + jax = sys.modules["jax"] + + tracer_type = getattr(getattr(jax, "core", None), "Tracer", None) + + if tracer_type is None: + return False + + return isinstance(getattr(array, "array", array), tracer_type) or isinstance( + getattr(array, "_array", None), tracer_type + ) + + +def in_worker_process() -> bool: + """ + Whether this is a multiprocessing worker (or a pid-changed fork), where no operator is ever + built: a lazy build there would be one operator per worker. Workers inherit the parent's cache + instead, because PyAutoFit evaluates one likelihood before forking. + """ + from autoarray import numba_util + + return not numba_util.parallel_kernel_allowed() + + +def lazy_build_blocked_reason( + dataset, xp, needs_operator: bool, settings=None +) -> Optional[str]: + """ + The reason the lazy sparse operator is neither built nor returned for this call, or `None` if + it may be (a cached operator is then returned, or one is built when the call is not inside a + worker). + + Nothing is built or returned when: + + - `needs_operator` is False (no pixelization, e.g. an MGE-only fit); + - the policy is off (`lazy_sparse_operator_enabled`); + - `xp` is not NumPy, or the noise-map is a JAX tracer (the JAX path stays modeling-applied or + explicit); + - the dataset has an explicit setup whose operator is not ``"sparse"`` (e.g. a dense setup). + + Parameters + ---------- + dataset + The real `Imaging` / `Interferometer` dataset. + xp + The array module of the fit (`numpy` or `jax.numpy`). + needs_operator + Whether the fit has a pixelization, i.e. would use a sparse operator at all. + settings + The `Settings` of the fit, if any; `None` reads the config. + """ + import numpy as np + + if not needs_operator: + return "the fit needs no sparse operator" + + if not lazy_sparse_operator_enabled(settings=settings): + return "the lazy sparse operator policy is off" + + if xp is not np: + return "the array backend is not NumPy" + + if is_jax_tracer(dataset.noise_map): + return "the noise-map is a JAX tracer" + + setup = getattr(dataset, "setup", None) + + if setup is not None and setup.operator != "sparse": + return f"the dataset has an explicit {setup.operator!r} setup" + + return None diff --git a/autoarray/settings.py b/autoarray/settings.py index 7771e898b..02a333731 100644 --- a/autoarray/settings.py +++ b/autoarray/settings.py @@ -29,6 +29,7 @@ def __init__( certified_fallback: Optional[str] = None, certified_tau_rel: Optional[float] = None, nnls_preconditioning_no_mapper: Optional[str] = None, + lazy_sparse_operator: Optional[str] = None, ): """ The settings of an Inversion, customizing how a linear set of equations are solved for. @@ -274,6 +275,17 @@ def __init__( Inversions containing a `Mapper` always use ``"jacobi"`` (`AbstractInversion.positive_only_preconditioning_used` records the decision). The NumPy path always runs fnnls and ignores this. + lazy_sparse_operator + Whether a dataset builds its sparse operator lazily, on the first NumPy pixelized fit that + needs one, when none is attached (`Imaging.sparse_operator_for` / + `Interferometer.sparse_operator_for`). `None` (default) reads the packaged value ``"off"``. + + - ``"off"`` (default) -- nothing is built; a dataset without an attached operator takes the + dense mapping-matrix route, as before. + - ``"auto"`` -- the dataset builds the numba sparse operator (imaging) or the NUFFT w-tilde + operator (interferometer) once, caches it privately and reuses it. `PYAUTO_SETUP=auto` also + turns this on, unless this argument is given explicitly (see + `autoarray.dataset.lazy_operator.lazy_sparse_operator_enabled`). """ self.use_mixed_precision = use_mixed_precision self.nnls_solver_tol = nnls_solver_tol @@ -300,6 +312,7 @@ def __init__( self._certified_fallback = certified_fallback self._certified_tau_rel = certified_tau_rel self._nnls_preconditioning_no_mapper = nnls_preconditioning_no_mapper + self._lazy_sparse_operator = lazy_sparse_operator # Validate explicit values eagerly, so a typo fails at construction rather than deep inside a fit. if positive_only_solver is not None: @@ -312,6 +325,8 @@ def __init__( self.interferometer_route if interferometer_direct_conv_symmetric_max_work_fraction is not None: self.interferometer_direct_conv_symmetric_max_work_fraction + if lazy_sparse_operator is not None: + self.lazy_sparse_operator @property def use_positive_only_solver(self): @@ -522,6 +537,30 @@ def interferometer_direct_conv_symmetric_max_work_fraction(self) -> float: return value + @property + def lazy_sparse_operator(self) -> str: + """ + The lazy sparse operator policy: ``"off"`` (default) or ``"auto"``. + + See the constructor docstring. YAML 1.1 reads an unquoted ``off`` / ``on`` as a boolean, so + `False` is accepted as ``"off"`` and `True` as ``"auto"``; `None` means the default. + """ + value = self._lazy_sparse_operator + if value is None: + value = self._inversion_config_value("lazy_sparse_operator", "off") + + if value is None or value is False: + value = "off" + elif value is True: + value = "auto" + + if value not in ("off", "auto"): + raise ValueError( + f"lazy_sparse_operator={value!r} is invalid; expected 'off' or 'auto'." + ) + + return value + def _inversion_config_value(self, key, default): # A workspace `general.yaml` normally omits the newer keys, so autoconf's config-path # list falls through to autoarray's packaged value. The fallback fires only when the diff --git a/test_autoarray/inversion/inversion/test_lazy_operator.py b/test_autoarray/inversion/inversion/test_lazy_operator.py new file mode 100644 index 000000000..cf000f45a --- /dev/null +++ b/test_autoarray/inversion/inversion/test_lazy_operator.py @@ -0,0 +1,471 @@ +import logging + +import numpy as np +import pytest + +import autoarray as aa +from autoarray import numba_util +from autoarray.dataset import lazy_operator +from autoarray.operators import transformer + +IMAGING_LOGGER = "autoarray.dataset.imaging.dataset" +INTERFEROMETER_LOGGER = "autoarray.dataset.interferometer.dataset" + +ON = aa.Settings(lazy_sparse_operator="auto") + + +@pytest.fixture(autouse=True) +def _no_ambient_setup(monkeypatch): + # An ambient `PYAUTO_SETUP=auto` turns the policy on; every test sets its own. + monkeypatch.delenv("PYAUTO_SETUP", raising=False) + + +def _interferometer(mask_2d_7x7, noise_imag_factor=1.0, n_vis=7): + rng = np.random.default_rng(1) + data = rng.normal(size=n_vis) + 1j * rng.normal(size=n_vis) + sigma = rng.uniform(1.0, 2.0, size=n_vis) + noise_map = sigma + 1j * sigma * noise_imag_factor + uv_wavelengths = rng.uniform(-2.0e5, 2.0e5, size=(n_vis, 2)) + + return aa.Interferometer( + data=aa.Visibilities(visibilities=data), + noise_map=aa.VisibilitiesNoiseMap(visibilities=noise_map), + uv_wavelengths=uv_wavelengths, + real_space_mask=mask_2d_7x7, + transformer_class=transformer.TransformerDFT, + ) + + +def _assert_imaging_operator_equal(operator, reference): + np.testing.assert_array_equal( + operator.psf_precision_operator_sparse, + reference.psf_precision_operator_sparse, + ) + np.testing.assert_array_equal(operator.indexes, reference.indexes) + np.testing.assert_array_equal(operator.lengths, reference.lengths) + + +def _assert_interferometer_operator_close(operator, reference, rtol=1.0e-12): + np.testing.assert_allclose( + operator.nufft_precision_operator, + reference.nufft_precision_operator, + rtol=rtol, + atol=rtol * np.abs(reference.nufft_precision_operator).max(), + ) + np.testing.assert_allclose( + operator.dirty_image, + reference.dirty_image, + rtol=rtol, + atol=rtol * np.abs(reference.dirty_image).max(), + ) + assert operator.data_term == pytest.approx(reference.data_term, rel=rtol) + assert operator.noise_normalization == pytest.approx( + reference.noise_normalization, rel=rtol + ) + + +# Policy + + +def test__settings__lazy_sparse_operator__default_off_and_validated(): + assert aa.Settings().lazy_sparse_operator == "off" + assert aa.Settings(lazy_sparse_operator="auto").lazy_sparse_operator == "auto" + assert aa.Settings(lazy_sparse_operator=False).lazy_sparse_operator == "off" + + with pytest.raises(ValueError): + aa.Settings(lazy_sparse_operator="sometimes") + + +def test__policy__config_and_pyauto_setup(monkeypatch): + assert lazy_operator.lazy_sparse_operator_enabled() is False + + monkeypatch.setattr( + aa.Settings, + "_inversion_config_value", + lambda self, key, default: "auto" if key == "lazy_sparse_operator" else default, + ) + assert lazy_operator.lazy_sparse_operator_enabled() is True + # An explicit Settings value wins over the config. + assert ( + lazy_operator.lazy_sparse_operator_enabled( + settings=aa.Settings(lazy_sparse_operator="off") + ) + is False + ) + + monkeypatch.undo() + monkeypatch.delenv("PYAUTO_SETUP", raising=False) + + for value, enabled in ( + ("auto", True), + (" AUTO ", True), + ("", False), + ("cpu", False), + ("numba_cpu_sparse_fp64", False), + ("not-a-setup", False), + ): + monkeypatch.setenv("PYAUTO_SETUP", value) + assert lazy_operator.lazy_sparse_operator_enabled() is enabled, value + + monkeypatch.setenv("PYAUTO_SETUP", "auto") + assert ( + lazy_operator.lazy_sparse_operator_enabled( + settings=aa.Settings(lazy_sparse_operator="off") + ) + is False + ) + + +def test__visibility_budget__default(): + assert lazy_operator.visibility_budget() == lazy_operator.VISIBILITY_BUDGET == 1e6 + + +def test__is_jax_tracer(): + jax = pytest.importorskip("jax") + + assert lazy_operator.is_jax_tracer(np.ones(3)) is False + + seen = [] + + def f(x): + seen.append(lazy_operator.is_jax_tracer(x)) + return x + + jax.jit(f)(np.ones(3)) + + assert seen == [True] + + +# Imaging + + +def test__imaging__policy_off__none_and_nothing_built(masked_imaging_7x7, monkeypatch): + called = [] + monkeypatch.setattr( + aa.Imaging, + "apply_sparse_operator_cpu", + lambda self: called.append(1), + ) + + assert masked_imaging_7x7.sparse_operator_for(xp=np, needs_operator=True) is None + assert masked_imaging_7x7._lazy_sparse_operator is None + assert called == [] + + +def test__imaging__policy_on__built_once_cached_reused_and_logged( + masked_imaging_7x7, caplog +): + pytest.importorskip("numba") + + with caplog.at_level(logging.INFO, logger=IMAGING_LOGGER): + operator = masked_imaging_7x7.sparse_operator_for( + xp=np, needs_operator=True, settings=ON + ) + + build_lines = [ + r.message for r in caplog.records if "built numba sparse operator" in r.message + ] + assert len(build_lines) == 1 + assert "(9 pixels)" in build_lines[0] + + from autoarray.inversion.inversion.imaging_numba.inversion_imaging_numba_util import ( + SparseLinAlgImagingNumba, + ) + + assert isinstance(operator, SparseLinAlgImagingNumba) + assert masked_imaging_7x7._lazy_sparse_operator is operator + # The attached operator is untouched: the cache is private. + assert masked_imaging_7x7.sparse_operator is None + + caplog.clear() + + with caplog.at_level(logging.INFO, logger=IMAGING_LOGGER): + assert ( + masked_imaging_7x7.sparse_operator_for( + xp=np, needs_operator=True, settings=ON + ) + is operator + ) + + assert not any("built numba" in r.message for r in caplog.records) + + _assert_imaging_operator_equal( + operator, masked_imaging_7x7.apply_sparse_operator_cpu().sparse_operator + ) + + +def test__imaging__policy_on_via_config_and_pyauto_setup( + masked_imaging_7x7, monkeypatch +): + pytest.importorskip("numba") + + monkeypatch.setattr( + aa.Settings, + "_inversion_config_value", + lambda self, key, default: "auto" if key == "lazy_sparse_operator" else default, + ) + assert ( + masked_imaging_7x7.sparse_operator_for(xp=np, needs_operator=True) is not None + ) + + monkeypatch.undo() + monkeypatch.delenv("PYAUTO_SETUP", raising=False) + + dataset = masked_imaging_7x7.apply_over_sampling(over_sample_size_lp=2) + dataset._lazy_sparse_operator = None + assert dataset.sparse_operator_for(xp=np, needs_operator=True) is None + + monkeypatch.setenv("PYAUTO_SETUP", "auto") + assert dataset.sparse_operator_for(xp=np, needs_operator=True) is not None + + +def test__imaging__gates__return_none(masked_imaging_7x7, monkeypatch): + pytest.importorskip("numba") + + # needs_operator False (e.g. MGE only). + assert ( + masked_imaging_7x7.sparse_operator_for(xp=np, needs_operator=False, settings=ON) + is None + ) + + # An explicit dense setup. + dense = masked_imaging_7x7.apply_setup("numba_cpu_dense_fp64") + assert dense.sparse_operator_for(xp=np, needs_operator=True, settings=ON) is None + assert dense._lazy_sparse_operator is None + + # An oversampled PSF, which apply_sparse_operator_cpu rejects. + oversampled = masked_imaging_7x7.apply_over_sampling( + over_sample_size_pixelization=2 + ) + oversampled.psf = aa.Convolver( + kernel=oversampled.psf.kernel, convolve_over_sample_size=2 + ) + assert ( + oversampled.sparse_operator_for(xp=np, needs_operator=True, settings=ON) is None + ) + + # A multiprocessing worker never builds. + monkeypatch.setattr(numba_util, "parallel_kernel_allowed", lambda: False) + assert ( + masked_imaging_7x7.sparse_operator_for(xp=np, needs_operator=True, settings=ON) + is None + ) + assert masked_imaging_7x7._lazy_sparse_operator is None + + +def test__imaging__worker__inherits_parent_cache(masked_imaging_7x7, monkeypatch): + pytest.importorskip("numba") + + operator = masked_imaging_7x7.sparse_operator_for( + xp=np, needs_operator=True, settings=ON + ) + + monkeypatch.setattr(numba_util, "parallel_kernel_allowed", lambda: False) + + assert ( + masked_imaging_7x7.sparse_operator_for(xp=np, needs_operator=True, settings=ON) + is operator + ) + + +def test__imaging__jax_xp__none(masked_imaging_7x7): + jnp = pytest.importorskip("jax.numpy") + + assert ( + masked_imaging_7x7.sparse_operator_for(xp=jnp, needs_operator=True, settings=ON) + is None + ) + assert masked_imaging_7x7._lazy_sparse_operator is None + + +def test__imaging__attached_operator_returned_as_is(masked_imaging_7x7): + pytest.importorskip("numba") + + dataset = masked_imaging_7x7.apply_sparse_operator_cpu() + + for settings in (None, ON): + assert ( + dataset.sparse_operator_for(xp=np, needs_operator=True, settings=settings) + is dataset.sparse_operator + ) + + assert dataset._lazy_sparse_operator is None + + +def test__imaging__cache_carry_and_drop(imaging_7x7, mask_2d_7x7): + pytest.importorskip("numba") + + dataset = imaging_7x7.apply_mask(mask=mask_2d_7x7) + operator = dataset.sparse_operator_for(xp=np, needs_operator=True, settings=ON) + assert operator is not None + + assert ( + dataset.apply_over_sampling(over_sample_size_lp=2)._lazy_sparse_operator + is operator + ) + + assert dataset.apply_mask(mask=mask_2d_7x7)._lazy_sparse_operator is None + assert dataset.apply_setup("numba_cpu_dense_fp64")._lazy_sparse_operator is None + assert ( + dataset.trimmed_after_convolution_from( + kernel_shape=(3, 3) + )._lazy_sparse_operator + is None + ) + + unmasked = imaging_7x7.apply_over_sampling(over_sample_size_lp=2) + unmasked._lazy_sparse_operator = operator + assert unmasked.apply_noise_scaling(mask=mask_2d_7x7)._lazy_sparse_operator is None + + +# Interferometer + + +def test__interferometer__policy_off__none_and_nothing_built(mask_2d_7x7, monkeypatch): + dataset = _interferometer(mask_2d_7x7) + + called = [] + monkeypatch.setattr( + aa.Interferometer, + "apply_sparse_operator", + lambda self, **kwargs: called.append(1), + ) + + assert dataset.sparse_operator_for(xp=np, needs_operator=True) is None + assert dataset._lazy_sparse_operator is None + assert called == [] + + +def test__interferometer__policy_on__built_once_cached_matches_apply_sparse_operator( + mask_2d_7x7, caplog +): + pytest.importorskip("finufft") + + dataset = _interferometer(mask_2d_7x7) + + with caplog.at_level(logging.INFO, logger=INTERFEROMETER_LOGGER): + operator = dataset.sparse_operator_for(xp=np, needs_operator=True, settings=ON) + + build_lines = [ + r.message + for r in caplog.records + if "built NUFFT w-tilde sparse operator" in r.message + ] + assert len(build_lines) == 1 + assert "(7 visibilities, 9 pixels)" in build_lines[0] + + assert isinstance(operator, aa.InterferometerSparseOperator) + assert dataset.sparse_operator is None + assert ( + dataset.sparse_operator_for(xp=np, needs_operator=True, settings=ON) is operator + ) + + _assert_interferometer_operator_close( + operator, dataset.apply_sparse_operator().sparse_operator, rtol=1.0e-14 + ) + + +def test__interferometer__above_budget__chunked_builder( + mask_2d_7x7, monkeypatch, caplog +): + pytest.importorskip("finufft") + + dataset = _interferometer(mask_2d_7x7) + + monkeypatch.setattr(lazy_operator, "VISIBILITY_BUDGET", 3) + monkeypatch.setattr(lazy_operator, "CHUNK_VISIBILITIES", 3) + + chunk_lengths = [] + from_chunks = aa.Interferometer.apply_sparse_operator_from_chunks + + def spy(self, chunks, **kwargs): + chunks = list(chunks) + chunk_lengths.extend(len(chunk[0]) for chunk in chunks) + return from_chunks(self, chunks, **kwargs) + + monkeypatch.setattr(aa.Interferometer, "apply_sparse_operator_from_chunks", spy) + + with caplog.at_level(logging.INFO, logger=INTERFEROMETER_LOGGER): + operator = dataset.sparse_operator_for(xp=np, needs_operator=True, settings=ON) + + assert chunk_lengths == [3, 3, 1] + assert any(", chunked)" in r.message for r in caplog.records) + + _assert_interferometer_operator_close( + operator, dataset.apply_sparse_operator().sparse_operator + ) + + +def test__interferometer__unequal_real_imag_noise__none_one_time_warning_never_pooled( + mask_2d_7x7, monkeypatch +): + dataset = _interferometer(mask_2d_7x7, noise_imag_factor=1.5) + noise_map = dataset.noise_map + + called = [] + monkeypatch.setattr( + aa.Interferometer, + "apply_sparse_operator", + lambda self, **kwargs: called.append(kwargs), + ) + + with pytest.warns(UserWarning, match="real and imaginary noise"): + assert ( + dataset.sparse_operator_for(xp=np, needs_operator=True, settings=ON) is None + ) + + import warnings + + with warnings.catch_warnings(): + warnings.simplefilter("error") + assert ( + dataset.sparse_operator_for(xp=np, needs_operator=True, settings=ON) is None + ) + + assert called == [] + assert dataset.noise_map is noise_map + assert dataset._lazy_sparse_operator is None + + +def test__interferometer__gates__return_none(mask_2d_7x7, monkeypatch): + dataset = _interferometer(mask_2d_7x7) + + assert dataset.sparse_operator_for(xp=np, needs_operator=False, settings=ON) is None + + dense = dataset.apply_setup("numba_cpu_dense_fp64") + assert dense.sparse_operator_for(xp=np, needs_operator=True, settings=ON) is None + + monkeypatch.setattr(numba_util, "parallel_kernel_allowed", lambda: False) + assert dataset.sparse_operator_for(xp=np, needs_operator=True, settings=ON) is None + assert dataset._lazy_sparse_operator is None + + +def test__interferometer__jax_xp__none(mask_2d_7x7): + jnp = pytest.importorskip("jax.numpy") + + dataset = _interferometer(mask_2d_7x7) + + assert dataset.sparse_operator_for(xp=jnp, needs_operator=True, settings=ON) is None + + +def test__interferometer__attached_operator_returned_as_is(mask_2d_7x7): + pytest.importorskip("finufft") + + dataset = _interferometer(mask_2d_7x7).apply_sparse_operator() + + assert ( + dataset.sparse_operator_for(xp=np, needs_operator=True, settings=ON) + is dataset.sparse_operator + ) + assert dataset._lazy_sparse_operator is None + + +def test__interferometer__apply_setup_drops_cache(mask_2d_7x7): + pytest.importorskip("finufft") + + dataset = _interferometer(mask_2d_7x7) + assert ( + dataset.sparse_operator_for(xp=np, needs_operator=True, settings=ON) is not None + ) + + assert dataset.apply_setup("numba_cpu_dense_fp64")._lazy_sparse_operator is None