diff --git a/hpc/batch_cpu/submit_likelihood_breakdown_pdet_repin_ral_cpu_fp64 b/hpc/batch_cpu/submit_likelihood_breakdown_pdet_repin_ral_cpu_fp64 new file mode 100755 index 000000000..cf3c05369 --- /dev/null +++ b/hpc/batch_cpu/submit_likelihood_breakdown_pdet_repin_ral_cpu_fp64 @@ -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 diff --git a/scripts/datacube/delaunay/likelihood_breakdown.py b/scripts/datacube/delaunay/likelihood_breakdown.py index 76bad45d9..e18341310 100644 --- a/scripts/datacube/delaunay/likelihood_breakdown.py +++ b/scripts/datacube/delaunay/likelihood_breakdown.py @@ -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())) # --------------------------------------------------------------------------- @@ -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) @@ -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) @@ -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) @@ -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, } diff --git a/scripts/imaging/delaunay/likelihood_breakdown.py b/scripts/imaging/delaunay/likelihood_breakdown.py index 41c0fa8c8..43bf36eb6 100644 --- a/scripts/imaging/delaunay/likelihood_breakdown.py +++ b/scripts/imaging/delaunay/likelihood_breakdown.py @@ -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"): @@ -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)) @@ -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: @@ -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}") @@ -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 diff --git a/scripts/imaging/delaunay_nn/likelihood_breakdown.py b/scripts/imaging/delaunay_nn/likelihood_breakdown.py index c2119cc5e..2f63dd71d 100644 --- a/scripts/imaging/delaunay_nn/likelihood_breakdown.py +++ b/scripts/imaging/delaunay_nn/likelihood_breakdown.py @@ -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"): @@ -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)) @@ -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: @@ -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}") @@ -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 diff --git a/scripts/imaging/pixelized/matrix_free.py b/scripts/imaging/pixelized/matrix_free.py index 06dc40ede..142f86656 100644 --- a/scripts/imaging/pixelized/matrix_free.py +++ b/scripts/imaging/pixelized/matrix_free.py @@ -217,18 +217,23 @@ def _profiling_root() -> _Path: #: read from the ``*_hpc_a100_fp64_recon_split`` rows, now at ``results/imaging//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, }, } @@ -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}") @@ -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}") @@ -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 = { @@ -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)] diff --git a/scripts/imaging/rectangular/likelihood_breakdown.py b/scripts/imaging/rectangular/likelihood_breakdown.py index 8288f1f5c..ddbd3e93c 100644 --- a/scripts/imaging/rectangular/likelihood_breakdown.py +++ b/scripts/imaging/rectangular/likelihood_breakdown.py @@ -787,6 +787,11 @@ def overlay_grid_raw_fn(relocated_grid_raw): print("\n--- Extracting inversion matrices from FitImaging ---") 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"): @@ -1678,7 +1683,9 @@ def compute_log_evidence( 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 noise_normalization = jnp.sum(jnp.log(2 * jnp.pi * noise_map**2)) @@ -1815,7 +1822,12 @@ def compute_log_evidence( jit_profile(reconstruction_steps.log_det_cholesky, "log_det_curvature_reg_jit", _creg_reduced_row) 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_row) +# 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_row, +) reconstruction_sub_rows["Log det Cholesky (H reduced)"] = timer.records[-1][1] / 10 if _cli.use_sparse_operator: @@ -1837,6 +1849,7 @@ def compute_log_evidence( mapper_indices_jnp, _reg_reduced_row, _creg_reduced_row, + grounding=REG_GROUNDING, ) for _term, _value in log_evidence_term_values.items(): print(f" {_term:<24} {_value!r}") @@ -2143,10 +2156,15 @@ def compute_log_evidence( # #247): a different mesh fits the data differently, and comparing its evidence # to this number would flag drift that is not drift. Such a run writes # ``pinned_expected: null`` so the row says out loud that nothing checked it. +# 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 = { # 39x39 = 1521 source pixels, MGE-60 lens light, adapt_image=lensed_source - "bilinear": 28621.128714095972, - "rtu": 28505.343980143432, + "bilinear": 28631.6052079193, # was 28621.128714095972 + "rtu": 28515.531620400456, # was 28505.343980143432 }[_cli.rect_mesh] # The pins also describe hst at flat-1 over-sampling and nothing else (as the diff --git a/scripts/misc/likelihood_breakdown/fixed_light_cpu_common.py b/scripts/misc/likelihood_breakdown/fixed_light_cpu_common.py index b80c679fc..3436249b6 100644 --- a/scripts/misc/likelihood_breakdown/fixed_light_cpu_common.py +++ b/scripts/misc/likelihood_breakdown/fixed_light_cpu_common.py @@ -204,10 +204,10 @@ def log_evidence_terms_np(system, x) -> dict: log_det_curvature_reg = _log_det_cholesky_np(curv_reg_reduced) # The pseudo-determinant grounding of ``reconstruction_steps.log_evidence_terms`` - # (PyAutoArray#682): delete each grounded row/column, add ``sum log P_b``. - grounded, log_block_sizes = getattr(system, "reg_grounding", (np.zeros(0, dtype=int), 0.0)) - if len(grounded) > 0: - keep = np.setdiff1d(np.arange(reg_reduced.shape[0]), np.asarray(grounded, dtype=int)) + # (PyAutoArray#682): ``(keep, sum log P_b)`` from ``grounding_from``; None = plain. + grounding = getattr(system, "reg_grounding", None) + if grounding is not None: + keep, log_block_sizes = grounding log_det_regularization = log_block_sizes + _log_det_cholesky_np(reg_reduced[keep][:, keep]) else: log_det_regularization = _log_det_cholesky_np(reg_reduced) diff --git a/scripts/misc/likelihood_breakdown/fixed_light_system.py b/scripts/misc/likelihood_breakdown/fixed_light_system.py index f5a8aaaca..ede785f08 100644 --- a/scripts/misc/likelihood_breakdown/fixed_light_system.py +++ b/scripts/misc/likelihood_breakdown/fixed_light_system.py @@ -149,9 +149,9 @@ class FixedLightSystem: subtracted_light_image: np.ndarray | None = None subtracted_light_flux: float | None = None - # ``inversion._intrinsic_regularization_blocks`` (PyAutoArray#682): grounded - # block indexes and ``sum log P_b`` for the pseudo-determinant ``ln det(H)``. - reg_grounding: tuple = field(default=(np.zeros(0, dtype=int), 0.0), compare=False) + # ``reconstruction_steps.grounding_from(inversion)`` (PyAutoArray#682): the kept + # indices and ``sum log P_b`` of the pseudo-determinant ``ln det(H)``; None = plain. + reg_grounding: tuple | None = field(default=None, compare=False) _pdip: tuple | None = field(default=None, repr=False, compare=False) @@ -324,17 +324,21 @@ def _jacobi_scaled(curvature_reg_matrix, data_vector, scaling: str): ) -def _reg_grounding_from(inversion) -> tuple: - """The library's pseudo-determinant grounding of ``H`` (PyAutoArray#682). +def _grounding_from(inversion): + """``reconstruction_steps.grounding_from`` in pure numpy (no JAX import). - Older libraries have no ``_intrinsic_regularization_blocks``; they use the - plain ``ln det(H)``, so an empty grounding reproduces them. + A numba CPU cell builds systems without JAX, so this builder must not import + ``reconstruction_steps``. Pinned equal to it by ``test_pdet_grounding.py``. """ blocks = getattr(inversion, "_intrinsic_regularization_blocks", None) if blocks is None: - return (np.zeros(0, dtype=int), 0.0) + return None grounded, log_block_sizes = blocks - return (np.asarray(grounded, dtype=int), float(log_block_sizes)) + if len(grounded) == 0: + return None + n = int(np.asarray(inversion.regularization_matrix_reduced).shape[0]) + keep = np.setdiff1d(np.arange(n), np.asarray(grounded, dtype=int)) + return keep, float(log_block_sizes) def linear_system_from( @@ -386,7 +390,7 @@ def linear_system_from( mapper_indices=np.asarray(inversion.mapper_indices), reg_reduced=np.asarray(inversion.regularization_matrix_reduced, dtype=float), curv_reg_reduced=np.asarray(inversion.curvature_reg_matrix_reduced, dtype=float), - reg_grounding=_reg_grounding_from(inversion), + reg_grounding=_grounding_from(inversion), Q=np.asarray(Q, dtype=float), q=np.asarray(q, dtype=float), d_scale=np.asarray(d_scale, dtype=float), diff --git a/scripts/misc/likelihood_breakdown/reconstruction_steps.py b/scripts/misc/likelihood_breakdown/reconstruction_steps.py index 6e197e481..13568cfdd 100644 --- a/scripts/misc/likelihood_breakdown/reconstruction_steps.py +++ b/scripts/misc/likelihood_breakdown/reconstruction_steps.py @@ -140,6 +140,38 @@ def log_det_cholesky(matrix): return 2.0 * jnp.sum(jnp.log(jnp.diag(jnp.linalg.cholesky(matrix)))) +def grounding_from(inversion): + """The pseudo-determinant grounding of ``H`` that PyAutoArray uses since #682. + + Returns ``(keep, sum_log_P)``: the indices of ``regularization_matrix_reduced`` + left after deleting the first row/column of every regularized block whose + ``H`` has an exact constant null mode, and ``sum log P_b`` over those blocks. + ``keep`` is computed here, eagerly, so a jitted step only gathers with it. + ``None`` (an older library, or no such block) means the plain ``ln det(H)``. + """ + blocks = getattr(inversion, "_intrinsic_regularization_blocks", None) + if blocks is None: + return None + grounded, log_block_sizes = blocks + if len(grounded) == 0: + return None + n = int(np.asarray(inversion.regularization_matrix_reduced).shape[0]) + keep = np.setdiff1d(np.arange(n), np.asarray(grounded, dtype=int)) + return keep, float(log_block_sizes) + + +def log_det_regularization_from(reg_reduced, grounding=None): + """``ln det(H)`` as the library computes it: pseudo-determinant when grounded. + + ``pdet(H) = prod P_b * det(H with the grounded rows/columns deleted)`` + (PyAutoArray ``AbstractInversion.log_det_regularization_matrix_term``). + """ + if grounding is None: + return log_det_cholesky(reg_reduced) + keep, log_block_sizes = grounding + return log_block_sizes + log_det_cholesky(reg_reduced[keep][:, keep]) + + def log_evidence_terms( data, noise_map, @@ -163,12 +195,9 @@ def log_evidence_terms( ``H`` is rank-deficient by construction (non-regularised linear components such as an MGE lens light), so its log-det is ``-inf``. - ``grounding`` is ``inversion._intrinsic_regularization_blocks``: the first - index of every regularized block whose ``H`` has an exact constant null mode, - and ``sum log P_b`` over those blocks. Given it, ``ln det(H)`` is the - pseudo-determinant PyAutoArray uses since #682: delete each grounded row and - column, then add ``sum log P_b``. Without it, the plain ``ln det(H)`` (the - pre-#682 library value, which includes ``log`` of the 1e-8 jitter) is used. + ``grounding`` is ``grounding_from(inversion)``; given it, ``ln det(H)`` is the + pseudo-determinant PyAutoArray uses since #682. ``None`` is the plain + ``ln det(H)`` (the pre-#682 value, which includes ``log`` of the 1e-8 jitter). Returned values are Python floats — this is called **eagerly, once**, for the JSON, never inside a timed row. @@ -180,12 +209,7 @@ def log_evidence_terms( regularization_term = jnp.dot(s_reduced, jnp.dot(reg_reduced, s_reduced)) log_det_curvature_reg = log_det_cholesky(curv_reg_reduced) - if grounding is not None and len(grounding[0]) > 0: - grounded, log_block_sizes = grounding - keep = np.setdiff1d(np.arange(reg_reduced.shape[0]), np.asarray(grounded, dtype=int)) - log_det_regularization = log_block_sizes + log_det_cholesky(reg_reduced[keep][:, keep]) - else: - log_det_regularization = log_det_cholesky(reg_reduced) + log_det_regularization = log_det_regularization_from(reg_reduced, grounding) noise_normalization = jnp.sum(jnp.log(2 * jnp.pi * noise_map**2)) diff --git a/scripts/misc/likelihood_breakdown/sparse_steps.py b/scripts/misc/likelihood_breakdown/sparse_steps.py index 994baaa4a..63a062ae2 100644 --- a/scripts/misc/likelihood_breakdown/sparse_steps.py +++ b/scripts/misc/likelihood_breakdown/sparse_steps.py @@ -84,6 +84,8 @@ from autoarray.inversion.mappers import mapper_util from autoarray.structures.arrays.uniform_2d import Array2D +from likelihood_breakdown import reconstruction_steps + @dataclass(frozen=True) class SparseContext: @@ -108,6 +110,9 @@ class SparseContext: n_funcs: int add_to_diag_value: float no_regularization_index_list: tuple[int, ...] + # ``reconstruction_steps.grounding_from`` (PyAutoArray#682 pseudo-determinant + # ``ln det(H)``); static ``keep`` indices, None = plain ln det. + reg_grounding: Any = None @property def sparse_batch_size(self) -> int: @@ -155,6 +160,7 @@ def sparse_context_from(inversion, dataset) -> SparseContext: n_funcs=int(operated.shape[1]), add_to_diag_value=float(inversion.settings.no_regularization_add_to_curvature_diag_value), no_regularization_index_list=tuple(int(i) for i in inversion.no_regularization_index_list), + reg_grounding=reconstruction_steps.grounding_from(inversion), ) @@ -445,8 +451,9 @@ def log_evidence( 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, ctx.reg_grounding + ) noise_normalization = jnp.sum(jnp.log(2 * jnp.pi * noise_map**2)) diff --git a/scripts/misc/likelihood_breakdown/test/test_pdet_grounding.py b/scripts/misc/likelihood_breakdown/test/test_pdet_grounding.py new file mode 100644 index 000000000..22a1a2d4a --- /dev/null +++ b/scripts/misc/likelihood_breakdown/test/test_pdet_grounding.py @@ -0,0 +1,125 @@ +"""The cells' ``ln det(H)`` is the library's (PyAutoArray#682 pseudo-determinant). + +Every likelihood-breakdown cell computes ``ln det(H)`` through +``reconstruction_steps.log_det_regularization_from(reg_reduced, grounding_from(inversion))``. +These tests pin that to ``AbstractInversion.log_det_regularization_matrix_term``, +pin the JAX-free copy in ``fixed_light_system`` to the shared helper, and check +the grounded log det runs under ``jax.jit`` (the cells time it there). +""" + +from __future__ import annotations + +import sys as _sys +from pathlib import Path as _Path + +import jax + +jax.config.update("jax_enable_x64", True) +jax.config.update("jax_platform_name", "cpu") + +import jax.numpy as jnp # noqa: E402 +import numpy as np # noqa: E402 +import pytest # noqa: E402 + + +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 = _profiling_root() / "scripts" / "misc" +if str(_misc) not in _sys.path: + _sys.path.insert(0, str(_misc)) + +from likelihood_breakdown import fixed_light_system, reconstruction_steps # noqa: E402 + + +@pytest.fixture(scope="module") +def inversion(): + """Three linear lens Gaussians (unregularized) plus an 8x8 Constant-regularized mesh.""" + al = pytest.importorskip("autolens") + + grid = al.Grid2D.uniform(shape_native=(30, 30), pixel_scales=0.2) + psf = al.Convolver.from_gaussian(shape_native=(5, 5), sigma=0.3, pixel_scales=0.2) + simulator = al.SimulatorImaging( + exposure_time=300.0, psf=psf, background_sky_level=0.1, noise_seed=1 + ) + truth = al.Tracer( + galaxies=[ + al.Galaxy( + redshift=0.5, + bulge=al.lp.Sersic(centre=(0.0, 0.0), intensity=1.0, effective_radius=0.5), + mass=al.mp.Isothermal(centre=(0.0, 0.0), einstein_radius=1.0), + ), + al.Galaxy( + redshift=1.0, + bulge=al.lp.Sersic(centre=(0.05, 0.05), intensity=1.0, effective_radius=0.2), + ), + ] + ) + dataset = simulator.via_tracer_from(tracer=truth, grid=grid) + dataset = dataset.apply_mask( + mask=al.Mask2D.circular(shape_native=(30, 30), pixel_scales=0.2, radius=2.2) + ) + lens = al.Galaxy( + redshift=0.5, + bulge=al.lp_basis.Basis( + profile_list=[ + al.lp_linear.Gaussian(centre=(0.0, 0.0), sigma=sigma) for sigma in (0.2, 0.5, 1.0) + ] + ), + mass=al.mp.Isothermal(centre=(0.0, 0.0), einstein_radius=1.0), + ) + source = al.Galaxy( + redshift=1.0, + pixelization=al.Pixelization( + mesh=al.mesh.RectangularUniform(shape=(8, 8)), + regularization=al.reg.Constant(coefficient=1.0), + ), + ) + fit = al.FitImaging( + dataset=dataset, + tracer=al.Tracer(galaxies=[lens, source]), + settings=al.Settings(use_border_relocator=True), + xp=np, + ) + return fit.inversion + + +def test_grounded_log_det_is_the_library_term(inversion): + grounding = reconstruction_steps.grounding_from(inversion) + reg_reduced = jnp.asarray(np.asarray(inversion.regularization_matrix_reduced), jnp.float64) + ours = float(reconstruction_steps.log_det_regularization_from(reg_reduced, grounding)) + assert ours == pytest.approx(float(inversion.log_det_regularization_matrix_term), rel=1e-10) + + +def test_constant_regularization_is_grounded(inversion): + """``Constant`` has a constant null mode, so it must ground (unless the library predates #682).""" + if not hasattr(inversion, "_intrinsic_regularization_blocks"): + pytest.skip("installed PyAutoArray predates #682 (no pseudo-determinant)") + keep, log_block_sizes = reconstruction_steps.grounding_from(inversion) + n = np.asarray(inversion.regularization_matrix_reduced).shape[0] + assert len(keep) == n - 1 + assert log_block_sizes == pytest.approx(np.log(64)) + + +def test_jax_free_copy_matches_the_shared_helper(inversion): + shared = reconstruction_steps.grounding_from(inversion) + copy = fixed_light_system._grounding_from(inversion) + if shared is None: + assert copy is None + return + assert np.array_equal(shared[0], copy[0]) + assert shared[1] == copy[1] + + +def test_grounded_log_det_runs_under_jit(inversion): + grounding = reconstruction_steps.grounding_from(inversion) + reg_reduced = jnp.asarray(np.asarray(inversion.regularization_matrix_reduced), jnp.float64) + eager = reconstruction_steps.log_det_regularization_from(reg_reduced, grounding) + jitted = jax.jit(lambda h: reconstruction_steps.log_det_regularization_from(h, grounding))( + reg_reduced + ) + assert float(jitted) == pytest.approx(float(eager), rel=1e-12)