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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
100 changes: 100 additions & 0 deletions hpc/batch_cpu/submit_likelihood_breakdown_pdet_repin_ral_cpu_fp64
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
#!/bin/bash -l
#
# autolens_profiling#525: re-pin the likelihood-breakdown cells after PyAutoArray#682
# (pseudo-determinant ln det H, +9.21 nats per regularized mapper). CPU fp64, one array
# task per (cell, variant).
#
# WHAT THIS MEASURES. Each task runs one cell eagerly at its pinned configuration (HST,
# --over-sampling flat1, fiducial mesh) and logs:
# - "figure_of_merit (log_evidence) = ..." -> the library's evidence, i.e. the new pin;
# - "log_evidence (inv matrices)" vs "log_evidence (reference)" -> the cell's own
# grounded evidence against the library's (the #525 fix);
# - the cell's own regression line (PASSED/SKIPPED or the AssertionError naming "got").
# The old pins are expected to fail on today's library; the assertion message carries
# the measured value. matrix_free logs "exact log dets" (log_det_regularization re-pin).
#
# 0 delaunay constant_split 5 rectangular --rect-mesh rtu
# 1 delaunay adapt_split 6 matrix_free --mesh rectangular
# 2 delaunay_nn constant_split 7 matrix_free --mesh delaunay
# 3 delaunay_nn adapt_split 8 matrix_free --mesh delaunay_nn
# 4 rectangular --rect-mesh bilinear 9 datacube/delaunay --instrument sma (validation, no pin)
#
# LIBRARY CODE. A PRIVATE checkout of the five library mains at the SHAs below
# ($PYAUTO_PRIVATE_BASE), which include PyAutoArray#682. The job refuses to run if a
# library imports from elsewhere. The shared /mnt/ral/jnightin/PyAuto mirror is never used.
# PyAutoArray af80e69d PyAutoFit bdb7af0e PyAutoGalaxy bc3918a4
# PyAutoLens bb87dad3 PyAutoNerves 9b204c90
#
# NODE. `ral` only, exclusive per task, throttled to 5.
#
# WALL-BASIS:
# No recent CPU breakdown row in the repo to size from; the cells are eager plus
# jitted step rows on one HST dataset. 4 h per task is a generous cap.

#SBATCH -J lb_pdet_repin
#SBATCH --partition=ral
#SBATCH --exclusive
#SBATCH --ntasks=1
#SBATCH --cpus-per-task=8
#SBATCH --mem=64gb
#SBATCH --time=4:00:00
#SBATCH --array=0-9%5
#SBATCH -o output/output.%A_%a.out
#SBATCH -e error/error.%A_%a.err

# Submit from hpc/batch_cpu/ (the -o/-e paths are relative).
export AP_ROOT="$(cd "${SLURM_SUBMIT_DIR:-$(dirname "$0")}/../.." && pwd)"
export PYAUTO_PRIVATE_BASE="${PYAUTO_PRIVATE_BASE:-/mnt/ral/jnightin/PyAuto_wt/likelihood-breakdown-cells-pdet}"
echo "AP_ROOT=$AP_ROOT"
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
export MKL_NUM_THREADS=1
export OPENBLAS_NUM_THREADS=1
export NUMBA_NUM_THREADS=1
export NPROC=${SLURM_CPUS_PER_TASK:-8}
export JAX_PLATFORMS=cpu
export JAX_ENABLE_X64=1
export MPLBACKEND=Agg
export MPLCONFIGDIR=$AP_ROOT/output/mpl_${SLURM_JOB_ID:-local}
export NUMBA_CACHE_DIR=$AP_ROOT/output/numba_cache_${SLURM_JOB_ID:-local}
mkdir -p "$NUMBA_CACHE_DIR" "$MPLCONFIGDIR"
unset JAX_COMPILATION_CACHE_DIR PYAUTO_SMALL_DATASETS PYAUTO_FAST_PLOTS

