From 0cce186c2d887ce723f41cc8443f75e0892d0784 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Wed, 28 Oct 2026 21:17:16 +0000 Subject: [PATCH 1/9] 2d: multi_galaxy + group standard cells (cell builder, shared driver, 20 cell scripts) - scripts/misc/cell_builders/galaxy_group.py: the two datasets (workspace simulator galaxies, grid, exposure, over-sampling; instrument-preset PSF; multi_galaxy at hst 3.0" mask with the extra galaxy noise-scaled, group at euclid 7.5" mask), the workspace MGE modeling model with narrow truth priors, the hst production pixelization at the standard size (Delaunay 1250 + 30, rectangular 35x35), the seeded iid stream. Stdlib at import. - scripts/misc/likelihood_breakdown/galaxy_group_standard.py: run_jax_runtime (jit block, steady median, vmap with OOM halving; parity.json then fit.png), run_jax_breakdown (seven jitted fit_from prefixes split by successive differences), run_numba_runtime (iid stream, warm median; parity, fit.png), run_numba_breakdown (eager stage walk, warm medians). --fast for local checks; without --output-path rows go to output/p2d_local/results/. - scripts/{multi_galaxy,group}/{mge,rectangular,delaunay}/likelihood_{runtime,breakdown}[_numba].py: thin wrappers (numba ones pin threads before numpy). - .gitignore: dataset/multi_galaxy/ (simulated on first use). Refs autolens_profiling#473 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016nhQ8QrXN6x7n82QzZyz93 --- .gitignore | 1 + .../group/delaunay/likelihood_breakdown.py | 39 + .../delaunay/likelihood_breakdown_numba.py | 44 ++ scripts/group/delaunay/likelihood_runtime.py | 40 + .../delaunay/likelihood_runtime_numba.py | 45 ++ scripts/group/mge/likelihood_breakdown.py | 39 + scripts/group/mge/likelihood_runtime.py | 40 + .../group/rectangular/likelihood_breakdown.py | 39 + .../rectangular/likelihood_breakdown_numba.py | 44 ++ .../group/rectangular/likelihood_runtime.py | 40 + .../rectangular/likelihood_runtime_numba.py | 45 ++ scripts/misc/cell_builders/README.md | 6 +- scripts/misc/cell_builders/galaxy_group.py | 745 ++++++++++++++++++ .../galaxy_group_standard.py | 721 +++++++++++++++++ .../delaunay/likelihood_breakdown.py | 39 + .../delaunay/likelihood_breakdown_numba.py | 44 ++ .../delaunay/likelihood_runtime.py | 40 + .../delaunay/likelihood_runtime_numba.py | 45 ++ .../multi_galaxy/mge/likelihood_breakdown.py | 39 + .../multi_galaxy/mge/likelihood_runtime.py | 40 + .../rectangular/likelihood_breakdown.py | 39 + .../rectangular/likelihood_breakdown_numba.py | 44 ++ .../rectangular/likelihood_runtime.py | 40 + .../rectangular/likelihood_runtime_numba.py | 45 ++ 24 files changed, 2302 insertions(+), 1 deletion(-) create mode 100644 scripts/group/delaunay/likelihood_breakdown.py create mode 100644 scripts/group/delaunay/likelihood_breakdown_numba.py create mode 100644 scripts/group/delaunay/likelihood_runtime.py create mode 100644 scripts/group/delaunay/likelihood_runtime_numba.py create mode 100644 scripts/group/mge/likelihood_breakdown.py create mode 100644 scripts/group/mge/likelihood_runtime.py create mode 100644 scripts/group/rectangular/likelihood_breakdown.py create mode 100644 scripts/group/rectangular/likelihood_breakdown_numba.py create mode 100644 scripts/group/rectangular/likelihood_runtime.py create mode 100644 scripts/group/rectangular/likelihood_runtime_numba.py create mode 100644 scripts/misc/cell_builders/galaxy_group.py create mode 100644 scripts/misc/likelihood_breakdown/galaxy_group_standard.py create mode 100644 scripts/multi_galaxy/delaunay/likelihood_breakdown.py create mode 100644 scripts/multi_galaxy/delaunay/likelihood_breakdown_numba.py create mode 100644 scripts/multi_galaxy/delaunay/likelihood_runtime.py create mode 100644 scripts/multi_galaxy/delaunay/likelihood_runtime_numba.py create mode 100644 scripts/multi_galaxy/mge/likelihood_breakdown.py create mode 100644 scripts/multi_galaxy/mge/likelihood_runtime.py create mode 100644 scripts/multi_galaxy/rectangular/likelihood_breakdown.py create mode 100644 scripts/multi_galaxy/rectangular/likelihood_breakdown_numba.py create mode 100644 scripts/multi_galaxy/rectangular/likelihood_runtime.py create mode 100644 scripts/multi_galaxy/rectangular/likelihood_runtime_numba.py diff --git a/.gitignore b/.gitignore index 9888fc19b..4c6a9b674 100644 --- a/.gitignore +++ b/.gitignore @@ -44,6 +44,7 @@ venv/ # simulator), point_source/simple/*.json (non-deterministic serialization). dataset/cluster/ dataset/group/ +dataset/multi_galaxy/ dataset/group4_mge/ dataset/imaging/group4_mge/ dataset/multi_dataset/ diff --git a/scripts/group/delaunay/likelihood_breakdown.py b/scripts/group/delaunay/likelihood_breakdown.py new file mode 100644 index 000000000..267b035b8 --- /dev/null +++ b/scripts/group/delaunay/likelihood_breakdown.py @@ -0,0 +1,39 @@ +""" +Group: delaunay JAX breakdown (likelihood-lifecycle 2d, autolens_profiling#473) +=============================================================================== + +The nested prefix walk of ``AnalysisImaging.fit_from`` (traced grids, blurred image, data vector, +curvature, F + H, reconstruction, figure of merit), each prefix jitted and timed, rows by +successive differences. Dense mapping route, or the JAX w-tilde operator with ``--sparse``. The +cell's ``parity.json`` and ``fit.png`` come from its runtime row. + +The cell is the group standard cell (Delaunay 1250 Hilbert vertices + 30 zeroed edge points, free AdaptSplit), built by +``scripts/misc/cell_builders/galaxy_group.py``; the driver is +``scripts/misc/likelihood_breakdown/galaxy_group_standard.py``. Dataset: ``dataset/group/euclid``, +simulated on first use. Output: the mirrored cell named by ``--output-path`` (the campaign submits +always pass one), else the scratch tree ``output/p2d_local/results/...``. ``--fast`` is a local +check; ``AUTOLENS_PROFILING_SMOKE=1`` exits after the imports. + + python scripts/group/delaunay/likelihood_breakdown.py --instrument euclid --sparse --fast +""" + +import sys as _sys +from pathlib import Path as _Path + + +def _profiling_root() -> _Path: + for _p in _Path(__file__).resolve().parents: + if (_p / "ruff.toml").exists(): + return _p + raise RuntimeError("autolens_profiling root (ruff.toml) not found") + + +_misc_dir = str(_profiling_root() / "scripts" / "misc") +if _misc_dir not in _sys.path: + _sys.path.insert(0, _misc_dir) +_sys.path.insert(0, str(_profiling_root())) + +# Stdlib only until the driver runs. +from likelihood_breakdown import galaxy_group_standard as _driver # noqa: E402 + +_driver.main("group", "delaunay", "breakdown", "jax", script_file=__file__) diff --git a/scripts/group/delaunay/likelihood_breakdown_numba.py b/scripts/group/delaunay/likelihood_breakdown_numba.py new file mode 100644 index 000000000..101ae84ba --- /dev/null +++ b/scripts/group/delaunay/likelihood_breakdown_numba.py @@ -0,0 +1,44 @@ +""" +Group: delaunay numba CPU breakdown (likelihood-lifecycle 2d, autolens_profiling#473) +===================================================================================== + +The eager stage walk of the numba sparse fit on the seeded iid stream (each lazily-evaluated +property timed on first access), per-stage medians over the warm instances. The cell's +``parity.json`` and ``fit.png`` come from its runtime row. + +The cell is the group standard cell (Delaunay 1250 Hilbert vertices + 30 zeroed edge points, free AdaptSplit), built by +``scripts/misc/cell_builders/galaxy_group.py``; the driver is +``scripts/misc/likelihood_breakdown/galaxy_group_standard.py``. Dataset: ``dataset/group/euclid``, +simulated on first use. Output: the mirrored cell named by ``--output-path`` (the campaign submits +always pass one), else the scratch tree ``output/p2d_local/results/...``. ``--fast`` is a local +check; ``AUTOLENS_PROFILING_SMOKE=1`` exits after the imports. + + python scripts/group/delaunay/likelihood_breakdown_numba.py --instrument euclid --fast +""" + +import sys as _sys +from pathlib import Path as _Path + + +def _profiling_root() -> _Path: + for _p in _Path(__file__).resolve().parents: + if (_p / "ruff.toml").exists(): + return _p + raise RuntimeError("autolens_profiling root (ruff.toml) not found") + + +_misc_dir = str(_profiling_root() / "scripts" / "misc") +if _misc_dir not in _sys.path: + _sys.path.insert(0, _misc_dir) +_sys.path.insert(0, str(_profiling_root())) + +# Threads are pinned BEFORE numpy (and numba) is imported: OpenBLAS / MKL read their thread +# counts once, when the library loads. _production_config is stdlib-only at import. +from _production_config import pin_thread_env as _pin_thread_env # noqa: E402 + +_pin_thread_env(1) + +# Stdlib only until the driver runs (numba: threads pinned above). +from likelihood_breakdown import galaxy_group_standard as _driver # noqa: E402 + +_driver.main("group", "delaunay", "breakdown", "numba", script_file=__file__) diff --git a/scripts/group/delaunay/likelihood_runtime.py b/scripts/group/delaunay/likelihood_runtime.py new file mode 100644 index 000000000..4390da61a --- /dev/null +++ b/scripts/group/delaunay/likelihood_runtime.py @@ -0,0 +1,40 @@ +""" +Group: delaunay JAX runtime (likelihood-lifecycle 2d, autolens_profiling#473) +============================================================================= + +``AnalysisImaging(use_jax=True)`` on the dense mapping route (setup ``jax_*_dense_fp64``) or, with +``--sparse``, the JAX w-tilde sparse operator (``jax_*_sparse_fp64``): the jitted full pipeline +(lower / compile / first call / steady block), its steady median, and the vmap per call the +catalogue reads as the JAX headline. Then ``parity.json`` (vs the eager NumPy dense reference) and +``fit.png`` beside the row. + +The cell is the group standard cell (Delaunay 1250 Hilbert vertices + 30 zeroed edge points, free AdaptSplit), built by +``scripts/misc/cell_builders/galaxy_group.py``; the driver is +``scripts/misc/likelihood_breakdown/galaxy_group_standard.py``. Dataset: ``dataset/group/euclid``, +simulated on first use. Output: the mirrored cell named by ``--output-path`` (the campaign submits +always pass one), else the scratch tree ``output/p2d_local/results/...``. ``--fast`` is a local +check; ``AUTOLENS_PROFILING_SMOKE=1`` exits after the imports. + + python scripts/group/delaunay/likelihood_runtime.py --instrument euclid --sparse --fast +""" + +import sys as _sys +from pathlib import Path as _Path + + +def _profiling_root() -> _Path: + for _p in _Path(__file__).resolve().parents: + if (_p / "ruff.toml").exists(): + return _p + raise RuntimeError("autolens_profiling root (ruff.toml) not found") + + +_misc_dir = str(_profiling_root() / "scripts" / "misc") +if _misc_dir not in _sys.path: + _sys.path.insert(0, _misc_dir) +_sys.path.insert(0, str(_profiling_root())) + +# Stdlib only until the driver runs. +from likelihood_breakdown import galaxy_group_standard as _driver # noqa: E402 + +_driver.main("group", "delaunay", "runtime", "jax", script_file=__file__) diff --git a/scripts/group/delaunay/likelihood_runtime_numba.py b/scripts/group/delaunay/likelihood_runtime_numba.py new file mode 100644 index 000000000..994c26791 --- /dev/null +++ b/scripts/group/delaunay/likelihood_runtime_numba.py @@ -0,0 +1,45 @@ +""" +Group: delaunay numba CPU runtime (likelihood-lifecycle 2d, autolens_profiling#473) +=================================================================================== + +``AnalysisImaging(use_jax=False)`` on the numba CPU sparse operator (setup +``numba_cpu_sparse_fp64``), threads pinned to 1, over the seeded iid stream: instance 0 discarded +(numba compile), ``--cold-evals`` cold, the rest warm; the headline is the warm iid median. Then +``parity.json`` and ``fit.png`` beside the row. + +The cell is the group standard cell (Delaunay 1250 Hilbert vertices + 30 zeroed edge points, free AdaptSplit), built by +``scripts/misc/cell_builders/galaxy_group.py``; the driver is +``scripts/misc/likelihood_breakdown/galaxy_group_standard.py``. Dataset: ``dataset/group/euclid``, +simulated on first use. Output: the mirrored cell named by ``--output-path`` (the campaign submits +always pass one), else the scratch tree ``output/p2d_local/results/...``. ``--fast`` is a local +check; ``AUTOLENS_PROFILING_SMOKE=1`` exits after the imports. + + python scripts/group/delaunay/likelihood_runtime_numba.py --instrument euclid --fast +""" + +import sys as _sys +from pathlib import Path as _Path + + +def _profiling_root() -> _Path: + for _p in _Path(__file__).resolve().parents: + if (_p / "ruff.toml").exists(): + return _p + raise RuntimeError("autolens_profiling root (ruff.toml) not found") + + +_misc_dir = str(_profiling_root() / "scripts" / "misc") +if _misc_dir not in _sys.path: + _sys.path.insert(0, _misc_dir) +_sys.path.insert(0, str(_profiling_root())) + +# Threads are pinned BEFORE numpy (and numba) is imported: OpenBLAS / MKL read their thread +# counts once, when the library loads. _production_config is stdlib-only at import. +from _production_config import pin_thread_env as _pin_thread_env # noqa: E402 + +_pin_thread_env(1) + +# Stdlib only until the driver runs (numba: threads pinned above). +from likelihood_breakdown import galaxy_group_standard as _driver # noqa: E402 + +_driver.main("group", "delaunay", "runtime", "numba", script_file=__file__) diff --git a/scripts/group/mge/likelihood_breakdown.py b/scripts/group/mge/likelihood_breakdown.py new file mode 100644 index 000000000..5357700fd --- /dev/null +++ b/scripts/group/mge/likelihood_breakdown.py @@ -0,0 +1,39 @@ +""" +Group: mge JAX breakdown (likelihood-lifecycle 2d, autolens_profiling#473) +========================================================================== + +The nested prefix walk of ``AnalysisImaging.fit_from`` (traced grids, blurred image, data vector, +curvature, F + H, reconstruction, figure of merit), each prefix jitted and timed, rows by +successive differences. Dense mapping route, or the JAX w-tilde operator with ``--sparse``. The +cell's ``parity.json`` and ``fit.png`` come from its runtime row. + +The cell is the group standard cell (MGE source of 20 linear Gaussians), built by +``scripts/misc/cell_builders/galaxy_group.py``; the driver is +``scripts/misc/likelihood_breakdown/galaxy_group_standard.py``. Dataset: ``dataset/group/euclid``, +simulated on first use. Output: the mirrored cell named by ``--output-path`` (the campaign submits +always pass one), else the scratch tree ``output/p2d_local/results/...``. ``--fast`` is a local +check; ``AUTOLENS_PROFILING_SMOKE=1`` exits after the imports. + + python scripts/group/mge/likelihood_breakdown.py --instrument euclid --fast +""" + +import sys as _sys +from pathlib import Path as _Path + + +def _profiling_root() -> _Path: + for _p in _Path(__file__).resolve().parents: + if (_p / "ruff.toml").exists(): + return _p + raise RuntimeError("autolens_profiling root (ruff.toml) not found") + + +_misc_dir = str(_profiling_root() / "scripts" / "misc") +if _misc_dir not in _sys.path: + _sys.path.insert(0, _misc_dir) +_sys.path.insert(0, str(_profiling_root())) + +# Stdlib only until the driver runs. +from likelihood_breakdown import galaxy_group_standard as _driver # noqa: E402 + +_driver.main("group", "mge", "breakdown", "jax", script_file=__file__) diff --git a/scripts/group/mge/likelihood_runtime.py b/scripts/group/mge/likelihood_runtime.py new file mode 100644 index 000000000..71a65a628 --- /dev/null +++ b/scripts/group/mge/likelihood_runtime.py @@ -0,0 +1,40 @@ +""" +Group: mge JAX runtime (likelihood-lifecycle 2d, autolens_profiling#473) +======================================================================== + +``AnalysisImaging(use_jax=True)`` on the dense mapping route (setup ``jax_*_dense_fp64``) or, with +``--sparse``, the JAX w-tilde sparse operator (``jax_*_sparse_fp64``): the jitted full pipeline +(lower / compile / first call / steady block), its steady median, and the vmap per call the +catalogue reads as the JAX headline. Then ``parity.json`` (vs the eager NumPy dense reference) and +``fit.png`` beside the row. + +The cell is the group standard cell (MGE source of 20 linear Gaussians), built by +``scripts/misc/cell_builders/galaxy_group.py``; the driver is +``scripts/misc/likelihood_breakdown/galaxy_group_standard.py``. Dataset: ``dataset/group/euclid``, +simulated on first use. Output: the mirrored cell named by ``--output-path`` (the campaign submits +always pass one), else the scratch tree ``output/p2d_local/results/...``. ``--fast`` is a local +check; ``AUTOLENS_PROFILING_SMOKE=1`` exits after the imports. + + python scripts/group/mge/likelihood_runtime.py --instrument euclid --fast +""" + +import sys as _sys +from pathlib import Path as _Path + + +def _profiling_root() -> _Path: + for _p in _Path(__file__).resolve().parents: + if (_p / "ruff.toml").exists(): + return _p + raise RuntimeError("autolens_profiling root (ruff.toml) not found") + + +_misc_dir = str(_profiling_root() / "scripts" / "misc") +if _misc_dir not in _sys.path: + _sys.path.insert(0, _misc_dir) +_sys.path.insert(0, str(_profiling_root())) + +# Stdlib only until the driver runs. +from likelihood_breakdown import galaxy_group_standard as _driver # noqa: E402 + +_driver.main("group", "mge", "runtime", "jax", script_file=__file__) diff --git a/scripts/group/rectangular/likelihood_breakdown.py b/scripts/group/rectangular/likelihood_breakdown.py new file mode 100644 index 000000000..54bc32170 --- /dev/null +++ b/scripts/group/rectangular/likelihood_breakdown.py @@ -0,0 +1,39 @@ +""" +Group: rectangular JAX breakdown (likelihood-lifecycle 2d, autolens_profiling#473) +================================================================================== + +The nested prefix walk of ``AnalysisImaging.fit_from`` (traced grids, blurred image, data vector, +curvature, F + H, reconstruction, figure of merit), each prefix jitted and timed, rows by +successive differences. Dense mapping route, or the JAX w-tilde operator with ``--sparse``. The +cell's ``parity.json`` and ``fit.png`` come from its runtime row. + +The cell is the group standard cell (RectangularBilinearAdaptImage 35 x 35, free Adapt), built by +``scripts/misc/cell_builders/galaxy_group.py``; the driver is +``scripts/misc/likelihood_breakdown/galaxy_group_standard.py``. Dataset: ``dataset/group/euclid``, +simulated on first use. Output: the mirrored cell named by ``--output-path`` (the campaign submits +always pass one), else the scratch tree ``output/p2d_local/results/...``. ``--fast`` is a local +check; ``AUTOLENS_PROFILING_SMOKE=1`` exits after the imports. + + python scripts/group/rectangular/likelihood_breakdown.py --instrument euclid --sparse --fast +""" + +import sys as _sys +from pathlib import Path as _Path + + +def _profiling_root() -> _Path: + for _p in _Path(__file__).resolve().parents: + if (_p / "ruff.toml").exists(): + return _p + raise RuntimeError("autolens_profiling root (ruff.toml) not found") + + +_misc_dir = str(_profiling_root() / "scripts" / "misc") +if _misc_dir not in _sys.path: + _sys.path.insert(0, _misc_dir) +_sys.path.insert(0, str(_profiling_root())) + +# Stdlib only until the driver runs. +from likelihood_breakdown import galaxy_group_standard as _driver # noqa: E402 + +_driver.main("group", "rectangular", "breakdown", "jax", script_file=__file__) diff --git a/scripts/group/rectangular/likelihood_breakdown_numba.py b/scripts/group/rectangular/likelihood_breakdown_numba.py new file mode 100644 index 000000000..824f25e32 --- /dev/null +++ b/scripts/group/rectangular/likelihood_breakdown_numba.py @@ -0,0 +1,44 @@ +""" +Group: rectangular numba CPU breakdown (likelihood-lifecycle 2d, autolens_profiling#473) +======================================================================================== + +The eager stage walk of the numba sparse fit on the seeded iid stream (each lazily-evaluated +property timed on first access), per-stage medians over the warm instances. The cell's +``parity.json`` and ``fit.png`` come from its runtime row. + +The cell is the group standard cell (RectangularBilinearAdaptImage 35 x 35, free Adapt), built by +``scripts/misc/cell_builders/galaxy_group.py``; the driver is +``scripts/misc/likelihood_breakdown/galaxy_group_standard.py``. Dataset: ``dataset/group/euclid``, +simulated on first use. Output: the mirrored cell named by ``--output-path`` (the campaign submits +always pass one), else the scratch tree ``output/p2d_local/results/...``. ``--fast`` is a local +check; ``AUTOLENS_PROFILING_SMOKE=1`` exits after the imports. + + python scripts/group/rectangular/likelihood_breakdown_numba.py --instrument euclid --fast +""" + +import sys as _sys +from pathlib import Path as _Path + + +def _profiling_root() -> _Path: + for _p in _Path(__file__).resolve().parents: + if (_p / "ruff.toml").exists(): + return _p + raise RuntimeError("autolens_profiling root (ruff.toml) not found") + + +_misc_dir = str(_profiling_root() / "scripts" / "misc") +if _misc_dir not in _sys.path: + _sys.path.insert(0, _misc_dir) +_sys.path.insert(0, str(_profiling_root())) + +# Threads are pinned BEFORE numpy (and numba) is imported: OpenBLAS / MKL read their thread +# counts once, when the library loads. _production_config is stdlib-only at import. +from _production_config import pin_thread_env as _pin_thread_env # noqa: E402 + +_pin_thread_env(1) + +# Stdlib only until the driver runs (numba: threads pinned above). +from likelihood_breakdown import galaxy_group_standard as _driver # noqa: E402 + +_driver.main("group", "rectangular", "breakdown", "numba", script_file=__file__) diff --git a/scripts/group/rectangular/likelihood_runtime.py b/scripts/group/rectangular/likelihood_runtime.py new file mode 100644 index 000000000..6a2e5181b --- /dev/null +++ b/scripts/group/rectangular/likelihood_runtime.py @@ -0,0 +1,40 @@ +""" +Group: rectangular JAX runtime (likelihood-lifecycle 2d, autolens_profiling#473) +================================================================================ + +``AnalysisImaging(use_jax=True)`` on the dense mapping route (setup ``jax_*_dense_fp64``) or, with +``--sparse``, the JAX w-tilde sparse operator (``jax_*_sparse_fp64``): the jitted full pipeline +(lower / compile / first call / steady block), its steady median, and the vmap per call the +catalogue reads as the JAX headline. Then ``parity.json`` (vs the eager NumPy dense reference) and +``fit.png`` beside the row. + +The cell is the group standard cell (RectangularBilinearAdaptImage 35 x 35, free Adapt), built by +``scripts/misc/cell_builders/galaxy_group.py``; the driver is +``scripts/misc/likelihood_breakdown/galaxy_group_standard.py``. Dataset: ``dataset/group/euclid``, +simulated on first use. Output: the mirrored cell named by ``--output-path`` (the campaign submits +always pass one), else the scratch tree ``output/p2d_local/results/...``. ``--fast`` is a local +check; ``AUTOLENS_PROFILING_SMOKE=1`` exits after the imports. + + python scripts/group/rectangular/likelihood_runtime.py --instrument euclid --sparse --fast +""" + +import sys as _sys +from pathlib import Path as _Path + + +def _profiling_root() -> _Path: + for _p in _Path(__file__).resolve().parents: + if (_p / "ruff.toml").exists(): + return _p + raise RuntimeError("autolens_profiling root (ruff.toml) not found") + + +_misc_dir = str(_profiling_root() / "scripts" / "misc") +if _misc_dir not in _sys.path: + _sys.path.insert(0, _misc_dir) +_sys.path.insert(0, str(_profiling_root())) + +# Stdlib only until the driver runs. +from likelihood_breakdown import galaxy_group_standard as _driver # noqa: E402 + +_driver.main("group", "rectangular", "runtime", "jax", script_file=__file__) diff --git a/scripts/group/rectangular/likelihood_runtime_numba.py b/scripts/group/rectangular/likelihood_runtime_numba.py new file mode 100644 index 000000000..4a8860572 --- /dev/null +++ b/scripts/group/rectangular/likelihood_runtime_numba.py @@ -0,0 +1,45 @@ +""" +Group: rectangular numba CPU runtime (likelihood-lifecycle 2d, autolens_profiling#473) +====================================================================================== + +``AnalysisImaging(use_jax=False)`` on the numba CPU sparse operator (setup +``numba_cpu_sparse_fp64``), threads pinned to 1, over the seeded iid stream: instance 0 discarded +(numba compile), ``--cold-evals`` cold, the rest warm; the headline is the warm iid median. Then +``parity.json`` and ``fit.png`` beside the row. + +The cell is the group standard cell (RectangularBilinearAdaptImage 35 x 35, free Adapt), built by +``scripts/misc/cell_builders/galaxy_group.py``; the driver is +``scripts/misc/likelihood_breakdown/galaxy_group_standard.py``. Dataset: ``dataset/group/euclid``, +simulated on first use. Output: the mirrored cell named by ``--output-path`` (the campaign submits +always pass one), else the scratch tree ``output/p2d_local/results/...``. ``--fast`` is a local +check; ``AUTOLENS_PROFILING_SMOKE=1`` exits after the imports. + + python scripts/group/rectangular/likelihood_runtime_numba.py --instrument euclid --fast +""" + +import sys as _sys +from pathlib import Path as _Path + + +def _profiling_root() -> _Path: + for _p in _Path(__file__).resolve().parents: + if (_p / "ruff.toml").exists(): + return _p + raise RuntimeError("autolens_profiling root (ruff.toml) not found") + + +_misc_dir = str(_profiling_root() / "scripts" / "misc") +if _misc_dir not in _sys.path: + _sys.path.insert(0, _misc_dir) +_sys.path.insert(0, str(_profiling_root())) + +# Threads are pinned BEFORE numpy (and numba) is imported: OpenBLAS / MKL read their thread +# counts once, when the library loads. _production_config is stdlib-only at import. +from _production_config import pin_thread_env as _pin_thread_env # noqa: E402 + +_pin_thread_env(1) + +# Stdlib only until the driver runs (numba: threads pinned above). +from likelihood_breakdown import galaxy_group_standard as _driver # noqa: E402 + +_driver.main("group", "rectangular", "runtime", "numba", script_file=__file__) diff --git a/scripts/misc/cell_builders/README.md b/scripts/misc/cell_builders/README.md index 3f716a032..179fcd40c 100644 --- a/scripts/misc/cell_builders/README.md +++ b/scripts/misc/cell_builders/README.md @@ -6,6 +6,10 @@ the scripts build exactly the same thing. - `imaging_mge.py` prepares the masked imaging dataset and builds the MGE model and analysis. `scripts/imaging/mge/likelihood_runtime.py` and the [`jax_compile/`](../jax_compile/README.md) probes both use it. +- `galaxy_group.py` simulates the multi_galaxy (hst) and group (euclid) datasets, masks them and + builds the likelihood-lifecycle 2d cells (workspace MGE model, standard-size pixelization) + for every setup of `scripts/{multi_galaxy,group}/` through + `likelihood_breakdown/galaxy_group_standard.py` (autolens_profiling#473). -Nothing here runs on its own or writes results. The tests are in +Nothing here runs on its own or writes results (`galaxy_group.py` writes only its datasets). The tests are in [`jax_compile/test/`](../jax_compile/test/test_current_compile_builder.py). diff --git a/scripts/misc/cell_builders/galaxy_group.py b/scripts/misc/cell_builders/galaxy_group.py new file mode 100644 index 000000000..8d3524c80 --- /dev/null +++ b/scripts/misc/cell_builders/galaxy_group.py @@ -0,0 +1,745 @@ +"""The multi_galaxy and group standard cells (likelihood-lifecycle 2d, autolens_profiling#473). + +One definition of each dataset, its masked and over-sampled form, and the cell model, so every +setup of a likelihood (JAX dense / sparse, numba sparse; runtime and breakdown) fits the same +thing. Nothing runs on import (stdlib only at module level); callers own timing and output. + +Datasets mirror the workspace simulators and the autolens_visualization producers +(``autolens_workspace/scripts/{multi_galaxy,group}/simulator.py``, +``autolens_visualization/true_models/{multi_galaxy,group}.py``): the same galaxies, grid, +exposure, sky and over-sampling. The PSF is the instrument preset's +(``instruments/imaging.py``, 21 x 21), so the cells compare with the imaging cells of the same +instrument (decision D2 on the campaign page). + +- ``multi_galaxy`` at ``hst`` (0.05"/px, 200 x 200, 3.0" mask): two co-dominant lenses + (Sersic light + Isothermal mass), an external shear, a light-only extra galaxy whose pixels are + noise-scaled (``mask_extra_galaxies``) as ``multi_galaxy/modeling.py`` does, and a SersicCore + source. +- ``group`` at ``euclid`` (0.1"/px, 250 x 250, 7.5" mask): one main lens (SersicSph + + IsothermalSph), two extra galaxies (SersicSph + dPIEMassSph), a SersicCore source. + +The cell model is the workspace modeling model (``{multi_galaxy,group}/modeling.py``, the MGE +form): each main lens an MGE of 20 linear Gaussians + Isothermal, an external shear, each group +extra galaxy an MGE of 10 Gaussians (centre fixed) + dPIEMassSph (sigma free), and the source an +MGE of 20 Gaussians (variant ``mge``) or the standard-size production pixelization (variants +``delaunay`` / ``rectangular``: the hst production preset at the standard size, as the imaging +cells, ``_production_config.standard_size_preset``). Mass priors are narrow Gaussians on the +truth so the seeded iid draws (central 20 % of every prior, the imaging cells' sequence) stay +physical. +""" + +from __future__ import annotations + +import inspect +import json +import math +from dataclasses import dataclass, field, replace +from pathlib import Path + +#: The dataset types and likelihood variants this module builds. +DATASET_TYPES = ("multi_galaxy", "group") +VARIANTS = ("mge", "rectangular", "delaunay") +PIXELIZED = ("rectangular", "delaunay") + + +@dataclass(frozen=True) +class DatasetSpec: + """One dataset type's simulation and masking (the workspace simulator, instrument PSF).""" + + dataset_type: str + instrument: str + pixel_scale: float + shape_native: tuple[int, int] + mask_radius: float + psf_shape: tuple[int, int] + psf_sigma: float + exposure_time: float + background_sky_level: float + noise_seed: int + main_lens_centres: tuple + extra_galaxies_centres: tuple = () + #: (centre, radius) of the noise-scaled extra-galaxy region (multi_galaxy only). + noise_scaled: tuple | None = None + provenance: str = "" + lp_sub_size_list: tuple = (4, 2, 2) + lp_radial_list: tuple = (0.3, 0.6) + simulate_sub_size_list: tuple = (32, 8, 2) + notes: list = field(default_factory=list) + + @property + def centres(self) -> list[tuple[float, float]]: + """Every galaxy centre the light-profile over-sampling is centred on (workspace rule).""" + return [tuple(c) for c in (*self.main_lens_centres, *self.extra_galaxies_centres)] + + @property + def masked_pixels(self) -> int: + """Image pixels inside the circular mask: pi r^2 / pixel_scale^2.""" + return int(math.pi * self.mask_radius**2 / self.pixel_scale**2) + + +SPECS = { + "multi_galaxy": DatasetSpec( + dataset_type="multi_galaxy", + instrument="hst", + pixel_scale=0.05, + shape_native=(200, 200), + mask_radius=3.0, + psf_shape=(21, 21), + psf_sigma=0.05, + exposure_time=900.0, + background_sky_level=0.1, + noise_seed=1, + main_lens_centres=((0.35, 0.25), (-0.35, -0.25)), + noise_scaled=((2.2, 1.6), 0.9), + provenance=( + 'autolens_workspace scripts/multi_galaxy/simulator.py (grid 200x200 at 0.05", ' + 'galaxies, exposure 900 s, sky 0.1, mask_extra_galaxies 3 x 0.3") and ' + 'modeling.py (3.0" mask, noise scaling, radial-bin over-sampling on both lenses); ' + "autolens_visualization true_models/multi_galaxy.py; PSF from instruments/imaging.py " + 'hst (21x21, sigma 0.05")' + ), + ), + "group": DatasetSpec( + dataset_type="group", + instrument="euclid", + pixel_scale=0.1, + shape_native=(250, 250), + mask_radius=7.5, + psf_shape=(21, 21), + psf_sigma=0.1, + exposure_time=300.0, + background_sky_level=0.1, + noise_seed=1, + main_lens_centres=((0.0, 0.0),), + extra_galaxies_centres=((3.5, 2.5), (-4.4, -5.0)), + provenance=( + 'autolens_workspace scripts/group/simulator.py (grid 250x250 at 0.1", galaxies, ' + 'exposure 300 s, sky 0.1) and modeling.py (7.5" mask, radial-bin over-sampling on ' + "every galaxy); autolens_visualization true_models/group.py; PSF from " + 'instruments/imaging.py euclid (21x21, sigma 0.1")' + ), + ), +} + +#: The instrument each dataset type is measured on (decision D2). +INSTRUMENTS = {dt: spec.instrument for dt, spec in SPECS.items()} + +#: The seeded iid instance sequence (the imaging production presets': unit values uniform in the +#: central 20 % of every prior, seed 235), used by the MGE variant, which has no mesh preset. +IID_SEED = 235 +IID_UNIT_LOW, IID_UNIT_HIGH = 0.4, 0.6 + + +def spec_for(dataset_type: str, instrument: str | None = None) -> DatasetSpec: + if dataset_type not in SPECS: + raise KeyError(f"no galaxy/group cell for dataset type {dataset_type!r}") + spec = SPECS[dataset_type] + if instrument not in (None, spec.instrument): + raise SystemExit( + f"{dataset_type} is planned at {spec.instrument} only (decision D2); got {instrument!r}" + ) + return spec + + +def dataset_path(dataset_type: str, root: Path) -> Path: + spec = SPECS[dataset_type] + return Path(root) / "dataset" / dataset_type / spec.instrument + + +# --------------------------------------------------------------------------- truth galaxies + + +def truth_galaxies(dataset_type: str): + """``(galaxies, fields)`` of the simulator's true model (the visualization true models).""" + import autolens as al + + if dataset_type == "multi_galaxy": + lens_0 = al.Galaxy( + redshift=0.5, + bulge=al.lp.Sersic( + centre=(0.35, 0.25), + ell_comps=al.convert.ell_comps_from(axis_ratio=0.8, angle=45.0), + intensity=1.2, + effective_radius=0.6, + sersic_index=4.0, + ), + mass=al.mp.Isothermal( + centre=(0.30, 0.28), + ell_comps=al.convert.ell_comps_from(axis_ratio=0.85, angle=45.0), + einstein_radius=1.0, + ), + ) + lens_1 = al.Galaxy( + redshift=0.5, + bulge=al.lp.Sersic( + centre=(-0.35, -0.25), + ell_comps=al.convert.ell_comps_from(axis_ratio=0.7, angle=120.0), + intensity=1.0, + effective_radius=0.5, + sersic_index=4.0, + ), + mass=al.mp.Isothermal( + centre=(-0.31, -0.22), + ell_comps=al.convert.ell_comps_from(axis_ratio=0.8, angle=120.0), + einstein_radius=0.8, + ), + ) + extra = al.Galaxy( + redshift=0.5, + light=al.lp.ExponentialSph(centre=(2.2, 1.6), intensity=1.0, effective_radius=0.3), + ) + source = al.Galaxy( + redshift=1.0, + bulge=al.lp.SersicCore( + centre=(0.0, 0.03), + ell_comps=al.convert.ell_comps_from(axis_ratio=0.8, angle=60.0), + intensity=3.0, + effective_radius=0.15, + sersic_index=1.0, + ), + ) + field = al.MassField(redshift=0.5, shear=al.mp.ExternalShear(gamma_1=0.05, gamma_2=0.05)) + return [lens_0, lens_1, extra, source], [field] + + if dataset_type == "group": + lens_0 = al.Galaxy( + redshift=0.5, + bulge=al.lp.SersicSph( + centre=(0.0, 0.0), intensity=0.7, effective_radius=2.0, sersic_index=4.0 + ), + mass=al.mp.IsothermalSph(centre=(0.0, 0.0), einstein_radius=4.0), + ) + extras = [ + al.Galaxy( + redshift=0.5, + bulge=al.lp.SersicSph( + centre=centre, intensity=0.9, effective_radius=0.8, sersic_index=3.0 + ), + mass=al.mp.dPIEMassSph( + centre=centre, + sigma=sigma, + r_core=0.0, + r_cut=10.0, + redshift_object=0.5, + redshift_source=1.0, + ), + ) + for centre, sigma in zip(SPECS["group"].extra_galaxies_centres, (212.0, 239.0)) + ] + source = al.Galaxy( + redshift=1.0, + bulge=al.lp.SersicCore( + centre=(0.0, 0.1), + ell_comps=al.convert.ell_comps_from(axis_ratio=0.8, angle=60.0), + intensity=3.0, + effective_radius=0.4, + sersic_index=1.0, + ), + ) + return [lens_0, *extras, source], [] + + raise KeyError(dataset_type) + + +#: The truth the cell model's narrow mass priors sit on: (centre, einstein_radius, axis_ratio, +#: angle) per main lens, shear (gamma_1, gamma_2), extra-galaxy dPIE sigma. +TRUTH = { + "multi_galaxy": { + "lenses": [((0.35, 0.25), 1.0, 0.85, 45.0), ((-0.35, -0.25), 0.8, 0.8, 120.0)], + "lens_light_ell": [(0.8, 45.0), (0.7, 120.0)], + "shear": (0.05, 0.05), + "extra_sigma": (), + "source": ((0.0, 0.03), 0.8, 60.0), + }, + "group": { + "lenses": [((0.0, 0.0), 4.0, 1.0, 0.0)], + "lens_light_ell": [(1.0, 0.0)], + "shear": (0.0, 0.0), + "extra_sigma": (212.0, 239.0), + "source": ((0.0, 0.1), 0.8, 60.0), + }, +} + + +def _light_priors_on_truth(basis, *, centre=None, axis_ratio=1.0, angle=0.0) -> None: + """Re-centre an MGE basis's shared light priors on the truth (narrow Gaussians), one new + prior per parameter shared by every Gaussian, as ``mge_model_from`` shares its own. The + workspace's generic MGE priors put the iid draws' lens light ~0.1 off in ellipticity, a + chi-squared of ~30 per pixel at hst depth: not the regime a sampler spends its time in.""" + import autofit as af + import autolens as al + + ell = al.convert.ell_comps_from(axis_ratio=axis_ratio, angle=angle) + e0 = af.GaussianPrior(mean=ell[0], sigma=0.02) + e1 = af.GaussianPrior(mean=ell[1], sigma=0.02) + c0 = c1 = None + if centre is not None: + c0 = af.GaussianPrior(mean=centre[0], sigma=0.01) + c1 = af.GaussianPrior(mean=centre[1], sigma=0.01) + for gaussian in basis.profile_list: + if hasattr(gaussian, "ell_comps"): + gaussian.ell_comps.ell_comps_0 = e0 + gaussian.ell_comps.ell_comps_1 = e1 + if c0 is not None: + gaussian.centre.centre_0 = c0 + gaussian.centre.centre_1 = c1 + + +# --------------------------------------------------------------------------- simulation + + +def simulate(dataset_type: str, root: Path) -> Path: + """Write ``dataset///`` (data, psf, noise map, tracer.json, centres). + + Deterministic (``noise_seed``); the submits call it under a lock before the first leg of an + instrument, and the cell scripts call it when the dataset is missing. + """ + import autolens as al + + spec = SPECS[dataset_type] + path = dataset_path(dataset_type, root) + path.mkdir(parents=True, exist_ok=True) + grid = al.Grid2D.uniform(shape_native=spec.shape_native, pixel_scales=spec.pixel_scale) + over_sample_size = al.util.over_sample.over_sample_size_via_radial_bins_from( + grid=grid, + sub_size_list=list(spec.simulate_sub_size_list), + radial_list=list(spec.lp_radial_list), + centre_list=spec.centres, + ) + grid = grid.apply_over_sampling(over_sample_size=over_sample_size) + psf = al.Convolver.from_gaussian( + shape_native=spec.psf_shape, sigma=spec.psf_sigma, pixel_scales=grid.pixel_scales + ) + simulator = al.SimulatorImaging( + exposure_time=spec.exposure_time, + psf=psf, + background_sky_level=spec.background_sky_level, + add_poisson_noise_to_data=True, + noise_seed=spec.noise_seed, + ) + galaxies, fields = truth_galaxies(dataset_type) + tracer = al.Tracer(galaxies=galaxies, fields=fields) if fields else al.Tracer(galaxies=galaxies) + dataset = simulator.via_tracer_from(tracer=tracer, grid=grid) + import autolens.plot as aplt + + aplt.fits_imaging( + dataset=dataset, + data_path=path / "data.fits", + psf_path=path / "psf.fits", + noise_map_path=path / "noise_map.fits", + overwrite=True, + ) + al.output_to_json(obj=tracer, file_path=path / "tracer.json") + al.output_to_json( + obj=al.Grid2DIrregular([list(c) for c in spec.main_lens_centres]), + file_path=path / "main_lens_centres.json", + ) + if spec.extra_galaxies_centres: + al.output_to_json( + obj=al.Grid2DIrregular([list(c) for c in spec.extra_galaxies_centres]), + file_path=path / "extra_galaxies_centres.json", + ) + (path / "simulation.json").write_text( + json.dumps( + { + "dataset_type": dataset_type, + "instrument": spec.instrument, + "provenance": spec.provenance, + "shape_native": list(spec.shape_native), + "pixel_scale": spec.pixel_scale, + "psf": {"shape": list(spec.psf_shape), "sigma": spec.psf_sigma}, + "exposure_time": spec.exposure_time, + "background_sky_level": spec.background_sky_level, + "noise_seed": spec.noise_seed, + "over_sampling": { + "sub_size_list": list(spec.simulate_sub_size_list), + "radial_list": list(spec.lp_radial_list), + "centres": [list(c) for c in spec.centres], + }, + }, + indent=2, + ) + ) + return path + + +def simulate_if_missing(dataset_type: str, root: Path) -> Path: + path = dataset_path(dataset_type, root) + if not (path / "tracer.json").is_file() or not (path / "data.fits").is_file(): + print(f" [simulate] {path} missing; simulating the {dataset_type} dataset") + simulate(dataset_type, root) + return path + + +def ensure_dataset(dataset_type: str, root: Path) -> Path: + """:func:`simulate_if_missing` under a lock (array tasks of one dataset start together).""" + import fcntl + + lock_dir = Path(root) / "output" + lock_dir.mkdir(parents=True, exist_ok=True) + with open(lock_dir / f"p2d_dataset_{dataset_type}.lock", "w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX) + return simulate_if_missing(dataset_type, root) + + +# --------------------------------------------------------------------------- the masked dataset + + +def load_masked(dataset_type: str, root: Path): + """The simulated dataset, masked and (multi_galaxy) noise-scaled, light-profile over-sampled + on every galaxy centre (workspace ``modeling.py``). Pixelization over-sampling is added by + :func:`standard_pixelized_data` for the mesh variants.""" + import autolens as al + + spec = SPECS[dataset_type] + path = ensure_dataset(dataset_type, root) + dataset = al.Imaging.from_fits( + data_path=path / "data.fits", + psf_path=path / "psf.fits", + noise_map_path=path / "noise_map.fits", + pixel_scales=spec.pixel_scale, + ) + if spec.noise_scaled is not None: + centre, radius = spec.noise_scaled + scaled = al.Mask2D.circular( + shape_native=dataset.shape_native, + pixel_scales=dataset.pixel_scales, + centre=centre, + radius=radius, + ) + # apply_noise_scaling scales the pixels where the mask is False, i.e. inside this circle. + # (The workspace simulator writes this mask with invert=True, which under the current + # library scales the complement instead: flagged on the campaign page, not mirrored.) + dataset = dataset.apply_noise_scaling(mask=scaled) + mask = al.Mask2D.circular( + shape_native=dataset.shape_native, + pixel_scales=dataset.pixel_scales, + radius=spec.mask_radius, + ) + dataset = dataset.apply_mask(mask=mask) + dataset = dataset.apply_over_sampling(over_sample_size_lp=lp_over_sample_size(spec, dataset)) + return dataset, path + + +def lp_over_sample_size(spec: DatasetSpec, dataset): + import autolens as al + + return al.util.over_sample.over_sample_size_via_radial_bins_from( + grid=dataset.grid, + sub_size_list=list(spec.lp_sub_size_list), + radial_list=list(spec.lp_radial_list), + centre_list=spec.centres, + ) + + +def standard_preset(dataset_type: str, variant: str): + """The hst production preset of ``variant`` at the standard size (decision D5), renamed and + with this dataset type's light-profile over-sampling (bins on every galaxy centre).""" + import _production_config as pc + + spec = SPECS[dataset_type] + family = pc.STANDARD_FAMILY[variant] + base = pc.standard_size_preset(family, pc.STANDARD_SIZE_REFERENCE_INSTRUMENT) + note = ( + f"likelihood-lifecycle 2d (#473, decision D5): the {base.name} preset (hst, standard size) " + f"on the {dataset_type} dataset at {spec.instrument}; light-profile over-sampling " + f"{list(spec.lp_sub_size_list)} at {list(spec.lp_radial_list)} on every galaxy centre " + "(workspace modeling.py); lens light = the workspace MGE (not the preset's); no positions " + "penalty" + ) + return replace( + base, + name=f"{base.name}_{dataset_type}", + provenance=f"{base.provenance} — {note}", + size_override=f"{base.size_override}; {note}" if base.size_override else note, + lp_sub_size_list=tuple(spec.lp_sub_size_list), + lp_radial_list=tuple(spec.lp_radial_list), + positions_factor=None, + positions_minimum_threshold=None, + ) + + +def standard_pixelized_data(dataset_type: str, dataset, path: Path, preset, sparse=None): + """``(dataset, mesh adapt image, record)``: ``_production_config.production_standard_data`` + with the light-profile bins on every galaxy centre. The source adapt image is the subtracted + S/N (every lens-plane galaxy of the truth tracer removed), the pixelization over-sampling is + cut on the uncapped map and the mesh / regularization image capped at the preset's S/N.""" + import autolens as al + import numpy as np + + import _production_config as pc + + spec = SPECS[dataset_type] + lp = lp_over_sample_size(spec, dataset) + dataset = dataset.apply_over_sampling( + over_sample_size_lp=lp, over_sample_size_pixelization=preset.pix_low + ) + snr, minimum_percent = pc.production_source_snr(dataset, path) + above = np.asarray(snr) > preset.pix_snr_cut + pix = al.Array2D(values=np.where(above, preset.pix_high, preset.pix_low), mask=dataset.mask) + dataset = dataset.apply_over_sampling(over_sample_size_lp=lp, over_sample_size_pixelization=pix) + dataset = apply_sparse(dataset, sparse) + mesh_adapt = snr + if preset.adapt_snr_cap is not None: + mesh_adapt = al.Array2D( + values=np.minimum(np.asarray(snr), preset.adapt_snr_cap), mask=dataset.mask + ) + record = { + "over_sampling_preset": preset.name, + "over_sample_size_lp_rule": { + "sub_size_list": list(spec.lp_sub_size_list), + "radial_list": list(spec.lp_radial_list), + "centres": [list(c) for c in spec.centres], + }, + "over_sample_size_pixelization_rule": { + "source_snr_cut": preset.pix_snr_cut, + "sub_size_above": preset.pix_high, + "sub_size_below": preset.pix_low, + "threshold_map": "uncapped subtracted S/N (production)", + "pixels_above": int(above.sum()), + "pixels_below": int((~above).sum()), + }, + "adapt_image": "subtracted S/N (truth tracer, every lens-plane galaxy removed), floored", + "lens_light_source": "truth", + "adapt_minimum_percent": minimum_percent, + "mesh_adapt_snr_cap": preset.adapt_snr_cap, + } + return dataset, mesh_adapt, record + + +def apply_sparse(dataset, sparse): + """``sparse``: ``"cpu"`` the numba CPU operator, an int the JAX operator at that batch size.""" + if sparse == "cpu": + return dataset.apply_sparse_operator_cpu() + if sparse: + return dataset.apply_sparse_operator(batch_size=int(sparse)) + return dataset + + +# --------------------------------------------------------------------------- the cell model + + +def _dpie_constants(mass) -> None: + """Fix the dPIE's non-parameters as the workspace does (``H0`` / ``Om0`` only where the + pinned library has them).""" + import autolens as al + + mass.r_core = 0.0 + mass.r_cut = 10.0 + mass.redshift_object = 0.5 + mass.redshift_source = 1.0 + params = inspect.signature(al.mp.dPIEMassSph.__init__).parameters + if "H0" in params: + mass.H0 = 67.66 + if "Om0" in params: + mass.Om0 = 0.30966 + + +def build_model(dataset_type: str, variant: str, *, source_pixelization=None): + """The workspace modeling model (MGE form) with this variant's source. + + ``source_pixelization``: the ``al.Pixelization`` (or its ``af.Model``) of a mesh variant; + None for ``mge`` (an MGE source of 20 Gaussians). Prior creation order is fixed (main lenses, + shear, extra galaxies, source) so the seeded iid draws land on the same parameters. + """ + import autofit as af + import autolens as al + + spec = SPECS[dataset_type] + truth = TRUTH[dataset_type] + sigma_min = spec.pixel_scale / 10.0 + + lenses = {} + for i, (centre, einstein_radius, axis_ratio, angle) in enumerate(truth["lenses"]): + bulge = al.model_util.mge_model_from( + mask_radius=spec.mask_radius, + total_gaussians=20, + centre_prior_is_uniform=True, + centre=tuple(centre), + sigma_min=sigma_min, + ) + light_q, light_angle = truth["lens_light_ell"][i] + _light_priors_on_truth(bulge, centre=centre, axis_ratio=light_q, angle=light_angle) + mass = af.Model(al.mp.Isothermal) + if dataset_type == "multi_galaxy": + mass.centre = tuple(centre) # fixed to the light centre (multi_galaxy/modeling.py) + else: + mass.centre.centre_0 = af.GaussianPrior(mean=centre[0], sigma=0.005) + mass.centre.centre_1 = af.GaussianPrior(mean=centre[1], sigma=0.005) + ell = al.convert.ell_comps_from(axis_ratio=axis_ratio, angle=angle) + mass.ell_comps.ell_comps_0 = af.GaussianPrior(mean=ell[0], sigma=0.01) + mass.ell_comps.ell_comps_1 = af.GaussianPrior(mean=ell[1], sigma=0.01) + mass.einstein_radius = af.GaussianPrior(mean=einstein_radius, sigma=0.05) + lenses[f"lens_{i}"] = af.Model(al.Galaxy, redshift=0.5, bulge=bulge, mass=mass) + + shear = af.Model(al.mp.ExternalShear) + shear.gamma_1 = af.GaussianPrior(mean=truth["shear"][0], sigma=0.005) + shear.gamma_2 = af.GaussianPrior(mean=truth["shear"][1], sigma=0.005) + field = af.Model(al.MassField, redshift=0.5, shear=shear) + + extras = [] + for centre, sigma in zip(spec.extra_galaxies_centres, truth["extra_sigma"]): + bulge = al.model_util.mge_model_from( + mask_radius=spec.mask_radius, + total_gaussians=10, + centre_fixed=tuple(centre), + sigma_min=sigma_min, + ) + _light_priors_on_truth(bulge) # SersicSph truth: round light + mass = af.Model(al.mp.dPIEMassSph) + mass.centre = tuple(centre) + mass.sigma = af.GaussianPrior(mean=sigma, sigma=10.0) + _dpie_constants(mass) + extras.append(af.Model(al.Galaxy, redshift=0.5, bulge=bulge, mass=mass)) + + if source_pixelization is None: + source_bulge = al.model_util.mge_model_from( + mask_radius=spec.mask_radius, + total_gaussians=20, + gaussian_per_basis=1, + centre_prior_is_uniform=False, + ) + source_centre, source_q, source_angle = truth["source"] + _light_priors_on_truth( + source_bulge, centre=source_centre, axis_ratio=source_q, angle=source_angle + ) + source = af.Model(al.Galaxy, redshift=1.0, bulge=source_bulge) + else: + source = af.Model(al.Galaxy, redshift=1.0, pixelization=source_pixelization) + + kwargs = {"galaxies": af.Collection(**lenses, source=source), "fields": field} + if extras: + kwargs["extra_galaxies"] = af.Collection(extras) + return af.Collection(**kwargs) + + +def iid_instances(model, n: int, *, seed: int = IID_SEED, low=IID_UNIT_LOW, high=IID_UNIT_HIGH): + """``n`` seeded iid draws from the central 20 % of every prior, with their unit vectors.""" + import numpy as np + + rng = np.random.default_rng(seed) + out = [] + for _ in range(n): + unit = [float(u) for u in rng.uniform(low, high, size=model.prior_count)] + out.append((model.instance_from_unit_vector(unit_vector=unit), unit)) + return out + + +def standard_cell( + dataset_type: str, + variant: str, + *, + root: Path, + sparse=None, + memo: str = "off", + n_instances: int = 1, + use_mixed_precision: bool = False, +): + """Everything one setup of a galaxy/group likelihood needs, built the one shared way. + + ``sparse``: None (dense mapping), ``"cpu"`` (numba operator) or an int (JAX operator batch + size). Returns a dict: ``spec``, ``dataset``, ``dataset_path``, ``preset`` (None for mge), + ``adapt_image``, ``image_plane_mesh_grid``, ``n_source_pixels``, + ``source_pixels_requested``, ``model``, ``instances`` / ``unit_vectors`` (the seeded iid + stream; draw 0 is the cell's instance), ``settings``, ``memo_provenance``, ``record``. + """ + import autolens as al + + import _production_config as pc + + if variant not in VARIANTS: + raise KeyError(f"no {dataset_type} cell for variant {variant!r}") + spec = SPECS[dataset_type] + dataset, path = load_masked(dataset_type, root) + record: dict = { + "dataset_type": dataset_type, + "instrument": spec.instrument, + "dataset": spec.provenance, + "mask_radius_arcsec": spec.mask_radius, + "noise_scaled_region": ( + {"centre": list(spec.noise_scaled[0]), "radius": spec.noise_scaled[1]} + if spec.noise_scaled + else None + ), + "lens_light": "workspace MGE: 20 linear Gaussians per main lens" + + (", 10 per extra galaxy (centre fixed)" if spec.extra_galaxies_centres else ""), + "main_lenses": len(spec.main_lens_centres), + "extra_galaxies": len(spec.extra_galaxies_centres), + "ruling": "likelihood-lifecycle 2d draft (#473), decisions D1-D9 on the campaign page", + } + preset = grid = adapt_image = None + if variant == "mge": + dataset = apply_sparse(dataset, sparse) + model = build_model(dataset_type, variant) + n_source_pixels = requested = None + # analysis_settings reads only the memo and precision here (no mesh preset for MGE). + settings, memo_provenance = pc.analysis_settings( + pc.preset_for("pixelization_numba", "hst"), + memo, + use_mixed_precision=use_mixed_precision, + ) + record.update( + source="MGE, 20 linear Gaussians (one basis)", + sequence={ + "kind": "iid", + "unit_low": IID_UNIT_LOW, + "unit_high": IID_UNIT_HIGH, + "seed": IID_SEED, + }, + ) + seed, low, high = IID_SEED, IID_UNIT_LOW, IID_UNIT_HIGH + else: + preset = standard_preset(dataset_type, variant) + dataset, adapt_image, data_record = standard_pixelized_data( + dataset_type, dataset, path, preset, sparse=sparse + ) + if preset.mesh_kind == "delaunay": + grid = pc.production_image_mesh_grid(dataset, adapt_image, preset, spec.mask_radius) + n_source_pixels = int(grid.shape[0]) + requested = pc.STANDARD_HILBERT_PIXELS + mesh = pc.production_mesh( + preset, n_vertices=n_source_pixels, mesh_class=al.mesh.Delaunay + ) + else: + n_source_pixels = preset.rect_pixels_yx**2 + requested = pc.STANDARD_RECT_PIXELS_YX**2 + mesh = pc.production_mesh(preset) + import autofit as af + + reg = pc.regularization_model(preset) + if isinstance(reg, af.Model) or isinstance(mesh, af.Model): + pixelization = af.Model(al.Pixelization, mesh=mesh, regularization=reg) + else: + pixelization = al.Pixelization(mesh=mesh, regularization=reg) + model = build_model(dataset_type, variant, source_pixelization=pixelization) + settings, memo_provenance = pc.analysis_settings( + preset, memo, use_mixed_precision=use_mixed_precision + ) + record.update(production_preset=preset.as_json(), production_data_record=data_record) + seed, low, high = preset.seed, preset.iid_unit_low, preset.iid_unit_high + draws = iid_instances(model, max(1, int(n_instances)), seed=seed, low=low, high=high) + return { + "spec": spec, + "dataset": dataset, + "dataset_path": path, + "preset": preset, + "adapt_image": adapt_image, + "image_plane_mesh_grid": grid, + "n_source_pixels": n_source_pixels, + "source_pixels_requested": requested, + "model": model, + "instances": [d[0] for d in draws], + "unit_vectors": [d[1] for d in draws], + "settings": settings, + "memo_provenance": memo_provenance, + "record": record, + } + + +def adapt_images_for(cell: dict, instance): + """``al.AdaptImages`` for ``instance`` (None for mge: no adaptive component).""" + import _production_config as pc + + if cell["adapt_image"] is None: + return None + return pc.adapt_images_for(instance, cell["image_plane_mesh_grid"], cell["adapt_image"]) diff --git a/scripts/misc/likelihood_breakdown/galaxy_group_standard.py b/scripts/misc/likelihood_breakdown/galaxy_group_standard.py new file mode 100644 index 000000000..108732702 --- /dev/null +++ b/scripts/misc/likelihood_breakdown/galaxy_group_standard.py @@ -0,0 +1,721 @@ +"""Shared drivers for the multi_galaxy and group standard cells (likelihood-lifecycle 2d, #473). + +Every setup of a ``multi_galaxy`` / ``group`` likelihood x instrument evaluates one likelihood: +the standard cell of ``scripts/misc/cell_builders/galaxy_group.py`` (the workspace modeling +model, MGE lens light, with an MGE source or the standard-size production pixelization) at its +seeded iid draw 0. The cell scripts under ``scripts/{multi_galaxy,group}//`` are thin +wrappers over :func:`main`, so the setups cannot drift: + +- ``likelihood_runtime.py [--sparse]`` -- :func:`run_jax_runtime`: ``AnalysisImaging(use_jax= + True)`` on the dense mapping route (setup ``jax_*_dense_fp64``) or the JAX w-tilde sparse + operator (``--sparse``, ``jax_*_sparse_fp64``): lower / compile / first call / steady block, + the steady median, and the vmap per call the catalogue reads as the JAX headline; then, after + every timed region, ``parity.json`` against the eager NumPy dense reference and ``fit.png``. +- ``likelihood_breakdown.py [--sparse]`` -- :func:`run_jax_breakdown`: a nested prefix walk of + ``AnalysisImaging.fit_from`` (traced grids, blurred image, data vector, curvature, F + H, + reconstruction, figure of merit), each prefix jitted and timed, rows by successive differences + (``timing.split_by_successive_differences``; the XLA fusion caveat applies). +- ``likelihood_runtime_numba.py`` -- :func:`run_numba_runtime`: ``AnalysisImaging(use_jax=False)`` + on the numba CPU sparse operator over the iid stream (instance 0 discarded, ``--cold-evals`` + cold, the rest warm; headline the warm iid median), threads pinned to 1; parity and fit.png. +- ``likelihood_breakdown_numba.py`` -- :func:`run_numba_breakdown`: the eager stage walk of the + same fit on the iid stream (each stage's lazily-evaluated property timed in the library's own + order), the per-stage median over the warm instances. + +As in the imaging cells, the runtime row writes the cell's ``parity.json`` and ``fit.png``; the +breakdown row leaves both to it (they share the cell folder). Without ``--output-path`` a row +goes to the gitignored scratch tree ``output/p2d_local/results/...`` (never ``results/``). +``--fast`` (a local check, never a campaign leg) cuts repeats, the median and the stream. + +Stdlib only at import: the numba scripts pin their threads before numpy loads. +""" + +from __future__ import annotations + +import argparse +import gc +import json +import os +import sys +import time +from pathlib import Path +from typing import Any + +#: Provisional A100 vmap batch per variant (decision D8): by analogy with the imaging hst rows of +#: ``vram/config.py`` (pixelized 16, MGE 64; these datasets have 11k / 18k masked pixels against +#: imaging hst's 15k). An out-of-memory batch halves until one fits. Non-GPU backends cap at 3. +VMAP_BATCH_GPU = {"mge": 64, "rectangular": 16, "delaunay": 16} +NON_GPU_VMAP_BATCH = 3 + +#: The JAX breakdown's prefix stages, in order (key -> row name). +JAX_STAGES = { + 1: "Ray-trace grids (tracer)", + 2: "Blurred image (non-linear light)", + 3: "Data vector D (mapping + PSF)", + 4: "Curvature matrix F", + 5: "Regularization (F + H)", + 6: "Reconstruction (NNLS)", + 7: "Mapped reconstruction, chi-squared & log evidence", +} +#: The numba breakdown's eager stages, in the library's lazy-evaluation order. +NUMBA_STAGES = ( + "FitImaging construct (tracer)", + "Blurred image (non-linear light)", + "Inversion build (trace + mesh + mappers)", + "Data vector D [numba]", + "Curvature matrix F [numba]", + "Regularization (F + H)", + "Reconstruction (NNLS)", + "Mapped reconstructed image", + "Chi-squared & log evidence", +) +STAGE_NOTE = ( + "Each row is one stage of AnalysisImaging.fit_from in the library's own lazy order; the " + "rows sum to total_step_by_step. JAX rows are successive differences of jitted prefixes " + "(params -> stage k), so XLA fusion can move work across a boundary and a small negative " + "row is noise; numba rows time each cached property on first access, per instance, and " + "report the median over the warm instances." +) +PARITY_QUANTITY = ( + "figure_of_merit (the cell's log_likelihood_function value: the log evidence) at iid draw 0" +) + + +def _driver_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser(allow_abbrev=False) + parser.add_argument( + "--fast", + action="store_true", + help="Local check only: 2 steady repeats, a 5-call median, vmap batch 2, 4 instances.", + ) + return parser + + +def _setup_id(engine: str, cli) -> str: + sparse = engine == "numba" or bool(cli.use_sparse_operator) + if engine == "numba": + return "numba_cpu_sparse_fp64" + import jax + + device = "gpu" if jax.default_backend() == "gpu" else "cpu" + precision = "mixed" if cli.use_mixed_precision else "fp64" + return f"jax_{device}_{'sparse' if sparse else 'dense'}_{precision}" + + +def _host_class(cli) -> str: + name = cli.config_name or "" + for host in ("hpc_ral_cpu", "hpc_a100"): + if name.startswith(host): + return host + return "local_gpu" if "gpu" in name else "local_laptop" + + +def output_path(cli, *, dataset_type, variant, instrument, engine, measurement, root) -> Path: + """``--output-path`` when given (the campaign submits always pass one), else the scratch + mirror ``output/p2d_local/results/
/////.json``.""" + if getattr(cli, "output_path", None) is not None: + path = Path(cli.output_path) + else: + path = ( + Path(root) + / "output" + / "p2d_local" + / "results" + / dataset_type + / variant + / instrument + / _setup_id(engine, cli) + / _host_class(cli) + / f"{measurement}.json" + ) + path.parent.mkdir(parents=True, exist_ok=True) + return path + + +def _configuration(cell: dict, **extra) -> dict: + spec, dataset = cell["spec"], cell["dataset"] + return { + "dataset_type": spec.dataset_type, + "pixel_scale_arcsec": spec.pixel_scale, + "mask_radius_arcsec": spec.mask_radius, + "image_pixels_masked": int(dataset.data.shape[0]), + "over_sampled_pixels": int(dataset.grids.lp.over_sampled.shape[0]), + "source_pixels": cell["n_source_pixels"], + # What was asked for (Delaunay 1250 Hilbert points, rectangular 1225); built is above. + "source_pixels_requested": cell["source_pixels_requested"], + "standard_size": True, + "galaxy_group_cell": cell["record"], + "memo_provenance": cell["memo_provenance"], + "instance": "iid draw 0 of the seeded sequence", + "instance_unit_vector": cell["unit_vectors"][0], + **extra, + } + + +def _analysis(cell: dict, instance, *, use_jax: bool, dataset=None): + import autolens as al + from cell_builders import galaxy_group as gg + + return al.AnalysisImaging( + dataset=cell["dataset"] if dataset is None else dataset, + adapt_images=gg.adapt_images_for(cell, instance), + settings=cell["settings"], + use_jax=use_jax, + ) + + +def _reference_and_fit(cell: dict, instance): + """``(reference log evidence, eager NumPy dense fit)`` at ``instance``; a failure costs only + the witness and the figure, never the row.""" + import _production_config as pc + + try: + analysis = _analysis( + cell, instance, use_jax=False, dataset=pc.numpy_dense_twin(cell["dataset"]) + ) + fit = analysis.fit_from(instance=instance) + return float(fit.figure_of_merit), fit + except Exception as exc: # noqa: BLE001 + print(f" WARNING: eager NumPy dense reference failed: {type(exc).__name__}: {exc}") + return float("nan"), None + + +def _write_witness_and_figure( + dict_path: Path, cell: dict, *, value, use_mixed_precision, autolens_version, cli, note +): + """``parity.json`` then ``fit.png`` beside the row, after every timed region.""" + from _profile_cli import render_fit_png, write_parity_json + + reference, fit = _reference_and_fit(cell, cell["instances"][0]) + spec = cell["spec"] + write_parity_json( + dict_path.parent, + log_likelihood=value, + reference_log_likelihood=reference, + use_mixed_precision=use_mixed_precision, + reference_source=( + "eager NumPy dense-mapping al.AnalysisImaging(use_jax=False, no sparse operator) in " + f"the same process: {spec.dataset_type}/{spec.instrument}, same dataset, model and " + f"instance ({note})" + ), + autolens_version=autolens_version, + source_pixels=cell["n_source_pixels"], + source_pixels_requested=cell["source_pixels_requested"], + quantity=PARITY_QUANTITY, + dataset_type=spec.dataset_type, + ) + if fit is not None: + render_fit_png(fit, dict_path.parent, dataset_type="imaging", cli=cli) + return reference + + +def _write(dict_path: Path, summary: dict) -> None: + dict_path.write_text(json.dumps(summary, indent=2, default=float)) + print(f"\n Row written: {dict_path}") + + +# --------------------------------------------------------------------------- JAX + + +def _jax_cell(dataset_type, variant, cli, root, n_instances=1): + import jax + from cell_builders import galaxy_group as gg + + if not jax.config.x64_enabled: + raise SystemExit("JAX x64 is off: export JAX_ENABLE_X64=True (fp32 truncation).") + sparse = int(cli.sparse_batch_size) if cli.use_sparse_operator else None + return gg.standard_cell( + dataset_type, + variant, + root=root, + sparse=sparse, + memo=cli.memo, + n_instances=n_instances, + use_mixed_precision=cli.use_mixed_precision, + ) + + +def _check_route(analysis, params_tree, sparse: bool) -> str: + """The inversion class the traced pipeline builds (a shape-only trace, no compute).""" + import jax + + info: dict[str, str] = {} + + def traced(params): + fit = analysis.fit_from(instance=params) + info["inversion_class"] = type(fit.inversion).__name__ + return fit.figure_of_merit + + jax.eval_shape(traced, params_tree) + want = "InversionImagingSparse" if sparse else "InversionImagingMapping" + if info.get("inversion_class") != want: + raise SystemExit(f"expected {want} on this setup, traced {info}") + print(f" inversion class (traced): {info['inversion_class']}") + return info["inversion_class"] + + +def run_jax_runtime(dataset_type, variant, cli, args, *, script_file, root) -> Path: + import autolens as al + import jax + import jax.numpy as jnp + from autofit.jax import register_model + + from _profile_cli import device_info_dict, resources_dict + + from . import timing + + timer = timing.Timer() + jit_records: dict[str, dict] = {} + load_start = list(os.getloadavg()) + sparse = bool(cli.use_sparse_operator) + print(f"--- {script_file} [{dataset_type}/{variant}] {'sparse' if sparse else 'dense'} ---") + with timer.section("cell_build"): + cell = _jax_cell(dataset_type, variant, cli, root) + instance = cell["instances"][0] + model = cell["model"] + register_model(model) + params_tree = jax.tree_util.tree_map(jnp.asarray, instance) + analysis = _analysis(cell, instance, use_jax=True) + inversion_class = _check_route(analysis, params_tree, sparse) + n_repeats = 2 if args.fast else 10 + + def full_pipeline(params): + return analysis.log_likelihood_function(instance=params) + + print("\n--- Full pipeline: jax.jit(AnalysisImaging.log_likelihood_function) ---") + compiled, full_result = timing.jit_profile( + full_pipeline, + "full_pipeline", + params_tree, + n_repeats=n_repeats, + timer=timer, + jit_records=jit_records, + ) + full_per_call = jit_records["full_pipeline"]["steady_per_call_s"] + full_median = timing.headline_steady_median( + compiled, + params_tree, + block_mean_s=full_per_call, + n_timed=5 if args.fast else None, + block_mean_is=timing.single_jit_block_is(n_repeats), + ) + value = float(full_result) + print(f" full log evidence = {value!r}") + del compiled + jax.clear_caches() + gc.collect() + + on_gpu = jax.default_backend() == "gpu" + batch = 2 if args.fast else (VMAP_BATCH_GPU[variant] if on_gpu else NON_GPU_VMAP_BATCH) + vmap, attempts = None, [] + for nb in sorted({batch, max(1, batch // 2), max(1, batch // 4), 1}, reverse=True): + batched = jax.tree_util.tree_map( + lambda leaf, n=nb: jnp.broadcast_to(leaf, (n, *leaf.shape)), params_tree + ) + try: + per_call = timing.vmap_profile( + full_pipeline, + "full_pipeline", + batched, + nb, + n_repeats=n_repeats, + timer=timer, + jit_records=jit_records, + ) + except Exception as exc: # noqa: BLE001 + text = str(exc) + if "RESOURCE_EXHAUSTED" not in text and "out of memory" not in text.lower(): + raise + attempts.append({"batch": nb, "status": "oom", "error": text.splitlines()[0][:300]}) + print(f" vmap batch {nb}: out of memory, trying smaller") + jax.clear_caches() + gc.collect() + continue + vmap = { + "batch_size": nb, + "batch_size_requested": batch, + "batch_size_source": "galaxy_group_standard.VMAP_BATCH_GPU (provisional, D8)" + if on_gpu + else f"non-GPU cap {NON_GPU_VMAP_BATCH}", + "batch_time": per_call * nb, + "per_call": per_call, + "speedup_vs_single_jit": round(full_per_call / per_call, 2), + "instances": "draw 0 broadcast to the batch (the runtime cells' convention)", + "attempts": attempts, + } + break + jax.clear_caches() + gc.collect() + + al_version = al.__version__ + summary: dict[str, Any] = { + "autolens_version": al_version, + "device": device_info_dict(), + "resources": resources_dict("jax"), + "instrument": cell["spec"].instrument, + "model": variant, + "use_mixed_precision": bool(cli.use_mixed_precision), + "configuration": _configuration( + cell, + inversion_path="sparse" if sparse else "dense", + inversion_class=inversion_class, + sparse_batch_size=int(cli.sparse_batch_size) if sparse else None, + free_parameters=int(model.total_free_parameters), + n_repeats=n_repeats, + fast=bool(args.fast), + host_load_avg_start=load_start, + host_load_avg_end=list(os.getloadavg()), + ), + "log_evidence_jit": value, + "full_pipeline_single_jit": full_per_call, + **full_median, + "vmap": vmap + if vmap is not None + else {"status": "oom", "attempts": attempts, "note": "every vmap batch OOM'd"}, + "jit_phases": jit_records, + "timer": dict(timer.records), + } + dict_path = output_path( + cli, + dataset_type=dataset_type, + variant=variant, + instrument=cell["spec"].instrument, + engine="jax", + measurement="runtime", + root=root, + ) + _write(dict_path, summary) + reference = _write_witness_and_figure( + dict_path, + cell, + value=value, + use_mixed_precision=cli.use_mixed_precision, + autolens_version=al_version, + cli=cli, + note="the JIT log_likelihood_function value", + ) + summary["parity_reference_log_evidence"] = reference + summary["resources"] = resources_dict("jax") + _write(dict_path, summary) + return dict_path + + +def _stage_value(fit, stage: int): + """The sum of every quantity up to ``stage`` (forces XLA to compute them all).""" + import jax.numpy as jnp + + def raw(x): + return jnp.asarray(getattr(x, "array", x)) + + total = jnp.sum(raw(fit.tracer.traced_grid_2d_list_from(grid=fit.grids.lp)[-1])) + if stage >= 2: + total = total + jnp.sum(raw(fit.blurred_image)) + inversion = fit.inversion + if stage >= 3: + total = total + jnp.sum(inversion.data_vector) + if stage >= 4: + total = total + jnp.sum(inversion.curvature_matrix) + if stage >= 5: + total = total + jnp.sum(inversion.curvature_reg_matrix) + if stage >= 6: + total = total + jnp.sum(inversion.reconstruction) + if stage >= 7: + total = total + fit.figure_of_merit + return total + + +def run_jax_breakdown(dataset_type, variant, cli, args, *, script_file, root) -> Path: + import autolens as al + import jax + import jax.numpy as jnp + from autofit.jax import register_model + + from _profile_cli import device_info_dict, resources_dict + + from . import timing + + timer = timing.Timer() + jit_records: dict[str, dict] = {} + sparse = bool(cli.use_sparse_operator) + print(f"--- {script_file} [{dataset_type}/{variant}] {'sparse' if sparse else 'dense'} ---") + with timer.section("cell_build"): + cell = _jax_cell(dataset_type, variant, cli, root) + instance = cell["instances"][0] + register_model(cell["model"]) + params_tree = jax.tree_util.tree_map(jnp.asarray, instance) + analysis = _analysis(cell, instance, use_jax=True) + inversion_class = _check_route(analysis, params_tree, sparse) + n_repeats = 2 if args.fast else 10 + + prefix_per_call: dict[int, float] = {} + for stage, label in JAX_STAGES.items(): + print(f"\n--- prefix {stage}: {label} ---") + + def prefix(params, stage=stage): + return _stage_value(analysis.fit_from(instance=params), stage) + + compiled, _ = timing.jit_profile( + prefix, + f"prefix_{stage}", + params_tree, + n_repeats=n_repeats, + timer=timer, + jit_records=jit_records, + ) + prefix_per_call[stage] = jit_records[f"prefix_{stage}"]["steady_per_call_s"] + del compiled + jax.clear_caches() + gc.collect() + steps = timing.split_by_successive_differences(prefix_per_call, JAX_STAGES) + + al_version = al.__version__ + summary = { + "autolens_version": al_version, + "device": device_info_dict(), + "resources": resources_dict("jax"), + "instrument": cell["spec"].instrument, + "model": variant, + "use_mixed_precision": bool(cli.use_mixed_precision), + "configuration": _configuration( + cell, + inversion_path="sparse" if sparse else "dense", + inversion_class=inversion_class, + sparse_batch_size=int(cli.sparse_batch_size) if sparse else None, + n_repeats=n_repeats, + fast=bool(args.fast), + ), + "steps": steps, + "total_step_by_step": float(sum(steps.values())), + "prefix_per_call_s": {JAX_STAGES[k]: v for k, v in prefix_per_call.items()}, + "steps_note": STAGE_NOTE, + "jit_phases": jit_records, + } + dict_path = output_path( + cli, + dataset_type=dataset_type, + variant=variant, + instrument=cell["spec"].instrument, + engine="jax", + measurement="breakdown", + root=root, + ) + _write(dict_path, summary) + return dict_path + + +# --------------------------------------------------------------------------- numba + + +def _numba_cell(dataset_type, variant, cli, root, args): + from cell_builders import galaxy_group as gg + + n_cold = 1 if args.fast else int(cli.cold_evals) + n_instances = (2 + n_cold + 1) if args.fast else max(int(cli.n_instances), 2 + n_cold) + cell = gg.standard_cell( + dataset_type, variant, root=root, sparse="cpu", memo=cli.memo, n_instances=n_instances + ) + return cell, n_cold + + +def _guard_numba_route(cell) -> str: + from autoarray.inversion.inversion.imaging_numba.sparse import InversionImagingSparseNumba + + instance = cell["instances"][0] + fit = _analysis(cell, instance, use_jax=False).fit_from(instance=instance) + if not isinstance(fit.inversion, InversionImagingSparseNumba): + raise SystemExit( + f"expected InversionImagingSparseNumba, got {type(fit.inversion).__name__}: the numba " + "sparse-operator path is not engaged" + ) + return type(fit.inversion).__name__ + + +def run_numba_runtime(dataset_type, variant, cli, args, thread_env, *, script_file, root) -> Path: + import autolens as al + import numpy as np + + import _production_config as pc + from _profile_cli import device_info_dict, resources_dict + + print(f"--- {script_file} [{dataset_type}/{variant}] numba sparse ---") + cell, n_cold = _numba_cell(dataset_type, variant, cli, root, args) + inversion_class = _guard_numba_route(cell) + per_eval, values = [], [] + for i, instance in enumerate(cell["instances"]): + analysis = _analysis(cell, instance, use_jax=False) + t0 = time.perf_counter() + value = analysis.log_likelihood_function(instance=instance) + per_eval.append(time.perf_counter() - t0) + values.append(float(value)) + print(f" [{i:>2}] {per_eval[-1] * 1e3:9.2f} ms log L = {values[-1]:.6f}") + timing = pc.timing_summary(per_eval, n_cold=n_cold) + print( + f" cold median {timing['cold_eval_median_s']:.6f} s, warm iid median " + f"{timing['warm_iid_median_s']:.6f} s (n = {timing['n_warm']})" + ) + al_version = al.__version__ + summary = { + "autolens_version": al_version, + "device": device_info_dict(), + "resources": resources_dict("numba"), + "instrument": cell["spec"].instrument, + "model": variant, + "configuration": _configuration( + cell, + inversion_path="sparse_numba", + inversion_class=inversion_class, + use_jax=False, + n_instances=len(cell["instances"]), + thread_env=thread_env, + omp_num_threads=os.environ.get("OMP_NUM_THREADS"), + fast=bool(args.fast), + ), + # Headline key aggregate.py reads: the warm iid MEDIAN (the imaging numba cells' rule). + "full_pipeline_single_jit": timing["warm_iid_median_s"], + **timing, + "first_call_incl_numba_compile_s": per_eval[0], + "first_call_finite": bool(np.isfinite(values[0])), + "log_likelihood": values[0] if len(values) == 1 else values[-1], + "log_likelihood_draw0": values[0], + "log_likelihood_sequence": values, + } + dict_path = output_path( + cli, + dataset_type=dataset_type, + variant=variant, + instrument=cell["spec"].instrument, + engine="numba", + measurement="runtime", + root=root, + ) + _write(dict_path, summary) + # Draw 0 again, after the timed stream: the warm-up value may be the cold-cache hazard. + instance = cell["instances"][0] + value = float( + _analysis(cell, instance, use_jax=False).log_likelihood_function(instance=instance) + ) + reference = _write_witness_and_figure( + dict_path, + cell, + value=value, + use_mixed_precision=False, + autolens_version=al_version, + cli=cli, + note="the numba sparse log_likelihood_function value", + ) + summary["parity_reference_log_evidence"] = reference + summary["resources"] = resources_dict("numba") + _write(dict_path, summary) + return dict_path + + +def _eager_stage_times(analysis, instance) -> tuple[list[float], float]: + """Per-stage seconds of one eager fit, each lazily-evaluated property timed on first access.""" + steps = [] + + def timed(fn): + t0 = time.perf_counter() + out = fn() + steps.append(time.perf_counter() - t0) + return out + + fit = timed(lambda: analysis.fit_from(instance=instance)) + timed(lambda: fit.blurred_image) + inversion = timed(lambda: fit.inversion) + timed(lambda: inversion.data_vector) + timed(lambda: inversion.curvature_matrix) + timed(lambda: inversion.curvature_reg_matrix) + timed(lambda: inversion.reconstruction) + timed(lambda: inversion.mapped_reconstructed_data) + value = timed(lambda: float(fit.figure_of_merit)) + return steps, value + + +def run_numba_breakdown(dataset_type, variant, cli, args, thread_env, *, script_file, root): + import autolens as al + import numpy as np + + from _profile_cli import device_info_dict, resources_dict + + print(f"--- {script_file} [{dataset_type}/{variant}] numba sparse, stage walk ---") + cell, n_cold = _numba_cell(dataset_type, variant, cli, root, args) + inversion_class = _guard_numba_route(cell) + per_instance = [] + for i, instance in enumerate(cell["instances"]): + steps, value = _eager_stage_times(_analysis(cell, instance, use_jax=False), instance) + per_instance.append(steps) + print(f" [{i:>2}] {sum(steps) * 1e3:9.2f} ms log L = {value:.6f}") + warm = np.array(per_instance[1 + n_cold :]) + medians = {label: float(np.median(warm[:, k])) for k, label in enumerate(NUMBA_STAGES)} + al_version = al.__version__ + summary = { + "autolens_version": al_version, + "device": device_info_dict(), + "resources": resources_dict("numba"), + "instrument": cell["spec"].instrument, + "model": variant, + "configuration": _configuration( + cell, + inversion_path="sparse_numba", + inversion_class=inversion_class, + use_jax=False, + n_instances=len(cell["instances"]), + n_cold=n_cold, + thread_env=thread_env, + omp_num_threads=os.environ.get("OMP_NUM_THREADS"), + fast=bool(args.fast), + ), + "steps": medians, + "total_step_by_step": float(sum(medians.values())), + "steps_note": STAGE_NOTE, + "steps_per_instance_s": per_instance, + "protocol": ( + "instance 0 discarded (numba compile), the next n_cold excluded, per-stage median " + "over the remaining warm iid instances" + ), + } + dict_path = output_path( + cli, + dataset_type=dataset_type, + variant=variant, + instrument=cell["spec"].instrument, + engine="numba", + measurement="breakdown", + root=root, + ) + _write(dict_path, summary) + return dict_path + + +# --------------------------------------------------------------------------- entry point + + +def main(dataset_type: str, variant: str, measurement: str, engine: str, *, script_file: str): + """Run one cell script. ``engine`` ``jax`` or ``numba``; numba scripts pin their threads + (``_production_config.pin_thread_env(1)``) before calling this.""" + root = next(p for p in Path(script_file).resolve().parents if (p / "ruff.toml").exists()) + for path in (root, root / "scripts" / "misc"): + if str(path) not in sys.path: + sys.path.insert(0, str(path)) + from cell_builders import galaxy_group as gg + + from _production_config import observe_thread_env, pin_thread_env + from _profile_cli import parse_profile_cli + + cli = parse_profile_cli() + args, _ = _driver_parser().parse_known_args() + gg.spec_for(dataset_type, cli.instrument) + thread_env = pin_thread_env(1) if engine == "numba" else observe_thread_env() + if os.environ.get("AUTOLENS_PROFILING_SMOKE") == "1": + print(f"[smoke] {script_file}: imports + module setup OK; exiting.") + return None + if engine == "numba": + if cli.use_sparse_operator: + raise SystemExit("the numba cells are sparse by construction; drop --sparse") + import numba + + numba.set_num_threads(1) + run = run_numba_runtime if measurement == "runtime" else run_numba_breakdown + return run(dataset_type, variant, cli, args, thread_env, script_file=script_file, root=root) + run = run_jax_runtime if measurement == "runtime" else run_jax_breakdown + return run(dataset_type, variant, cli, args, script_file=script_file, root=root) diff --git a/scripts/multi_galaxy/delaunay/likelihood_breakdown.py b/scripts/multi_galaxy/delaunay/likelihood_breakdown.py new file mode 100644 index 000000000..000c1ecf1 --- /dev/null +++ b/scripts/multi_galaxy/delaunay/likelihood_breakdown.py @@ -0,0 +1,39 @@ +""" +Multi-Galaxy: delaunay JAX breakdown (likelihood-lifecycle 2d, autolens_profiling#473) +====================================================================================== + +The nested prefix walk of ``AnalysisImaging.fit_from`` (traced grids, blurred image, data vector, +curvature, F + H, reconstruction, figure of merit), each prefix jitted and timed, rows by +successive differences. Dense mapping route, or the JAX w-tilde operator with ``--sparse``. The +cell's ``parity.json`` and ``fit.png`` come from its runtime row. + +The cell is the multi_galaxy standard cell (Delaunay 1250 Hilbert vertices + 30 zeroed edge points, free AdaptSplit), built by +``scripts/misc/cell_builders/galaxy_group.py``; the driver is +``scripts/misc/likelihood_breakdown/galaxy_group_standard.py``. Dataset: ``dataset/multi_galaxy/hst``, +simulated on first use. Output: the mirrored cell named by ``--output-path`` (the campaign submits +always pass one), else the scratch tree ``output/p2d_local/results/...``. ``--fast`` is a local +check; ``AUTOLENS_PROFILING_SMOKE=1`` exits after the imports. + + python scripts/multi_galaxy/delaunay/likelihood_breakdown.py --instrument hst --sparse --fast +""" + +import sys as _sys +from pathlib import Path as _Path + + +def _profiling_root() -> _Path: + for _p in _Path(__file__).resolve().parents: + if (_p / "ruff.toml").exists(): + return _p + raise RuntimeError("autolens_profiling root (ruff.toml) not found") + + +_misc_dir = str(_profiling_root() / "scripts" / "misc") +if _misc_dir not in _sys.path: + _sys.path.insert(0, _misc_dir) +_sys.path.insert(0, str(_profiling_root())) + +# Stdlib only until the driver runs. +from likelihood_breakdown import galaxy_group_standard as _driver # noqa: E402 + +_driver.main("multi_galaxy", "delaunay", "breakdown", "jax", script_file=__file__) diff --git a/scripts/multi_galaxy/delaunay/likelihood_breakdown_numba.py b/scripts/multi_galaxy/delaunay/likelihood_breakdown_numba.py new file mode 100644 index 000000000..7cbabbeeb --- /dev/null +++ b/scripts/multi_galaxy/delaunay/likelihood_breakdown_numba.py @@ -0,0 +1,44 @@ +""" +Multi-Galaxy: delaunay numba CPU breakdown (likelihood-lifecycle 2d, autolens_profiling#473) +============================================================================================ + +The eager stage walk of the numba sparse fit on the seeded iid stream (each lazily-evaluated +property timed on first access), per-stage medians over the warm instances. The cell's +``parity.json`` and ``fit.png`` come from its runtime row. + +The cell is the multi_galaxy standard cell (Delaunay 1250 Hilbert vertices + 30 zeroed edge points, free AdaptSplit), built by +``scripts/misc/cell_builders/galaxy_group.py``; the driver is +``scripts/misc/likelihood_breakdown/galaxy_group_standard.py``. Dataset: ``dataset/multi_galaxy/hst``, +simulated on first use. Output: the mirrored cell named by ``--output-path`` (the campaign submits +always pass one), else the scratch tree ``output/p2d_local/results/...``. ``--fast`` is a local +check; ``AUTOLENS_PROFILING_SMOKE=1`` exits after the imports. + + python scripts/multi_galaxy/delaunay/likelihood_breakdown_numba.py --instrument hst --fast +""" + +import sys as _sys +from pathlib import Path as _Path + + +def _profiling_root() -> _Path: + for _p in _Path(__file__).resolve().parents: + if (_p / "ruff.toml").exists(): + return _p + raise RuntimeError("autolens_profiling root (ruff.toml) not found") + + +_misc_dir = str(_profiling_root() / "scripts" / "misc") +if _misc_dir not in _sys.path: + _sys.path.insert(0, _misc_dir) +_sys.path.insert(0, str(_profiling_root())) + +# Threads are pinned BEFORE numpy (and numba) is imported: OpenBLAS / MKL read their thread +# counts once, when the library loads. _production_config is stdlib-only at import. +from _production_config import pin_thread_env as _pin_thread_env # noqa: E402 + +_pin_thread_env(1) + +# Stdlib only until the driver runs (numba: threads pinned above). +from likelihood_breakdown import galaxy_group_standard as _driver # noqa: E402 + +_driver.main("multi_galaxy", "delaunay", "breakdown", "numba", script_file=__file__) diff --git a/scripts/multi_galaxy/delaunay/likelihood_runtime.py b/scripts/multi_galaxy/delaunay/likelihood_runtime.py new file mode 100644 index 000000000..13993d886 --- /dev/null +++ b/scripts/multi_galaxy/delaunay/likelihood_runtime.py @@ -0,0 +1,40 @@ +""" +Multi-Galaxy: delaunay JAX runtime (likelihood-lifecycle 2d, autolens_profiling#473) +==================================================================================== + +``AnalysisImaging(use_jax=True)`` on the dense mapping route (setup ``jax_*_dense_fp64``) or, with +``--sparse``, the JAX w-tilde sparse operator (``jax_*_sparse_fp64``): the jitted full pipeline +(lower / compile / first call / steady block), its steady median, and the vmap per call the +catalogue reads as the JAX headline. Then ``parity.json`` (vs the eager NumPy dense reference) and +``fit.png`` beside the row. + +The cell is the multi_galaxy standard cell (Delaunay 1250 Hilbert vertices + 30 zeroed edge points, free AdaptSplit), built by +``scripts/misc/cell_builders/galaxy_group.py``; the driver is +``scripts/misc/likelihood_breakdown/galaxy_group_standard.py``. Dataset: ``dataset/multi_galaxy/hst``, +simulated on first use. Output: the mirrored cell named by ``--output-path`` (the campaign submits +always pass one), else the scratch tree ``output/p2d_local/results/...``. ``--fast`` is a local +check; ``AUTOLENS_PROFILING_SMOKE=1`` exits after the imports. + + python scripts/multi_galaxy/delaunay/likelihood_runtime.py --instrument hst --sparse --fast +""" + +import sys as _sys +from pathlib import Path as _Path + + +def _profiling_root() -> _Path: + for _p in _Path(__file__).resolve().parents: + if (_p / "ruff.toml").exists(): + return _p + raise RuntimeError("autolens_profiling root (ruff.toml) not found") + + +_misc_dir = str(_profiling_root() / "scripts" / "misc") +if _misc_dir not in _sys.path: + _sys.path.insert(0, _misc_dir) +_sys.path.insert(0, str(_profiling_root())) + +# Stdlib only until the driver runs. +from likelihood_breakdown import galaxy_group_standard as _driver # noqa: E402 + +_driver.main("multi_galaxy", "delaunay", "runtime", "jax", script_file=__file__) diff --git a/scripts/multi_galaxy/delaunay/likelihood_runtime_numba.py b/scripts/multi_galaxy/delaunay/likelihood_runtime_numba.py new file mode 100644 index 000000000..e2654da1c --- /dev/null +++ b/scripts/multi_galaxy/delaunay/likelihood_runtime_numba.py @@ -0,0 +1,45 @@ +""" +Multi-Galaxy: delaunay numba CPU runtime (likelihood-lifecycle 2d, autolens_profiling#473) +========================================================================================== + +``AnalysisImaging(use_jax=False)`` on the numba CPU sparse operator (setup +``numba_cpu_sparse_fp64``), threads pinned to 1, over the seeded iid stream: instance 0 discarded +(numba compile), ``--cold-evals`` cold, the rest warm; the headline is the warm iid median. Then +``parity.json`` and ``fit.png`` beside the row. + +The cell is the multi_galaxy standard cell (Delaunay 1250 Hilbert vertices + 30 zeroed edge points, free AdaptSplit), built by +``scripts/misc/cell_builders/galaxy_group.py``; the driver is +``scripts/misc/likelihood_breakdown/galaxy_group_standard.py``. Dataset: ``dataset/multi_galaxy/hst``, +simulated on first use. Output: the mirrored cell named by ``--output-path`` (the campaign submits +always pass one), else the scratch tree ``output/p2d_local/results/...``. ``--fast`` is a local +check; ``AUTOLENS_PROFILING_SMOKE=1`` exits after the imports. + + python scripts/multi_galaxy/delaunay/likelihood_runtime_numba.py --instrument hst --fast +""" + +import sys as _sys +from pathlib import Path as _Path + + +def _profiling_root() -> _Path: + for _p in _Path(__file__).resolve().parents: + if (_p / "ruff.toml").exists(): + return _p + raise RuntimeError("autolens_profiling root (ruff.toml) not found") + + +_misc_dir = str(_profiling_root() / "scripts" / "misc") +if _misc_dir not in _sys.path: + _sys.path.insert(0, _misc_dir) +_sys.path.insert(0, str(_profiling_root())) + +# Threads are pinned BEFORE numpy (and numba) is imported: OpenBLAS / MKL read their thread +# counts once, when the library loads. _production_config is stdlib-only at import. +from _production_config import pin_thread_env as _pin_thread_env # noqa: E402 + +_pin_thread_env(1) + +# Stdlib only until the driver runs (numba: threads pinned above). +from likelihood_breakdown import galaxy_group_standard as _driver # noqa: E402 + +_driver.main("multi_galaxy", "delaunay", "runtime", "numba", script_file=__file__) diff --git a/scripts/multi_galaxy/mge/likelihood_breakdown.py b/scripts/multi_galaxy/mge/likelihood_breakdown.py new file mode 100644 index 000000000..a27982337 --- /dev/null +++ b/scripts/multi_galaxy/mge/likelihood_breakdown.py @@ -0,0 +1,39 @@ +""" +Multi-Galaxy: mge JAX breakdown (likelihood-lifecycle 2d, autolens_profiling#473) +================================================================================= + +The nested prefix walk of ``AnalysisImaging.fit_from`` (traced grids, blurred image, data vector, +curvature, F + H, reconstruction, figure of merit), each prefix jitted and timed, rows by +successive differences. Dense mapping route, or the JAX w-tilde operator with ``--sparse``. The +cell's ``parity.json`` and ``fit.png`` come from its runtime row. + +The cell is the multi_galaxy standard cell (MGE source of 20 linear Gaussians), built by +``scripts/misc/cell_builders/galaxy_group.py``; the driver is +``scripts/misc/likelihood_breakdown/galaxy_group_standard.py``. Dataset: ``dataset/multi_galaxy/hst``, +simulated on first use. Output: the mirrored cell named by ``--output-path`` (the campaign submits +always pass one), else the scratch tree ``output/p2d_local/results/...``. ``--fast`` is a local +check; ``AUTOLENS_PROFILING_SMOKE=1`` exits after the imports. + + python scripts/multi_galaxy/mge/likelihood_breakdown.py --instrument hst --fast +""" + +import sys as _sys +from pathlib import Path as _Path + + +def _profiling_root() -> _Path: + for _p in _Path(__file__).resolve().parents: + if (_p / "ruff.toml").exists(): + return _p + raise RuntimeError("autolens_profiling root (ruff.toml) not found") + + +_misc_dir = str(_profiling_root() / "scripts" / "misc") +if _misc_dir not in _sys.path: + _sys.path.insert(0, _misc_dir) +_sys.path.insert(0, str(_profiling_root())) + +# Stdlib only until the driver runs. +from likelihood_breakdown import galaxy_group_standard as _driver # noqa: E402 + +_driver.main("multi_galaxy", "mge", "breakdown", "jax", script_file=__file__) diff --git a/scripts/multi_galaxy/mge/likelihood_runtime.py b/scripts/multi_galaxy/mge/likelihood_runtime.py new file mode 100644 index 000000000..7f378256b --- /dev/null +++ b/scripts/multi_galaxy/mge/likelihood_runtime.py @@ -0,0 +1,40 @@ +""" +Multi-Galaxy: mge JAX runtime (likelihood-lifecycle 2d, autolens_profiling#473) +=============================================================================== + +``AnalysisImaging(use_jax=True)`` on the dense mapping route (setup ``jax_*_dense_fp64``) or, with +``--sparse``, the JAX w-tilde sparse operator (``jax_*_sparse_fp64``): the jitted full pipeline +(lower / compile / first call / steady block), its steady median, and the vmap per call the +catalogue reads as the JAX headline. Then ``parity.json`` (vs the eager NumPy dense reference) and +``fit.png`` beside the row. + +The cell is the multi_galaxy standard cell (MGE source of 20 linear Gaussians), built by +``scripts/misc/cell_builders/galaxy_group.py``; the driver is +``scripts/misc/likelihood_breakdown/galaxy_group_standard.py``. Dataset: ``dataset/multi_galaxy/hst``, +simulated on first use. Output: the mirrored cell named by ``--output-path`` (the campaign submits +always pass one), else the scratch tree ``output/p2d_local/results/...``. ``--fast`` is a local +check; ``AUTOLENS_PROFILING_SMOKE=1`` exits after the imports. + + python scripts/multi_galaxy/mge/likelihood_runtime.py --instrument hst --fast +""" + +import sys as _sys +from pathlib import Path as _Path + + +def _profiling_root() -> _Path: + for _p in _Path(__file__).resolve().parents: + if (_p / "ruff.toml").exists(): + return _p + raise RuntimeError("autolens_profiling root (ruff.toml) not found") + + +_misc_dir = str(_profiling_root() / "scripts" / "misc") +if _misc_dir not in _sys.path: + _sys.path.insert(0, _misc_dir) +_sys.path.insert(0, str(_profiling_root())) + +# Stdlib only until the driver runs. +from likelihood_breakdown import galaxy_group_standard as _driver # noqa: E402 + +_driver.main("multi_galaxy", "mge", "runtime", "jax", script_file=__file__) diff --git a/scripts/multi_galaxy/rectangular/likelihood_breakdown.py b/scripts/multi_galaxy/rectangular/likelihood_breakdown.py new file mode 100644 index 000000000..012892164 --- /dev/null +++ b/scripts/multi_galaxy/rectangular/likelihood_breakdown.py @@ -0,0 +1,39 @@ +""" +Multi-Galaxy: rectangular JAX breakdown (likelihood-lifecycle 2d, autolens_profiling#473) +========================================================================================= + +The nested prefix walk of ``AnalysisImaging.fit_from`` (traced grids, blurred image, data vector, +curvature, F + H, reconstruction, figure of merit), each prefix jitted and timed, rows by +successive differences. Dense mapping route, or the JAX w-tilde operator with ``--sparse``. The +cell's ``parity.json`` and ``fit.png`` come from its runtime row. + +The cell is the multi_galaxy standard cell (RectangularBilinearAdaptImage 35 x 35, free Adapt), built by +``scripts/misc/cell_builders/galaxy_group.py``; the driver is +``scripts/misc/likelihood_breakdown/galaxy_group_standard.py``. Dataset: ``dataset/multi_galaxy/hst``, +simulated on first use. Output: the mirrored cell named by ``--output-path`` (the campaign submits +always pass one), else the scratch tree ``output/p2d_local/results/...``. ``--fast`` is a local +check; ``AUTOLENS_PROFILING_SMOKE=1`` exits after the imports. + + python scripts/multi_galaxy/rectangular/likelihood_breakdown.py --instrument hst --sparse --fast +""" + +import sys as _sys +from pathlib import Path as _Path + + +def _profiling_root() -> _Path: + for _p in _Path(__file__).resolve().parents: + if (_p / "ruff.toml").exists(): + return _p + raise RuntimeError("autolens_profiling root (ruff.toml) not found") + + +_misc_dir = str(_profiling_root() / "scripts" / "misc") +if _misc_dir not in _sys.path: + _sys.path.insert(0, _misc_dir) +_sys.path.insert(0, str(_profiling_root())) + +# Stdlib only until the driver runs. +from likelihood_breakdown import galaxy_group_standard as _driver # noqa: E402 + +_driver.main("multi_galaxy", "rectangular", "breakdown", "jax", script_file=__file__) diff --git a/scripts/multi_galaxy/rectangular/likelihood_breakdown_numba.py b/scripts/multi_galaxy/rectangular/likelihood_breakdown_numba.py new file mode 100644 index 000000000..ff51d8c1d --- /dev/null +++ b/scripts/multi_galaxy/rectangular/likelihood_breakdown_numba.py @@ -0,0 +1,44 @@ +""" +Multi-Galaxy: rectangular numba CPU breakdown (likelihood-lifecycle 2d, autolens_profiling#473) +=============================================================================================== + +The eager stage walk of the numba sparse fit on the seeded iid stream (each lazily-evaluated +property timed on first access), per-stage medians over the warm instances. The cell's +``parity.json`` and ``fit.png`` come from its runtime row. + +The cell is the multi_galaxy standard cell (RectangularBilinearAdaptImage 35 x 35, free Adapt), built by +``scripts/misc/cell_builders/galaxy_group.py``; the driver is +``scripts/misc/likelihood_breakdown/galaxy_group_standard.py``. Dataset: ``dataset/multi_galaxy/hst``, +simulated on first use. Output: the mirrored cell named by ``--output-path`` (the campaign submits +always pass one), else the scratch tree ``output/p2d_local/results/...``. ``--fast`` is a local +check; ``AUTOLENS_PROFILING_SMOKE=1`` exits after the imports. + + python scripts/multi_galaxy/rectangular/likelihood_breakdown_numba.py --instrument hst --fast +""" + +import sys as _sys +from pathlib import Path as _Path + + +def _profiling_root() -> _Path: + for _p in _Path(__file__).resolve().parents: + if (_p / "ruff.toml").exists(): + return _p + raise RuntimeError("autolens_profiling root (ruff.toml) not found") + + +_misc_dir = str(_profiling_root() / "scripts" / "misc") +if _misc_dir not in _sys.path: + _sys.path.insert(0, _misc_dir) +_sys.path.insert(0, str(_profiling_root())) + +# Threads are pinned BEFORE numpy (and numba) is imported: OpenBLAS / MKL read their thread +# counts once, when the library loads. _production_config is stdlib-only at import. +from _production_config import pin_thread_env as _pin_thread_env # noqa: E402 + +_pin_thread_env(1) + +# Stdlib only until the driver runs (numba: threads pinned above). +from likelihood_breakdown import galaxy_group_standard as _driver # noqa: E402 + +_driver.main("multi_galaxy", "rectangular", "breakdown", "numba", script_file=__file__) diff --git a/scripts/multi_galaxy/rectangular/likelihood_runtime.py b/scripts/multi_galaxy/rectangular/likelihood_runtime.py new file mode 100644 index 000000000..a1d492412 --- /dev/null +++ b/scripts/multi_galaxy/rectangular/likelihood_runtime.py @@ -0,0 +1,40 @@ +""" +Multi-Galaxy: rectangular JAX runtime (likelihood-lifecycle 2d, autolens_profiling#473) +======================================================================================= + +``AnalysisImaging(use_jax=True)`` on the dense mapping route (setup ``jax_*_dense_fp64``) or, with +``--sparse``, the JAX w-tilde sparse operator (``jax_*_sparse_fp64``): the jitted full pipeline +(lower / compile / first call / steady block), its steady median, and the vmap per call the +catalogue reads as the JAX headline. Then ``parity.json`` (vs the eager NumPy dense reference) and +``fit.png`` beside the row. + +The cell is the multi_galaxy standard cell (RectangularBilinearAdaptImage 35 x 35, free Adapt), built by +``scripts/misc/cell_builders/galaxy_group.py``; the driver is +``scripts/misc/likelihood_breakdown/galaxy_group_standard.py``. Dataset: ``dataset/multi_galaxy/hst``, +simulated on first use. Output: the mirrored cell named by ``--output-path`` (the campaign submits +always pass one), else the scratch tree ``output/p2d_local/results/...``. ``--fast`` is a local +check; ``AUTOLENS_PROFILING_SMOKE=1`` exits after the imports. + + python scripts/multi_galaxy/rectangular/likelihood_runtime.py --instrument hst --sparse --fast +""" + +import sys as _sys +from pathlib import Path as _Path + + +def _profiling_root() -> _Path: + for _p in _Path(__file__).resolve().parents: + if (_p / "ruff.toml").exists(): + return _p + raise RuntimeError("autolens_profiling root (ruff.toml) not found") + + +_misc_dir = str(_profiling_root() / "scripts" / "misc") +if _misc_dir not in _sys.path: + _sys.path.insert(0, _misc_dir) +_sys.path.insert(0, str(_profiling_root())) + +# Stdlib only until the driver runs. +from likelihood_breakdown import galaxy_group_standard as _driver # noqa: E402 + +_driver.main("multi_galaxy", "rectangular", "runtime", "jax", script_file=__file__) diff --git a/scripts/multi_galaxy/rectangular/likelihood_runtime_numba.py b/scripts/multi_galaxy/rectangular/likelihood_runtime_numba.py new file mode 100644 index 000000000..f6c2d6652 --- /dev/null +++ b/scripts/multi_galaxy/rectangular/likelihood_runtime_numba.py @@ -0,0 +1,45 @@ +""" +Multi-Galaxy: rectangular numba CPU runtime (likelihood-lifecycle 2d, autolens_profiling#473) +============================================================================================= + +``AnalysisImaging(use_jax=False)`` on the numba CPU sparse operator (setup +``numba_cpu_sparse_fp64``), threads pinned to 1, over the seeded iid stream: instance 0 discarded +(numba compile), ``--cold-evals`` cold, the rest warm; the headline is the warm iid median. Then +``parity.json`` and ``fit.png`` beside the row. + +The cell is the multi_galaxy standard cell (RectangularBilinearAdaptImage 35 x 35, free Adapt), built by +``scripts/misc/cell_builders/galaxy_group.py``; the driver is +``scripts/misc/likelihood_breakdown/galaxy_group_standard.py``. Dataset: ``dataset/multi_galaxy/hst``, +simulated on first use. Output: the mirrored cell named by ``--output-path`` (the campaign submits +always pass one), else the scratch tree ``output/p2d_local/results/...``. ``--fast`` is a local +check; ``AUTOLENS_PROFILING_SMOKE=1`` exits after the imports. + + python scripts/multi_galaxy/rectangular/likelihood_runtime_numba.py --instrument hst --fast +""" + +import sys as _sys +from pathlib import Path as _Path + + +def _profiling_root() -> _Path: + for _p in _Path(__file__).resolve().parents: + if (_p / "ruff.toml").exists(): + return _p + raise RuntimeError("autolens_profiling root (ruff.toml) not found") + + +_misc_dir = str(_profiling_root() / "scripts" / "misc") +if _misc_dir not in _sys.path: + _sys.path.insert(0, _misc_dir) +_sys.path.insert(0, str(_profiling_root())) + +# Threads are pinned BEFORE numpy (and numba) is imported: OpenBLAS / MKL read their thread +# counts once, when the library loads. _production_config is stdlib-only at import. +from _production_config import pin_thread_env as _pin_thread_env # noqa: E402 + +_pin_thread_env(1) + +# Stdlib only until the driver runs (numba: threads pinned above). +from likelihood_breakdown import galaxy_group_standard as _driver # noqa: E402 + +_driver.main("multi_galaxy", "rectangular", "runtime", "numba", script_file=__file__) From 909152a125e947b795c2e6a000813b0989164f82 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Wed, 28 Oct 2026 21:17:16 +0000 Subject: [PATCH 2/9] 2d: declare the 48 planned multi_galaxy / group cells; register the new scripts with the gates MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - catalogue/registry.json (additive): families multi_galaxy and group, cells {multi_galaxy/{mge,rectangular,delaunay}/hst, group/{mge,rectangular,delaunay}/euclid}. The §3.3 rows already route both types to the imaging tables, so the plan is 48 cells (20 hpc_ral_cpu, 28 hpc_a100); provisional_designations.json is unchanged. - wall/rates.py: the six JAX runtime scripts take the headline median (HEADLINE_MEDIAN_SCRIPTS). - tests: NOT_YET_MEASURED gains the six script variants; the driver is a SHARED_RENDERER and is discarded from the headline-median site scan in favour of its six wrappers. Refs autolens_profiling#473 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016nhQ8QrXN6x7n82QzZyz93 --- catalogue/registry.json | 38 +++++++++++++++++++ .../test/test_headline_completion.py | 8 ++++ scripts/misc/tooling/test/test_fit_png.py | 3 ++ .../test/test_results_mirror_scripts.py | 7 ++++ scripts/misc/wall/rates.py | 7 ++++ 5 files changed, 63 insertions(+) diff --git a/catalogue/registry.json b/catalogue/registry.json index 2420acd9b..db93ebe7e 100644 --- a/catalogue/registry.json +++ b/catalogue/registry.json @@ -9,6 +9,8 @@ "point_source_source": "Point source: source plane", "cluster": "Cluster", "multi_dataset": "Multiple datasets", + "multi_galaxy": "Multi-galaxy lenses", + "group": "Group-scale lenses", "lens": "Library components", "experiments": "Other experiments" }, @@ -248,6 +250,42 @@ "dataset": "multi_dataset", "model": "delaunay", "instrument": null + }, + { + "id": "multi_galaxy/mge/hst", + "dataset": "multi_galaxy", + "model": "mge", + "instrument": "hst" + }, + { + "id": "multi_galaxy/rectangular/hst", + "dataset": "multi_galaxy", + "model": "rectangular", + "instrument": "hst" + }, + { + "id": "multi_galaxy/delaunay/hst", + "dataset": "multi_galaxy", + "model": "delaunay", + "instrument": "hst" + }, + { + "id": "group/mge/euclid", + "dataset": "group", + "model": "mge", + "instrument": "euclid" + }, + { + "id": "group/rectangular/euclid", + "dataset": "group", + "model": "rectangular", + "instrument": "euclid" + }, + { + "id": "group/delaunay/euclid", + "dataset": "group", + "model": "delaunay", + "instrument": "euclid" } ], "devices": [ diff --git a/scripts/misc/likelihood_breakdown/test/test_headline_completion.py b/scripts/misc/likelihood_breakdown/test/test_headline_completion.py index 12f63b305..a8ce3442b 100644 --- a/scripts/misc/likelihood_breakdown/test/test_headline_completion.py +++ b/scripts/misc/likelihood_breakdown/test/test_headline_completion.py @@ -211,6 +211,14 @@ def test_every_opted_in_script_is_in_the_wall_basis_set(): # The standard-size driver (2b) runs inside the interferometer delaunay / rectangular # likelihood_runtime.py cells, which are already in the set. sites.discard("scripts/misc/likelihood_breakdown/interferometer_standard.py") + # The galaxy/group driver (2d) runs inside the six multi_galaxy / group likelihood_runtime.py + # cells (thin wrappers), which are in the set by name. + sites.discard("scripts/misc/likelihood_breakdown/galaxy_group_standard.py") + sites |= { + f"scripts/{dt}/{v}/likelihood_runtime.py" + for dt in ("multi_galaxy", "group") + for v in ("mge", "rectangular", "delaunay") + } sites |= { "scripts/interferometer/delaunay/likelihood_breakdown.py", "scripts/interferometer/rectangular/likelihood_breakdown.py", diff --git a/scripts/misc/tooling/test/test_fit_png.py b/scripts/misc/tooling/test/test_fit_png.py index 862facd94..dfa9b911c 100644 --- a/scripts/misc/tooling/test/test_fit_png.py +++ b/scripts/misc/tooling/test/test_fit_png.py @@ -45,6 +45,9 @@ SHARED_RENDERERS = { "scripts/misc/likelihood_breakdown/interferometer_standard.py", "scripts/interferometer/rectangular/likelihood_runtime_matrixfree.py", + # likelihood-lifecycle 2d (#473): the multi_galaxy / group runtime scripts are thin wrappers; + # the driver renders after the row and the parity witness. + "scripts/misc/likelihood_breakdown/galaxy_group_standard.py", } diff --git a/scripts/misc/tooling/test/test_results_mirror_scripts.py b/scripts/misc/tooling/test/test_results_mirror_scripts.py index 2e298719b..6cd9acc96 100644 --- a/scripts/misc/tooling/test/test_results_mirror_scripts.py +++ b/scripts/misc/tooling/test/test_results_mirror_scripts.py @@ -36,6 +36,13 @@ ("cluster", "source_plane"), ("imaging", "sersic"), ("multi_dataset", "delaunay"), + # likelihood-lifecycle 2d (#473): new cell scripts, no committed row until the RAL campaign. + ("group", "delaunay"), + ("group", "mge"), + ("group", "rectangular"), + ("multi_galaxy", "delaunay"), + ("multi_galaxy", "mge"), + ("multi_galaxy", "rectangular"), } MISC_WITHOUT_SCRIPTS = { "logs": "committed SLURM job logs, one folder per campaign; provenance, never a result", diff --git a/scripts/misc/wall/rates.py b/scripts/misc/wall/rates.py index aa850af96..68b1f964a 100644 --- a/scripts/misc/wall/rates.py +++ b/scripts/misc/wall/rates.py @@ -219,6 +219,13 @@ "scripts/datacube/delaunay/likelihood_runtime.py", "scripts/imaging/mge_mass/likelihood_runtime_jax.py", "scripts/imaging/rectangular/likelihood_runtime_numba_mge_mass.py", + # likelihood-lifecycle 2d (#473): the JAX runtime cells of the shared galaxy/group driver + "scripts/group/delaunay/likelihood_runtime.py", + "scripts/group/mge/likelihood_runtime.py", + "scripts/group/rectangular/likelihood_runtime.py", + "scripts/multi_galaxy/delaunay/likelihood_runtime.py", + "scripts/multi_galaxy/mge/likelihood_runtime.py", + "scripts/multi_galaxy/rectangular/likelihood_runtime.py", } ) From c68ca938311991710865e5587a29e710059dbbab Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Wed, 28 Oct 2026 21:17:16 +0000 Subject: [PATCH 3/9] 2d: campaigns/multi_galaxy_group_p2d.py and the 2d submits (DRAFT, not submitted) - The 48-cell manifest on _common.py (unchanged; 2a and 2b --check byte-identical), pin 2026.10.25.1 from the private checkout, prepare_dataset by instrument (hst -> multi_galaxy, euclid -> group) under a lock. - Batch 0 (D9): every group leg, RAL array of 10 (%8) and A100 array of 14 (%2), 4:00:00 and 32 GB per task, WALL-BASIS unmeasured guesses of 3600 s (3x floor). - Batch 1: one ral array (10) and one --gres=gpu:1 job (14) per dataset type, WALL_BASIS_STATUS=provisional: placeholder --time / --mem and a submit that refuses to run. - Tests (test_multi_galaxy_group_p2d.py) and a README section. Refs autolens_profiling#473 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016nhQ8QrXN6x7n82QzZyz93 --- .../submit_campaign_p2d_batch0_ral_cpu_fp64 | 240 ++++++++++ ...mit_campaign_p2d_group_ral_cpu_euclid_fp64 | 244 ++++++++++ ...campaign_p2d_multi_galaxy_ral_cpu_hst_fp64 | 244 ++++++++++ .../submit_campaign_p2d_batch0_a100_fp64 | 261 +++++++++++ ...submit_campaign_p2d_group_a100_euclid_fp64 | 265 +++++++++++ ...it_campaign_p2d_multi_galaxy_a100_hst_fp64 | 265 +++++++++++ scripts/misc/campaigns/README.md | 46 ++ .../misc/campaigns/multi_galaxy_group_p2d.py | 442 ++++++++++++++++++ .../test/test_multi_galaxy_group_p2d.py | 268 +++++++++++ 9 files changed, 2275 insertions(+) create mode 100755 hpc/batch_cpu/submit_campaign_p2d_batch0_ral_cpu_fp64 create mode 100755 hpc/batch_cpu/submit_campaign_p2d_group_ral_cpu_euclid_fp64 create mode 100755 hpc/batch_cpu/submit_campaign_p2d_multi_galaxy_ral_cpu_hst_fp64 create mode 100755 hpc/batch_gpu/submit_campaign_p2d_batch0_a100_fp64 create mode 100755 hpc/batch_gpu/submit_campaign_p2d_group_a100_euclid_fp64 create mode 100755 hpc/batch_gpu/submit_campaign_p2d_multi_galaxy_a100_hst_fp64 create mode 100644 scripts/misc/campaigns/multi_galaxy_group_p2d.py create mode 100644 scripts/misc/campaigns/test/test_multi_galaxy_group_p2d.py diff --git a/hpc/batch_cpu/submit_campaign_p2d_batch0_ral_cpu_fp64 b/hpc/batch_cpu/submit_campaign_p2d_batch0_ral_cpu_fp64 new file mode 100755 index 000000000..b57be690e --- /dev/null +++ b/hpc/batch_cpu/submit_campaign_p2d_batch0_ral_cpu_fp64 @@ -0,0 +1,240 @@ +#!/bin/bash -l +# +# Batch-0 timing arm, RAL CPU: every hpc_ral_cpu group cell (the bounding dataset). +# Likelihood-lifecycle phase 2d multi_galaxy + group campaign (autolens_profiling#473), batch 0: 10 cell(s). +# DRAFT FOR REVIEW: the cell design (decisions D1-D10, wiki/campaigns/multi_galaxy/ +# likelihood_lifecycle_p2d.md) awaits the human; do not submit without a batch go. +# GENERATED by scripts/misc/campaigns/multi_galaxy_group_p2d.py --write; edit the generator, +# not this file (the campaign test fails on a hand edit). The batch procedure is in +# scripts/misc/campaigns/README.md. +# +# LIBRARY CODE. A private checkout of the five libraries at tag 2026.10.25.1 ($PYAUTO_PRIVATE_BASE, +# default /mnt/ral/jnightin/profiling/PyAuto_2026.10.25.1) is prepended to PYTHONPATH over the shared venv +# ($PYAUTO_HPC_BASE, default /mnt/ral/jnightin/PyAuto, third-party packages only). The job refuses to +# run if a library imports from anywhere else or sits at another tag, and after each leg it +# checks the row's library_revisions equal the checkout's HEADs. The shared mirror is never +# pulled or used. AP_ROOT is the checkout this was submitted from (hpc//../..). +# +# CELLS. Every leg runs one cell script of the shared galaxy/group driver on the standard +# cell (MGE source, or Delaunay 1250 + 30 edge / rectangular 35x35) and writes its row +# (runtime legs also parity.json and fit.png) into the mirrored cell named by --output-path +# under the gitignored output/p2d_batch0/ scratch tree, never in place over results/. +# +# MEMORY. --mem=32gb, PROVISIONAL (group/euclid 17671 masked pixels): the imaging hst legs +# (15k masked pixels) peaked at 10.2 GiB MaxRSS; batch 0's sacct MaxRSS replaces this +# (next 16/32/64 GB step >= 1.5x the peak) before batch 1. +# One cell per array task on `ral` (CPU work never goes on `gpu`). numba cells pin their +# BLAS threads to 1 (production per-worker cost); JAX CPU cells get NPROC=8. +# +# BATCH 0 = TIMING ARM (decision D9). It runs every group leg: group bounds +# multi_galaxy (1.6x the masked pixels, two dPIE extra galaxies). Each leg's wall lands +# in output/p2d_logs/walls.tsv; batch 1's WALL-BASIS rows will cite them +# (source: measured-wall) and its --time / --mem are set from them. +# +# WALL-BASIS: nothing measured yet; 3600 s per leg is a declared guess +# (3x floor), ~10x the imaging hst legs of the nearest measured size. +# 3 leg(s): delaunay jax_cpu_sparse_fp64 breakdown, mge jax_cpu_dense_fp64 breakdown, rectangular jax_cpu_sparse_fp64 breakdown +# cell: group/likelihood_breakdown/euclid device: ral_cpu precision: fp64 +# source: unmeasured probe-first: yes wall: 3600 headroom: 3.0 +# 2 leg(s): delaunay numba_cpu_sparse_fp64 breakdown, rectangular numba_cpu_sparse_fp64 breakdown +# cell: group/likelihood_breakdown_numba/euclid device: ral_cpu precision: fp64 +# source: unmeasured probe-first: yes wall: 3600 headroom: 3.0 +# 3 leg(s): delaunay jax_cpu_sparse_fp64 runtime, mge jax_cpu_dense_fp64 runtime, rectangular jax_cpu_sparse_fp64 runtime +# cell: group/likelihood_runtime/euclid device: ral_cpu precision: fp64 +# source: unmeasured probe-first: yes wall: 3600 headroom: 3.0 +# 2 leg(s): delaunay numba_cpu_sparse_fp64 runtime, rectangular numba_cpu_sparse_fp64 runtime +# cell: group/likelihood_runtime_numba/euclid device: ral_cpu precision: fp64 +# source: unmeasured probe-first: yes wall: 3600 headroom: 3.0 + +#SBATCH -J p2d_b0_batch0_ral_cpu_fp64 +#SBATCH --partition=ral +#SBATCH --array=0-9%8 +#SBATCH --ntasks=1 +#SBATCH --cpus-per-task=8 +#SBATCH --mem=32gb +#SBATCH --time=4:00:00 +#SBATCH -o output/output.%A_%a.out +#SBATCH -e error/error.%A_%a.err + +# Submit from hpc/batch_cpu/ or hpc/batch_gpu/ (the -o/-e paths are relative). +export AP_ROOT="$(cd "${SLURM_SUBMIT_DIR:-$(dirname "$0")}/../.." && pwd)" +export PYAUTO_HPC_BASE="${PYAUTO_HPC_BASE:-/mnt/ral/jnightin/PyAuto}" +export PYAUTO_PRIVATE_BASE="${PYAUTO_PRIVATE_BASE:-/mnt/ral/jnightin/profiling/PyAuto_2026.10.25.1}" +export P2D_PIN=2026.10.25.1 +echo "AP_ROOT=$AP_ROOT PYAUTO_PRIVATE_BASE=$PYAUTO_PRIVATE_BASE pin=$P2D_PIN" +source "$AP_ROOT/activate.sh" +export PYTHONPATH=$PYAUTO_PRIVATE_BASE/PyAutoNerves:$PYAUTO_PRIVATE_BASE/PyAutoFit:$PYAUTO_PRIVATE_BASE/PyAutoArray:$PYAUTO_PRIVATE_BASE/PyAutoGalaxy:$PYAUTO_PRIVATE_BASE/PyAutoLens:$PYTHONPATH + +export OMP_NUM_THREADS=1 MKL_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 NUMBA_NUM_THREADS=1 +export NPROC=${SLURM_CPUS_PER_TASK:-8} +export JAX_ENABLE_X64=True +export XLA_PYTHON_CLIENT_PREALLOCATE=false +export XLA_FLAGS="--xla_disable_hlo_passes=constant_folding" +unset PYAUTO_SMALL_DATASETS +export NUMBA_CACHE_DIR="$AP_ROOT/output/numba_cache/p2d_${SLURM_JOB_ID:-local}_${SLURM_ARRAY_TASK_ID:-0}" +mkdir -p "$NUMBA_CACHE_DIR" "$MPLCONFIGDIR" "$AP_ROOT/output/p2d_logs" + +echo "==========================================" +date +hostname +lscpu | grep 'Model name' || true +echo "partition: ${SLURM_JOB_PARTITION:-unset} nodelist: ${SLURM_JOB_NODELIST:-unset} cpus: ${SLURM_CPUS_PER_TASK:-unset}" +echo "loadavg: $(cat /proc/loadavg)" +for r in PyAutoNerves PyAutoFit PyAutoArray PyAutoGalaxy PyAutoLens; do + printf '%-14s %s %s\n' "$r" "$(git -C $PYAUTO_PRIVATE_BASE/$r rev-parse HEAD 2>&1)" "$(git -C $PYAUTO_PRIVATE_BASE/$r describe --tags 2>&1)" +done +echo "AP_ROOT rev: $(git -C $AP_ROOT rev-parse HEAD 2>&1)" + +cd "$AP_ROOT" +# The libraries must import from the private checkout at the pinned tag, never the shared mirror. +python3 - <<'EOF_PY' || exit 3 +import os, subprocess +import autoarray, autofit, autogalaxy, autolens, autonerves +base, pin = os.path.realpath(os.environ["PYAUTO_PRIVATE_BASE"]), os.environ["P2D_PIN"] +for m in (autonerves, autofit, autoarray, autogalaxy, autolens): + print(f"{m.__name__:<11} {m.__file__}") + if not os.path.realpath(m.__file__).startswith(base + os.sep): + raise SystemExit(f"REFUSING: {m.__name__} imported from {m.__file__}, not {base}") + repo = os.path.dirname(os.path.dirname(os.path.realpath(m.__file__))) + tag = subprocess.check_output(["git", "-C", repo, "describe", "--tags"], text=True).strip() + if tag != pin: + raise SystemExit(f"REFUSING: {repo} is at {tag}, not tag {pin}") +print(f"import origin + tag {pin}: OK") +EOF_PY + +# After each leg: the row's recorded library revisions must be the private checkout's HEADs. +check_revisions() { +python3 - "$1" <<'EOF_PY' +import json, os, subprocess, sys +path = sys.argv[1] +revs = json.load(open(path))["device"]["provenance"]["library_revisions"] +base = os.environ["PYAUTO_PRIVATE_BASE"] +for repo in ("PyAutoNerves", "PyAutoFit", "PyAutoArray", "PyAutoGalaxy", "PyAutoLens"): + head = subprocess.check_output(["git", "-C", f"{base}/{repo}", "rev-parse", "HEAD"], text=True).strip() + if revs.get(repo) != head: + raise SystemExit(f"MISMATCH {path}: {repo} row {revs.get(repo)} != private checkout {head}") +print("revisions OK", path) +EOF_PY +} + +# Simulate a missing dataset and cache its adapt image once per instrument, under a lock. +prepare_dataset() { +python3 - "$1" <<'EOF_PY' +import sys +sys.path.insert(0, "scripts/misc/campaigns") +from multi_galaxy_group_p2d import prepare_dataset +prepare_dataset(sys.argv[1]) +EOF_PY +} + +# One leg: fresh JAX compile cache, the leg's platform, wall clock logged, revisions checked. +# A failed leg is recorded and the job carries on (|| keeps activate.sh's ERR trap out of it). +STATUS=0 +run_leg() { + local I=$1 + local LOG="$AP_ROOT/output/p2d_logs/submit_campaign_p2d_batch0_ral_cpu_fp64_${SLURM_JOB_ID:-local}_${I}.log" + export JAX_PLATFORMS=${PLATFORMS[$I]} + export JAX_COMPILATION_CACHE_DIR="$AP_ROOT/output/jax_cache/p2d_${SLURM_JOB_ID:-local}_${I}" + rm -rf "$JAX_COMPILATION_CACHE_DIR" && mkdir -p "$JAX_COMPILATION_CACHE_DIR" + prepare_dataset ${INSTS[$I]} || { echo "LEG $I: dataset preparation FAILED"; STATUS=5; return 0; } + echo "------------------------------------------" + echo "LEG $I: ${CELLNAMES[$I]}" + echo " cell script: scripts/${CELLS[$I]}.py ${FLAGS[$I]} -> $RESULTS_ROOT/${OUTS[$I]}" + echo " JAX_PLATFORMS=$JAX_PLATFORMS NPROC=$NPROC log=$LOG" + local T0=$(date +%s) + # A START line first, so a leg killed at --time (which never reaches its WALL line) still shows. + printf 'START\t%s\t%s\t%s\t%s\n' "${SLURM_JOB_ID:-local}" "$I" "$T0" "${CELLNAMES[$I]}" >> "$AP_ROOT/output/p2d_logs/walls.tsv" + python3 -u scripts/${CELLS[$I]}.py --instrument ${INSTS[$I]} ${FLAGS[$I]} --output-path "$RESULTS_ROOT/${OUTS[$I]}" > "$LOG" 2>&1 \ + || { echo "LEG $I FAILED (rc $?), see $LOG"; tail -20 "$LOG"; STATUS=4; } + local WALL=$(( $(date +%s) - T0 )) + printf 'WALL\t%s\t%s\t%s\t%s\n' "${SLURM_JOB_ID:-local}" "$I" "$WALL" "${CELLNAMES[$I]}" | tee -a "$AP_ROOT/output/p2d_logs/walls.tsv" + if [ -f "$RESULTS_ROOT/${OUTS[$I]}" ]; then + check_revisions "$RESULTS_ROOT/${OUTS[$I]}" || STATUS=4 + else + echo "LEG $I: no row at $RESULTS_ROOT/${OUTS[$I]}"; STATUS=4 + fi +} + +# The manifest: one entry per leg (multi_galaxy_group_p2d.Task). +CELLNAMES=( + "group/delaunay/euclid jax_cpu_sparse_fp64@hpc_ral_cpu [breakdown]" + "group/delaunay/euclid jax_cpu_sparse_fp64@hpc_ral_cpu [runtime]" + "group/delaunay/euclid numba_cpu_sparse_fp64@hpc_ral_cpu [breakdown]" + "group/delaunay/euclid numba_cpu_sparse_fp64@hpc_ral_cpu [runtime]" + "group/mge/euclid jax_cpu_dense_fp64@hpc_ral_cpu [breakdown]" + "group/mge/euclid jax_cpu_dense_fp64@hpc_ral_cpu [runtime]" + "group/rectangular/euclid jax_cpu_sparse_fp64@hpc_ral_cpu [breakdown]" + "group/rectangular/euclid jax_cpu_sparse_fp64@hpc_ral_cpu [runtime]" + "group/rectangular/euclid numba_cpu_sparse_fp64@hpc_ral_cpu [breakdown]" + "group/rectangular/euclid numba_cpu_sparse_fp64@hpc_ral_cpu [runtime]" +) +CELLS=( + group/delaunay/likelihood_breakdown + group/delaunay/likelihood_runtime + group/delaunay/likelihood_breakdown_numba + group/delaunay/likelihood_runtime_numba + group/mge/likelihood_breakdown + group/mge/likelihood_runtime + group/rectangular/likelihood_breakdown + group/rectangular/likelihood_runtime + group/rectangular/likelihood_breakdown_numba + group/rectangular/likelihood_runtime_numba +) +INSTS=( + euclid + euclid + euclid + euclid + euclid + euclid + euclid + euclid + euclid + euclid +) +FLAGS=( + "--sparse --config-name hpc_ral_cpu_fp64" + "--sparse --config-name hpc_ral_cpu_fp64" + "--config-name hpc_ral_cpu_fp64" + "--config-name hpc_ral_cpu_fp64" + "--config-name hpc_ral_cpu_fp64" + "--config-name hpc_ral_cpu_fp64" + "--sparse --config-name hpc_ral_cpu_fp64" + "--sparse --config-name hpc_ral_cpu_fp64" + "--config-name hpc_ral_cpu_fp64" + "--config-name hpc_ral_cpu_fp64" +) +PLATFORMS=( + cpu + cpu + cpu + cpu + cpu + cpu + cpu + cpu + cpu + cpu +) +OUTS=( + results/group/delaunay/euclid/jax_cpu_sparse_fp64/hpc_ral_cpu/breakdown.json + results/group/delaunay/euclid/jax_cpu_sparse_fp64/hpc_ral_cpu/runtime.json + results/group/delaunay/euclid/numba_cpu_sparse_fp64/hpc_ral_cpu/breakdown.json + results/group/delaunay/euclid/numba_cpu_sparse_fp64/hpc_ral_cpu/runtime.json + results/group/mge/euclid/jax_cpu_dense_fp64/hpc_ral_cpu/breakdown.json + results/group/mge/euclid/jax_cpu_dense_fp64/hpc_ral_cpu/runtime.json + results/group/rectangular/euclid/jax_cpu_sparse_fp64/hpc_ral_cpu/breakdown.json + results/group/rectangular/euclid/jax_cpu_sparse_fp64/hpc_ral_cpu/runtime.json + results/group/rectangular/euclid/numba_cpu_sparse_fp64/hpc_ral_cpu/breakdown.json + results/group/rectangular/euclid/numba_cpu_sparse_fp64/hpc_ral_cpu/runtime.json +) +RESULTS_ROOT="$AP_ROOT/output/p2d_batch0" + +I=${SLURM_ARRAY_TASK_ID:?"submit as an array (sbatch from hpc//)"} +run_leg $I + +echo "==========================================" +echo "exit status: $STATUS (0 ok, 4 a leg failed or its revisions/row check failed, 5 dataset)" +echo "loadavg: $(cat /proc/loadavg)" +date +exit $STATUS diff --git a/hpc/batch_cpu/submit_campaign_p2d_group_ral_cpu_euclid_fp64 b/hpc/batch_cpu/submit_campaign_p2d_group_ral_cpu_euclid_fp64 new file mode 100755 index 000000000..578c04d16 --- /dev/null +++ b/hpc/batch_cpu/submit_campaign_p2d_group_ral_cpu_euclid_fp64 @@ -0,0 +1,244 @@ +#!/bin/bash -l +# +# RAL CPU array: the hpc_ral_cpu group cells at euclid. +# Likelihood-lifecycle phase 2d multi_galaxy + group campaign (autolens_profiling#473), batch 1: 10 cell(s). +# DRAFT FOR REVIEW: the cell design (decisions D1-D10, wiki/campaigns/multi_galaxy/ +# likelihood_lifecycle_p2d.md) awaits the human; do not submit without a batch go. +# GENERATED by scripts/misc/campaigns/multi_galaxy_group_p2d.py --write; edit the generator, +# not this file (the campaign test fails on a hand edit). The batch procedure is in +# scripts/misc/campaigns/README.md. +# +# LIBRARY CODE. A private checkout of the five libraries at tag 2026.10.25.1 ($PYAUTO_PRIVATE_BASE, +# default /mnt/ral/jnightin/profiling/PyAuto_2026.10.25.1) is prepended to PYTHONPATH over the shared venv +# ($PYAUTO_HPC_BASE, default /mnt/ral/jnightin/PyAuto, third-party packages only). The job refuses to +# run if a library imports from anywhere else or sits at another tag, and after each leg it +# checks the row's library_revisions equal the checkout's HEADs. The shared mirror is never +# pulled or used. AP_ROOT is the checkout this was submitted from (hpc//../..). +# +# CELLS. Every leg runs one cell script of the shared galaxy/group driver on the standard +# cell (MGE source, or Delaunay 1250 + 30 edge / rectangular 35x35) and writes its row +# (runtime legs also parity.json and fit.png) into the mirrored cell named by --output-path +# under the gitignored output/p2d_batch1/ scratch tree, never in place over results/. +# +# MEMORY. --mem=32gb, PROVISIONAL (group/euclid 17671 masked pixels): the imaging hst legs +# (15k masked pixels) peaked at 10.2 GiB MaxRSS; batch 0's sacct MaxRSS replaces this +# (next 16/32/64 GB step >= 1.5x the peak) before batch 1. +# One cell per array task on `ral` (CPU work never goes on `gpu`). numba cells pin their +# BLAS threads to 1 (production per-worker cost); JAX CPU cells get NPROC=8. +# +# WALL-BASIS: PROVISIONAL. No cell has a wall yet; batch 0 measures them. Every row is +# `unmeasured` until batch 0 lands, and the job refuses to run while +# WALL_BASIS_STATUS=provisional (export P2D_ALLOW_PROVISIONAL_WALL=1 overrides it). +# 3 leg(s): delaunay jax_cpu_sparse_fp64 breakdown, mge jax_cpu_dense_fp64 breakdown, rectangular jax_cpu_sparse_fp64 breakdown +# cell: group/likelihood_breakdown/euclid device: ral_cpu precision: fp64 +# source: unmeasured probe-first: yes +# 2 leg(s): delaunay numba_cpu_sparse_fp64 breakdown, rectangular numba_cpu_sparse_fp64 breakdown +# cell: group/likelihood_breakdown_numba/euclid device: ral_cpu precision: fp64 +# source: unmeasured probe-first: yes +# 3 leg(s): delaunay jax_cpu_sparse_fp64 runtime, mge jax_cpu_dense_fp64 runtime, rectangular jax_cpu_sparse_fp64 runtime +# cell: group/likelihood_runtime/euclid device: ral_cpu precision: fp64 +# source: unmeasured probe-first: yes +# 2 leg(s): delaunay numba_cpu_sparse_fp64 runtime, rectangular numba_cpu_sparse_fp64 runtime +# cell: group/likelihood_runtime_numba/euclid device: ral_cpu precision: fp64 +# source: unmeasured probe-first: yes + +#SBATCH -J p2d_b1_group_ral_cpu_euclid_fp64 +#SBATCH --partition=ral +#SBATCH --array=0-9%16 +#SBATCH --ntasks=1 +#SBATCH --cpus-per-task=8 +#SBATCH --mem=32gb +#SBATCH --time=4:00:00 +#SBATCH -o output/output.%A_%a.out +#SBATCH -e error/error.%A_%a.err + +# Submit from hpc/batch_cpu/ or hpc/batch_gpu/ (the -o/-e paths are relative). +# Batch 1 runs only once batch 0's walls have replaced the provisional WALL-BASIS rows above +# (source: measured-wall, --time from the measurement) and this reads "measured". +WALL_BASIS_STATUS=provisional +if [ "$WALL_BASIS_STATUS" != measured ] && [ "${P2D_ALLOW_PROVISIONAL_WALL:-0}" != 1 ]; then + echo "REFUSING: WALL_BASIS_STATUS=$WALL_BASIS_STATUS. Run batch 0, set --time from its walls" + echo "and mark the WALL-BASIS rows measured-wall first (scripts/misc/campaigns/README.md)." + exit 2 +fi +export AP_ROOT="$(cd "${SLURM_SUBMIT_DIR:-$(dirname "$0")}/../.." && pwd)" +export PYAUTO_HPC_BASE="${PYAUTO_HPC_BASE:-/mnt/ral/jnightin/PyAuto}" +export PYAUTO_PRIVATE_BASE="${PYAUTO_PRIVATE_BASE:-/mnt/ral/jnightin/profiling/PyAuto_2026.10.25.1}" +export P2D_PIN=2026.10.25.1 +echo "AP_ROOT=$AP_ROOT PYAUTO_PRIVATE_BASE=$PYAUTO_PRIVATE_BASE pin=$P2D_PIN" +source "$AP_ROOT/activate.sh" +export PYTHONPATH=$PYAUTO_PRIVATE_BASE/PyAutoNerves:$PYAUTO_PRIVATE_BASE/PyAutoFit:$PYAUTO_PRIVATE_BASE/PyAutoArray:$PYAUTO_PRIVATE_BASE/PyAutoGalaxy:$PYAUTO_PRIVATE_BASE/PyAutoLens:$PYTHONPATH + +export OMP_NUM_THREADS=1 MKL_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 NUMBA_NUM_THREADS=1 +export NPROC=${SLURM_CPUS_PER_TASK:-8} +export JAX_ENABLE_X64=True +export XLA_PYTHON_CLIENT_PREALLOCATE=false +export XLA_FLAGS="--xla_disable_hlo_passes=constant_folding" +unset PYAUTO_SMALL_DATASETS +export NUMBA_CACHE_DIR="$AP_ROOT/output/numba_cache/p2d_${SLURM_JOB_ID:-local}_${SLURM_ARRAY_TASK_ID:-0}" +mkdir -p "$NUMBA_CACHE_DIR" "$MPLCONFIGDIR" "$AP_ROOT/output/p2d_logs" + +echo "==========================================" +date +hostname +lscpu | grep 'Model name' || true +echo "partition: ${SLURM_JOB_PARTITION:-unset} nodelist: ${SLURM_JOB_NODELIST:-unset} cpus: ${SLURM_CPUS_PER_TASK:-unset}" +echo "loadavg: $(cat /proc/loadavg)" +for r in PyAutoNerves PyAutoFit PyAutoArray PyAutoGalaxy PyAutoLens; do + printf '%-14s %s %s\n' "$r" "$(git -C $PYAUTO_PRIVATE_BASE/$r rev-parse HEAD 2>&1)" "$(git -C $PYAUTO_PRIVATE_BASE/$r describe --tags 2>&1)" +done +echo "AP_ROOT rev: $(git -C $AP_ROOT rev-parse HEAD 2>&1)" + +cd "$AP_ROOT" +# The libraries must import from the private checkout at the pinned tag, never the shared mirror. +python3 - <<'EOF_PY' || exit 3 +import os, subprocess +import autoarray, autofit, autogalaxy, autolens, autonerves +base, pin = os.path.realpath(os.environ["PYAUTO_PRIVATE_BASE"]), os.environ["P2D_PIN"] +for m in (autonerves, autofit, autoarray, autogalaxy, autolens): + print(f"{m.__name__:<11} {m.__file__}") + if not os.path.realpath(m.__file__).startswith(base + os.sep): + raise SystemExit(f"REFUSING: {m.__name__} imported from {m.__file__}, not {base}") + repo = os.path.dirname(os.path.dirname(os.path.realpath(m.__file__))) + tag = subprocess.check_output(["git", "-C", repo, "describe", "--tags"], text=True).strip() + if tag != pin: + raise SystemExit(f"REFUSING: {repo} is at {tag}, not tag {pin}") +print(f"import origin + tag {pin}: OK") +EOF_PY + +# After each leg: the row's recorded library revisions must be the private checkout's HEADs. +check_revisions() { +python3 - "$1" <<'EOF_PY' +import json, os, subprocess, sys +path = sys.argv[1] +revs = json.load(open(path))["device"]["provenance"]["library_revisions"] +base = os.environ["PYAUTO_PRIVATE_BASE"] +for repo in ("PyAutoNerves", "PyAutoFit", "PyAutoArray", "PyAutoGalaxy", "PyAutoLens"): + head = subprocess.check_output(["git", "-C", f"{base}/{repo}", "rev-parse", "HEAD"], text=True).strip() + if revs.get(repo) != head: + raise SystemExit(f"MISMATCH {path}: {repo} row {revs.get(repo)} != private checkout {head}") +print("revisions OK", path) +EOF_PY +} + +# Simulate a missing dataset and cache its adapt image once per instrument, under a lock. +prepare_dataset() { +python3 - "$1" <<'EOF_PY' +import sys +sys.path.insert(0, "scripts/misc/campaigns") +from multi_galaxy_group_p2d import prepare_dataset +prepare_dataset(sys.argv[1]) +EOF_PY +} + +# One leg: fresh JAX compile cache, the leg's platform, wall clock logged, revisions checked. +# A failed leg is recorded and the job carries on (|| keeps activate.sh's ERR trap out of it). +STATUS=0 +run_leg() { + local I=$1 + local LOG="$AP_ROOT/output/p2d_logs/submit_campaign_p2d_group_ral_cpu_euclid_fp64_${SLURM_JOB_ID:-local}_${I}.log" + export JAX_PLATFORMS=${PLATFORMS[$I]} + export JAX_COMPILATION_CACHE_DIR="$AP_ROOT/output/jax_cache/p2d_${SLURM_JOB_ID:-local}_${I}" + rm -rf "$JAX_COMPILATION_CACHE_DIR" && mkdir -p "$JAX_COMPILATION_CACHE_DIR" + prepare_dataset ${INSTS[$I]} || { echo "LEG $I: dataset preparation FAILED"; STATUS=5; return 0; } + echo "------------------------------------------" + echo "LEG $I: ${CELLNAMES[$I]}" + echo " cell script: scripts/${CELLS[$I]}.py ${FLAGS[$I]} -> $RESULTS_ROOT/${OUTS[$I]}" + echo " JAX_PLATFORMS=$JAX_PLATFORMS NPROC=$NPROC log=$LOG" + local T0=$(date +%s) + # A START line first, so a leg killed at --time (which never reaches its WALL line) still shows. + printf 'START\t%s\t%s\t%s\t%s\n' "${SLURM_JOB_ID:-local}" "$I" "$T0" "${CELLNAMES[$I]}" >> "$AP_ROOT/output/p2d_logs/walls.tsv" + python3 -u scripts/${CELLS[$I]}.py --instrument ${INSTS[$I]} ${FLAGS[$I]} --output-path "$RESULTS_ROOT/${OUTS[$I]}" > "$LOG" 2>&1 \ + || { echo "LEG $I FAILED (rc $?), see $LOG"; tail -20 "$LOG"; STATUS=4; } + local WALL=$(( $(date +%s) - T0 )) + printf 'WALL\t%s\t%s\t%s\t%s\n' "${SLURM_JOB_ID:-local}" "$I" "$WALL" "${CELLNAMES[$I]}" | tee -a "$AP_ROOT/output/p2d_logs/walls.tsv" + if [ -f "$RESULTS_ROOT/${OUTS[$I]}" ]; then + check_revisions "$RESULTS_ROOT/${OUTS[$I]}" || STATUS=4 + else + echo "LEG $I: no row at $RESULTS_ROOT/${OUTS[$I]}"; STATUS=4 + fi +} + +# The manifest: one entry per leg (multi_galaxy_group_p2d.Task). +CELLNAMES=( + "group/delaunay/euclid jax_cpu_sparse_fp64@hpc_ral_cpu [breakdown]" + "group/delaunay/euclid jax_cpu_sparse_fp64@hpc_ral_cpu [runtime]" + "group/delaunay/euclid numba_cpu_sparse_fp64@hpc_ral_cpu [breakdown]" + "group/delaunay/euclid numba_cpu_sparse_fp64@hpc_ral_cpu [runtime]" + "group/mge/euclid jax_cpu_dense_fp64@hpc_ral_cpu [breakdown]" + "group/mge/euclid jax_cpu_dense_fp64@hpc_ral_cpu [runtime]" + "group/rectangular/euclid jax_cpu_sparse_fp64@hpc_ral_cpu [breakdown]" + "group/rectangular/euclid jax_cpu_sparse_fp64@hpc_ral_cpu [runtime]" + "group/rectangular/euclid numba_cpu_sparse_fp64@hpc_ral_cpu [breakdown]" + "group/rectangular/euclid numba_cpu_sparse_fp64@hpc_ral_cpu [runtime]" +) +CELLS=( + group/delaunay/likelihood_breakdown + group/delaunay/likelihood_runtime + group/delaunay/likelihood_breakdown_numba + group/delaunay/likelihood_runtime_numba + group/mge/likelihood_breakdown + group/mge/likelihood_runtime + group/rectangular/likelihood_breakdown + group/rectangular/likelihood_runtime + group/rectangular/likelihood_breakdown_numba + group/rectangular/likelihood_runtime_numba +) +INSTS=( + euclid + euclid + euclid + euclid + euclid + euclid + euclid + euclid + euclid + euclid +) +FLAGS=( + "--sparse --config-name hpc_ral_cpu_fp64" + "--sparse --config-name hpc_ral_cpu_fp64" + "--config-name hpc_ral_cpu_fp64" + "--config-name hpc_ral_cpu_fp64" + "--config-name hpc_ral_cpu_fp64" + "--config-name hpc_ral_cpu_fp64" + "--sparse --config-name hpc_ral_cpu_fp64" + "--sparse --config-name hpc_ral_cpu_fp64" + "--config-name hpc_ral_cpu_fp64" + "--config-name hpc_ral_cpu_fp64" +) +PLATFORMS=( + cpu + cpu + cpu + cpu + cpu + cpu + cpu + cpu + cpu + cpu +) +OUTS=( + results/group/delaunay/euclid/jax_cpu_sparse_fp64/hpc_ral_cpu/breakdown.json + results/group/delaunay/euclid/jax_cpu_sparse_fp64/hpc_ral_cpu/runtime.json + results/group/delaunay/euclid/numba_cpu_sparse_fp64/hpc_ral_cpu/breakdown.json + results/group/delaunay/euclid/numba_cpu_sparse_fp64/hpc_ral_cpu/runtime.json + results/group/mge/euclid/jax_cpu_dense_fp64/hpc_ral_cpu/breakdown.json + results/group/mge/euclid/jax_cpu_dense_fp64/hpc_ral_cpu/runtime.json + results/group/rectangular/euclid/jax_cpu_sparse_fp64/hpc_ral_cpu/breakdown.json + results/group/rectangular/euclid/jax_cpu_sparse_fp64/hpc_ral_cpu/runtime.json + results/group/rectangular/euclid/numba_cpu_sparse_fp64/hpc_ral_cpu/breakdown.json + results/group/rectangular/euclid/numba_cpu_sparse_fp64/hpc_ral_cpu/runtime.json +) +RESULTS_ROOT="$AP_ROOT/output/p2d_batch1" + +I=${SLURM_ARRAY_TASK_ID:?"submit as an array (sbatch from hpc//)"} +run_leg $I + +echo "==========================================" +echo "exit status: $STATUS (0 ok, 4 a leg failed or its revisions/row check failed, 5 dataset)" +echo "loadavg: $(cat /proc/loadavg)" +date +exit $STATUS diff --git a/hpc/batch_cpu/submit_campaign_p2d_multi_galaxy_ral_cpu_hst_fp64 b/hpc/batch_cpu/submit_campaign_p2d_multi_galaxy_ral_cpu_hst_fp64 new file mode 100755 index 000000000..4bb5b0f32 --- /dev/null +++ b/hpc/batch_cpu/submit_campaign_p2d_multi_galaxy_ral_cpu_hst_fp64 @@ -0,0 +1,244 @@ +#!/bin/bash -l +# +# RAL CPU array: the hpc_ral_cpu multi_galaxy cells at hst. +# Likelihood-lifecycle phase 2d multi_galaxy + group campaign (autolens_profiling#473), batch 1: 10 cell(s). +# DRAFT FOR REVIEW: the cell design (decisions D1-D10, wiki/campaigns/multi_galaxy/ +# likelihood_lifecycle_p2d.md) awaits the human; do not submit without a batch go. +# GENERATED by scripts/misc/campaigns/multi_galaxy_group_p2d.py --write; edit the generator, +# not this file (the campaign test fails on a hand edit). The batch procedure is in +# scripts/misc/campaigns/README.md. +# +# LIBRARY CODE. A private checkout of the five libraries at tag 2026.10.25.1 ($PYAUTO_PRIVATE_BASE, +# default /mnt/ral/jnightin/profiling/PyAuto_2026.10.25.1) is prepended to PYTHONPATH over the shared venv +# ($PYAUTO_HPC_BASE, default /mnt/ral/jnightin/PyAuto, third-party packages only). The job refuses to +# run if a library imports from anywhere else or sits at another tag, and after each leg it +# checks the row's library_revisions equal the checkout's HEADs. The shared mirror is never +# pulled or used. AP_ROOT is the checkout this was submitted from (hpc//../..). +# +# CELLS. Every leg runs one cell script of the shared galaxy/group driver on the standard +# cell (MGE source, or Delaunay 1250 + 30 edge / rectangular 35x35) and writes its row +# (runtime legs also parity.json and fit.png) into the mirrored cell named by --output-path +# under the gitignored output/p2d_batch1/ scratch tree, never in place over results/. +# +# MEMORY. --mem=32gb, PROVISIONAL (multi_galaxy/hst 11309 masked pixels): the imaging hst legs +# (15k masked pixels) peaked at 10.2 GiB MaxRSS; batch 0's sacct MaxRSS replaces this +# (next 16/32/64 GB step >= 1.5x the peak) before batch 1. +# One cell per array task on `ral` (CPU work never goes on `gpu`). numba cells pin their +# BLAS threads to 1 (production per-worker cost); JAX CPU cells get NPROC=8. +# +# WALL-BASIS: PROVISIONAL. No cell has a wall yet; batch 0 measures them. Every row is +# `unmeasured` until batch 0 lands, and the job refuses to run while +# WALL_BASIS_STATUS=provisional (export P2D_ALLOW_PROVISIONAL_WALL=1 overrides it). +# 3 leg(s): delaunay jax_cpu_sparse_fp64 breakdown, mge jax_cpu_dense_fp64 breakdown, rectangular jax_cpu_sparse_fp64 breakdown +# cell: multi_galaxy/likelihood_breakdown/hst device: ral_cpu precision: fp64 +# source: unmeasured probe-first: yes +# 2 leg(s): delaunay numba_cpu_sparse_fp64 breakdown, rectangular numba_cpu_sparse_fp64 breakdown +# cell: multi_galaxy/likelihood_breakdown_numba/hst device: ral_cpu precision: fp64 +# source: unmeasured probe-first: yes +# 3 leg(s): delaunay jax_cpu_sparse_fp64 runtime, mge jax_cpu_dense_fp64 runtime, rectangular jax_cpu_sparse_fp64 runtime +# cell: multi_galaxy/likelihood_runtime/hst device: ral_cpu precision: fp64 +# source: unmeasured probe-first: yes +# 2 leg(s): delaunay numba_cpu_sparse_fp64 runtime, rectangular numba_cpu_sparse_fp64 runtime +# cell: multi_galaxy/likelihood_runtime_numba/hst device: ral_cpu precision: fp64 +# source: unmeasured probe-first: yes + +#SBATCH -J p2d_b1_multi_galaxy_ral_cpu_hst_fp64 +#SBATCH --partition=ral +#SBATCH --array=0-9%16 +#SBATCH --ntasks=1 +#SBATCH --cpus-per-task=8 +#SBATCH --mem=32gb +#SBATCH --time=4:00:00 +#SBATCH -o output/output.%A_%a.out +#SBATCH -e error/error.%A_%a.err + +# Submit from hpc/batch_cpu/ or hpc/batch_gpu/ (the -o/-e paths are relative). +# Batch 1 runs only once batch 0's walls have replaced the provisional WALL-BASIS rows above +# (source: measured-wall, --time from the measurement) and this reads "measured". +WALL_BASIS_STATUS=provisional +if [ "$WALL_BASIS_STATUS" != measured ] && [ "${P2D_ALLOW_PROVISIONAL_WALL:-0}" != 1 ]; then + echo "REFUSING: WALL_BASIS_STATUS=$WALL_BASIS_STATUS. Run batch 0, set --time from its walls" + echo "and mark the WALL-BASIS rows measured-wall first (scripts/misc/campaigns/README.md)." + exit 2 +fi +export AP_ROOT="$(cd "${SLURM_SUBMIT_DIR:-$(dirname "$0")}/../.." && pwd)" +export PYAUTO_HPC_BASE="${PYAUTO_HPC_BASE:-/mnt/ral/jnightin/PyAuto}" +export PYAUTO_PRIVATE_BASE="${PYAUTO_PRIVATE_BASE:-/mnt/ral/jnightin/profiling/PyAuto_2026.10.25.1}" +export P2D_PIN=2026.10.25.1 +echo "AP_ROOT=$AP_ROOT PYAUTO_PRIVATE_BASE=$PYAUTO_PRIVATE_BASE pin=$P2D_PIN" +source "$AP_ROOT/activate.sh" +export PYTHONPATH=$PYAUTO_PRIVATE_BASE/PyAutoNerves:$PYAUTO_PRIVATE_BASE/PyAutoFit:$PYAUTO_PRIVATE_BASE/PyAutoArray:$PYAUTO_PRIVATE_BASE/PyAutoGalaxy:$PYAUTO_PRIVATE_BASE/PyAutoLens:$PYTHONPATH + +export OMP_NUM_THREADS=1 MKL_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 NUMBA_NUM_THREADS=1 +export NPROC=${SLURM_CPUS_PER_TASK:-8} +export JAX_ENABLE_X64=True +export XLA_PYTHON_CLIENT_PREALLOCATE=false +export XLA_FLAGS="--xla_disable_hlo_passes=constant_folding" +unset PYAUTO_SMALL_DATASETS +export NUMBA_CACHE_DIR="$AP_ROOT/output/numba_cache/p2d_${SLURM_JOB_ID:-local}_${SLURM_ARRAY_TASK_ID:-0}" +mkdir -p "$NUMBA_CACHE_DIR" "$MPLCONFIGDIR" "$AP_ROOT/output/p2d_logs" + +echo "==========================================" +date +hostname +lscpu | grep 'Model name' || true +echo "partition: ${SLURM_JOB_PARTITION:-unset} nodelist: ${SLURM_JOB_NODELIST:-unset} cpus: ${SLURM_CPUS_PER_TASK:-unset}" +echo "loadavg: $(cat /proc/loadavg)" +for r in PyAutoNerves PyAutoFit PyAutoArray PyAutoGalaxy PyAutoLens; do + printf '%-14s %s %s\n' "$r" "$(git -C $PYAUTO_PRIVATE_BASE/$r rev-parse HEAD 2>&1)" "$(git -C $PYAUTO_PRIVATE_BASE/$r describe --tags 2>&1)" +done +echo "AP_ROOT rev: $(git -C $AP_ROOT rev-parse HEAD 2>&1)" + +cd "$AP_ROOT" +# The libraries must import from the private checkout at the pinned tag, never the shared mirror. +python3 - <<'EOF_PY' || exit 3 +import os, subprocess +import autoarray, autofit, autogalaxy, autolens, autonerves +base, pin = os.path.realpath(os.environ["PYAUTO_PRIVATE_BASE"]), os.environ["P2D_PIN"] +for m in (autonerves, autofit, autoarray, autogalaxy, autolens): + print(f"{m.__name__:<11} {m.__file__}") + if not os.path.realpath(m.__file__).startswith(base + os.sep): + raise SystemExit(f"REFUSING: {m.__name__} imported from {m.__file__}, not {base}") + repo = os.path.dirname(os.path.dirname(os.path.realpath(m.__file__))) + tag = subprocess.check_output(["git", "-C", repo, "describe", "--tags"], text=True).strip() + if tag != pin: + raise SystemExit(f"REFUSING: {repo} is at {tag}, not tag {pin}") +print(f"import origin + tag {pin}: OK") +EOF_PY + +# After each leg: the row's recorded library revisions must be the private checkout's HEADs. +check_revisions() { +python3 - "$1" <<'EOF_PY' +import json, os, subprocess, sys +path = sys.argv[1] +revs = json.load(open(path))["device"]["provenance"]["library_revisions"] +base = os.environ["PYAUTO_PRIVATE_BASE"] +for repo in ("PyAutoNerves", "PyAutoFit", "PyAutoArray", "PyAutoGalaxy", "PyAutoLens"): + head = subprocess.check_output(["git", "-C", f"{base}/{repo}", "rev-parse", "HEAD"], text=True).strip() + if revs.get(repo) != head: + raise SystemExit(f"MISMATCH {path}: {repo} row {revs.get(repo)} != private checkout {head}") +print("revisions OK", path) +EOF_PY +} + +# Simulate a missing dataset and cache its adapt image once per instrument, under a lock. +prepare_dataset() { +python3 - "$1" <<'EOF_PY' +import sys +sys.path.insert(0, "scripts/misc/campaigns") +from multi_galaxy_group_p2d import prepare_dataset +prepare_dataset(sys.argv[1]) +EOF_PY +} + +# One leg: fresh JAX compile cache, the leg's platform, wall clock logged, revisions checked. +# A failed leg is recorded and the job carries on (|| keeps activate.sh's ERR trap out of it). +STATUS=0 +run_leg() { + local I=$1 + local LOG="$AP_ROOT/output/p2d_logs/submit_campaign_p2d_multi_galaxy_ral_cpu_hst_fp64_${SLURM_JOB_ID:-local}_${I}.log" + export JAX_PLATFORMS=${PLATFORMS[$I]} + export JAX_COMPILATION_CACHE_DIR="$AP_ROOT/output/jax_cache/p2d_${SLURM_JOB_ID:-local}_${I}" + rm -rf "$JAX_COMPILATION_CACHE_DIR" && mkdir -p "$JAX_COMPILATION_CACHE_DIR" + prepare_dataset ${INSTS[$I]} || { echo "LEG $I: dataset preparation FAILED"; STATUS=5; return 0; } + echo "------------------------------------------" + echo "LEG $I: ${CELLNAMES[$I]}" + echo " cell script: scripts/${CELLS[$I]}.py ${FLAGS[$I]} -> $RESULTS_ROOT/${OUTS[$I]}" + echo " JAX_PLATFORMS=$JAX_PLATFORMS NPROC=$NPROC log=$LOG" + local T0=$(date +%s) + # A START line first, so a leg killed at --time (which never reaches its WALL line) still shows. + printf 'START\t%s\t%s\t%s\t%s\n' "${SLURM_JOB_ID:-local}" "$I" "$T0" "${CELLNAMES[$I]}" >> "$AP_ROOT/output/p2d_logs/walls.tsv" + python3 -u scripts/${CELLS[$I]}.py --instrument ${INSTS[$I]} ${FLAGS[$I]} --output-path "$RESULTS_ROOT/${OUTS[$I]}" > "$LOG" 2>&1 \ + || { echo "LEG $I FAILED (rc $?), see $LOG"; tail -20 "$LOG"; STATUS=4; } + local WALL=$(( $(date +%s) - T0 )) + printf 'WALL\t%s\t%s\t%s\t%s\n' "${SLURM_JOB_ID:-local}" "$I" "$WALL" "${CELLNAMES[$I]}" | tee -a "$AP_ROOT/output/p2d_logs/walls.tsv" + if [ -f "$RESULTS_ROOT/${OUTS[$I]}" ]; then + check_revisions "$RESULTS_ROOT/${OUTS[$I]}" || STATUS=4 + else + echo "LEG $I: no row at $RESULTS_ROOT/${OUTS[$I]}"; STATUS=4 + fi +} + +# The manifest: one entry per leg (multi_galaxy_group_p2d.Task). +CELLNAMES=( + "multi_galaxy/delaunay/hst jax_cpu_sparse_fp64@hpc_ral_cpu [breakdown]" + "multi_galaxy/delaunay/hst jax_cpu_sparse_fp64@hpc_ral_cpu [runtime]" + "multi_galaxy/delaunay/hst numba_cpu_sparse_fp64@hpc_ral_cpu [breakdown]" + "multi_galaxy/delaunay/hst numba_cpu_sparse_fp64@hpc_ral_cpu [runtime]" + "multi_galaxy/mge/hst jax_cpu_dense_fp64@hpc_ral_cpu [breakdown]" + "multi_galaxy/mge/hst jax_cpu_dense_fp64@hpc_ral_cpu [runtime]" + "multi_galaxy/rectangular/hst jax_cpu_sparse_fp64@hpc_ral_cpu [breakdown]" + "multi_galaxy/rectangular/hst jax_cpu_sparse_fp64@hpc_ral_cpu [runtime]" + "multi_galaxy/rectangular/hst numba_cpu_sparse_fp64@hpc_ral_cpu [breakdown]" + "multi_galaxy/rectangular/hst numba_cpu_sparse_fp64@hpc_ral_cpu [runtime]" +) +CELLS=( + multi_galaxy/delaunay/likelihood_breakdown + multi_galaxy/delaunay/likelihood_runtime + multi_galaxy/delaunay/likelihood_breakdown_numba + multi_galaxy/delaunay/likelihood_runtime_numba + multi_galaxy/mge/likelihood_breakdown + multi_galaxy/mge/likelihood_runtime + multi_galaxy/rectangular/likelihood_breakdown + multi_galaxy/rectangular/likelihood_runtime + multi_galaxy/rectangular/likelihood_breakdown_numba + multi_galaxy/rectangular/likelihood_runtime_numba +) +INSTS=( + hst + hst + hst + hst + hst + hst + hst + hst + hst + hst +) +FLAGS=( + "--sparse --config-name hpc_ral_cpu_fp64" + "--sparse --config-name hpc_ral_cpu_fp64" + "--config-name hpc_ral_cpu_fp64" + "--config-name hpc_ral_cpu_fp64" + "--config-name hpc_ral_cpu_fp64" + "--config-name hpc_ral_cpu_fp64" + "--sparse --config-name hpc_ral_cpu_fp64" + "--sparse --config-name hpc_ral_cpu_fp64" + "--config-name hpc_ral_cpu_fp64" + "--config-name hpc_ral_cpu_fp64" +) +PLATFORMS=( + cpu + cpu + cpu + cpu + cpu + cpu + cpu + cpu + cpu + cpu +) +OUTS=( + results/multi_galaxy/delaunay/hst/jax_cpu_sparse_fp64/hpc_ral_cpu/breakdown.json + results/multi_galaxy/delaunay/hst/jax_cpu_sparse_fp64/hpc_ral_cpu/runtime.json + results/multi_galaxy/delaunay/hst/numba_cpu_sparse_fp64/hpc_ral_cpu/breakdown.json + results/multi_galaxy/delaunay/hst/numba_cpu_sparse_fp64/hpc_ral_cpu/runtime.json + results/multi_galaxy/mge/hst/jax_cpu_dense_fp64/hpc_ral_cpu/breakdown.json + results/multi_galaxy/mge/hst/jax_cpu_dense_fp64/hpc_ral_cpu/runtime.json + results/multi_galaxy/rectangular/hst/jax_cpu_sparse_fp64/hpc_ral_cpu/breakdown.json + results/multi_galaxy/rectangular/hst/jax_cpu_sparse_fp64/hpc_ral_cpu/runtime.json + results/multi_galaxy/rectangular/hst/numba_cpu_sparse_fp64/hpc_ral_cpu/breakdown.json + results/multi_galaxy/rectangular/hst/numba_cpu_sparse_fp64/hpc_ral_cpu/runtime.json +) +RESULTS_ROOT="$AP_ROOT/output/p2d_batch1" + +I=${SLURM_ARRAY_TASK_ID:?"submit as an array (sbatch from hpc//)"} +run_leg $I + +echo "==========================================" +echo "exit status: $STATUS (0 ok, 4 a leg failed or its revisions/row check failed, 5 dataset)" +echo "loadavg: $(cat /proc/loadavg)" +date +exit $STATUS diff --git a/hpc/batch_gpu/submit_campaign_p2d_batch0_a100_fp64 b/hpc/batch_gpu/submit_campaign_p2d_batch0_a100_fp64 new file mode 100755 index 000000000..111fc95d2 --- /dev/null +++ b/hpc/batch_gpu/submit_campaign_p2d_batch0_a100_fp64 @@ -0,0 +1,261 @@ +#!/bin/bash -l +# +# Batch-0 timing arm, A100: every hpc_a100 group cell (the bounding dataset). +# Likelihood-lifecycle phase 2d multi_galaxy + group campaign (autolens_profiling#473), batch 0: 14 cell(s). +# DRAFT FOR REVIEW: the cell design (decisions D1-D10, wiki/campaigns/multi_galaxy/ +# likelihood_lifecycle_p2d.md) awaits the human; do not submit without a batch go. +# GENERATED by scripts/misc/campaigns/multi_galaxy_group_p2d.py --write; edit the generator, +# not this file (the campaign test fails on a hand edit). The batch procedure is in +# scripts/misc/campaigns/README.md. +# +# LIBRARY CODE. A private checkout of the five libraries at tag 2026.10.25.1 ($PYAUTO_PRIVATE_BASE, +# default /mnt/ral/jnightin/profiling/PyAuto_2026.10.25.1) is prepended to PYTHONPATH over the shared venv +# ($PYAUTO_HPC_BASE, default /mnt/ral/jnightin/PyAuto, third-party packages only). The job refuses to +# run if a library imports from anywhere else or sits at another tag, and after each leg it +# checks the row's library_revisions equal the checkout's HEADs. The shared mirror is never +# pulled or used. AP_ROOT is the checkout this was submitted from (hpc//../..). +# +# CELLS. Every leg runs one cell script of the shared galaxy/group driver on the standard +# cell (MGE source, or Delaunay 1250 + 30 edge / rectangular 35x35) and writes its row +# (runtime legs also parity.json and fit.png) into the mirrored cell named by --output-path +# under the gitignored output/p2d_batch0/ scratch tree, never in place over results/. +# +# MEMORY. --mem=32gb, PROVISIONAL (group/euclid 17671 masked pixels): the imaging hst legs +# (15k masked pixels) peaked at 10.2 GiB MaxRSS; batch 0's sacct MaxRSS replaces this +# (next 16/32/64 GB step >= 1.5x the peak) before batch 1. +# One leg per array task, each with --gres=gpu:1, throttled to %2 so the timing arm +# holds at most two A100s. The jax_cpu_sparse legs run on the GPU node's CPU inside +# their GPU task (JAX_PLATFORMS=cpu, NPROC=8). +# +# BATCH 0 = TIMING ARM (decision D9). It runs every group leg: group bounds +# multi_galaxy (1.6x the masked pixels, two dPIE extra galaxies). Each leg's wall lands +# in output/p2d_logs/walls.tsv; batch 1's WALL-BASIS rows will cite them +# (source: measured-wall) and its --time / --mem are set from them. +# +# WALL-BASIS: nothing measured yet; 3600 s per leg is a declared guess +# (3x floor), ~10x the imaging hst legs of the nearest measured size. +# 7 leg(s): delaunay jax_cpu_sparse_fp64 breakdown, delaunay jax_gpu_dense_fp64 breakdown, delaunay jax_gpu_sparse_fp64 breakdown, mge jax_gpu_dense_fp64 breakdown, rectangular jax_cpu_sparse_fp64 breakdown, rectangular jax_gpu_dense_fp64 breakdown, rectangular jax_gpu_sparse_fp64 breakdown +# cell: group/likelihood_breakdown/euclid device: a100 precision: fp64 +# source: unmeasured probe-first: yes wall: 3600 headroom: 3.0 +# 7 leg(s): delaunay jax_cpu_sparse_fp64 runtime, delaunay jax_gpu_dense_fp64 runtime, delaunay jax_gpu_sparse_fp64 runtime, mge jax_gpu_dense_fp64 runtime, rectangular jax_cpu_sparse_fp64 runtime, rectangular jax_gpu_dense_fp64 runtime, rectangular jax_gpu_sparse_fp64 runtime +# cell: group/likelihood_runtime/euclid device: a100 precision: fp64 +# source: unmeasured probe-first: yes wall: 3600 headroom: 3.0 + +#SBATCH -J p2d_b0_batch0_a100_fp64 +#SBATCH --partition=gpu +#SBATCH --gres=gpu:1 +#SBATCH --array=0-13%2 +#SBATCH --ntasks=1 +#SBATCH --cpus-per-task=8 +#SBATCH --mem=32gb +#SBATCH --time=4:00:00 +#SBATCH -o output/output.%A_%a.out +#SBATCH -e error/error.%A_%a.err + +# Submit from hpc/batch_cpu/ or hpc/batch_gpu/ (the -o/-e paths are relative). +export AP_ROOT="$(cd "${SLURM_SUBMIT_DIR:-$(dirname "$0")}/../.." && pwd)" +export PYAUTO_HPC_BASE="${PYAUTO_HPC_BASE:-/mnt/ral/jnightin/PyAuto}" +export PYAUTO_PRIVATE_BASE="${PYAUTO_PRIVATE_BASE:-/mnt/ral/jnightin/profiling/PyAuto_2026.10.25.1}" +export P2D_PIN=2026.10.25.1 +echo "AP_ROOT=$AP_ROOT PYAUTO_PRIVATE_BASE=$PYAUTO_PRIVATE_BASE pin=$P2D_PIN" +source "$AP_ROOT/activate.sh" +export PYTHONPATH=$PYAUTO_PRIVATE_BASE/PyAutoNerves:$PYAUTO_PRIVATE_BASE/PyAutoFit:$PYAUTO_PRIVATE_BASE/PyAutoArray:$PYAUTO_PRIVATE_BASE/PyAutoGalaxy:$PYAUTO_PRIVATE_BASE/PyAutoLens:$PYTHONPATH + +export OMP_NUM_THREADS=1 MKL_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 NUMBA_NUM_THREADS=1 +export NPROC=${SLURM_CPUS_PER_TASK:-8} +export JAX_ENABLE_X64=True +export XLA_PYTHON_CLIENT_PREALLOCATE=false +export XLA_FLAGS="--xla_disable_hlo_passes=constant_folding" +unset PYAUTO_SMALL_DATASETS +export NUMBA_CACHE_DIR="$AP_ROOT/output/numba_cache/p2d_${SLURM_JOB_ID:-local}_${SLURM_ARRAY_TASK_ID:-0}" +mkdir -p "$NUMBA_CACHE_DIR" "$MPLCONFIGDIR" "$AP_ROOT/output/p2d_logs" + +echo "==========================================" +date +hostname +lscpu | grep 'Model name' || true +echo "partition: ${SLURM_JOB_PARTITION:-unset} nodelist: ${SLURM_JOB_NODELIST:-unset} cpus: ${SLURM_CPUS_PER_TASK:-unset}" +echo "loadavg: $(cat /proc/loadavg)" +for r in PyAutoNerves PyAutoFit PyAutoArray PyAutoGalaxy PyAutoLens; do + printf '%-14s %s %s\n' "$r" "$(git -C $PYAUTO_PRIVATE_BASE/$r rev-parse HEAD 2>&1)" "$(git -C $PYAUTO_PRIVATE_BASE/$r describe --tags 2>&1)" +done +echo "AP_ROOT rev: $(git -C $AP_ROOT rev-parse HEAD 2>&1)" + +cd "$AP_ROOT" +# The libraries must import from the private checkout at the pinned tag, never the shared mirror. +python3 - <<'EOF_PY' || exit 3 +import os, subprocess +import autoarray, autofit, autogalaxy, autolens, autonerves +base, pin = os.path.realpath(os.environ["PYAUTO_PRIVATE_BASE"]), os.environ["P2D_PIN"] +for m in (autonerves, autofit, autoarray, autogalaxy, autolens): + print(f"{m.__name__:<11} {m.__file__}") + if not os.path.realpath(m.__file__).startswith(base + os.sep): + raise SystemExit(f"REFUSING: {m.__name__} imported from {m.__file__}, not {base}") + repo = os.path.dirname(os.path.dirname(os.path.realpath(m.__file__))) + tag = subprocess.check_output(["git", "-C", repo, "describe", "--tags"], text=True).strip() + if tag != pin: + raise SystemExit(f"REFUSING: {repo} is at {tag}, not tag {pin}") +print(f"import origin + tag {pin}: OK") +EOF_PY + +# After each leg: the row's recorded library revisions must be the private checkout's HEADs. +check_revisions() { +python3 - "$1" <<'EOF_PY' +import json, os, subprocess, sys +path = sys.argv[1] +revs = json.load(open(path))["device"]["provenance"]["library_revisions"] +base = os.environ["PYAUTO_PRIVATE_BASE"] +for repo in ("PyAutoNerves", "PyAutoFit", "PyAutoArray", "PyAutoGalaxy", "PyAutoLens"): + head = subprocess.check_output(["git", "-C", f"{base}/{repo}", "rev-parse", "HEAD"], text=True).strip() + if revs.get(repo) != head: + raise SystemExit(f"MISMATCH {path}: {repo} row {revs.get(repo)} != private checkout {head}") +print("revisions OK", path) +EOF_PY +} + +# Simulate a missing dataset and cache its adapt image once per instrument, under a lock. +prepare_dataset() { +python3 - "$1" <<'EOF_PY' +import sys +sys.path.insert(0, "scripts/misc/campaigns") +from multi_galaxy_group_p2d import prepare_dataset +prepare_dataset(sys.argv[1]) +EOF_PY +} + +# One leg: fresh JAX compile cache, the leg's platform, wall clock logged, revisions checked. +# A failed leg is recorded and the job carries on (|| keeps activate.sh's ERR trap out of it). +STATUS=0 +run_leg() { + local I=$1 + local LOG="$AP_ROOT/output/p2d_logs/submit_campaign_p2d_batch0_a100_fp64_${SLURM_JOB_ID:-local}_${I}.log" + export JAX_PLATFORMS=${PLATFORMS[$I]} + export JAX_COMPILATION_CACHE_DIR="$AP_ROOT/output/jax_cache/p2d_${SLURM_JOB_ID:-local}_${I}" + rm -rf "$JAX_COMPILATION_CACHE_DIR" && mkdir -p "$JAX_COMPILATION_CACHE_DIR" + prepare_dataset ${INSTS[$I]} || { echo "LEG $I: dataset preparation FAILED"; STATUS=5; return 0; } + echo "------------------------------------------" + echo "LEG $I: ${CELLNAMES[$I]}" + echo " cell script: scripts/${CELLS[$I]}.py ${FLAGS[$I]} -> $RESULTS_ROOT/${OUTS[$I]}" + echo " JAX_PLATFORMS=$JAX_PLATFORMS NPROC=$NPROC log=$LOG" + local T0=$(date +%s) + # A START line first, so a leg killed at --time (which never reaches its WALL line) still shows. + printf 'START\t%s\t%s\t%s\t%s\n' "${SLURM_JOB_ID:-local}" "$I" "$T0" "${CELLNAMES[$I]}" >> "$AP_ROOT/output/p2d_logs/walls.tsv" + python3 -u scripts/${CELLS[$I]}.py --instrument ${INSTS[$I]} ${FLAGS[$I]} --output-path "$RESULTS_ROOT/${OUTS[$I]}" > "$LOG" 2>&1 \ + || { echo "LEG $I FAILED (rc $?), see $LOG"; tail -20 "$LOG"; STATUS=4; } + local WALL=$(( $(date +%s) - T0 )) + printf 'WALL\t%s\t%s\t%s\t%s\n' "${SLURM_JOB_ID:-local}" "$I" "$WALL" "${CELLNAMES[$I]}" | tee -a "$AP_ROOT/output/p2d_logs/walls.tsv" + if [ -f "$RESULTS_ROOT/${OUTS[$I]}" ]; then + check_revisions "$RESULTS_ROOT/${OUTS[$I]}" || STATUS=4 + else + echo "LEG $I: no row at $RESULTS_ROOT/${OUTS[$I]}"; STATUS=4 + fi +} + +# The manifest: one entry per leg (multi_galaxy_group_p2d.Task). +CELLNAMES=( + "group/delaunay/euclid jax_cpu_sparse_fp64@hpc_a100 [breakdown]" + "group/delaunay/euclid jax_cpu_sparse_fp64@hpc_a100 [runtime]" + "group/delaunay/euclid jax_gpu_dense_fp64@hpc_a100 [breakdown]" + "group/delaunay/euclid jax_gpu_dense_fp64@hpc_a100 [runtime]" + "group/delaunay/euclid jax_gpu_sparse_fp64@hpc_a100 [breakdown]" + "group/delaunay/euclid jax_gpu_sparse_fp64@hpc_a100 [runtime]" + "group/mge/euclid jax_gpu_dense_fp64@hpc_a100 [breakdown]" + "group/mge/euclid jax_gpu_dense_fp64@hpc_a100 [runtime]" + "group/rectangular/euclid jax_cpu_sparse_fp64@hpc_a100 [breakdown]" + "group/rectangular/euclid jax_cpu_sparse_fp64@hpc_a100 [runtime]" + "group/rectangular/euclid jax_gpu_dense_fp64@hpc_a100 [breakdown]" + "group/rectangular/euclid jax_gpu_dense_fp64@hpc_a100 [runtime]" + "group/rectangular/euclid jax_gpu_sparse_fp64@hpc_a100 [breakdown]" + "group/rectangular/euclid jax_gpu_sparse_fp64@hpc_a100 [runtime]" +) +CELLS=( + group/delaunay/likelihood_breakdown + group/delaunay/likelihood_runtime + group/delaunay/likelihood_breakdown + group/delaunay/likelihood_runtime + group/delaunay/likelihood_breakdown + group/delaunay/likelihood_runtime + group/mge/likelihood_breakdown + group/mge/likelihood_runtime + group/rectangular/likelihood_breakdown + group/rectangular/likelihood_runtime + group/rectangular/likelihood_breakdown + group/rectangular/likelihood_runtime + group/rectangular/likelihood_breakdown + group/rectangular/likelihood_runtime +) +INSTS=( + euclid + euclid + euclid + euclid + euclid + euclid + euclid + euclid + euclid + euclid + euclid + euclid + euclid + euclid +) +FLAGS=( + "--sparse --config-name hpc_a100_cpu_fp64" + "--sparse --config-name hpc_a100_cpu_fp64" + "--config-name hpc_a100_fp64" + "--config-name hpc_a100_fp64" + "--sparse --config-name hpc_a100_fp64" + "--sparse --config-name hpc_a100_fp64" + "--config-name hpc_a100_fp64" + "--config-name hpc_a100_fp64" + "--sparse --config-name hpc_a100_cpu_fp64" + "--sparse --config-name hpc_a100_cpu_fp64" + "--config-name hpc_a100_fp64" + "--config-name hpc_a100_fp64" + "--sparse --config-name hpc_a100_fp64" + "--sparse --config-name hpc_a100_fp64" +) +PLATFORMS=( + cpu + cpu + cuda,cpu + cuda,cpu + cuda,cpu + cuda,cpu + cuda,cpu + cuda,cpu + cpu + cpu + cuda,cpu + cuda,cpu + cuda,cpu + cuda,cpu +) +OUTS=( + results/group/delaunay/euclid/jax_cpu_sparse_fp64/hpc_a100/breakdown.json + results/group/delaunay/euclid/jax_cpu_sparse_fp64/hpc_a100/runtime.json + results/group/delaunay/euclid/jax_gpu_dense_fp64/hpc_a100/breakdown.json + results/group/delaunay/euclid/jax_gpu_dense_fp64/hpc_a100/runtime.json + results/group/delaunay/euclid/jax_gpu_sparse_fp64/hpc_a100/breakdown.json + results/group/delaunay/euclid/jax_gpu_sparse_fp64/hpc_a100/runtime.json + results/group/mge/euclid/jax_gpu_dense_fp64/hpc_a100/breakdown.json + results/group/mge/euclid/jax_gpu_dense_fp64/hpc_a100/runtime.json + results/group/rectangular/euclid/jax_cpu_sparse_fp64/hpc_a100/breakdown.json + results/group/rectangular/euclid/jax_cpu_sparse_fp64/hpc_a100/runtime.json + results/group/rectangular/euclid/jax_gpu_dense_fp64/hpc_a100/breakdown.json + results/group/rectangular/euclid/jax_gpu_dense_fp64/hpc_a100/runtime.json + results/group/rectangular/euclid/jax_gpu_sparse_fp64/hpc_a100/breakdown.json + results/group/rectangular/euclid/jax_gpu_sparse_fp64/hpc_a100/runtime.json +) +RESULTS_ROOT="$AP_ROOT/output/p2d_batch0" + +I=${SLURM_ARRAY_TASK_ID:?"submit as an array (sbatch from hpc//)"} +nvidia-smi || true +run_leg $I + +echo "==========================================" +echo "exit status: $STATUS (0 ok, 4 a leg failed or its revisions/row check failed, 5 dataset)" +echo "loadavg: $(cat /proc/loadavg)" +date +exit $STATUS diff --git a/hpc/batch_gpu/submit_campaign_p2d_group_a100_euclid_fp64 b/hpc/batch_gpu/submit_campaign_p2d_group_a100_euclid_fp64 new file mode 100755 index 000000000..3d407a7e4 --- /dev/null +++ b/hpc/batch_gpu/submit_campaign_p2d_group_a100_euclid_fp64 @@ -0,0 +1,265 @@ +#!/bin/bash -l +# +# A100 job: the hpc_a100 group cells at euclid. +# Likelihood-lifecycle phase 2d multi_galaxy + group campaign (autolens_profiling#473), batch 1: 14 cell(s). +# DRAFT FOR REVIEW: the cell design (decisions D1-D10, wiki/campaigns/multi_galaxy/ +# likelihood_lifecycle_p2d.md) awaits the human; do not submit without a batch go. +# GENERATED by scripts/misc/campaigns/multi_galaxy_group_p2d.py --write; edit the generator, +# not this file (the campaign test fails on a hand edit). The batch procedure is in +# scripts/misc/campaigns/README.md. +# +# LIBRARY CODE. A private checkout of the five libraries at tag 2026.10.25.1 ($PYAUTO_PRIVATE_BASE, +# default /mnt/ral/jnightin/profiling/PyAuto_2026.10.25.1) is prepended to PYTHONPATH over the shared venv +# ($PYAUTO_HPC_BASE, default /mnt/ral/jnightin/PyAuto, third-party packages only). The job refuses to +# run if a library imports from anywhere else or sits at another tag, and after each leg it +# checks the row's library_revisions equal the checkout's HEADs. The shared mirror is never +# pulled or used. AP_ROOT is the checkout this was submitted from (hpc//../..). +# +# CELLS. Every leg runs one cell script of the shared galaxy/group driver on the standard +# cell (MGE source, or Delaunay 1250 + 30 edge / rectangular 35x35) and writes its row +# (runtime legs also parity.json and fit.png) into the mirrored cell named by --output-path +# under the gitignored output/p2d_batch1/ scratch tree, never in place over results/. +# +# MEMORY. --mem=32gb, PROVISIONAL (group/euclid 17671 masked pixels): the imaging hst legs +# (15k masked pixels) peaked at 10.2 GiB MaxRSS; batch 0's sacct MaxRSS replaces this +# (next 16/32/64 GB step >= 1.5x the peak) before batch 1. +# One A100 job runs this dataset type's hpc_a100 cells in turn. The jax_cpu_sparse legs +# run on the GPU node's CPU inside this GPU job (JAX_PLATFORMS=cpu, NPROC=8): the +# hpc_a100 host class's CPU setup, never a CPU array on the gpu partition. +# +# WALL-BASIS: PROVISIONAL. No cell has a wall yet; batch 0 measures them. Every row is +# `unmeasured` until batch 0 lands, and the job refuses to run while +# WALL_BASIS_STATUS=provisional (export P2D_ALLOW_PROVISIONAL_WALL=1 overrides it). +# 7 leg(s): delaunay jax_cpu_sparse_fp64 breakdown, delaunay jax_gpu_dense_fp64 breakdown, delaunay jax_gpu_sparse_fp64 breakdown, mge jax_gpu_dense_fp64 breakdown, rectangular jax_cpu_sparse_fp64 breakdown, rectangular jax_gpu_dense_fp64 breakdown, rectangular jax_gpu_sparse_fp64 breakdown +# cell: group/likelihood_breakdown/euclid device: a100 precision: fp64 +# source: unmeasured probe-first: yes +# 7 leg(s): delaunay jax_cpu_sparse_fp64 runtime, delaunay jax_gpu_dense_fp64 runtime, delaunay jax_gpu_sparse_fp64 runtime, mge jax_gpu_dense_fp64 runtime, rectangular jax_cpu_sparse_fp64 runtime, rectangular jax_gpu_dense_fp64 runtime, rectangular jax_gpu_sparse_fp64 runtime +# cell: group/likelihood_runtime/euclid device: a100 precision: fp64 +# source: unmeasured probe-first: yes + +#SBATCH -J p2d_b1_group_a100_euclid_fp64 +#SBATCH --partition=gpu +#SBATCH --gres=gpu:1 +#SBATCH --ntasks=1 +#SBATCH --cpus-per-task=8 +#SBATCH --mem=32gb +#SBATCH --time=2-00:00:00 +#SBATCH -o output/output.%A.out +#SBATCH -e error/error.%A.err + +# Submit from hpc/batch_cpu/ or hpc/batch_gpu/ (the -o/-e paths are relative). +# Batch 1 runs only once batch 0's walls have replaced the provisional WALL-BASIS rows above +# (source: measured-wall, --time from the measurement) and this reads "measured". +WALL_BASIS_STATUS=provisional +if [ "$WALL_BASIS_STATUS" != measured ] && [ "${P2D_ALLOW_PROVISIONAL_WALL:-0}" != 1 ]; then + echo "REFUSING: WALL_BASIS_STATUS=$WALL_BASIS_STATUS. Run batch 0, set --time from its walls" + echo "and mark the WALL-BASIS rows measured-wall first (scripts/misc/campaigns/README.md)." + exit 2 +fi +export AP_ROOT="$(cd "${SLURM_SUBMIT_DIR:-$(dirname "$0")}/../.." && pwd)" +export PYAUTO_HPC_BASE="${PYAUTO_HPC_BASE:-/mnt/ral/jnightin/PyAuto}" +export PYAUTO_PRIVATE_BASE="${PYAUTO_PRIVATE_BASE:-/mnt/ral/jnightin/profiling/PyAuto_2026.10.25.1}" +export P2D_PIN=2026.10.25.1 +echo "AP_ROOT=$AP_ROOT PYAUTO_PRIVATE_BASE=$PYAUTO_PRIVATE_BASE pin=$P2D_PIN" +source "$AP_ROOT/activate.sh" +export PYTHONPATH=$PYAUTO_PRIVATE_BASE/PyAutoNerves:$PYAUTO_PRIVATE_BASE/PyAutoFit:$PYAUTO_PRIVATE_BASE/PyAutoArray:$PYAUTO_PRIVATE_BASE/PyAutoGalaxy:$PYAUTO_PRIVATE_BASE/PyAutoLens:$PYTHONPATH + +export OMP_NUM_THREADS=1 MKL_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 NUMBA_NUM_THREADS=1 +export NPROC=${SLURM_CPUS_PER_TASK:-8} +export JAX_ENABLE_X64=True +export XLA_PYTHON_CLIENT_PREALLOCATE=false +export XLA_FLAGS="--xla_disable_hlo_passes=constant_folding" +unset PYAUTO_SMALL_DATASETS +export NUMBA_CACHE_DIR="$AP_ROOT/output/numba_cache/p2d_${SLURM_JOB_ID:-local}_${SLURM_ARRAY_TASK_ID:-0}" +mkdir -p "$NUMBA_CACHE_DIR" "$MPLCONFIGDIR" "$AP_ROOT/output/p2d_logs" + +echo "==========================================" +date +hostname +lscpu | grep 'Model name' || true +echo "partition: ${SLURM_JOB_PARTITION:-unset} nodelist: ${SLURM_JOB_NODELIST:-unset} cpus: ${SLURM_CPUS_PER_TASK:-unset}" +echo "loadavg: $(cat /proc/loadavg)" +for r in PyAutoNerves PyAutoFit PyAutoArray PyAutoGalaxy PyAutoLens; do + printf '%-14s %s %s\n' "$r" "$(git -C $PYAUTO_PRIVATE_BASE/$r rev-parse HEAD 2>&1)" "$(git -C $PYAUTO_PRIVATE_BASE/$r describe --tags 2>&1)" +done +echo "AP_ROOT rev: $(git -C $AP_ROOT rev-parse HEAD 2>&1)" + +cd "$AP_ROOT" +# The libraries must import from the private checkout at the pinned tag, never the shared mirror. +python3 - <<'EOF_PY' || exit 3 +import os, subprocess +import autoarray, autofit, autogalaxy, autolens, autonerves +base, pin = os.path.realpath(os.environ["PYAUTO_PRIVATE_BASE"]), os.environ["P2D_PIN"] +for m in (autonerves, autofit, autoarray, autogalaxy, autolens): + print(f"{m.__name__:<11} {m.__file__}") + if not os.path.realpath(m.__file__).startswith(base + os.sep): + raise SystemExit(f"REFUSING: {m.__name__} imported from {m.__file__}, not {base}") + repo = os.path.dirname(os.path.dirname(os.path.realpath(m.__file__))) + tag = subprocess.check_output(["git", "-C", repo, "describe", "--tags"], text=True).strip() + if tag != pin: + raise SystemExit(f"REFUSING: {repo} is at {tag}, not tag {pin}") +print(f"import origin + tag {pin}: OK") +EOF_PY + +# After each leg: the row's recorded library revisions must be the private checkout's HEADs. +check_revisions() { +python3 - "$1" <<'EOF_PY' +import json, os, subprocess, sys +path = sys.argv[1] +revs = json.load(open(path))["device"]["provenance"]["library_revisions"] +base = os.environ["PYAUTO_PRIVATE_BASE"] +for repo in ("PyAutoNerves", "PyAutoFit", "PyAutoArray", "PyAutoGalaxy", "PyAutoLens"): + head = subprocess.check_output(["git", "-C", f"{base}/{repo}", "rev-parse", "HEAD"], text=True).strip() + if revs.get(repo) != head: + raise SystemExit(f"MISMATCH {path}: {repo} row {revs.get(repo)} != private checkout {head}") +print("revisions OK", path) +EOF_PY +} + +# Simulate a missing dataset and cache its adapt image once per instrument, under a lock. +prepare_dataset() { +python3 - "$1" <<'EOF_PY' +import sys +sys.path.insert(0, "scripts/misc/campaigns") +from multi_galaxy_group_p2d import prepare_dataset +prepare_dataset(sys.argv[1]) +EOF_PY +} + +# One leg: fresh JAX compile cache, the leg's platform, wall clock logged, revisions checked. +# A failed leg is recorded and the job carries on (|| keeps activate.sh's ERR trap out of it). +STATUS=0 +run_leg() { + local I=$1 + local LOG="$AP_ROOT/output/p2d_logs/submit_campaign_p2d_group_a100_euclid_fp64_${SLURM_JOB_ID:-local}_${I}.log" + export JAX_PLATFORMS=${PLATFORMS[$I]} + export JAX_COMPILATION_CACHE_DIR="$AP_ROOT/output/jax_cache/p2d_${SLURM_JOB_ID:-local}_${I}" + rm -rf "$JAX_COMPILATION_CACHE_DIR" && mkdir -p "$JAX_COMPILATION_CACHE_DIR" + prepare_dataset ${INSTS[$I]} || { echo "LEG $I: dataset preparation FAILED"; STATUS=5; return 0; } + echo "------------------------------------------" + echo "LEG $I: ${CELLNAMES[$I]}" + echo " cell script: scripts/${CELLS[$I]}.py ${FLAGS[$I]} -> $RESULTS_ROOT/${OUTS[$I]}" + echo " JAX_PLATFORMS=$JAX_PLATFORMS NPROC=$NPROC log=$LOG" + local T0=$(date +%s) + # A START line first, so a leg killed at --time (which never reaches its WALL line) still shows. + printf 'START\t%s\t%s\t%s\t%s\n' "${SLURM_JOB_ID:-local}" "$I" "$T0" "${CELLNAMES[$I]}" >> "$AP_ROOT/output/p2d_logs/walls.tsv" + python3 -u scripts/${CELLS[$I]}.py --instrument ${INSTS[$I]} ${FLAGS[$I]} --output-path "$RESULTS_ROOT/${OUTS[$I]}" > "$LOG" 2>&1 \ + || { echo "LEG $I FAILED (rc $?), see $LOG"; tail -20 "$LOG"; STATUS=4; } + local WALL=$(( $(date +%s) - T0 )) + printf 'WALL\t%s\t%s\t%s\t%s\n' "${SLURM_JOB_ID:-local}" "$I" "$WALL" "${CELLNAMES[$I]}" | tee -a "$AP_ROOT/output/p2d_logs/walls.tsv" + if [ -f "$RESULTS_ROOT/${OUTS[$I]}" ]; then + check_revisions "$RESULTS_ROOT/${OUTS[$I]}" || STATUS=4 + else + echo "LEG $I: no row at $RESULTS_ROOT/${OUTS[$I]}"; STATUS=4 + fi +} + +# The manifest: one entry per leg (multi_galaxy_group_p2d.Task). +CELLNAMES=( + "group/delaunay/euclid jax_cpu_sparse_fp64@hpc_a100 [breakdown]" + "group/delaunay/euclid jax_cpu_sparse_fp64@hpc_a100 [runtime]" + "group/delaunay/euclid jax_gpu_dense_fp64@hpc_a100 [breakdown]" + "group/delaunay/euclid jax_gpu_dense_fp64@hpc_a100 [runtime]" + "group/delaunay/euclid jax_gpu_sparse_fp64@hpc_a100 [breakdown]" + "group/delaunay/euclid jax_gpu_sparse_fp64@hpc_a100 [runtime]" + "group/mge/euclid jax_gpu_dense_fp64@hpc_a100 [breakdown]" + "group/mge/euclid jax_gpu_dense_fp64@hpc_a100 [runtime]" + "group/rectangular/euclid jax_cpu_sparse_fp64@hpc_a100 [breakdown]" + "group/rectangular/euclid jax_cpu_sparse_fp64@hpc_a100 [runtime]" + "group/rectangular/euclid jax_gpu_dense_fp64@hpc_a100 [breakdown]" + "group/rectangular/euclid jax_gpu_dense_fp64@hpc_a100 [runtime]" + "group/rectangular/euclid jax_gpu_sparse_fp64@hpc_a100 [breakdown]" + "group/rectangular/euclid jax_gpu_sparse_fp64@hpc_a100 [runtime]" +) +CELLS=( + group/delaunay/likelihood_breakdown + group/delaunay/likelihood_runtime + group/delaunay/likelihood_breakdown + group/delaunay/likelihood_runtime + group/delaunay/likelihood_breakdown + group/delaunay/likelihood_runtime + group/mge/likelihood_breakdown + group/mge/likelihood_runtime + group/rectangular/likelihood_breakdown + group/rectangular/likelihood_runtime + group/rectangular/likelihood_breakdown + group/rectangular/likelihood_runtime + group/rectangular/likelihood_breakdown + group/rectangular/likelihood_runtime +) +INSTS=( + euclid + euclid + euclid + euclid + euclid + euclid + euclid + euclid + euclid + euclid + euclid + euclid + euclid + euclid +) +FLAGS=( + "--sparse --config-name hpc_a100_cpu_fp64" + "--sparse --config-name hpc_a100_cpu_fp64" + "--config-name hpc_a100_fp64" + "--config-name hpc_a100_fp64" + "--sparse --config-name hpc_a100_fp64" + "--sparse --config-name hpc_a100_fp64" + "--config-name hpc_a100_fp64" + "--config-name hpc_a100_fp64" + "--sparse --config-name hpc_a100_cpu_fp64" + "--sparse --config-name hpc_a100_cpu_fp64" + "--config-name hpc_a100_fp64" + "--config-name hpc_a100_fp64" + "--sparse --config-name hpc_a100_fp64" + "--sparse --config-name hpc_a100_fp64" +) +PLATFORMS=( + cpu + cpu + cuda,cpu + cuda,cpu + cuda,cpu + cuda,cpu + cuda,cpu + cuda,cpu + cpu + cpu + cuda,cpu + cuda,cpu + cuda,cpu + cuda,cpu +) +OUTS=( + results/group/delaunay/euclid/jax_cpu_sparse_fp64/hpc_a100/breakdown.json + results/group/delaunay/euclid/jax_cpu_sparse_fp64/hpc_a100/runtime.json + results/group/delaunay/euclid/jax_gpu_dense_fp64/hpc_a100/breakdown.json + results/group/delaunay/euclid/jax_gpu_dense_fp64/hpc_a100/runtime.json + results/group/delaunay/euclid/jax_gpu_sparse_fp64/hpc_a100/breakdown.json + results/group/delaunay/euclid/jax_gpu_sparse_fp64/hpc_a100/runtime.json + results/group/mge/euclid/jax_gpu_dense_fp64/hpc_a100/breakdown.json + results/group/mge/euclid/jax_gpu_dense_fp64/hpc_a100/runtime.json + results/group/rectangular/euclid/jax_cpu_sparse_fp64/hpc_a100/breakdown.json + results/group/rectangular/euclid/jax_cpu_sparse_fp64/hpc_a100/runtime.json + results/group/rectangular/euclid/jax_gpu_dense_fp64/hpc_a100/breakdown.json + results/group/rectangular/euclid/jax_gpu_dense_fp64/hpc_a100/runtime.json + results/group/rectangular/euclid/jax_gpu_sparse_fp64/hpc_a100/breakdown.json + results/group/rectangular/euclid/jax_gpu_sparse_fp64/hpc_a100/runtime.json +) +RESULTS_ROOT="$AP_ROOT/output/p2d_batch1" + +nvidia-smi || true +for I in "${!CELLS[@]}"; do + run_leg $I +done + +echo "==========================================" +echo "exit status: $STATUS (0 ok, 4 a leg failed or its revisions/row check failed, 5 dataset)" +echo "loadavg: $(cat /proc/loadavg)" +date +exit $STATUS diff --git a/hpc/batch_gpu/submit_campaign_p2d_multi_galaxy_a100_hst_fp64 b/hpc/batch_gpu/submit_campaign_p2d_multi_galaxy_a100_hst_fp64 new file mode 100755 index 000000000..bb14b30d9 --- /dev/null +++ b/hpc/batch_gpu/submit_campaign_p2d_multi_galaxy_a100_hst_fp64 @@ -0,0 +1,265 @@ +#!/bin/bash -l +# +# A100 job: the hpc_a100 multi_galaxy cells at hst. +# Likelihood-lifecycle phase 2d multi_galaxy + group campaign (autolens_profiling#473), batch 1: 14 cell(s). +# DRAFT FOR REVIEW: the cell design (decisions D1-D10, wiki/campaigns/multi_galaxy/ +# likelihood_lifecycle_p2d.md) awaits the human; do not submit without a batch go. +# GENERATED by scripts/misc/campaigns/multi_galaxy_group_p2d.py --write; edit the generator, +# not this file (the campaign test fails on a hand edit). The batch procedure is in +# scripts/misc/campaigns/README.md. +# +# LIBRARY CODE. A private checkout of the five libraries at tag 2026.10.25.1 ($PYAUTO_PRIVATE_BASE, +# default /mnt/ral/jnightin/profiling/PyAuto_2026.10.25.1) is prepended to PYTHONPATH over the shared venv +# ($PYAUTO_HPC_BASE, default /mnt/ral/jnightin/PyAuto, third-party packages only). The job refuses to +# run if a library imports from anywhere else or sits at another tag, and after each leg it +# checks the row's library_revisions equal the checkout's HEADs. The shared mirror is never +# pulled or used. AP_ROOT is the checkout this was submitted from (hpc//../..). +# +# CELLS. Every leg runs one cell script of the shared galaxy/group driver on the standard +# cell (MGE source, or Delaunay 1250 + 30 edge / rectangular 35x35) and writes its row +# (runtime legs also parity.json and fit.png) into the mirrored cell named by --output-path +# under the gitignored output/p2d_batch1/ scratch tree, never in place over results/. +# +# MEMORY. --mem=32gb, PROVISIONAL (multi_galaxy/hst 11309 masked pixels): the imaging hst legs +# (15k masked pixels) peaked at 10.2 GiB MaxRSS; batch 0's sacct MaxRSS replaces this +# (next 16/32/64 GB step >= 1.5x the peak) before batch 1. +# One A100 job runs this dataset type's hpc_a100 cells in turn. The jax_cpu_sparse legs +# run on the GPU node's CPU inside this GPU job (JAX_PLATFORMS=cpu, NPROC=8): the +# hpc_a100 host class's CPU setup, never a CPU array on the gpu partition. +# +# WALL-BASIS: PROVISIONAL. No cell has a wall yet; batch 0 measures them. Every row is +# `unmeasured` until batch 0 lands, and the job refuses to run while +# WALL_BASIS_STATUS=provisional (export P2D_ALLOW_PROVISIONAL_WALL=1 overrides it). +# 7 leg(s): delaunay jax_cpu_sparse_fp64 breakdown, delaunay jax_gpu_dense_fp64 breakdown, delaunay jax_gpu_sparse_fp64 breakdown, mge jax_gpu_dense_fp64 breakdown, rectangular jax_cpu_sparse_fp64 breakdown, rectangular jax_gpu_dense_fp64 breakdown, rectangular jax_gpu_sparse_fp64 breakdown +# cell: multi_galaxy/likelihood_breakdown/hst device: a100 precision: fp64 +# source: unmeasured probe-first: yes +# 7 leg(s): delaunay jax_cpu_sparse_fp64 runtime, delaunay jax_gpu_dense_fp64 runtime, delaunay jax_gpu_sparse_fp64 runtime, mge jax_gpu_dense_fp64 runtime, rectangular jax_cpu_sparse_fp64 runtime, rectangular jax_gpu_dense_fp64 runtime, rectangular jax_gpu_sparse_fp64 runtime +# cell: multi_galaxy/likelihood_runtime/hst device: a100 precision: fp64 +# source: unmeasured probe-first: yes + +#SBATCH -J p2d_b1_multi_galaxy_a100_hst_fp64 +#SBATCH --partition=gpu +#SBATCH --gres=gpu:1 +#SBATCH --ntasks=1 +#SBATCH --cpus-per-task=8 +#SBATCH --mem=32gb +#SBATCH --time=2-00:00:00 +#SBATCH -o output/output.%A.out +#SBATCH -e error/error.%A.err + +# Submit from hpc/batch_cpu/ or hpc/batch_gpu/ (the -o/-e paths are relative). +# Batch 1 runs only once batch 0's walls have replaced the provisional WALL-BASIS rows above +# (source: measured-wall, --time from the measurement) and this reads "measured". +WALL_BASIS_STATUS=provisional +if [ "$WALL_BASIS_STATUS" != measured ] && [ "${P2D_ALLOW_PROVISIONAL_WALL:-0}" != 1 ]; then + echo "REFUSING: WALL_BASIS_STATUS=$WALL_BASIS_STATUS. Run batch 0, set --time from its walls" + echo "and mark the WALL-BASIS rows measured-wall first (scripts/misc/campaigns/README.md)." + exit 2 +fi +export AP_ROOT="$(cd "${SLURM_SUBMIT_DIR:-$(dirname "$0")}/../.." && pwd)" +export PYAUTO_HPC_BASE="${PYAUTO_HPC_BASE:-/mnt/ral/jnightin/PyAuto}" +export PYAUTO_PRIVATE_BASE="${PYAUTO_PRIVATE_BASE:-/mnt/ral/jnightin/profiling/PyAuto_2026.10.25.1}" +export P2D_PIN=2026.10.25.1 +echo "AP_ROOT=$AP_ROOT PYAUTO_PRIVATE_BASE=$PYAUTO_PRIVATE_BASE pin=$P2D_PIN" +source "$AP_ROOT/activate.sh" +export PYTHONPATH=$PYAUTO_PRIVATE_BASE/PyAutoNerves:$PYAUTO_PRIVATE_BASE/PyAutoFit:$PYAUTO_PRIVATE_BASE/PyAutoArray:$PYAUTO_PRIVATE_BASE/PyAutoGalaxy:$PYAUTO_PRIVATE_BASE/PyAutoLens:$PYTHONPATH + +export OMP_NUM_THREADS=1 MKL_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 NUMBA_NUM_THREADS=1 +export NPROC=${SLURM_CPUS_PER_TASK:-8} +export JAX_ENABLE_X64=True +export XLA_PYTHON_CLIENT_PREALLOCATE=false +export XLA_FLAGS="--xla_disable_hlo_passes=constant_folding" +unset PYAUTO_SMALL_DATASETS +export NUMBA_CACHE_DIR="$AP_ROOT/output/numba_cache/p2d_${SLURM_JOB_ID:-local}_${SLURM_ARRAY_TASK_ID:-0}" +mkdir -p "$NUMBA_CACHE_DIR" "$MPLCONFIGDIR" "$AP_ROOT/output/p2d_logs" + +echo "==========================================" +date +hostname +lscpu | grep 'Model name' || true +echo "partition: ${SLURM_JOB_PARTITION:-unset} nodelist: ${SLURM_JOB_NODELIST:-unset} cpus: ${SLURM_CPUS_PER_TASK:-unset}" +echo "loadavg: $(cat /proc/loadavg)" +for r in PyAutoNerves PyAutoFit PyAutoArray PyAutoGalaxy PyAutoLens; do + printf '%-14s %s %s\n' "$r" "$(git -C $PYAUTO_PRIVATE_BASE/$r rev-parse HEAD 2>&1)" "$(git -C $PYAUTO_PRIVATE_BASE/$r describe --tags 2>&1)" +done +echo "AP_ROOT rev: $(git -C $AP_ROOT rev-parse HEAD 2>&1)" + +cd "$AP_ROOT" +# The libraries must import from the private checkout at the pinned tag, never the shared mirror. +python3 - <<'EOF_PY' || exit 3 +import os, subprocess +import autoarray, autofit, autogalaxy, autolens, autonerves +base, pin = os.path.realpath(os.environ["PYAUTO_PRIVATE_BASE"]), os.environ["P2D_PIN"] +for m in (autonerves, autofit, autoarray, autogalaxy, autolens): + print(f"{m.__name__:<11} {m.__file__}") + if not os.path.realpath(m.__file__).startswith(base + os.sep): + raise SystemExit(f"REFUSING: {m.__name__} imported from {m.__file__}, not {base}") + repo = os.path.dirname(os.path.dirname(os.path.realpath(m.__file__))) + tag = subprocess.check_output(["git", "-C", repo, "describe", "--tags"], text=True).strip() + if tag != pin: + raise SystemExit(f"REFUSING: {repo} is at {tag}, not tag {pin}") +print(f"import origin + tag {pin}: OK") +EOF_PY + +# After each leg: the row's recorded library revisions must be the private checkout's HEADs. +check_revisions() { +python3 - "$1" <<'EOF_PY' +import json, os, subprocess, sys +path = sys.argv[1] +revs = json.load(open(path))["device"]["provenance"]["library_revisions"] +base = os.environ["PYAUTO_PRIVATE_BASE"] +for repo in ("PyAutoNerves", "PyAutoFit", "PyAutoArray", "PyAutoGalaxy", "PyAutoLens"): + head = subprocess.check_output(["git", "-C", f"{base}/{repo}", "rev-parse", "HEAD"], text=True).strip() + if revs.get(repo) != head: + raise SystemExit(f"MISMATCH {path}: {repo} row {revs.get(repo)} != private checkout {head}") +print("revisions OK", path) +EOF_PY +} + +# Simulate a missing dataset and cache its adapt image once per instrument, under a lock. +prepare_dataset() { +python3 - "$1" <<'EOF_PY' +import sys +sys.path.insert(0, "scripts/misc/campaigns") +from multi_galaxy_group_p2d import prepare_dataset +prepare_dataset(sys.argv[1]) +EOF_PY +} + +# One leg: fresh JAX compile cache, the leg's platform, wall clock logged, revisions checked. +# A failed leg is recorded and the job carries on (|| keeps activate.sh's ERR trap out of it). +STATUS=0 +run_leg() { + local I=$1 + local LOG="$AP_ROOT/output/p2d_logs/submit_campaign_p2d_multi_galaxy_a100_hst_fp64_${SLURM_JOB_ID:-local}_${I}.log" + export JAX_PLATFORMS=${PLATFORMS[$I]} + export JAX_COMPILATION_CACHE_DIR="$AP_ROOT/output/jax_cache/p2d_${SLURM_JOB_ID:-local}_${I}" + rm -rf "$JAX_COMPILATION_CACHE_DIR" && mkdir -p "$JAX_COMPILATION_CACHE_DIR" + prepare_dataset ${INSTS[$I]} || { echo "LEG $I: dataset preparation FAILED"; STATUS=5; return 0; } + echo "------------------------------------------" + echo "LEG $I: ${CELLNAMES[$I]}" + echo " cell script: scripts/${CELLS[$I]}.py ${FLAGS[$I]} -> $RESULTS_ROOT/${OUTS[$I]}" + echo " JAX_PLATFORMS=$JAX_PLATFORMS NPROC=$NPROC log=$LOG" + local T0=$(date +%s) + # A START line first, so a leg killed at --time (which never reaches its WALL line) still shows. + printf 'START\t%s\t%s\t%s\t%s\n' "${SLURM_JOB_ID:-local}" "$I" "$T0" "${CELLNAMES[$I]}" >> "$AP_ROOT/output/p2d_logs/walls.tsv" + python3 -u scripts/${CELLS[$I]}.py --instrument ${INSTS[$I]} ${FLAGS[$I]} --output-path "$RESULTS_ROOT/${OUTS[$I]}" > "$LOG" 2>&1 \ + || { echo "LEG $I FAILED (rc $?), see $LOG"; tail -20 "$LOG"; STATUS=4; } + local WALL=$(( $(date +%s) - T0 )) + printf 'WALL\t%s\t%s\t%s\t%s\n' "${SLURM_JOB_ID:-local}" "$I" "$WALL" "${CELLNAMES[$I]}" | tee -a "$AP_ROOT/output/p2d_logs/walls.tsv" + if [ -f "$RESULTS_ROOT/${OUTS[$I]}" ]; then + check_revisions "$RESULTS_ROOT/${OUTS[$I]}" || STATUS=4 + else + echo "LEG $I: no row at $RESULTS_ROOT/${OUTS[$I]}"; STATUS=4 + fi +} + +# The manifest: one entry per leg (multi_galaxy_group_p2d.Task). +CELLNAMES=( + "multi_galaxy/delaunay/hst jax_cpu_sparse_fp64@hpc_a100 [breakdown]" + "multi_galaxy/delaunay/hst jax_cpu_sparse_fp64@hpc_a100 [runtime]" + "multi_galaxy/delaunay/hst jax_gpu_dense_fp64@hpc_a100 [breakdown]" + "multi_galaxy/delaunay/hst jax_gpu_dense_fp64@hpc_a100 [runtime]" + "multi_galaxy/delaunay/hst jax_gpu_sparse_fp64@hpc_a100 [breakdown]" + "multi_galaxy/delaunay/hst jax_gpu_sparse_fp64@hpc_a100 [runtime]" + "multi_galaxy/mge/hst jax_gpu_dense_fp64@hpc_a100 [breakdown]" + "multi_galaxy/mge/hst jax_gpu_dense_fp64@hpc_a100 [runtime]" + "multi_galaxy/rectangular/hst jax_cpu_sparse_fp64@hpc_a100 [breakdown]" + "multi_galaxy/rectangular/hst jax_cpu_sparse_fp64@hpc_a100 [runtime]" + "multi_galaxy/rectangular/hst jax_gpu_dense_fp64@hpc_a100 [breakdown]" + "multi_galaxy/rectangular/hst jax_gpu_dense_fp64@hpc_a100 [runtime]" + "multi_galaxy/rectangular/hst jax_gpu_sparse_fp64@hpc_a100 [breakdown]" + "multi_galaxy/rectangular/hst jax_gpu_sparse_fp64@hpc_a100 [runtime]" +) +CELLS=( + multi_galaxy/delaunay/likelihood_breakdown + multi_galaxy/delaunay/likelihood_runtime + multi_galaxy/delaunay/likelihood_breakdown + multi_galaxy/delaunay/likelihood_runtime + multi_galaxy/delaunay/likelihood_breakdown + multi_galaxy/delaunay/likelihood_runtime + multi_galaxy/mge/likelihood_breakdown + multi_galaxy/mge/likelihood_runtime + multi_galaxy/rectangular/likelihood_breakdown + multi_galaxy/rectangular/likelihood_runtime + multi_galaxy/rectangular/likelihood_breakdown + multi_galaxy/rectangular/likelihood_runtime + multi_galaxy/rectangular/likelihood_breakdown + multi_galaxy/rectangular/likelihood_runtime +) +INSTS=( + hst + hst + hst + hst + hst + hst + hst + hst + hst + hst + hst + hst + hst + hst +) +FLAGS=( + "--sparse --config-name hpc_a100_cpu_fp64" + "--sparse --config-name hpc_a100_cpu_fp64" + "--config-name hpc_a100_fp64" + "--config-name hpc_a100_fp64" + "--sparse --config-name hpc_a100_fp64" + "--sparse --config-name hpc_a100_fp64" + "--config-name hpc_a100_fp64" + "--config-name hpc_a100_fp64" + "--sparse --config-name hpc_a100_cpu_fp64" + "--sparse --config-name hpc_a100_cpu_fp64" + "--config-name hpc_a100_fp64" + "--config-name hpc_a100_fp64" + "--sparse --config-name hpc_a100_fp64" + "--sparse --config-name hpc_a100_fp64" +) +PLATFORMS=( + cpu + cpu + cuda,cpu + cuda,cpu + cuda,cpu + cuda,cpu + cuda,cpu + cuda,cpu + cpu + cpu + cuda,cpu + cuda,cpu + cuda,cpu + cuda,cpu +) +OUTS=( + results/multi_galaxy/delaunay/hst/jax_cpu_sparse_fp64/hpc_a100/breakdown.json + results/multi_galaxy/delaunay/hst/jax_cpu_sparse_fp64/hpc_a100/runtime.json + results/multi_galaxy/delaunay/hst/jax_gpu_dense_fp64/hpc_a100/breakdown.json + results/multi_galaxy/delaunay/hst/jax_gpu_dense_fp64/hpc_a100/runtime.json + results/multi_galaxy/delaunay/hst/jax_gpu_sparse_fp64/hpc_a100/breakdown.json + results/multi_galaxy/delaunay/hst/jax_gpu_sparse_fp64/hpc_a100/runtime.json + results/multi_galaxy/mge/hst/jax_gpu_dense_fp64/hpc_a100/breakdown.json + results/multi_galaxy/mge/hst/jax_gpu_dense_fp64/hpc_a100/runtime.json + results/multi_galaxy/rectangular/hst/jax_cpu_sparse_fp64/hpc_a100/breakdown.json + results/multi_galaxy/rectangular/hst/jax_cpu_sparse_fp64/hpc_a100/runtime.json + results/multi_galaxy/rectangular/hst/jax_gpu_dense_fp64/hpc_a100/breakdown.json + results/multi_galaxy/rectangular/hst/jax_gpu_dense_fp64/hpc_a100/runtime.json + results/multi_galaxy/rectangular/hst/jax_gpu_sparse_fp64/hpc_a100/breakdown.json + results/multi_galaxy/rectangular/hst/jax_gpu_sparse_fp64/hpc_a100/runtime.json +) +RESULTS_ROOT="$AP_ROOT/output/p2d_batch1" + +nvidia-smi || true +for I in "${!CELLS[@]}"; do + run_leg $I +done + +echo "==========================================" +echo "exit status: $STATUS (0 ok, 4 a leg failed or its revisions/row check failed, 5 dataset)" +echo "loadavg: $(cat /proc/loadavg)" +date +exit $STATUS diff --git a/scripts/misc/campaigns/README.md b/scripts/misc/campaigns/README.md index 5cc6bdca9..2489066d5 100644 --- a/scripts/misc/campaigns/README.md +++ b/scripts/misc/campaigns/README.md @@ -10,6 +10,7 @@ the same list. | [`imaging_p2a.py`](imaging_p2a.py) | Phase 2a, `imaging/{mge, rectangular, delaunay, delaunay_nn}` at the standard size on 2026.10.23.1 (autolens_profiling#456) | `hpc/batch_cpu/submit_campaign_p2a_imaging_*`, `hpc/batch_gpu/submit_campaign_p2a_imaging_*` | | [`imaging_p2a.py`](imaging_p2a.py) (`rect28_tasks`) | Phase 2a size variant: hst rectangular at 28x28 = 784 source pixels on 2026.10.25.1 (autolens_profiling#468) | `hpc/batch_cpu/submit_campaign_p2a_rect28_ral_cpu_fp64`, `hpc/batch_gpu/submit_campaign_p2a_rect28_a100_fp64` | | [`interferometer_p2b.py`](interferometer_p2b.py) | Phase 2b, `interferometer/{mge, rectangular, delaunay}` at the standard size on 2026.10.25.1 (autolens_profiling#469), plus the dense parity references and the matrix-free experiment | `hpc/batch_cpu/submit_campaign_p2b_*`, `hpc/batch_gpu/submit_campaign_p2b_*` | +| [`multi_galaxy_group_p2d.py`](multi_galaxy_group_p2d.py) | Phase 2d DRAFT, `{multi_galaxy,group}/{mge, rectangular, delaunay}` at the standard size on 2026.10.25.1 (autolens_profiling#473); decisions D1-D11 await the human | `hpc/batch_cpu/submit_campaign_p2d_*`, `hpc/batch_gpu/submit_campaign_p2d_*` | | [`_common.py`](_common.py) | The submit machinery both generators share (preamble, guards, WALL-BASIS rows, `#SBATCH` block) | none of its own | | [`peak_rss_backfill.py`](peak_rss_backfill.py) | Phase 2x backfill of 2a's peak memory and cores per call from sacct (autolens_profiling#462) | writes `catalogue/peak_rss_backfill.json`, no submits | @@ -20,6 +21,9 @@ python scripts/misc/campaigns/imaging_p2a.py --check # exit 1 if a submit is o python scripts/misc/campaigns/interferometer_p2b.py --list # the 60 cells, 6 references, 7 matrix-free legs python scripts/misc/campaigns/interferometer_p2b.py --write # re-render the 2b submits python scripts/misc/campaigns/interferometer_p2b.py --check +python scripts/misc/campaigns/multi_galaxy_group_p2d.py --list # the 48 draft 2d cells +python scripts/misc/campaigns/multi_galaxy_group_p2d.py --write # re-render the 2d submits +python scripts/misc/campaigns/multi_galaxy_group_p2d.py --check pytest scripts/misc/campaigns/test -q ``` @@ -334,3 +338,45 @@ the final row, `fit.png`, a `parity.json` that passes `parity_witness.py --check `size_fallback` rows and the stale MGE row to `history/_/` first, then regenerates the catalogue and coverage. +## Phase 2d multi_galaxy + group (DRAFT, not submitted) + +**Status.** A draft for the human's review (autolens_profiling#473). The cell design is +decisions D1-D11 on the campaign page, +[`wiki/campaigns/multi_galaxy/likelihood_lifecycle_p2d.md`](../../../wiki/campaigns/multi_galaxy/likelihood_lifecycle_p2d.md). +No submit has run; each batch needs the human's go. + +**Cells.** 48 planned cells (`catalogue/registry.json`, §3.3 "as imaging"): `multi_galaxy` at +hst and `group` at euclid, each `mge` (`jax_cpu_dense_fp64`@`hpc_ral_cpu`, +`jax_gpu_dense_fp64`@`hpc_a100`) and `rectangular` / `delaunay` (`numba_cpu_sparse_fp64` and +`jax_cpu_sparse_fp64`@`hpc_ral_cpu`; `jax_gpu_dense_fp64`, `jax_gpu_sparse_fp64` and +`jax_cpu_sparse_fp64`@`hpc_a100`), runtime and breakdown: 20 RAL CPU, 28 A100. The scripts are +new (`scripts/{multi_galaxy,group}//likelihood_{runtime,breakdown}[_numba].py`), thin +wrappers over one driver, `scripts/misc/likelihood_breakdown/galaxy_group_standard.py`, on one +cell builder, `scripts/misc/cell_builders/galaxy_group.py` (dataset simulation, masking, the +workspace modeling model, the standard-size pixelization). JAX legs take `--sparse` for the +sparse setups; nothing else but `--config-name`. + +**Submits.** + +| Submit | Partition | Tasks | `--time` | `--mem` | +|--------|-----------|-------|----------|---------| +| `batch_cpu/submit_campaign_p2d_batch0_ral_cpu_fp64` | `ral`, array `%8` | 10 (batch 0, every group RAL leg) | 4:00:00 | 32 GB | +| `batch_gpu/submit_campaign_p2d_batch0_a100_fp64` | `gpu`, `--gres=gpu:1`, array `%2` | 14 (batch 0, every group A100 leg) | 4:00:00 | 32 GB | +| `batch_cpu/submit_campaign_p2d__ral_cpu__fp64` | `ral`, array `%16` | 10 each | 4:00:00 (provisional) | 32 GB (provisional) | +| `batch_gpu/submit_campaign_p2d__a100__fp64` | `gpu`, `--gres=gpu:1` | one job each, 14 legs in turn | 2-00:00:00 (provisional) | 32 GB (provisional) | + +The `jax_cpu_sparse_fp64@hpc_a100` legs run on the GPU node's CPU inside the GPU job, as in 2a. +Batch 0 is the timing arm (D9): group bounds multi_galaxy (1.6x the masked pixels, two dPIE +extra galaxies), so its legs set batch 1's walls. Its rows declare `source: unmeasured` with a +3600 s guess (3x floor). Batch 1 renders `WALL_BASIS_STATUS=provisional` and refuses to run +(`P2D_ALLOW_PROVISIONAL_WALL=1` overrides) until `BATCH0_WALLS` holds batch 0's walls and the +generator sets `WALL_BASIS_STATUS = "measured"`: then `--time` is 1.25x the bounding group leg (an +A100 job: the sum of its legs) plus 15 min, rounded up to 30 min, and `--mem` the next step at +or above 1.5x batch 0's MaxRSS, as 2a and 2b. Pin, private checkout and guards are 2b's +(`P2D_PIN=2026.10.25.1`); logs and `walls.tsv` go to `output/p2d_logs/`. A missing dataset is +simulated under a lock (`prepare_dataset`, by instrument: hst -> multi_galaxy, euclid -> group). + +**Local check.** Every cell script takes `--fast` (2 repeats, a 5-call median, vmap batch 2, a +4-instance stream) and, without `--output-path`, writes into the gitignored +`output/p2d_local/results/...`, never `results/`. + diff --git a/scripts/misc/campaigns/multi_galaxy_group_p2d.py b/scripts/misc/campaigns/multi_galaxy_group_p2d.py new file mode 100644 index 000000000..6e39ee377 --- /dev/null +++ b/scripts/misc/campaigns/multi_galaxy_group_p2d.py @@ -0,0 +1,442 @@ +"""Likelihood-lifecycle phase 2d: the multi_galaxy + group campaign's task manifest and submits. + +autolens_profiling#473 measures the 48 planned ``multi_galaxy`` and ``group`` cells +(``{multi_galaxy,group}/{mge, rectangular, delaunay}``; ``dashboard/coverage.json``) at the +standard size on the pinned release 2026.10.25.1, from a private RAL checkout, with the new cell +scripts under ``scripts/{multi_galaxy,group}/`` (one shared driver, +``scripts/misc/likelihood_breakdown/galaxy_group_standard.py``). This module is the one copy of +that work list: every cell becomes one :class:`Task`, and the submits under ``hpc/`` are rendered +from the tasks with the shared machinery in ``_common.py`` (as phases 2a and 2b):: + + python scripts/misc/campaigns/multi_galaxy_group_p2d.py --write # (re)render the submits + python scripts/misc/campaigns/multi_galaxy_group_p2d.py --check # exit 1 if a submit is stale + python scripts/misc/campaigns/multi_galaxy_group_p2d.py --list # print the manifest + +DRAFT FOR REVIEW. The cell design (decisions D1-D10 on +``wiki/campaigns/multi_galaxy/likelihood_lifecycle_p2d.md``) is awaiting the human, and no +submit here has been run. The submits: + +- batch 0, the timing arm (decision D9): ``hpc/batch_cpu/submit_campaign_p2d_batch0_ral_cpu_fp64`` + (``--partition=ral`` array of 10) and ``hpc/batch_gpu/submit_campaign_p2d_batch0_a100_fp64`` + (``--gres=gpu:1`` array of 14, ``%2``): every group leg (group bounds multi_galaxy: 1.6x the + masked pixels, three lens-plane galaxies with mass), writing into the gitignored + ``output/p2d_batch0/``. Walls are declared guesses (``source: unmeasured``, 3x floor); +- batch 1, one ``--partition=ral`` array and one ``--gres=gpu:1`` job per dataset type + (``submit_campaign_p2d__{ral_cpu,a100}__fp64``), refusing to run + while :data:`WALL_BASIS_STATUS` is ``provisional`` (batch 0 sets their ``--time`` / ``--mem``). + +Stdlib only; nothing here imports the modelling stack except :func:`prepare_dataset`, which the +submits call to simulate a missing dataset under a lock. +""" + +from __future__ import annotations + +import argparse +import sys +from dataclasses import dataclass +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[3] +if str(ROOT) not in sys.path: + sys.path.insert(0, str(ROOT)) +if str(Path(__file__).resolve().parent) not in sys.path: + sys.path.insert(0, str(Path(__file__).resolve().parent)) +if str(ROOT / "scripts" / "misc") not in sys.path: + sys.path.insert(0, str(ROOT / "scripts" / "misc")) + +import _common # noqa: E402 +from cell_builders import galaxy_group as gg # noqa: E402 (stdlib at import) + +#: The release every cell is measured on (as 2b), and the private RAL checkout at that tag. +PIN = "2026.10.25.1" +PRIVATE_BASE = f"/mnt/ral/jnightin/profiling/PyAuto_{PIN}" +#: The shared virtualenv (third-party packages only). +HPC_BASE = "/mnt/ral/jnightin/PyAuto" +ISSUE = "autolens_profiling#473" + +DATASET_TYPES = gg.DATASET_TYPES +#: One instrument per dataset type (decision D2): the workspace simulator's pixel scale. +INSTRUMENTS = dict(gg.INSTRUMENTS) +#: The planned variants (decision D1): MGE, rectangular, Delaunay; no delaunay_nn, no sersic. +VARIANTS = gg.VARIANTS +PIXELIZED = gg.PIXELIZED +#: §3.3 "multi_galaxy/*, group/* — as imaging rules" (``catalogue/provisional_designations.json`` +#: tables ``parametric`` and ``pixelized``), optimal and secondary per host class. +SETUPS = { + "parametric": { + "hpc_ral_cpu": ("jax_cpu_dense_fp64",), + "hpc_a100": ("jax_gpu_dense_fp64",), + }, + "pixelized": { + "hpc_ral_cpu": ("numba_cpu_sparse_fp64", "jax_cpu_sparse_fp64"), + "hpc_a100": ("jax_gpu_dense_fp64", "jax_gpu_sparse_fp64", "jax_cpu_sparse_fp64"), + }, +} +MEASUREMENTS = ("runtime", "breakdown") +#: ``--config-name`` per (host class, device), as phase 2a. +CONFIG_NAMES = { + ("hpc_ral_cpu", "cpu"): "hpc_ral_cpu_fp64", + ("hpc_a100", "gpu"): "hpc_a100_fp64", + ("hpc_a100", "cpu"): "hpc_a100_cpu_fp64", +} + +#: Batch 0 measures the dataset type that bounds the other (decision D9): group, 17.7k masked +#: pixels at 0.1"/px against multi_galaxy's 11.3k at 0.05"/px, with two dPIE extra galaxies. +BATCH0_DATASET_TYPE = "group" +#: Batch 0's declared per-leg wall guess (``source: unmeasured``, 3x floor) and its ``--time``. +#: The imaging hst legs (15k masked pixels, the nearest measured size) took 67-357 s on RAL CPU +#: and 59-329 s on the A100 (``imaging_p2a.BATCH0_WALLS`` delaunay_nn/hst); an hour is ~10x that. +BATCH0_WALL_GUESS_S = 3600 +BATCH0_TIME = "4:00:00" +#: Provisional: batch 1 renders unmeasured rows, the placeholder ``--time`` below and a submit +#: that refuses to run until batch 0's walls replace them (README "Setting batch 1's --time"). +WALL_BASIS_STATUS = "provisional" +BATCH1_PROVISIONAL_TIME = {"ral_cpu": "4:00:00", "a100": "2-00:00:00"} +#: ``--mem`` until batch 0's sacct MaxRSS is in: the imaging hst legs peaked at 10.2 GiB +#: (``imaging_p2a.BATCH0_PEAK_RSS_KIB``) on a larger image; 32 GB is ~3x that. +PROVISIONAL_MEM_GB = 32 +#: The rules batch 1 will take from batch 0 (as 2a / 2b): --time = 1.25x the measured wall plus +#: 15 min, rounded up to 30 min; --mem the next 16/32/64 GB step >= 1.5x the batch-0 MaxRSS. +WALL_HEADROOM = 1.25 +WALL_ROUND_S = 1800 +WALL_MIN_SLACK_S = 900 +MEM_HEADROOM = 1.5 +#: Batch 0's measured legs, cell -> (walls.tsv WALL, sacct Elapsed, task). Empty until batch 0. +BATCH0_WALLS: dict = {} +BATCH0_LIMITATIONS: dict = {} + + +@dataclass(frozen=True, order=True) +class Task: + """One planned cell: ``// @ []``.""" + + dataset_type: str + variant: str + setup_id: str + host_class: str + measurement: str + + @property + def instrument(self) -> str: + return INSTRUMENTS[self.dataset_type] + + @property + def backend(self) -> str: + return self.setup_id.split("_")[0] + + @property + def device(self) -> str: + return self.setup_id.split("_")[1] + + @property + def operator(self) -> str: + return self.setup_id.split("_")[2] + + @property + def cell(self) -> str: + """The coverage-matrix cell name (``dashboard/coverage.json`` ``cells[].cell``).""" + return ( + f"{self.dataset_type}/{self.variant}/{self.instrument} " + f"{self.setup_id}@{self.host_class} [{self.measurement}]" + ) + + @property + def script(self) -> str: + """The cell script, relative to ``scripts/`` and without ``.py``.""" + suffix = "_numba" if self.backend == "numba" else "" + return f"{self.dataset_type}/{self.variant}/likelihood_{self.measurement}{suffix}" + + @property + def gate_cell(self) -> str: + """The WALL-BASIS cell id ``/