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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions autoarray/config/general.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
4 changes: 4 additions & 0 deletions autoarray/dataset/abstract/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
)
Expand Down
105 changes: 103 additions & 2 deletions autoarray/dataset/imaging/dataset.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import copy
import logging
import time
import numpy as np
from pathlib import Path
from typing import Optional, Union
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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":
Expand Down
137 changes: 137 additions & 0 deletions autoarray/dataset/interferometer/dataset.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import copy
import dataclasses
import logging
import time
import warnings
import numpy as np
from typing import Optional, Tuple, Union
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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,
Expand Down
Loading
Loading