Skip to content

feat: lazy, size-gated sparse operator on the dataset (5B-3) #711

Done

Description

@Jammy2211

Overview

Likelihood-lifecycle epic, phase 5B-3 (PyAutoArray). 5C applies the compute setup only in modify_before_fit, so calculations outside modeling stay on the slow, memory-heavy dense mapping route on CPU: a plain FitImaging(dataset, tracer), aggregator reloads, and fit_from before a search. This phase adds dataset.sparse_operator_for(xp, needs_operator), which builds the designated sparse operator once, lazily, and caches it on the real dataset. It is off by default (R6). The Galaxy/Lens fits call it in 5C-3.

Plan

  • Add Imaging.sparse_operator_for(xp, needs_operator) and Interferometer.sparse_operator_for(xp, needs_operator):
    • return the attached operator if there is one;
    • otherwise, with the policy on, build once, cache privately on the dataset and log the build time: the numba operator for imaging, w-tilde via the NUFFT builder for interferometer;
    • with the policy off, return None (unchanged behaviour).
  • Never build when:
    • xp isn't numpy, or a JAX tracer is detected;
    • the call is inside a multiprocessing worker;
    • the dataset has an explicit dense setup;
    • needs_operator is False (no pixelization, e.g. MGE).
  • Policy: a general.yaml key inversion: lazy_sparse_operator: off|auto (a Settings property) or PYAUTO_SETUP=auto. Default off.
  • Interferometer: above a visibility budget (default 1e6) use the chunked builder instead of refusing. If the real and imaginary noise differ, skip with a one-time warning; never pool the noise map.
  • Cache lifetime: apply_over_sampling carries it; apply_mask / apply_noise_scaling drop it.

Design calls (human-approved 2026-11-24, after a read-only survey):

  1. The hook is on the real dataset, not the inversion factory. Every fit wraps its data in a fresh aa.DatasetInterface with no setup and no back-reference, so a factory cache would be lost after each fit. The fit call sites are 5C-3.
  2. The interferometer size gate is on n_vis (the unchunked NUFFT spreader buffer is about 3 GB at 1e6 and 15 GB at 5e6); above it, use apply_sparse_operator_from_chunks.
  3. Never change the data silently: real ≠ imaginary noise → skip, never pool.
  4. Workers never build; they inherit the parent's cache, because PyAutoFit evaluates one likelihood before forking.
  • Tier + merge mode: effective level: supervised; merge mode: human /prm
Detailed implementation plan

Affected Repositories

  • PyAutoArray (primary)

Branch Survey

Repository Current Branch Dirty?
./PyAutoArray main clean

Suggested branch: feature/likelihood-lifecycle-p5b3-array