cd $AP_ROOT
python3 - <<'EOF'
import os, autoarray, autofit, autogalaxy, autolens, autonerves
base = os.path.realpath(os.environ["PYAUTO_PRIVATE_BASE"])
for m in (autoarray, autofit, autogalaxy, autolens, autonerves):
path = os.path.realpath(m.__file__)
if not path.startswith(base + os.sep):
raise SystemExit(f"REFUSING: {m.__name__} imports from {path}, not {base}")
print(m.__name__, path)
from autoarray.inversion.inversion.abstract import AbstractInversion
assert hasattr(AbstractInversion, "_intrinsic_regularization_blocks"), "library predates #682"
EOF

CONFIG=ral_cpu_fp64_pdet_repin
case ${SLURM_ARRAY_TASK_ID} in
0) CMD="scripts/imaging/delaunay/likelihood_breakdown.py --regularization constant_split" ;;
1) CMD="scripts/imaging/delaunay/likelihood_breakdown.py --regularization adapt_split" ;;
2) CMD="scripts/imaging/delaunay_nn/likelihood_breakdown.py --regularization constant_split" ;;
3) CMD="scripts/imaging/delaunay_nn/likelihood_breakdown.py --regularization adapt_split" ;;
4) CMD="scripts/imaging/rectangular/likelihood_breakdown.py --rect-mesh bilinear" ;;
5) CMD="scripts/imaging/rectangular/likelihood_breakdown.py --rect-mesh rtu" ;;
6) CMD="scripts/imaging/pixelized/matrix_free.py --mesh rectangular" ;;
7) CMD="scripts/imaging/pixelized/matrix_free.py --mesh delaunay" ;;
8) CMD="scripts/imaging/pixelized/matrix_free.py --mesh delaunay_nn" ;;
9) CMD="scripts/datacube/delaunay/likelihood_breakdown.py --instrument sma" ;;
*) echo "no task ${SLURM_ARRAY_TASK_ID}"; exit 1 ;;
esac

echo "TASK ${SLURM_ARRAY_TASK_ID}: python3 -u $CMD --config-name $CONFIG"
# The old pins are expected to fail; keep going so the measured value is logged.
# (`|| rc=$?` so activate.sh's ERR trap does not abort the task on that failure.)
rc=0
python3 -u $CMD --config-name $CONFIG || rc=$?
echo "EXIT $rc"
echo "Finished."
date
17 changes: 14 additions & 3 deletions scripts/datacube/delaunay/likelihood_breakdown.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ def _profiling_root() -> _Path:
import jax.numpy as jnp
import numpy as np
from autofit.jax import register_model as _register_model_pytrees
from likelihood_breakdown import reconstruction_steps # noqa: E402

sys.path.insert(0, str(_profiling_root()))
# ---------------------------------------------------------------------------
Expand Down Expand Up @@ -515,6 +516,11 @@ def ray_trace_mesh_raw(mesh_raw):

inversion = fit.inversion

# ``ln det(H)`` is the pseudo-determinant PyAutoArray uses since #682: ground one
# pixel per intrinsic regularized block and add ``sum log P_b``. Resolved eagerly
# (static ``keep`` indices), read by the evidence step below; None = plain ln det.
REG_GROUNDING = reconstruction_steps.grounding_from(inversion)

