From 470473f7473eef6770b149c2c85b1a0afd2e6a34 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Mon, 7 Sep 2026 16:57:56 -0400 Subject: [PATCH] fix(messages): keep the full covariance through coupled transforms in from_mode (#1569) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `TransformedMessage.from_mode` reduced a LinearOperator covariance to its diagonal before applying the transform Jacobians, so a coupled Jacobian (MultinomialLogitTransform's ShermanMorrison, used by MultiLogitNormalMessage) contracted the vector as J(Jᵀv) instead of diag(J Σ Jᵀ): operator inputs gave [2.3611, 2.1875] where the equivalent ndarray gave [1.2222, 1.2431]. Keep the dense matrix through the Jacobian loop when transforms are present; take the diagonal only in the no-transform case. Scalar transforms are unchanged. Pre-#1560 this path raised; #1560 made it silently wrong. Codex review of the phase-2 fixes, finding 3. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01Gu4YysuvpQ4k6zkQjiwabd --- autofit/messages/composed_transform.py | 15 ++++- .../messages/test_transformed_from_mode.py | 57 ++++++++++++++++++- 2 files changed, 68 insertions(+), 4 deletions(-) diff --git a/autofit/messages/composed_transform.py b/autofit/messages/composed_transform.py index 493a71d7b..5f9534aec 100644 --- a/autofit/messages/composed_transform.py +++ b/autofit/messages/composed_transform.py @@ -436,8 +436,8 @@ def from_mode(self, mode: np.ndarray, covariance, **kwargs): way, ``jac.quad`` being the inverse of the ``invquad`` composition that ``variance`` applies base -> physical. A ``LinearOperator`` covariance (the 0-d or n-d ``DiagonalMatrix`` the Laplace optimiser - hands over) is reduced to its diagonal first, which is all the base - ``from_mode`` reads. + hands over) is densified first when there are transforms to apply, + and reduced to its diagonal when there are none. Physical-space ``lower_limit`` / ``upper_limit`` kwargs are dropped: the base message lives in base space and keeps its own support @@ -446,7 +446,16 @@ def from_mode(self, mode: np.ndarray, covariance, **kwargs): from autofit.mapper.operator import LinearOperator if isinstance(covariance, LinearOperator): - covariance = covariance.diagonal() + # A Jacobian may be coupled (``MultinomialLogitTransform`` returns a + # ``ShermanMorrison`` operator), and ``jac.quad`` contracts a 1-D + # argument as a vector, ``J(J.T v)``, not as ``diag(v)``. Handing it + # the diagonal would therefore lose the off-diagonal ``J S J.T`` mass + # that belongs on the diagonal, so keep the dense matrix whenever + # there is a transform to push through. With no transform the base + # message reads only the marginals, so the diagonal is enough. + covariance = ( + covariance.to_dense() if self.transforms else covariance.diagonal() + ) covariance = np.asanyarray(covariance) kwargs.pop("lower_limit", None) diff --git a/test_autofit/messages/test_transformed_from_mode.py b/test_autofit/messages/test_transformed_from_mode.py index 122e20a2a..d6b6535cb 100644 --- a/test_autofit/messages/test_transformed_from_mode.py +++ b/test_autofit/messages/test_transformed_from_mode.py @@ -7,7 +7,9 @@ import pytest import autofit as af -from autofit.mapper.operator import DiagonalMatrix +from autofit.mapper.operator import DiagonalMatrix, MatrixOperator +from autofit.messages import MultiLogitNormalMessage +from autofit.messages.transform import multinomial_logit_transform from autofit.mapper.variable import Variable from autofit.mapper.variable_operator import VariableFullOperator @@ -80,3 +82,56 @@ def test__two_transform_stack_one_d_matches_zero_d(): assert one_d.variance == pytest.approx([0.04]) assert zero_d.variance == pytest.approx(0.04) + + +@pytest.fixture(name="multi_logit_mode") +def make_multi_logit_mode(): + # Two simplex components, comfortably inside 0 < sum(p) < 1. + return np.array([0.3, 0.4]) + + +def _delta_method_variance(mode, covariance): + """``diag(J Sigma J.T)``, with J by central differences of the transform itself.""" + step = 1e-6 + jacobian = np.zeros((mode.size, mode.size)) + for i in range(mode.size): + offset = np.zeros(mode.size) + offset[i] = step + jacobian[:, i] = ( + multinomial_logit_transform.transform(mode + offset) + - multinomial_logit_transform.transform(mode - offset) + ) / (2 * step) + + return np.diag(jacobian @ covariance @ jacobian.T) + + +@pytest.mark.parametrize( + "covariance, diagonal", + [ + (np.diag([0.02, 0.03]), np.array([0.02, 0.03])), + (np.array([[0.02, 0.008], [0.008, 0.03]]), None), + ], + ids=["diagonal_covariance", "coupled_covariance"], +) +def test__coupled_jacobian_keeps_the_full_covariance( + multi_logit_mode, covariance, diagonal +): + # MultinomialLogitTransform's Jacobian is a coupled ShermanMorrison operator, + # and ``jac.quad`` contracts a 1-D argument as ``J(J.T v)``. Diagonalising an + # operator covariance first (PyAutoFit#1569) therefore returned [2.3611, 2.1875] + # for every operator input, against [1.2222, 1.2431] for the equivalent array. + forms = [covariance, MatrixOperator(covariance)] + if diagonal is not None: + forms.append(DiagonalMatrix(diagonal)) + + variances = [ + MultiLogitNormalMessage.from_mode(multi_logit_mode, form).base_message.variance + for form in forms + ] + + for variance in variances[1:]: + assert variance == pytest.approx(variances[0], rel=1.0e-6) + + assert variances[0] == pytest.approx( + _delta_method_variance(multi_logit_mode, covariance), rel=1.0e-4 + )