Implementation Steps

  1. Policy:
    • Add lazy_sparse_operator: off under inversion: in autoarray/config/general.yaml.
    • Add a Settings.lazy_sparse_operator property with constructor override and validation, following interferometer_route (settings.py:458-478, _inversion_config_value :525).
    • Add a helper lazy_sparse_operator_enabled(settings=None) that also honours PYAUTO_SETUP=auto (parsed via autonerves).
  2. Gates (a small shared helper module, e.g. autoarray/dataset/lazy_operator.py):
    • xp is np;
    • a defensive JAX tracer check on noise_map, only if "jax" in sys.modules, so JAX is never imported;
    • numba_util.parallel_kernel_allowed() (worker detection, numba_util.py:36);
    • an explicit dataset.setup with operator != "sparse" means never build;
    • numba importable (imaging).
  3. Imaging:
    • sparse_operator_for builds via the apply_sparse_operator_cpu internals (imaging/dataset.py:729-787): psf_precision_operator_sparse_from → SparseLinAlgImagingNumba.
    • It caches on self._lazy_sparse_operator and logs INVERSION - built numba sparse operator (<n> pixels) in <t> s.
    • Skip (debug log) if psf.convolve_over_sample_size > 1, which apply_sparse_operator_cpu rejects.
  4. Interferometer:
    • Use apply_sparse_operator internals with the NUFFT builder (interferometer/dataset.py:558); above the n_vis budget use apply_sparse_operator_from_chunks (:826).
    • Skip with a one-time warning when check_noise_map_real_imag_equal fails.
    • Build from the real dataset's data (the fits correct the dirty image / data term, autolens fit_interferometer.py:230-244).
    • Cache and log as for imaging.
  5. Carry and drop: apply_over_sampling carries _lazy_sparse_operator; apply_mask / apply_noise_scaling / apply_setup don't (apply_setup attaches its own operator).
  6. Tests (test_autoarray/inversion/inversion/test_lazy_operator.py, or the dataset test dirs):
    • policy off → None and nothing built;
    • policy on (config and PYAUTO_SETUP=auto) → built once, cached, reused, log line present;
    • jnp xp → None; worker (monkeypatched parallel_kernel_allowed) → None;
    • explicit dense setup → None; needs_operator=False → None;
    • an attached operator is returned as is;
    • interferometer: chunked path above a monkeypatched budget; real ≠ imaginary noise → None plus a one-time warning;
    • carry/drop through apply_*;
    • built operator equals apply_sparse_operator_cpu() / apply_sparse_operator() results.
    • numba, jax and finufft uses go behind pytest.importorskip.
  7. Full suite plus pyauto-heart smoke --affected-by PyAutoArray.

Key Files

  • autoarray/dataset/imaging/dataset.py, autoarray/dataset/interferometer/dataset.py
  • autoarray/settings.py, autoarray/config/general.yaml
  • autoarray/numba_util.py (worker detection)
  • new: autoarray/dataset/lazy_operator.py (gates and policy)

Original Prompt

Click to expand starting prompt

Likelihood lifecycle phase 5B-3: PyAutoArray lazy, size-gated sparse operator on the dataset (dataset.sparse_operator_for), so non-modeling calculations get the optimal setup

Type: feature
Target: PyAutoArray
Repos:

  • PyAutoArray
    Themes:
  • hpc-gpu
  • profiling
    Difficulty: large
    Autonomy: supervised
    Priority: high
    Status: draft
    Consequence: judge
    Witness: Imaging.sparse_operator_for(xp, needs_operator) and Interferometer.sparse_operator_for(xp, needs_operator) return the attached operator when there is one. Otherwise, with the policy on (general.yaml inversion: lazy_sparse_operator: auto, exposed as a Settings property, or PYAUTO_SETUP=auto), they build the designated operator once and cache it privately on the real dataset: imaging gets the numba operator, interferometer gets w-tilde via the NUFFT builder, switching to the chunked builder above a visibility budget (default 1e6). The build logs one line with its time. Nothing is built when xp isn't numpy, a JAX tracer is detected, the call is inside a multiprocessing worker, the dataset has an explicit dense setup, needs_operator is False, or (interferometer) the real and imaginary noise differ; that last case gives a one-time warning and the noise map is never pooled. apply_over_sampling carries the cache; apply_mask / apply_noise_scaling drop it. With the policy off (the default this release, R6), behaviour is unchanged. Full test suite green.
    Review-minutes: 30
    Unattended: no
    Lane: any
    Gate: 5C-2 MERGED (PyAutoLens setup wiring), so modeling's eager modify_before_fit apply is in place and this layer only complements it. Phasing approved by the human 2026-11-24.
    Epic: likelihood-lifecycle
    Phase: 5
    Parent: draft/research/autolens_profiling/likelihood_lifecycle_epic.md
    Filed: 2026-11-24