if dense_breakdown_feasible:
# ==================================================================
# DENSE PATH — full per-step breakdown (SMA scale)
Expand Down Expand Up @@ -774,7 +780,9 @@ def compute_log_evidence(
creg_reduced = curvature_reg_matrix[mapper_indices][:, mapper_indices]
reg_reduced = regularization_matrix[mapper_indices][:, mapper_indices]
log_det_curvature_reg = 2.0 * jnp.sum(jnp.log(jnp.diag(jnp.linalg.cholesky(creg_reduced))))
log_det_regularization = 2.0 * jnp.sum(jnp.log(jnp.diag(jnp.linalg.cholesky(reg_reduced))))
log_det_regularization = reconstruction_steps.log_det_regularization_from(
reg_reduced, REG_GROUNDING
)

noise_normalization = jnp.sum(jnp.log(2 * jnp.pi * noise_real**2)) + jnp.sum(
jnp.log(2 * jnp.pi * noise_imag**2)
Expand Down Expand Up @@ -1140,7 +1148,9 @@ def compute_log_evidence_sparse(
creg_reduced = curvature_reg_matrix[mapper_indices][:, mapper_indices]
reg_reduced = regularization_matrix[mapper_indices][:, mapper_indices]
log_det_curvature_reg = 2.0 * jnp.sum(jnp.log(jnp.diag(jnp.linalg.cholesky(creg_reduced))))
log_det_regularization = 2.0 * jnp.sum(jnp.log(jnp.diag(jnp.linalg.cholesky(reg_reduced))))
log_det_regularization = reconstruction_steps.log_det_regularization_from(
reg_reduced, REG_GROUNDING
)

noise_normalization = jnp.sum(jnp.log(2 * jnp.pi * noise_real**2)) + jnp.sum(
jnp.log(2 * jnp.pi * noise_imag**2)
Expand Down Expand Up @@ -1424,7 +1434,8 @@ def compute_log_evidence_sparse(
# For "alma" / "alma_high" the per-channel literal isn't pinned yet, so the
# assertion is skipped until the value below is filled in from a clean run.
EXPECTED_LOG_EVIDENCE_PER_CHANNEL = {
"sma": None,
# sma: pinned 2026-11-09 from RAL job 414743 (CPU fp64; cube -107454.92633864752 / 34 channels).
"sma": -3160.439009960221,
"alma": None,
"alma_high": None,
}
Expand Down
27 changes: 22 additions & 5 deletions scripts/imaging/delaunay/likelihood_breakdown.py
Original file line number Diff line number Diff line change
Expand Up @@ -887,6 +887,11 @@ def profile_subtract(data, blurred_image):

inversion = fit.inversion

# ``ln det(H)`` is the pseudo-determinant PyAutoArray uses since #682: ground one
# pixel per intrinsic regularized block and add ``sum log P_b``. Resolved eagerly
# (static ``keep`` indices), read by the evidence step below; None = plain ln det.
REG_GROUNDING = reconstruction_steps.grounding_from(inversion)

print(f" inversion class: {type(inversion).__name__}")

with timer.section("extract_inversion_matrices"):
Expand Down Expand Up @@ -1791,8 +1796,9 @@ def compute_log_evidence(
# linear parameters.
L_cr = jnp.linalg.cholesky(curv_reg_reduced)
log_det_curvature_reg = 2.0 * jnp.sum(jnp.log(jnp.diag(L_cr)))
L_r = jnp.linalg.cholesky(reg_reduced)
log_det_regularization = 2.0 * jnp.sum(jnp.log(jnp.diag(L_r)))
log_det_regularization = reconstruction_steps.log_det_regularization_from(
reg_reduced, REG_GROUNDING
)

# Noise normalization (over full masked image)
noise_normalization = jnp.sum(jnp.log(2 * jnp.pi * noise_map**2))
Expand Down Expand Up @@ -1924,7 +1930,12 @@ def _log_evidence_args(recon):
)
reconstruction_sub_rows["Log det Cholesky (F+λH reduced)"] = timer.records[-1][1] / 10

jit_profile(reconstruction_steps.log_det_cholesky, "log_det_regularization_jit", reg_reduced_jnp)
# The library's ln det(H) is the pseudo-determinant since PyAutoArray#682.
jit_profile(
lambda h: reconstruction_steps.log_det_regularization_from(h, REG_GROUNDING),
"log_det_regularization_jit",
reg_reduced_jnp,
)
reconstruction_sub_rows["Log det Cholesky (H reduced)"] = timer.records[-1][1] / 10

if _cli.use_sparse_operator:
Expand All @@ -1946,6 +1957,7 @@ def _log_evidence_args(recon):
reduced_indices_jnp,
reg_reduced_jnp,
curv_reg_reduced_jnp,
grounding=REG_GROUNDING,
)
for _term, _value in log_evidence_term_values.items():
print(f" {_term:<24} {_value!r}")
Expand Down Expand Up @@ -2228,9 +2240,14 @@ def _log_evidence_args(recon):
# pinned evidences moved. Measured from one eager run per scheme on this host
# (WSL, fp64). `constant_split` for delaunay_nn moved too but by 7.6e-5
# relative, inside rtol=1e-4, so it PASSED and is left as measured in August.
# Re-pinned 2026-11-09 (autolens_profiling#525) from RAL job 414743 (CPU fp64, library mains
# Array af80e69d / Fit bdb7af0e / Galaxy bc3918a4 / Lens bb87dad3 / Nerves 9b204c90): PyAutoArray#682's
# pseudo-determinant ln det H adds +9.21 nats per regularized mapper, and the shifts below also carry
# library changes since the previous pins. The cell's own grounded evidence matched the library
# (log_evidence (inv matrices) == reference) on every run.
EXPECTED_LOG_EVIDENCE_HST = {
"constant_split": 29083.548352148413, # was 29110.92085793
"adapt_split": 29140.29588193227, # was 29155.0010494252
"constant_split": 29120.132849358866, # was 29083.548352148413
"adapt_split": 29164.21050649178, # was 29140.29588193227
}

# The pins describe the 1500-vertex fiducial mesh and nothing else, so a run
Expand Down
27 changes: 22 additions & 5 deletions scripts/imaging/delaunay_nn/likelihood_breakdown.py
Original file line number Diff line number Diff line change
Expand Up @@ -1013,6 +1013,11 @@ def profile_subtract(data, blurred_image):

inversion = fit.inversion

# ``ln det(H)`` is the pseudo-determinant PyAutoArray uses since #682: ground one
# pixel per intrinsic regularized block and add ``sum log P_b``. Resolved eagerly
# (static ``keep`` indices), read by the evidence step below; None = plain ln det.
REG_GROUNDING = reconstruction_steps.grounding_from(inversion)

print(f" inversion class: {type(inversion).__name__}")

with timer.section("extract_inversion_matrices"):
Expand Down Expand Up @@ -1994,8 +1999,9 @@ def compute_log_evidence(
# linear parameters.
L_cr = jnp.linalg.cholesky(curv_reg_reduced)
log_det_curvature_reg = 2.0 * jnp.sum(jnp.log(jnp.diag(L_cr)))
L_r = jnp.linalg.cholesky(reg_reduced)
log_det_regularization = 2.0 * jnp.sum(jnp.log(jnp.diag(L_r)))
log_det_regularization = reconstruction_steps.log_det_regularization_from(
reg_reduced, REG_GROUNDING
)

# Noise normalization (over full masked image)
noise_normalization = jnp.sum(jnp.log(2 * jnp.pi * noise_map**2))
Expand Down Expand Up @@ -2127,7 +2133,12 @@ def _log_evidence_args(recon):
)
reconstruction_sub_rows["Log det Cholesky (F+λH reduced)"] = timer.records[-1][1] / 10

jit_profile(reconstruction_steps.log_det_cholesky, "log_det_regularization_jit", reg_reduced_jnp)
# The library's ln det(H) is the pseudo-determinant since PyAutoArray#682.
jit_profile(
lambda h: reconstruction_steps.log_det_regularization_from(h, REG_GROUNDING),
"log_det_regularization_jit",
reg_reduced_jnp,
)
reconstruction_sub_rows["Log det Cholesky (H reduced)"] = timer.records[-1][1] / 10

if _cli.use_sparse_operator:
Expand All @@ -2149,6 +2160,7 @@ def _log_evidence_args(recon):
reduced_indices_jnp,
reg_reduced_jnp,
curv_reg_reduced_jnp,
grounding=REG_GROUNDING,
)
for _term, _value in log_evidence_term_values.items():
print(f" {_term:<24} {_value!r}")
Expand Down Expand Up @@ -2481,9 +2493,14 @@ def _log_evidence_args(recon):
# pinned evidences moved. Measured from one eager run per scheme on this host
# (WSL, fp64). `constant_split` for delaunay_nn moved too but by 7.6e-5
# relative, inside rtol=1e-4, so it PASSED and is left as measured in August.
# Re-pinned 2026-11-09 (autolens_profiling#525) from RAL job 414743 (CPU fp64, library mains
# Array af80e69d / Fit bdb7af0e / Galaxy bc3918a4 / Lens bb87dad3 / Nerves 9b204c90): PyAutoArray#682's
# pseudo-determinant ln det H adds +9.21 nats per regularized mapper, and the shifts below also carry
# library changes since the previous pins. The cell's own grounded evidence matched the library
# (log_evidence (inv matrices) == reference) on every run.
EXPECTED_LOG_EVIDENCE_HST = {
"constant_split": 29144.581943885652, # PASSED unchanged (moved 7.6e-5)
"adapt_split": 29277.464588118037, # was 29348.90938612374
"constant_split": 29153.793506705144, # was 29144.581943885652 (+9.21: #682 alone)
"adapt_split": 29358.118243192344, # was 29277.464588118037
}

# The pins describe the 1500-vertex fiducial mesh and nothing else, so a run
Expand Down
58 changes: 45 additions & 13 deletions scripts/imaging/pixelized/matrix_free.py
Original file line number Diff line number Diff line change
Expand Up @@ -217,18 +217,23 @@ def _profiling_root() -> _Path:
#: read from the ``*_hpc_a100_fp64_recon_split`` rows, now at ``results/imaging/<mesh>/hst/
#: jax_gpu_dense_fp64/hpc_a100/experiments/recon_split/breakdown.json``
#: (``log_evidence_terms``). They are what an SLQ estimate is checked against.
#: Re-pinned 2026-11-09 (autolens_profiling#525) from RAL job 414743, CPU fp64, library mains incl.
#: PyAutoArray#682: ``log_det_regularization`` is now the pseudo-determinant (rectangular moved by exactly
#: ln 1e8 = +18.42); the Delaunay meshes also carry library changes since the 2026-09-11 A100 pins.
#: Previous values: rectangular 3888.258089645771 / 1692.7868170935546, delaunay 8360.401762997288 /
#: 7756.614958909804, delaunay_nn 7224.568777674853 / 6690.183751527879.
PINNED_LOG_DETS = {
"rectangular": {
"log_det_curvature_reg": 3888.258089645771,
"log_det_regularization": 1692.7868170935546,
"log_det_curvature_reg": 3878.498233358226,
"log_det_regularization": 1711.2075305507315,
},
"delaunay": {
"log_det_curvature_reg": 8360.401762997288,
"log_det_regularization": 7756.614958909804,
"log_det_curvature_reg": 8716.973825231513,
"log_det_regularization": 8137.151235880323,
},
"delaunay_nn": {
"log_det_curvature_reg": 7224.568777674853,
"log_det_regularization": 6690.183751527879,
"log_det_curvature_reg": 7133.99282196596,
"log_det_regularization": 6597.224578421075,
},
}

Expand Down Expand Up @@ -514,6 +519,11 @@ def max_abs_rel(got, reference):
log_evidence_ref = fit.figure_of_merit

inversion = fit.inversion

# ``ln det(H)`` is the pseudo-determinant PyAutoArray uses since #682: ground one
# pixel per intrinsic regularized block and add ``sum log P_b``. Resolved eagerly
# (static ``keep`` indices); None = plain ln det.
REG_GROUNDING = reconstruction_steps.grounding_from(inversion)
print(f" inversion class: {type(inversion).__name__}")
print(f" figure_of_merit (log_evidence) = {log_evidence_ref}")

Expand Down Expand Up @@ -666,7 +676,9 @@ def _matvec_1(V):

exact_log_dets = {
"log_det_curvature_reg": float(reconstruction_steps.log_det_cholesky(creg_reduced)),
"log_det_regularization": float(reconstruction_steps.log_det_cholesky(reg_reduced)),
"log_det_regularization": float(
reconstruction_steps.log_det_regularization_from(reg_reduced, REG_GROUNDING)
),
}
print(f" exact log dets: {exact_log_dets}")

Expand Down Expand Up @@ -803,27 +815,46 @@ def _pdip(D):
ctx, matrix_free_steps.bcoo_matvec(ctx.reg_bcoo)
)

# The library's ``ln det(H)`` is the pseudo-determinant (PyAutoArray#682): SLQ runs
# on the grounded subspace (embed with the grounded pixels at zero, read the kept
# rows back) and adds ``sum log P_b``, so it estimates the same term it is
# compared with. ``F + λH`` is untouched.
if REG_GROUNDING is None:
_reg_slq_matvec, _reg_slq_n, _reg_slq_offset = _reduced_reg_matvec, n_reduced, 0.0
else:
_reg_keep = jnp.asarray(REG_GROUNDING[0])
_reg_slq_offset = float(REG_GROUNDING[1])
_reg_slq_n = int(_reg_keep.shape[0])

def _reg_slq_matvec(V, _full=_reduced_reg_matvec, _keep=_reg_keep):
one_d = V.ndim == 1
V2 = V[:, None] if one_d else V
embedded = jnp.zeros((n_reduced, V2.shape[1]), dtype=V2.dtype).at[_keep].set(V2)
out = _full(embedded)[_keep]
return out[:, 0] if one_d else out


#: ``{(target, probes, steps): estimate}`` — the noise-vs-probes curve, and
#: where the default pair's value is read back from for the evidence row.
slq_estimates: dict[tuple, float] = {}

for _target, _matvec, _exact_key in (
("F+λH reduced", _reduced_curv_reg_matvec, "log_det_curvature_reg"),
("λH reduced", _reduced_reg_matvec, "log_det_regularization"),
for _target, _matvec, _exact_key, _n_slq, _slq_offset in (
("F+λH reduced", _reduced_curv_reg_matvec, "log_det_curvature_reg", n_reduced, 0.0),
("λH reduced", _reg_slq_matvec, "log_det_regularization", _reg_slq_n, _reg_slq_offset),
):
for _probes in SLQ_PROBES:
for _steps in SLQ_STEPS:

def _slq(key, matvec=_matvec, probes=_probes, steps=_steps):
def _slq(key, matvec=_matvec, probes=_probes, steps=_steps, n=_n_slq):
return matrix_free_steps.slq_logdet(
matvec, n_reduced, n_probes=probes, n_lanczos=steps, key=key
matvec, n, n_probes=probes, n_lanczos=steps, key=key
)

_label = f"slq_{_exact_key}_p{_probes}_m{_steps}"
_, _slq_out = jit_profile(_slq, _label, slq_key)
_slq_s = timer.records[-1][1] / 10
_estimate, _per_probe, _n_clamped = _slq_out
_estimate = float(_estimate)
_estimate = float(_estimate) + _slq_offset
slq_estimates[(_exact_key, _probes, _steps)] = _estimate

_facts = {
Expand Down Expand Up @@ -880,6 +911,7 @@ def _model_data_fn(x):
jnp.asarray(np.asarray(inversion.mapper_indices)),
reg_reduced,
creg_reduced,
grounding=REG_GROUNDING,
)

_slq_curv = slq_estimates[("log_det_curvature_reg", SLQ_DEFAULT_PROBES, SLQ_DEFAULT_STEPS)]
Expand Down
Loading
Loading