From a589c35b413ce144affd3f249d3037974c2d0e0d Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 09:26:20 +0000 Subject: [PATCH] fix: pseudo-determinant for intrinsic regularization log det H (#682) The smoothness schemes (Constant, ConstantSplit, Adapt, AdaptPower, AdaptSplit, AdaptSplitPower) build an H whose constant vector is an exact null mode, held up only by the net 1e-8 diagonal jitter. log det H thus contained log(1e-8 + O(eps*||H||)): an arbitrary constant plus round-off, which at large coefficients broke eager/jit agreement (Delaunay + AdaptSplit outer=10: 1.2e-8 on main) and blocks the #609 KNN fix. Treat H as an intrinsic GMRF precision and normalise with its pseudo-determinant: pdet(H_b) = P_b * det(H_b grounded on one pixel), per regularized block. Stays sparse and jit-static. Gated by a new AbstractRegularization.has_constant_null_mode flag, pinned by a unit test to each scheme's measured spectrum. Likelihood change (maintainer-approved): log evidence of every fit using these schemes shifts by a constant +0.5*ln(1e8) = +9.21 nats per regularized mapper; inference unchanged apart from noise removal. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016nhQ8MFwfRFgwBVbYjP9Xd --- autoarray/inversion/inversion/abstract.py | 64 ++++++- .../inversion/regularization/abstract.py | 17 ++ autoarray/inversion/regularization/adapt.py | 3 + .../regularization/adapt_split_zeroth.py | 3 + .../inversion/regularization/constant.py | 3 + .../inversion/test_intrinsic_log_det.py | 179 ++++++++++++++++++ .../inversion/test_log_det_sparse.py | 75 +++++++- 7 files changed, 335 insertions(+), 9 deletions(-) create mode 100644 test_autoarray/inversion/inversion/test_intrinsic_log_det.py diff --git a/autoarray/inversion/inversion/abstract.py b/autoarray/inversion/inversion/abstract.py index 94c40ca04..121f398f4 100644 --- a/autoarray/inversion/inversion/abstract.py +++ b/autoarray/inversion/inversion/abstract.py @@ -3,7 +3,7 @@ import warnings import numpy as np -from typing import Dict, List, Optional, Type, Union +from typing import Dict, List, Optional, Tuple, Type, Union from autonerves import cached_property, is_test_mode @@ -1253,10 +1253,68 @@ def log_det_regularization_matrix_term(self) -> float: if all(term is not None for term in term_list): return sum(term_list) - return self._log_det_symmetric_from( - self.regularization_matrix_reduced, sparse=self._xp is np + grounded_indexes, log_block_sizes = self._intrinsic_regularization_blocks + + if len(grounded_indexes) == 0: + return self._log_det_symmetric_from( + self.regularization_matrix_reduced, sparse=self._xp is np + ) + + # Pseudo-determinant of each intrinsic block (PyAutoArray#682). For a symmetric block `H_b` whose null + # vector is the constant `1 / sqrt(P_b)`, `pdet(H_b) = P_b * det(H_b with one row and column deleted)`: + # deleting ("grounding") one pixel removes the constant mode exactly, so the term no longer contains the + # `log` of the ~1e-8 diagonal jitter that otherwise holds that mode up, nor the rounding noise of order + # `eps * ||H|| / 1e-8` that came with it. The grounded matrix keeps `H`'s sparsity and its indices are + # static, so the sparse NumPy route and `jax.jit` are both unchanged. + matrix = self.regularization_matrix_reduced + keep = np.setdiff1d(np.arange(matrix.shape[0]), grounded_indexes) + + if keep.shape[0] == 0: + return log_block_sizes + + return log_block_sizes + self._log_det_symmetric_from( + matrix[keep][:, keep], sparse=self._xp is np ) + @property + def _intrinsic_regularization_blocks(self) -> Tuple[np.ndarray, float]: + """ + The blocks of `regularization_matrix_reduced` whose regularization has an exact constant null mode + (`AbstractRegularization.has_constant_null_mode`), as the index of the first parameter of every such block + in `regularization_matrix_reduced` coordinates, and the sum of `log(P_b)` over their sizes `P_b`. + + `regularization_matrix_reduced` is the block diagonal of every linear object's regularization matrix when + every linear object is regularized, and otherwise the restriction of that to the mapper parameters + (`mapper_indices`). In both cases each regularized block is contiguous, so its first index is the running + sum of the sizes of the blocks before it. + """ + if self.all_linear_obj_have_regularization: + linear_obj_list = self.linear_obj_list + else: + linear_obj_list = self.cls_list_from(cls=Mapper) + + if not any( + getattr(linear_obj.regularization, "has_constant_null_mode", False) + for linear_obj in linear_obj_list + ): + return np.asarray([], dtype=int), 0.0 + + grounded_indexes = [] + log_block_sizes = 0.0 + offset = 0 + + for linear_obj in linear_obj_list: + params = int(linear_obj.params) + regularization = linear_obj.regularization + + if regularization is not None and regularization.has_constant_null_mode: + grounded_indexes.append(offset) + log_block_sizes += float(np.log(params)) + + offset += params + + return np.asarray(grounded_indexes, dtype=int), log_block_sizes + @property def reconstruction_covariance_matrix(self) -> np.ndarray: """ diff --git a/autoarray/inversion/regularization/abstract.py b/autoarray/inversion/regularization/abstract.py index 8f30c7308..e6b78720c 100644 --- a/autoarray/inversion/regularization/abstract.py +++ b/autoarray/inversion/regularization/abstract.py @@ -73,6 +73,23 @@ class AbstractRegularization: combinations at construction. """ + has_constant_null_mode = False + """ + Whether this scheme's regularization matrix ``H`` has the constant vector as an exact null mode by + construction, i.e. it is the precision matrix of an *intrinsic* Gaussian prior that penalizes only differences + between pixels and leaves the overall level of the reconstruction unconstrained. + + This holds for the smoothness schemes whose every row of ``B`` sums to zero (``Constant``, ``ConstantSplit``, + ``Adapt``, ``AdaptPower``, ``AdaptSplit``, ``AdaptSplitPower``); their ``H`` is singular except for the small + diagonal jitter added for numerical stability. It does not hold for schemes with a zeroth-order term or a + kernel covariance, whose ``H`` is positive-definite in its own right. + + When ``True`` the Bayesian evidence normalises the prior with the **pseudo-determinant** of ``H`` (the product of + its non-zero eigenvalues) rather than its determinant, which would be set by the arbitrary jitter and carry its + rounding noise (PyAutoArray#682): see ``AbstractInversion.log_det_regularization_matrix_term``. A unit test pins + this flag to the measured spectrum of every scheme, so it must only be set where the null mode is exact. + """ + def __init__(self): """ Abstract base class for a regularization-scheme, which is applied to a pixelization to enforce a \ diff --git a/autoarray/inversion/regularization/adapt.py b/autoarray/inversion/regularization/adapt.py index ec3d36dc9..fcd4a720b 100644 --- a/autoarray/inversion/regularization/adapt.py +++ b/autoarray/inversion/regularization/adapt.py @@ -226,6 +226,9 @@ def weighted_regularization_matrix_single_scatter_from( class Adapt(AbstractRegularization): + # The rows of B sum to zero, so H's constant vector is an exact null mode (PyAutoArray#682). + has_constant_null_mode = True + def __init__( self, inner_coefficient: float = 1.0, diff --git a/autoarray/inversion/regularization/adapt_split_zeroth.py b/autoarray/inversion/regularization/adapt_split_zeroth.py index f6d151183..5e35c02d3 100644 --- a/autoarray/inversion/regularization/adapt_split_zeroth.py +++ b/autoarray/inversion/regularization/adapt_split_zeroth.py @@ -12,6 +12,9 @@ class AdaptSplitZeroth(Adapt): + # Inherits from `Adapt` but adds a zeroth-order term, so H is positive-definite in its own right. + has_constant_null_mode = False + is_split_regularization = True def __init__( diff --git a/autoarray/inversion/regularization/constant.py b/autoarray/inversion/regularization/constant.py index f27b291f5..a9b11d5b9 100644 --- a/autoarray/inversion/regularization/constant.py +++ b/autoarray/inversion/regularization/constant.py @@ -70,6 +70,9 @@ class in the module `autoarray.inversion.regularization`. class Constant(AbstractRegularization): + # The rows of B sum to zero, so H's constant vector is an exact null mode (PyAutoArray#682). + has_constant_null_mode = True + def __init__(self, coefficient: float = 1.0): """ Regularization which uses the neighbors of the mesh (e.g. shared Delaunay vertexes) and diff --git a/test_autoarray/inversion/inversion/test_intrinsic_log_det.py b/test_autoarray/inversion/inversion/test_intrinsic_log_det.py new file mode 100644 index 000000000..29c29f1e5 --- /dev/null +++ b/test_autoarray/inversion/inversion/test_intrinsic_log_det.py @@ -0,0 +1,179 @@ +""" +PyAutoArray#682: the evidence's ``log det H`` term for intrinsic regularization schemes. + +The smoothness schemes build an ``H`` whose constant vector is an exact null mode, held up only by the 1e-8 +diagonal jitter. The evidence therefore normalises them with the pseudo-determinant (the product of the +non-zero eigenvalues), and ``AbstractRegularization.has_constant_null_mode`` says which schemes those are. +""" + +import numpy as np +import pytest + +import autoarray as aa +from autoarray import fixtures + + +def _mappers(): + return { + "delaunay": fixtures.make_delaunay_mapper_9_3x3(), + "rectangular": fixtures.make_rectangular_mapper_7x7_3x3(), + } + + +SCHEMES = [ + aa.reg.Constant(coefficient=3.0), + aa.reg.ConstantSplit(coefficient=3.0), + aa.reg.Adapt(inner_coefficient=0.1, outer_coefficient=10.0), + aa.reg.AdaptPower(inner_coefficient=0.1, outer_coefficient=10.0), + aa.reg.AdaptSplit(inner_coefficient=0.1, outer_coefficient=10.0), + aa.reg.AdaptSplitPower(inner_coefficient=0.1, outer_coefficient=10.0), + aa.reg.Zeroth(coefficient=3.0), + aa.reg.ConstantZeroth(coefficient_neighbor=3.0, coefficient_zeroth=1.0), + aa.reg.AdaptSplitZeroth(inner_coefficient=0.1, outer_coefficient=10.0), + aa.reg.AdaptSplitZerothPower(inner_coefficient=0.1, outer_coefficient=10.0), + aa.reg.GaussianKernel(coefficient=3.0, scale=0.5), + aa.reg.ExponentialKernel(coefficient=3.0, scale=0.5), +] + + +def _cases(schemes): + """ + Every (scheme, mesh) pair the scheme applies to: split schemes need an adaptive mesh's split tables, + which the rectangular mesh does not provide, so they are paired with the Delaunay mesh only. + """ + return [ + pytest.param(scheme, mesh, id=f"{type(scheme).__name__}-{mesh}") + for scheme in schemes + for mesh in ("delaunay", "rectangular") + if mesh == "delaunay" or not scheme.is_split_regularization + ] + + +def _matrix_from(regularization, mapper): + return np.asarray(regularization.regularization_matrix_from(linear_obj=mapper)) + + +@pytest.mark.parametrize("regularization, mesh", _cases(SCHEMES)) +def test__has_constant_null_mode__matches_measured_spectrum(regularization, mesh): + """ + The flag must describe the matrix: an intrinsic scheme's smallest eigenvalue is the jitter with the + constant vector as its eigenvector and an O(1) gap above it; every other scheme is positive-definite + without the jitter. + """ + matrix = _matrix_from(regularization, _mappers()[mesh]) + + eigenvalues, eigenvectors = np.linalg.eigh(matrix) + pixels = matrix.shape[0] + overlap = abs(eigenvectors[:, 0] @ np.ones(pixels) / np.sqrt(pixels)) + + intrinsic = eigenvalues[0] < 1.0e-6 and overlap > 1.0 - 1.0e-9 + + assert regularization.has_constant_null_mode == intrinsic + + if intrinsic: + assert eigenvalues[1] > 1.0e-3 + + +def _inversion_from(mapper_list): + return aa.m.MockInversion( + linear_obj_list=mapper_list, + regularization_matrix=__import__("scipy.linalg").linalg.block_diag( + *[np.asarray(mapper.regularization_matrix) for mapper in mapper_list] + ), + ) + + +def _mapper_with(regularization, mesh): + mapper = _mappers()[mesh] + return type(mapper)( + interpolator=mapper.interpolator, + regularization=regularization, + image_plane_mesh_grid=mapper.image_plane_mesh_grid, + ) + + +@pytest.mark.parametrize( + "regularization, mesh", + _cases([scheme for scheme in SCHEMES if scheme.has_constant_null_mode]), +) +def test__log_det_regularization_matrix_term__intrinsic__is_pseudo_determinant( + regularization, mesh +): + """ + The term equals an independent eigenvalue pseudo-determinant (log of the non-zero eigenvalues), not the + full determinant, which differs from it by the log of the ~1e-8 jitter. + """ + mapper = _mapper_with(regularization, mesh) + matrix = np.asarray(mapper.regularization_matrix) + + eigenvalues = np.linalg.eigvalsh(matrix) + + log_det = _inversion_from([mapper]).log_det_regularization_matrix_term + + assert log_det == pytest.approx(np.sum(np.log(eigenvalues[1:])), abs=1.0e-7) + + # The full determinant differs by the log of the constant-mode eigenvalue: the 1e-8 jitter plus round-off + # of order eps * ||H||. That round-off is what the pseudo-determinant removes; at `Adapt` outer=10 it is + # ~2e-4 in the log here, hence the loose tolerance on this illustrative gap only. + assert np.sum(np.log(eigenvalues)) - log_det == pytest.approx( + np.log(1.0e-8), abs=1.0e-3 + ) + + +@pytest.mark.parametrize("mesh", ["delaunay", "rectangular"]) +def test__log_det_regularization_matrix_term__intrinsic__independent_of_constant_mode( + mesh, +): + """ + The pseudo-determinant does not see the constant mode at all: moving that mode's eigenvalue from the + jitter to 1e-5 leaves the term unchanged, where the full determinant would shift by ``log(1e3)``. + """ + mapper = _mapper_with( + aa.reg.Adapt(inner_coefficient=0.1, outer_coefficient=10.0), mesh + ) + matrix = np.asarray(mapper.regularization_matrix) + pixels = matrix.shape[0] + + lifted = matrix + 1.0e-5 * np.ones((pixels, pixels)) / pixels + + log_det = aa.m.MockInversion( + linear_obj_list=[mapper], regularization_matrix=matrix + ).log_det_regularization_matrix_term + log_det_lifted = aa.m.MockInversion( + linear_obj_list=[mapper], regularization_matrix=lifted + ).log_det_regularization_matrix_term + + assert log_det_lifted == pytest.approx(log_det, abs=1.0e-6) + + +def test__log_det_regularization_matrix_term__non_intrinsic__unchanged(): + """A positive-definite scheme keeps the full determinant.""" + mapper = _mapper_with(aa.reg.Zeroth(coefficient=3.0), "delaunay") + matrix = np.asarray(mapper.regularization_matrix) + + log_det = _inversion_from([mapper]).log_det_regularization_matrix_term + + assert log_det == pytest.approx(np.linalg.slogdet(matrix)[1], rel=1.0e-12) + + +def test__log_det_regularization_matrix_term__multiple_mappers__sum_of_blocks(): + """ + Each regularized mapper is its own block: an intrinsic block contributes its pseudo-determinant and a + positive-definite block its determinant, so the term is the sum of the per-mapper terms. + """ + mapper_0 = _mapper_with(aa.reg.Constant(coefficient=3.0), "delaunay") + mapper_1 = _mapper_with(aa.reg.Zeroth(coefficient=2.0), "rectangular") + mapper_2 = _mapper_with( + aa.reg.Adapt(inner_coefficient=0.1, outer_coefficient=10.0), "rectangular" + ) + + combined = _inversion_from([mapper_0, mapper_1, mapper_2]) + + separate = sum( + _inversion_from([mapper]).log_det_regularization_matrix_term + for mapper in (mapper_0, mapper_1, mapper_2) + ) + + assert combined.log_det_regularization_matrix_term == pytest.approx( + separate, rel=1.0e-12 + ) diff --git a/test_autoarray/inversion/inversion/test_log_det_sparse.py b/test_autoarray/inversion/inversion/test_log_det_sparse.py index 9e6e8d473..585a741c5 100644 --- a/test_autoarray/inversion/inversion/test_log_det_sparse.py +++ b/test_autoarray/inversion/inversion/test_log_det_sparse.py @@ -131,6 +131,15 @@ def _dense_log_det(matrix): return 2.0 * np.sum(np.log(np.diag(np.linalg.cholesky(matrix)))) +def _dense_log_pdet(matrix): + """ + The log pseudo-determinant of an intrinsic ``H`` (constant null mode, PyAutoArray#682) by the grounding + identity ``pdet(H) = P * det(H with its first row and column deleted)``, with the deleted-row determinant + taken by the same dense Cholesky as ``_dense_log_det``. + """ + return np.log(matrix.shape[0]) + _dense_log_det(matrix[1:, 1:]) + + @pytest.mark.parametrize( "pixels, band", [(256, 1), (300, 2), (400, 3), (512, 5)], @@ -235,8 +244,9 @@ def raise_splu(*args, **kwargs): regularization_matrix=matrix, ) + # `ConstantSplit` is intrinsic, so the term is the pseudo-determinant (PyAutoArray#682). assert inversion.log_det_regularization_matrix_term == pytest.approx( - _dense_log_det(matrix), rel=1.0e-12 + _dense_log_pdet(matrix), rel=1.0e-12 ) @@ -306,11 +316,15 @@ def test__log_det_regularization_matrix_term__real_split_inversion__matches_dens assert inversion.regularization_matrix_reduced.shape == matrix.shape + # `AdaptSplit` is intrinsic, so the term is the pseudo-determinant (PyAutoArray#682). At these + # coefficients the full-matrix determinant would carry the 1e-8 jitter's `log` and its round-off. + grounded = matrix[1:, 1:] + assert inversion.log_det_regularization_matrix_term == pytest.approx( - _dense_log_det(matrix), rel=1.0e-7 + _dense_log_pdet(matrix), rel=1.0e-12 ) assert inversion.log_det_regularization_matrix_term == pytest.approx( - np.linalg.slogdet(matrix)[1], rel=1.0e-7 + np.log(matrix.shape[0]) + np.linalg.slogdet(grounded)[1], rel=1.0e-12 ) @@ -481,8 +495,10 @@ def test__log_det_regularization_matrix_term__vertex_coincident_adapt_split__num The log-determinant routes themselves were never the cause: given the same ``H`` both agree with a 50-digit reference. That is pinned here only at moderate coefficients, where ``H`` is well-posed (``cond ~ 2e9``). At high coefficients (``max(coefficient)^4 >~ 1e6``) the absolute - 1e-8 diagonal jitter puts ``H``'s constant-mode eigenvalue at round-off level, so the log - determinant is round-off-determined on either backend and no parity is asserted. + 1e-8 diagonal jitter puts ``H``'s constant-mode eigenvalue at round-off level, so the full-matrix log + determinant is round-off-determined on either backend. Since PyAutoArray#682 the term is the + pseudo-determinant, which does not contain that eigenvalue, so parity at high coefficients is pinned too + (``..._high_coefficients__numpy_matches_jax`` below). """ jax = pytest.importorskip("jax") jax.config.update("jax_enable_x64", True) @@ -522,7 +538,54 @@ def test__log_det_regularization_matrix_term__vertex_coincident_adapt_split__num assert abs(log_det_np - log_det_jax) < 1.0e-6 - reference = _high_precision_log_det(matrix_np) + # `AdaptSplit` is intrinsic: the reference is the pseudo-determinant (PyAutoArray#682). + reference = np.log(matrix_np.shape[0]) + _high_precision_log_det( + matrix_np[1:, 1:] + ) assert abs(log_det_np - reference) < 1.0e-6 assert abs(log_det_jax - reference) < 1.0e-6 + + +def test__log_det_regularization_matrix_term__vertex_coincident_adapt_split_high_coefficients__numpy_matches_jax(): + """ + PyAutoArray#682: at high coefficients (``AdaptSplit`` outer 10, the setting of autolens_workspace_test + ``jax_grad``) the full-matrix log determinant was round-off-determined, because ``H``'s constant-mode + eigenvalue is the 1e-8 jitter. The pseudo-determinant drops that mode, so the two backends and a + 50-digit reference agree here as well. + """ + jax = pytest.importorskip("jax") + jax.config.update("jax_enable_x64", True) + import jax.numpy as jnp + + regularization = aa.reg.AdaptSplit( + inner_coefficient=0.1, outer_coefficient=10.0, signal_scale=0.3 + ) + + mapper_np = _vertex_coincident_adapt_split_mapper(regularization, xp=np) + mapper_jax = _vertex_coincident_adapt_split_mapper(regularization, xp=jnp) + + matrix_np = np.asarray( + regularization.regularization_matrix_from(linear_obj=mapper_np) + ) + matrix_jax = regularization.regularization_matrix_from( + linear_obj=mapper_jax, xp=jnp + ) + + inversion_np = aa.m.MockInversion( + linear_obj_list=[mapper_np], regularization_matrix=matrix_np + ) + inversion_jax = aa.m.MockInversion( + linear_obj_list=[mapper_jax], regularization_matrix=matrix_jax + ) + inversion_jax.use_jax = True + + log_det_np = float(inversion_np.log_det_regularization_matrix_term) + log_det_jax = float(inversion_jax.log_det_regularization_matrix_term) + + reference = np.log(matrix_np.shape[0]) + _high_precision_log_det( + matrix_np[1:, 1:] + ) + + assert abs(log_det_np - log_det_jax) < 1.0e-6 + assert abs(log_det_np - reference) < 1.0e-6