Context

  • Why: 5C resolves the setup in modify_before_fit, so only modeling gets the optimal operator. These do not:

    • direct fits: al.FitImaging(dataset, tracer) and similar, in 117 workspace scripts, of which 37 attach apply_sparse_operator by hand;
    • aggregator reloads (5C-3);
    • analysis.fit_from(...) before a search.

    On CPU a pixelized fit without an operator takes the dense mapping-matrix route: slow, with memory that grows as n_image × n_source.

  • The choke point (superseded 2026-11-24 by survey): every inversion goes through galaxy/to_inversion.py / lens/to_inversion.py → aa.Inversion → inversion_imaging_from / inversion_interferometer_from (autoarray/inversion/inversion/factory.py). The factory knows the dataset type, the mapper's mesh (the variant) and xp, so it can resolve the rule key itself.

  • The numpy path barely depends on the variant: every pixelized imaging CPU row is numba sparse, and inversions with only light profiles (MGE) take the mapping route regardless of any operator.

  • Risks to design against:

    1. The interferometer w-tilde precompute takes minutes and GBs at ALMA/JVLA scale, hence the size gate and a loud refusal.
    2. Multiprocessing: a lazy build in Nautilus workers is one operator per worker. Modeling must keep applying eagerly before the fork (5C does), and the lazy path must not be what modeling relies on.
    3. Cache lifetime across apply_* copies.
    4. The sparse and mapping routes differ by about 1e-4 relative, so hard-coded likelihoods may shift when the default flips.
    5. How far it reaches: every numpy pixelized test switches route when the policy is on, hence default off.
  • Existing code:

    • autoarray/inversion/inversion/factory.py (the operator/backend consistency check from 5B-2);
    • autoarray/dataset/imaging/dataset.py and autoarray/dataset/interferometer/dataset.py (apply_setup, apply_sparse_operator*);
    • autoarray/setup/setup.py (Setup.auto, setup_rules.yaml);
    • the interferometer route cost model in factory.py (_use_interferometer_numba).
  • Design calls (human-approved 2026-11-24, after the survey):

    1. The hook is on the real dataset, not the factory. Every fit wraps its data in a fresh aa.DatasetInterface (autogalaxy imaging/fit_imaging.py:143, autolens lens/to_inversion.py:209, …) with no setup and no back-reference, so a factory-side cache would be lost after every fit. The fit call sites move to 5C-3.
    2. The interferometer size gate is on n_vis: the unchunked NUFFT spreader buffer is about 3 GB at 1e6 visibilities and 15 GB at 5e6, while the stored operator is extent-sized. Above the budget use apply_sparse_operator_from_chunks; don't refuse.
    3. Never change the data silently: real ≠ imaginary noise → skip with a one-time warning; never pool.
    4. Workers never build (numba_util.parallel_kernel_allowed()); they inherit the parent's cache, because PyAutoFit evaluates one likelihood before forking.

Out of scope

  • The Galaxy/Lens fit call sites and aggregator reapplication of setup.json (5C-3).
  • The JAX path, which stays modeling-applied or explicit.
  • Flipping the policy on by default, which goes with the R6 default flip.
  • Workspace script cleanup (5F).

Activity

  1. Jammy2211 commented on Nov 24, 2026

    @Jammy2211
    CollaboratorAuthor

    5B-3 shipped as #712 (pending-release): Imaging/Interferometer.sparse_operator_for, the lazy-operator policy (off by default) and gates, and the chunked interferometer path above 1e6 visibilities. Gate: 2614 tests, Heart dev GREEN, smoke 7/7 against the branch. Next: 5C-3 (Galaxy/Lens fit call sites, aggregator reapply of setup.json).

  2. Jammy2211 commented on Nov 24, 2026

    @Jammy2211
    CollaboratorAuthor

    Shipped

    #712 (faa8034): Imaging/Interferometer.sparse_operator_for, the lazy-operator policy (general.yaml inversion: lazy_sparse_operator, default "off", or PYAUTO_SETUP=auto) and its gates, and the chunked interferometer path above 1e6 visibilities. Pending release. Next: 5C-3 (Galaxy/Lens fit call sites, aggregator reapply of setup.json, shared setup helper).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions