From c3b67cfc5214940f9858e1baebc0e282488f236b Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Wed, 2 Sep 2026 18:57:14 -0400 Subject: [PATCH 1/2] fix(graphical): Laplace projection uses a finite-difference Hessian at the mode; failed and narrower-than-cavity updates are skipped, not written (#1561) D2: `LaplaceOptimiser(hessian="fd")` (default) projects the inverse of a central finite-difference Hessian of the tilted gradient, assembled in Variable.id order and Cholesky-factorised as a full matrix (`newton.finite_difference_hessian`, `make_mode_hessian`); marginal blocks reach the messages through `MeanField.from_opt_state` -> `inv_hessian_blocks()`. A non-finite or non-concave Hessian is a BAD_PROJECTION that keeps the previous message. Factors above `hessian_max_size` (64) fall back to `hessian="quasi"`, whose `refine_state` now chains its secants and honours `n_refine=0`. The default path draws no random numbers: the two-variable analytic fixture is bit-equal across seeds and variable ids, and leg A of the analytic Gaussian benchmark gives mu 50.8596 +/- 4.1102 (closed form 4.1104) with 0 BAD_PROJECTION, identical across K = 1, 3, 6 throwaway priors. D3: `optimise_approx` returns the mean field unchanged when the optimiser did not succeed and `update_factor_mean_field` returns `last_dist` with `updated=False` (flag preserved), so a failed line search no longer projects the start point over the factor message. The per-variable `check_valid`/`update_invalid` backstop is kept and now names each reverted variable with precision(q*) and precision(cavity). `EPOptimiser` only counts a factor as updated when `status.updated`, so an always-skipped factor is reported by the stale-factor warning. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01C49DeRHoKss4xBnz5F7gUm --- .../expectation_propagation/optimiser.py | 18 +- autofit/graphical/laplace/newton.py | 43 +++- autofit/graphical/laplace/optimiser.py | 141 ++++++++++- autofit/graphical/mean_field.py | 53 ++++- .../functionality/test_ep_statistics_fixes.py | 7 +- .../functionality/test_laplace_hessian.py | 222 ++++++++++++++++++ .../hierarchical/test_hierarchical.py | 12 +- 7 files changed, 475 insertions(+), 21 deletions(-) create mode 100644 test_autofit/graphical/functionality/test_laplace_hessian.py diff --git a/autofit/graphical/expectation_propagation/optimiser.py b/autofit/graphical/expectation_propagation/optimiser.py index deb3cf54e..bce06d5cd 100644 --- a/autofit/graphical/expectation_propagation/optimiser.py +++ b/autofit/graphical/expectation_propagation/optimiser.py @@ -247,6 +247,7 @@ def __init__( # one successful update; together these identify a factor whose message # is still the one it started with. See `_stale_factor_warnings`. self._factors_raised: Set[Factor] = set() + self._factors_skipped: Set[Factor] = set() self._factors_updated: Set[Factor] = set() self.visualiser = None @@ -395,7 +396,12 @@ def _check_consecutive_failures( ) return True else: - self._factors_updated.add(factor) + if status.updated: + self._factors_updated.add(factor) + else: + # A skipped update (failed line search, bad projection): the + # message is unchanged, so this does not count as an update. + self._factors_skipped.add(factor) self._consecutive_failures.pop(factor, None) return False @@ -416,18 +422,20 @@ def _stale_factor_warnings(self) -> List[str]: strings are logged as warnings and written into `ep_diagnostics.results` alongside the sigma-collapse warnings. - The condition is deliberately narrow: a factor that raised at least once + The condition is deliberately narrow: a factor that raised, or whose + update was skipped (failed line search, bad projection), at least once and *never once* updated. A factor that failed intermittently but landed at least one update has a real message and is not reported. """ - stale = self._factors_raised - self._factors_updated + stale = (self._factors_raised | self._factors_skipped) - self._factors_updated if not stale: return [] names = ", ".join(sorted(factor.name for factor in stale)) return [ f"STALE FACTORS: {names} never completed a single update — their " - f"optimisers raised on every sweep. The mean field returned for " + f"optimisers raised or their updates were skipped on every sweep. " + f"The mean field returned for " f"them is the prior the fit started with, not a posterior. Do not " f"read those values as a result. Note that EP may also report " f"convergence in this state: with no factor updating, the KL step " @@ -489,6 +497,7 @@ def run( self._consecutive_failures = {} self._factors_raised = set() + self._factors_skipped = set() self._factors_updated = set() for _ in range(max_steps): @@ -674,6 +683,7 @@ def run( self._consecutive_failures = {} self._factors_raised = set() + self._factors_skipped = set() self._factors_updated = set() for _ in range(max_steps): diff --git a/autofit/graphical/laplace/newton.py b/autofit/graphical/laplace/newton.py index a4d3eaf6c..8b40996b5 100644 --- a/autofit/graphical/laplace/newton.py +++ b/autofit/graphical/laplace/newton.py @@ -1,12 +1,13 @@ import logging import warnings +from operator import attrgetter from typing import Optional, Dict, Tuple, Any, Callable import numpy as np from autofit import exc from autofit.graphical.laplace.line_search import line_search, OptimisationState -from autofit.graphical.utils import Status, StatusFlag, LogWarnings +from autofit.graphical.utils import Status, StatusFlag, LogWarnings, FlattenArrays from autofit.mapper.variable_operator import VariableData @@ -159,6 +160,46 @@ def __call__( full_diag_update = QuasiNewtonUpdate(diag_sr1_update, diag_quasi_deterministic_update) +## Finite-difference Hessian + + +def finite_difference_hessian( + state: OptimisationState, step: VariableData +) -> Tuple[np.ndarray, FlattenArrays]: + """ + Central finite-difference Hessian of `state`'s objective at its parameters. + + The free variables are flattened in `Variable.id` order so the matrix does + not depend on dict order, and the result is symmetrised. Costs two gradient + evaluations per flattened parameter; each perturbed state is a copy, so + `state` itself is untouched. + + Parameters + ---------- + state + The optimisation state at which to evaluate the Hessian. + step + Per-variable finite-difference step, same shapes as `state.parameters`. + + Returns + ------- + The symmetrised Hessian and the `FlattenArrays` describing its layout. + """ + variables = sorted(state.parameters.keys(), key=attrgetter("id")) + shapes = FlattenArrays({v: np.shape(state.parameters[v]) for v in variables}) + x0 = shapes.flatten(state.parameters) + h = shapes.flatten(step) + n = x0.size + H = np.empty((n, n)) + for i in range(n): + e = np.zeros(n) + e[i] = h[i] + gp = shapes.flatten(state.update(parameters=shapes.unflatten(x0 + e)).gradient) + gm = shapes.flatten(state.update(parameters=shapes.unflatten(x0 - e)).gradient) + H[i] = (gp - gm) / (2 * h[i]) + return 0.5 * (H + H.T), shapes + + ## Newton step diff --git a/autofit/graphical/laplace/optimiser.py b/autofit/graphical/laplace/optimiser.py index 4927f07ff..6a4877e3c 100644 --- a/autofit/graphical/laplace/optimiser.py +++ b/autofit/graphical/laplace/optimiser.py @@ -1,21 +1,47 @@ +import logging from typing import Optional, Dict, Tuple, Any, Union +import numpy as np + from autofit.graphical.expectation_propagation.ep_mean_field import EPMeanField from autofit.graphical.expectation_propagation.optimiser import AbstractFactorOptimiser from autofit.graphical.factor_graphs.factor import Factor from autofit.graphical.laplace import newton from autofit.graphical.mean_field import MeanField, FactorApproximation -from autofit.graphical.utils import Status -from autofit.mapper.variable_operator import VariableData +from autofit.graphical.utils import Status, StatusFlag +from autofit.mapper.variable_operator import VariableData, VariableFullOperator FactorApprox = Union[EPMeanField, FactorApproximation, Factor] +logger = logging.getLogger(__name__) + def make_posdef_hessian(mean_field, variables): return MeanField.precision(mean_field, variables) class LaplaceOptimiser(AbstractFactorOptimiser): + """ + Laplace projection of a factor's tilted distribution. + + The mode is found by quasi-Newton ascent (`newton.optimise_quasi_newton`). + The covariance projected onto the mean field is, by default + (``hessian="fd"``), the inverse of a central finite-difference Hessian of + the tilted gradient assembled at that mode (`newton.finite_difference_hessian`), + factorised as a full matrix so that its marginal blocks are exact. A Hessian + that is not finite (mode on a limit) or not negative definite (tilted density + not concave at the mode, e.g. a scale parameter driven to 0) is a + ``BAD_PROJECTION``: the factor's update is skipped rather than written from a + guess. Factors with more than ``hessian_max_size`` flattened free parameters + fall back to ``hessian="quasi"`` — the quasi-Newton secant estimate refined + with ``n_refine`` random draws from the mean field, which is *not* + deterministic across runs (PyAutoFit#1561). + + A failed optimisation (line-search failure) returns the mean field it was + handed, unchanged, so that the caller's projection reproduces the previous + message exactly. + """ + def __init__( self, make_hessian=make_posdef_hessian, @@ -26,6 +52,10 @@ def __init__( make_det_hessian=None, max_iter: int = 100, n_refine: int = 3, + hessian: str = "fd", + fd_step: float = 1e-2, + fd_min_step: float = 1e-8, + hessian_max_size: int = 64, hessian_kws: Optional[Dict[str, Any]] = None, det_hessian_kws: Optional[Dict[str, Any]] = None, search_direction_kws: Optional[Dict[str, Any]] = None, @@ -37,6 +67,11 @@ def __init__( ): super().__init__(**kwargs) + if hessian not in ("fd", "quasi"): + raise ValueError( + f"hessian must be 'fd' or 'quasi', got {hessian!r}" + ) + self.make_hessian = make_hessian self.make_det_hessian = make_det_hessian or make_hessian self.search_direction = search_direction @@ -46,6 +81,19 @@ def __init__( self.max_iter = max_iter self.n_refine = n_refine + # Covariance at the mode: "fd" (finite-difference Hessian, default) or + # "quasi" (the secant estimate refined with `n_refine` random draws). + self.hessian = hessian + # Finite-difference step per parameter, relative to the mean-field std + # (floored at `fd_min_step`). With forward-difference factor gradients + # (eps=1e-8) the gradient noise is ~2e-8·|f|, so the step should stay + # well above 1e-4·std; 1e-2·std keeps the central-difference truncation + # error below 1e-4 relative for a Gaussian. + self.fd_step = fd_step + self.fd_min_step = fd_min_step + # Above this many flattened free parameters the 2n gradient evaluations + # of the finite-difference Hessian are traded for the quasi-Newton path. + self.hessian_max_size = hessian_max_size self.hessian_kws = hessian_kws or {} self.det_hessian_kws = det_hessian_kws or hessian_kws or {} @@ -115,6 +163,41 @@ def optimise_state( kws = {**self.default_kws, **kwargs} return newton.optimise_quasi_newton(state, old_state, **kws) + def make_mode_hessian( + self, state: newton.OptimisationState, mean_field: MeanField + ) -> Tuple[Optional[VariableFullOperator], str]: + """ + The negative finite-difference Hessian of the tilted log-density at + `state`, as a Cholesky-factorised full operator over the free variables. + + Returns ``(operator, "")`` or ``(None, reason)`` when the Hessian is not + finite or not negative definite. + """ + # `variance` rather than `std`: TransformedMessage exposes only the former + variance = MeanField.variance.fget(mean_field) + step = VariableData( + { + v: np.maximum( + self.fd_step + * np.sqrt(np.abs(np.asanyarray(variance[v], dtype=float))), + self.fd_min_step, + ) + for v in state.parameters + } + ) + H, shapes = newton.finite_difference_hessian(state, step) + if not np.all(np.isfinite(H)): + return None, "non-finite Hessian at mode (mode on a limit / outside support)" + try: + # cho_factor raises LinAlgError if -H is not positive definite + return VariableFullOperator.from_posdef(-H, shapes), "" + except np.linalg.LinAlgError: + min_eig = np.linalg.eigvalsh(-H).min() + return ( + None, + f"tilted log-density not concave at mode (min eig {min_eig:.3g})", + ) + def optimise_approx( self, factor_approx: FactorApprox, @@ -126,19 +209,59 @@ def optimise_approx( mean_field = mean_field or factor_approx.model_dist state = self.prepare_state(factor_approx, mean_field, params) next_state, status = self.optimise_state(state, **kwargs) - # if status.flag != StatusFlag.SUCCESS: + if not status.success: + # The optimiser did not land anywhere: hand back the mean field + # unchanged so the projection reproduces the previous message. + return mean_field, status + next_state = max(state, next_state, key=lambda x: x.value) - next_state = self.refine_state( - next_state, mean_field.sample, n_refine=kwargs.get("n_refine") - ) + + n_params = sum(np.size(p) for p in next_state.parameters.values()) + if self.hessian == "fd" and n_params <= self.hessian_max_size: + hessian, reason = self.make_mode_hessian(next_state, mean_field) + if hessian is None: + factor_name = getattr( + getattr(factor_approx, "factor", factor_approx), "name", factor_approx + ) + return ( + mean_field, + Status( + success=False, + messages=status.messages + + (f"Laplace Hessian for {factor_name}: {reason}",), + updated=False, + flag=StatusFlag.BAD_PROJECTION, + result=status.result, + ), + ) + next_state.hessian = hessian + else: + if self.hessian == "fd": + logger.info( + "Laplace Hessian: %d free parameters exceed hessian_max_size=%d; " + "falling back to the quasi-Newton estimate (hessian='quasi')", + n_params, + self.hessian_max_size, + ) + next_state = self.refine_state( + next_state, mean_field.sample, n_refine=kwargs.get("n_refine") + ) projection = mean_field.from_opt_state(next_state) return projection, status def refine_state(self, state, new_param, n_refine=None): + """ + Refine the quasi-Newton Hessian estimate of `state` with `n_refine` + secant updates at parameters drawn from `new_param()`. The updates + chain: each draw's secant is applied to the previously refined + estimate, not to the original one. + """ + if n_refine is None: + n_refine = self.n_refine next_state = state - for i in range(n_refine or self.n_refine): - new_state = state.update(parameters=new_param()) + for _ in range(n_refine): + new_state = next_state.update(parameters=new_param()) next_state = self.quasi_newton_update( next_state, new_state, **self.quasi_newton_kws ) @@ -154,6 +277,8 @@ def refine_approx( ) -> Tuple[MeanField, Status]: mean_field = mean_field or factor_approx.model_dist state = self.prepare_state(factor_approx, mean_field, params) + if n_refine is None: + n_refine = self.n_refine next_state = self.refine_state(state, mean_field.sample, n_refine=n_refine) return mean_field.from_opt_state(next_state) diff --git a/autofit/graphical/mean_field.py b/autofit/graphical/mean_field.py index c91f76ccf..697618064 100755 --- a/autofit/graphical/mean_field.py +++ b/autofit/graphical/mean_field.py @@ -374,8 +374,12 @@ def project_mode(self, res: OptResult): return self.from_mode_covariance(res.mode, res.hess_inv, res.log_norm) def from_opt_state(self, state): + # Per-variable marginal blocks of the inverse Hessian: a full (e.g. + # Cholesky-factorised) Hessian is inverted as one matrix so that its + # off-diagonal coupling is accounted for; only the diagonal of each + # block is consumed by `from_mode`. return self.from_mode_covariance( - state.all_parameters, state.full_hessian.inv(), state.value + state.all_parameters, state.inv_hessian_blocks(), state.value ) def from_mode_covariance( @@ -477,6 +481,21 @@ def update_factor_mean_field( """ success, messages, _, flag = status updated = False + if not status.success and last_dist is not None: + # The optimiser did not succeed (failed line search, bad Hessian, + # exception): keep the previous message rather than projecting a + # start point or a guess. The flag is the optimiser's own. + messages += ("factor update skipped: optimisation did not succeed",) + return ( + last_dist, + Status( + success=False, + messages=messages, + updated=False, + flag=flag, + result=status.result, + ), + ) try: with LogWarnings( logger=_log_projection_warnings, action="always" @@ -494,6 +513,15 @@ def update_factor_mean_field( if not factor_dist.is_valid: success = False messages += (f"model projection for {self} is invalid",) + # Name the variables `update_invalid` reverts, with the + # precisions that made the quotient invalid (a projected + # marginal wider than the cavity has negative factor precision). + reverted = [ + v + for v, valid in factor_dist.check_valid().items() + if not np.all(valid) + ] + messages += self._reverted_variable_messages(reverted, cavity_dist) factor_dist = factor_dist.update_invalid(last_dist) # May want to check another way # e.g. factor_dist.check_valid().sum() / factor_dist.check_valid().size @@ -531,6 +559,29 @@ def update_factor_mean_field( ), ) + def _reverted_variable_messages(self, variables, cavity_dist) -> Tuple[str, ...]: + """ + One status message per variable whose projected factor message was + invalid and is reverted to its previous message, quoting the projected + and cavity precisions where both are messages with a variance. + """ + out = [] + for v in variables: + m, c = self.get(v), cavity_dist.get(v) + detail = "" + if is_message(m) and is_message(c): + try: + with np.errstate(divide="ignore"): + pq = float(np.min(1 / np.asanyarray(m.variance, dtype=float))) + pc = float(np.max(1 / np.asanyarray(c.variance, dtype=float))) + detail = f": precision(q*)={pq:.4g}, precision(cavity)={pc:.4g}" + except (AttributeError, NotImplementedError, TypeError): + pass + out.append( + f"model projection for {v.name} is invalid, previous message kept{detail}" + ) + return tuple(out) + class FactorApproximation(AbstractNode): """ diff --git a/test_autofit/graphical/functionality/test_ep_statistics_fixes.py b/test_autofit/graphical/functionality/test_ep_statistics_fixes.py index 0bf20274d..fd7af5a2d 100644 --- a/test_autofit/graphical/functionality/test_ep_statistics_fixes.py +++ b/test_autofit/graphical/functionality/test_ep_statistics_fixes.py @@ -112,5 +112,10 @@ def test__dead_newton_variants_removed(): for dead in ("diag_sr1_update_", "diag_sr1_bfgs_update", "bfgs1_update"): assert not hasattr(newton, dead) - for alive in ("bfgs_update", "sr1_update", "full_bfgs_update"): + for alive in ( + "bfgs_update", + "sr1_update", + "full_bfgs_update", + "finite_difference_hessian", + ): assert hasattr(newton, alive) diff --git a/test_autofit/graphical/functionality/test_laplace_hessian.py b/test_autofit/graphical/functionality/test_laplace_hessian.py new file mode 100644 index 000000000..13386438e --- /dev/null +++ b/test_autofit/graphical/functionality/test_laplace_hessian.py @@ -0,0 +1,222 @@ +""" +The Laplace projection's covariance is the inverse of a finite-difference +Hessian of the tilted log-density at the mode (PyAutoFit#1561, D2), and a +failed or invalid update leaves the factor's message untouched (D3). +""" +import pickle + +import numpy as np +import pytest + +from autofit import graphical as graph +from autofit.graphical.laplace import newton +from autofit.graphical.laplace.optimiser import LaplaceOptimiser +from autofit.graphical.utils import Status, StatusFlag +from autofit.mapper.variable import Variable +from autofit.messages import NormalMessage + +# Tilted precision of `make_approx`: factor curvature 1/sigma_f^2 = 0.01 on +# both variables (coupled), plus the cavity precisions 1/10^2 and 1/20^2. +P = np.array([[0.02, -0.01], [-0.01, 0.0125]]) +COV = np.linalg.inv(P) +P_CAVITY = np.diag([0.01, 0.0025]) +MODE = np.linalg.solve(P, P_CAVITY @ np.array([50.0, 55.0])) + + +def make_approx(sigma_f=10.0, convex=False): + """ + A two-variable Gaussian factor N(x | mu, sigma_f) with an analytic + Jacobian, so the finite-difference Hessian is exact to roundoff. + `convex=True` flips the sign: the tilted density is then not concave. + """ + mu_, x_ = Variable("mu"), Variable("x") + sign = 1.0 if convex else -1.0 + + def f(mu, x): + return sign * 0.5 * ((x - mu) / sigma_f) ** 2 + + def f_jac(mu, x): + d = -sign * (x - mu) / sigma_f**2 + return f(mu, x), (d, -d) + + factor = graph.Factor(f, mu_, x_, factor_jacobian=f_jac) + cavity = graph.MeanField( + {mu_: NormalMessage(50.0, 10.0), x_: NormalMessage(55.0, 20.0)} + ) + return graph.FactorApproximation(factor, cavity, cavity, cavity), mu_, x_ + + +def _projection_bits(proj, mu_, x_): + return tuple( + float(getattr(proj[v], attr)) for v in (mu_, x_) for attr in ("mean", "variance") + ) + + +def test__analytic_inverse_hessian_rng_independent(): + results = [] + for seed in (0, 1, 12345): + fa, mu_, x_ = make_approx() + np.random.seed(seed) + proj, status = LaplaceOptimiser().optimise_approx(fa) + assert status.success + assert proj[mu_].variance == pytest.approx(COV[0, 0], abs=1e-8) + assert proj[x_].variance == pytest.approx(COV[1, 1], abs=1e-8) + assert proj[mu_].mean == pytest.approx(MODE[0], abs=1e-3) + assert proj[x_].mean == pytest.approx(MODE[1], abs=1e-3) + results.append(_projection_bits(proj, mu_, x_)) + # bit-equal across seeds: the default path draws no random numbers + assert results[0] == results[1] == results[2] + + +def test__analytic_inverse_hessian_variable_id_independent(): + reference = None + for n_throwaway in (1, 3, 6): + _ = [Variable("k") for _ in range(n_throwaway)] + fa, mu_, x_ = make_approx() + np.random.seed(0) + proj, status = LaplaceOptimiser().optimise_approx(fa) + assert status.success + bits = _projection_bits(proj, mu_, x_) + if reference is None: + reference = bits + assert bits == reference + + +def test__finite_difference_hessian_matches_analytic(): + fa, mu_, x_ = make_approx() + opt = LaplaceOptimiser() + state = opt.prepare_state(fa, fa.model_dist) + step = graph.VariableData({mu_: 0.1, x_: 0.2}) + H, shapes = newton.finite_difference_hessian(state, step) + order = [shapes_v for shapes_v in shapes] + assert order == sorted(order, key=lambda v: v.id) + assert np.allclose(H, H.T) + P_ordered = P if order[0] is mu_ else P[::-1, ::-1] + assert np.allclose(-H, P_ordered, atol=1e-10) + # the state passed in is untouched + assert state.parameters is not None and state.hessian is not None + + +def test__line_search_failure_returns_last_dist_untouched(): + fa, mu_, x_ = make_approx() + # stepsize None -> "Line search failed" + opt = LaplaceOptimiser(calc_line_search=lambda state, old_state, **kw: (None, state)) + np.random.seed(0) + proj, status = opt.optimise(fa) + assert not status.success + assert status.flag is StatusFlag.FAILURE + # the mean field handed back is the one passed in, unchanged + assert proj is fa.model_dist + + new_fa, st = fa.project(proj, status=status) + assert new_fa.factor_dist is fa.factor_dist + assert st.updated is False + assert st.flag is StatusFlag.FAILURE + assert any("skipped" in m for m in st.messages) + + +def test__line_search_failure_ep_mean_field_byte_identical(): + from autofit.graphical.expectation_propagation.optimiser import SimplerUpdater + + fa, mu_, x_ = make_approx() + factor = fa.factor + model_approx = graph.EPMeanField.from_approx_dists( + graph.FactorGraph([factor]), + {mu_: NormalMessage(50.0, 10.0), x_: NormalMessage(55.0, 20.0)}, + ) + factor_approx = model_approx.factor_approximation(factor) + before = pickle.dumps(model_approx.factor_mean_field[factor]) + + opt = LaplaceOptimiser(calc_line_search=lambda state, old_state, **kw: (None, state)) + proj, status = opt.optimise(factor_approx) + assert status.flag is StatusFlag.FAILURE + + new_approx, st = SimplerUpdater().update_model_approx( + proj, factor_approx, model_approx, status + ) + assert st.updated is False + assert pickle.dumps(new_approx.factor_mean_field[factor]) == before + + +def test__non_concave_mode_is_bad_projection(): + fa, mu_, x_ = make_approx(convex=True) + # the optimiser would walk off the convex bowl: stop it at the start so the + # Hessian is evaluated there (a successful, NO_CHANGE optimisation) + opt = LaplaceOptimiser(stop_conditions=(lambda *a, **k: (True, "forced stop"),)) + proj, status = opt.optimise(fa) + assert not status.success + assert status.flag is StatusFlag.BAD_PROJECTION + assert status.updated is False + assert any("not concave" in m for m in status.messages) + assert proj is fa.model_dist + + new_fa, st = fa.project(proj, status=status) + assert new_fa.factor_dist is fa.factor_dist + assert st.updated is False + assert st.flag is StatusFlag.BAD_PROJECTION + + +def test__invalid_projection_reverts_variable_and_names_it(): + v, w = Variable("v"), Variable("w") + last = graph.MeanField({v: NormalMessage(0.0, 1.0), w: NormalMessage(0.0, 1.0)}) + # v's projection is wider than its cavity (negative factor precision); + # w's is a valid update + projected = graph.MeanField({v: NormalMessage(0.0, 3.0), w: NormalMessage(1.0, 1.0)}) + cavity = graph.MeanField({v: NormalMessage(0.0, 2.0), w: NormalMessage(0.0, 2.0)}) + factor_dist, status = projected.update_factor_mean_field(cavity, last_dist=last) + assert status.flag is StatusFlag.BAD_PROJECTION + assert not status.success + # per-variable backstop: v reverted to its previous message, w updated + assert status.updated is True + assert factor_dist[v].mean == last[v].mean and factor_dist[v].sigma == last[v].sigma + assert factor_dist[w].sigma == pytest.approx(np.sqrt(1 / (1 - 1 / 4))) + named = [m for m in status.messages if "for v " in m and "precision(q*)" in m] + assert len(named) == 1 + assert "precision(cavity)=0.25" in named[0] + assert not any("for w " in m for m in status.messages) + + +def test__n_refine_zero_is_honoured(): + fa, mu_, x_ = make_approx() + opt = LaplaceOptimiser(hessian="quasi", n_refine=0) + calls = [] + state = opt.prepare_state(fa, fa.model_dist) + + def new_param(): + calls.append(1) + return fa.model_dist.sample() + + refined = opt.refine_state(state, new_param, n_refine=0) + assert refined is state + assert calls == [] + opt.refine_state(state, new_param) + assert len(calls) == 0 + opt3 = LaplaceOptimiser(hessian="quasi", n_refine=3) + opt3.refine_state(state, new_param) + assert len(calls) == 3 + + +def test__quasi_hessian_refinement_chains_secants(): + fa, mu_, x_ = make_approx() + seen = [] + + def spy(state1, state, **kwargs): + seen.append(state.hessian) # B_k the secant is applied to + out = newton.full_diag_update(state1, state, **kwargs) + seen.append(out.hessian) # B_{k+1} + return out + + opt = LaplaceOptimiser(hessian="quasi", n_refine=3, quasi_newton_update=spy) + state = opt.prepare_state(fa, fa.model_dist) + np.random.seed(0) + refined = opt.refine_state(state, fa.model_dist.sample) + assert len(seen) == 6 + # each refinement starts from the previous one's estimate, not the original + assert seen[2] is seen[1] + assert seen[4] is seen[3] + assert refined.hessian is seen[5] + + +def test__hessian_option_validated(): + with pytest.raises(ValueError): + LaplaceOptimiser(hessian="exact") diff --git a/test_autofit/graphical/hierarchical/test_hierarchical.py b/test_autofit/graphical/hierarchical/test_hierarchical.py index 90fe3db20..53a454320 100644 --- a/test_autofit/graphical/hierarchical/test_hierarchical.py +++ b/test_autofit/graphical/hierarchical/test_hierarchical.py @@ -298,12 +298,12 @@ def test_full_hierachical(data): }, ) - # This fits a *marginal* hierarchical EP model whose Laplace refinement draws - # stochastic samples from the global np.random state (n_refine=3 via - # NormalMessage.sample). The fit sits near a convergence boundary, so its - # recovered fixed point (good vs sigma-collapse) depends on the ambient RNG - # state left by whatever ran before — an inherently stochastic test. Seed here - # so the fit is reproducible; this is the pragmatic fix (see PyAutoFit #1352). + # The default Laplace path (`hessian="fd"`, PyAutoFit#1561) draws no random + # numbers: the projected covariance is a finite-difference Hessian at the + # mode, so this fit is deterministic. The seed is kept so that the + # `hessian="quasi"` path (whose `n_refine` refinement samples the global + # np.random state via NormalMessage.sample) stays reproducible if anyone + # switches to it (see PyAutoFit #1352 for the history). np.random.seed(0) laplace = graph.LaplaceOptimiser() From 7ca8ae3392b6868e45eb5e52cd86b2c7dd1d09ac Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Wed, 2 Sep 2026 19:01:58 -0400 Subject: [PATCH 2/2] =?UTF-8?q?docs(graphical):=20README=20=E2=80=94=20Lap?= =?UTF-8?q?lace=20projection=20uses=20the=20Hessian=20at=20the=20mode;=20s?= =?UTF-8?q?kipped=20updates;=20the=20hierarchical-scatter=20caveat=20(#156?= =?UTF-8?q?1)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01C49DeRHoKss4xBnz5F7gUm --- autofit/graphical/README.md | 85 +++++++++++++++++++++++++++++++++++-- 1 file changed, 81 insertions(+), 4 deletions(-) diff --git a/autofit/graphical/README.md b/autofit/graphical/README.md index 2efefe50c..e8b9ec225 100644 --- a/autofit/graphical/README.md +++ b/autofit/graphical/README.md @@ -99,9 +99,22 @@ tilted distribution is then *fitted* by the factor's optimiser: is projected per §3.3. - **Laplace path** (`LaplaceOptimiser`, `graphical/laplace/`): quasi-Newton ascent on `log p̂ₐ` (`newton.py`: BFGS/SR1 with Wolfe - line search, `line_search.py`), then a Gaussian at the optimum with - covariance from the (approximate) Hessian inverse - (`MeanField.from_mode_covariance` via `from_mode` on each message). + line search, `line_search.py`), then a Gaussian at the optimum whose + covariance is the inverse of the **actual Hessian of `log p̂ₐ` at the + mode**, assembled by central finite differences of the tilted gradient + (`newton.finite_difference_hessian`; `hessian="fd"`, the default; step + `fd_step` = 1e-2 × the mean-field std, floored at `fd_min_step`) and + Cholesky-factorised as one full matrix so that the per-variable + marginal blocks of its inverse are exact + (`OptimisationState.inv_hessian_blocks` → `MeanField.from_opt_state` + → `from_mode_covariance`, `from_mode` on each message). If the Hessian + is not finite or not negative-definite at the mode — a boundary mode + such as a scatter driven to zero — the update is *skipped* with + `StatusFlag.BAD_PROJECTION` rather than written. Factors with more + than `hessian_max_size` (default 64) flattened free parameters fall + back, with a log line, to `hessian="quasi"`, which keeps the + pre-2026-09 path (the quasi-Newton diagonal secant, refined at + `n_refine` random draws from the mean field; not deterministic). - **Exact path** (`ExactFactorFit`, `expectation_propagation/factor_optimiser.py`): if the factor is itself a message of the same family as the cavity @@ -181,6 +194,24 @@ every sweep is not going to start working, so after resets on any sweep that does not raise. Every raise is recorded in `ep_history.csv` as an `EXCEPTION` row and logged as a warning. +**Skipped factor update**: an update whose optimiser returned +`success=False` (a failed line search), or whose Hessian at the mode is +not finite or not negative-definite (a boundary mode such as a scatter +driven to zero), is not written back: `optimise_approx` hands back the +mean field it was given, unchanged, and `update_factor_mean_field` then +returns the factor's previous message (`last_dist`) with `updated=False` +and the flag it arrived with — `FAILURE` from the line search, or +`BAD_PROJECTION` with a message naming the factor and the reason from +the Hessian check — plus a "factor update skipped" message. When the +projection succeeds but dividing out the cavity is invalid for *some* +variables (their marginal precision is below the cavity's), only those +variables revert to the previous message (`update_invalid`) and the +status names each of them with both precisions; the others update, so +the step is flagged `BAD_PROJECTION` but still counts as an update. A +skipped update does not count towards `max_consecutive_failures` (only +raises do), but a factor that is skipped on every sweep never updates, +and the **STALE FACTORS** warning covers that case too. + The result is still returned in that state — a partly-failed graph may still hold converged messages worth having — but never quietly. If enough factors raise, *nothing* in the mean field changes, so the KL @@ -188,13 +219,59 @@ step of Eq. (12) is zero and `EPHistory` declares convergence — in practice within two sweeps, before any per-factor count reaches its threshold — and the mean field holds the starting priors for those factors. `run` therefore checks, once the sweeps are over, whether any -factor both raised and never once updated, and emits a **STALE FACTORS** +factor raised or was skipped on every sweep and never once updated, and +emits a **STALE FACTORS** warning naming them: logged, and written into `ep_diagnostics.results` beside the sigma-collapse warnings. Read that file before trusting a mean field from a run that logged failures. A factor that failed intermittently but landed at least one update is not stale and is not reported. +### 3.5 Caveat — a hierarchical *scatter* cannot be projected by its mode + +For a hierarchical factor `N(xᵢ | μ, σ)` the tilted density in `σ` is +proportional to `1/σ` at `xᵢ = μ`: it is unbounded as `σ → 0`, so its +*mode* sits at or near the boundary even when its *mean* does not, and +its posterior is strongly skewed. A mode-based (Laplace) projection of +`σ` therefore has no valid Gaussian to write: before 2026-09 the +secant "covariance" let it write one anyway, collapsing the scatter to +~0 with a tiny error (#1405); with the Hessian at the mode the update is +skipped or reverted instead, so the scatter stays near its prior with +an honest width (closed-form benchmark, seed 0: EP 9.4 ± 3.6 against +the exact 6.6 ± 2.9, inside the exact 5–95 % interval, where it used to +read 2e-4 ± 0). The parent **mean** and the per-dataset variables are +recovered. This is a property of projecting by the mode, not of the +implementation: a hand-rolled EP with the same Gaussian family +reproduces the collapse under a Laplace projection and recovers the +closed form under moment matching +(`autofit_workspace_test/scripts/graphical/analytic_ep_minimal.py`, +autofit_workspace_test#91). + +What to do with it: + +- Trust EP for the parent **mean** and the per-dataset variables; read the + hierarchical **scatter** from a joint sampler over + `factor_graph.global_prior_model` (the `graphical/` pattern) before + quoting it, or wait for a moment-matching projection of the + hierarchical factor. +- Prefer a log-scale parameterisation of the scatter + (`LogGaussianPrior`), whose tilted density is bounded, over a + `GaussianPrior`/`TruncatedGaussianPrior` truncated at zero: it + updates (benchmark: 23 of 25 updates succeed) though it still carries + a bias (log σ 1.53 ± 0.39 vs 1.83 ± 0.36 exact). +- Read `ep_history.csv`: a hierarchical factor with zero `SUCCESS` + updates has returned its prior, whatever the numbers look like; the + STALE FACTORS warning names it. +- The achievable ceiling is not zero even for the right projection: + moment matching of a Gaussian site onto the skewed `σ` posterior + carries a bias of order `|Δmean|/std ≲ 0.08`, `|std/std_ref − 1| ≲ 0.15` + on the closed-form benchmark (seeds 0–4). Judge any EP scatter against + that, not against a sampler's digits. + +The closed-form benchmark and its parity tables are the regression +check for this section: +`autofit_workspace_test/scripts/graphical/analytic_*.py`. + ## 4. Convergence — `EPHistory` (`expectation_propagation/history.py`) After each factor update the history records the new `EPMeanField`.