Skip to content

fix(graphical): Laplace projection uses a real Hessian at the mode; failed updates no longer overwrite the message (EP) #1561

Closed

Description

@Jammy2211

Overview

Found by the analytic Gaussian benchmark (autofit_workspace_test#91 / PR #92) and root-caused read-only: the Laplace projection's "covariance" is not the Hessian of the tilted distribution — it is the mean-field diagonal precision seeded with no factor curvature plus one random diagonal secant that does not accumulate (D2) — and a failed line search still projects the start point and overwrites the factor message (D3). With D1 (#1558) in, the exactly Gaussian leg A still reports mu std 3.76 vs the closed form 4.11 (−8.5 %), 17/40 hierarchical updates BAD_PROJECTION, and the result depends on prior ids through the sampling order. This is the mechanism under the phase-2 scale-collapse prompt and #1405. Third and last fix of the EP campaign's fix wave (D1 #1558 merged → D4/D5 #1559 → D2/D3).

Plan

  • Compute a real Hessian at the converged mode: central finite differences of the (now correct) tilted gradient, assembled in id-sorted order, inverted as a full matrix, marginal blocks projected; non-finite or non-concave Hessians (boundary modes such as σ → 0) return BAD_PROJECTION and skip the update instead of writing a secant guess.
  • Keep the quasi-Newton path as an explicit option (hessian="quasi"), make its refinement accumulate, allow n_refine=0; the default path draws no random numbers.
  • Guard the projection: a projected message narrower than its cavity is a BAD_PROJECTION naming the variable, before any division; a failed optimisation returns the previous message with updated=False (D3), and a factor that never updates is reported stale.
  • Unit tests pin the analytic inverse Hessian to 1e-8 (bit-equal across RNG seeds and variable ids), the skip-on-failure byte-identity, the non-concave case and the guard; existing hierarchical tests are reported, not loosened.
  • Measure the referee: leg A mu std → 4.11 and bit-identical across prior-id orderings, 0 BAD_PROJECTION on leg A; leg B sigma and the collapse-config per-seed verdicts reported (PASS not required — the Laplace-on-scatter bias is the phase-2 caveat).
Detailed implementation plan

Affected Repositories

  • PyAutoFit (primary)

Branch Survey

Repository Current Branch Dirty?
./PyAutoFit main (9eb8085, post-#1560) clean (other claim resampling-info-summary-section is a web session on disjoint files)

Suggested branch: feature/ep-laplace-hessian
Worktree: ~/Code/PyAutoLabs-wt/ep-laplace-hessian/

Implementation Steps

  1. autofit/graphical/laplace/newton.py — new pure finite_difference_hessian(state, step) -> (H, shapes): central FD of state.gradient over free variables sorted by Variable.id, symmetrised.
  2. autofit/graphical/laplace/optimiser.py — LaplaceOptimiser(hessian="fd", fd_step=1e-2 [× model std], fd_min_step=1e-8, hessian_max_size=64, n_refine=3); make_mode_hessian → VariableFullOperator.from_posdef(-H) or (None, reason) on non-finite / non-PD; optimise_approx: return the unchanged mean field on status.success == False; on the fd path set next_state.hessian or return Status(success=False, updated=False, flag=BAD_PROJECTION, message); above hessian_max_size fall back to quasi with a log line; refine_state/refine_approx chain the secants (next_state.update, not state.update) and accept n_refine=0 (is None).
  3. autofit/graphical/mean_field.py — from_opt_state → from_mode_covariance(state.all_parameters, state.inv_hessian_blocks(), state.value) (dense marginal blocks; MatrixOperator.__getitem__ is broken so the blocks path is required); update_factor_mean_field: D3 guard first (not status.success and last_dist is not None → last_dist, updated=False, flag preserved), then _narrower_than_cavity precision guard before the divide (skip FixedMessage and float cavities), existing check_valid/update_invalid branch kept as backstop.
  4. autofit/graphical/expectation_propagation/optimiser.py:398 — gate _factors_updated.add(factor) on status.updated so an always-skipping factor is reported by the stale-factor warning.
  5. Tests: new test_autofit/graphical/functionality/test_laplace_hessian.py (a–d as in the Mind prompt); update the stale n_refine comment in hierarchical/test_hierarchical.py:296-305; add finite_difference_hessian to test_ep_statistics_fixes.py's alive list. pytest test_autofit -q; any moved expectation is reported with before/after numbers, not edited.
  6. Referee from the worktree: analytic_gaussian.py (leg A mu std, BAD_PROJECTION count, bit-identity across K = 1, 3, 6 throwaway priors), analytic_gaussian_priors.py, analytic_gaussian_collapse.py (per-seed verdicts); tables on this issue.

Key Files

  • autofit/graphical/laplace/optimiser.py — make_posdef_hessian, optimise_approx, refine_state
  • autofit/graphical/laplace/newton.py — diag_sr1_update, new finite_difference_hessian
  • autofit/graphical/mean_field.py — from_opt_state, from_mode_covariance, update_factor_mean_field
  • autofit/graphical/laplace/line_search.py — OptimisationState.inv_hessian_blocks, valid
  • autofit/graphical/expectation_propagation/optimiser.py — _factors_updated, _check_consecutive_failures
  • autofit_workspace_test/scripts/graphical/analytic_gaussian*.py — acceptance harness

Original Prompt

Click to expand starting prompt

EP Laplace: the projected "covariance" is not a Hessian, and a failed line search still projects and overwrites the message

Type: bug
Target: PyAutoFit
Repos:

  • PyAutoFit
    Themes:
  • graphical-ep
    Difficulty: medium
    Autonomy: supervised
    Priority: high
    Status: formalised
    Consequence: judge
    Review-minutes: 20
    Unattended: ready
    Epic: graphical-ep
    Filed: 2026-09-02

Two coupled defects (D2 + D3) found by the analytic Gaussian benchmark
(autofit_workspace_test#91). This is the mechanism under the phase-2
scale-collapse prompt
ep_scale_collapse_basin_cure_or_caveat.md and under
PyAutoFit#1405: a wrong per-update variance (D2) that is written back even when the
optimiser did nothing (D3). Requires D1
(ep_prior_id_zero_collides_with_factor_value.md) first — with the D1 gradient
still broken every hierarchical update fails before these paths matter.

Why

With the D1 gradient fixed, leg A (exactly Gaussian graph, Laplace should be
exact) still gives 17/40 hierarchical updates BAD_PROJECTION, and the mu std
depends on which random draw hits it: 3.76 (-8.5%) with refine_state,
4.26 (+3.7%) with it disabled, reference 4.11. Before D1, D3 is what drove
mu's mean field to sigma 20.6 > prior sigma 10 while the optimiser reported
Line search failed, iter=0 on all 90 updates.

D2 — the Laplace covariance is the mean-field precision plus one random diagonal secant

  • make_posdef_hessian (autofit/graphical/laplace/optimiser.py:14-15) seeds the
    Hessian with MeanField.precision of the model_dist — the factor's own old
    message included, no factor curvature at all. When the start is already the
    mode (gradient 0 -> NO_CHANGE) no quasi-Newton step ever touches it.

  • refine_state (optimiser.py:138-146) then applies diag_sr1_update
    (newton.py:60-76) at n_refine=3 random samples of mean_field.sample().
    state.update(...) copies the original Hessian each time and
    diag_sr1_update writes state1.hessian = Bk.diagonalupdate(...) from that
    original, so the refinements do not accumulate — only the last sample counts.
    For the exact tilted precision [[0.02, -0.01], [-0.01, 0.0125]] the diagonal
    secant is indefinite in sign, so the projected variance routinely exceeds the
    cavity variance -> q*/cavity invalid -> BAD_PROJECTION (mean_field.py:494-515).

  • Prior-id dependence: MeanField.sample draws np.random in dict order, and that
    order comes from factor.all_variables sets hashed by id
    (EPMeanField.from_approx_dists, ep_mean_field.py:180-183), so which variable
    consumes which draw changes with prior ids. Leg A with K throwaway priors
    created before the graph:

    K=0 (ids 0-5) mu 50.00 +/- 20.65 (D1), x_2 b 0.000; K=1 (ids 1-6) 50.8596 +/- 3.7599, b 0.018;
    K=3 (ids 3-8) 50.8596 +/- 4.0943, b 0.331; K=6 (ids 6-11) 50.8595 +/- 3.7466, b 0.004;
    K=1,3,6 with refine_state disabled: 50.8597 +/- 4.2627 identical to every digit, b 0.001.
    n_refine=0 cannot be requested (n_refine or self.n_refine, optimiser.py:140).

D3 — a failed line search still projects the start point as the mode

optimise_approx (laplace/optimiser.py:130-135) takes max(state, next_state)
— the start when the search failed — and projects it;
update_factor_mean_field (mean_field.py:478-517) never consults
status.success, so a FAILURE update replaces the message with
N(old mean, secant variance) / cavity. This is how mu's mean field drifted to
sigma 20.6 > prior 10 under D1. The exception branch at :519-521 already returns
last_dist with updated=False; the failed-search branch should do the same.

Minimal repro (after the D1 setup in the sibling prompt)

np.random.seed(0)
proj, status = af.LaplaceOptimiser().optimise(fa)          # fa: the hierarchical FactorApproximation
_, st = proj.update_factor_mean_field(fa.cavity_dist, fa.factor_dist, status=status)
print(status.flag, "->", st.flag)   # NO_CHANGE (iter=0) -> BAD_PROJECTION
# q* sigma {mu: 11.559, x: 72.995} vs cavity (10, 20): the "Hessian" is the mean-field precision
# plus one random diagonal secant, never the tilted curvature

Fix sketch

  1. At the converged mode compute a real Hessian: finite-difference the (now
    correct, post-D1) gradient, or use the messages' analytic
    _normal_gradient_hessian plus the factor's numerical Hessian. Invert the full
    matrix and project the marginal variances.
  2. Make refine_state accumulate across samples, or drop it once a real Hessian
    exists; allow n_refine=0.
  3. Guard the projection: require precision(q*) >= precision(cavity) per variable
    before dividing, and flag otherwise (a real BAD_PROJECTION, not a secant
    artefact).
  4. On status.success == False return last_dist with updated=False, mirroring
    the exception branch.

Finding for the phase-2 "caveat" half — state it, do not re-derive it

The benchmark's minimal EP (analytic_ep_minimal.py) reproduces the scale
collapse deterministically under a mode-based (Laplace) projection on sigma:
the tilted density is proportional to 1/sigma at x_i = mu, so its mode sits at
the boundary and the projected message shrinks on every sweep. Moment matching in
the same script passes every cell. A Laplace projection of the scatter therefore
cannot be made exact; the fix above (real Hessian + precision guard) makes leg A
exact and stops the leg-B churn, but the cure for the scatter is moment
matching or a log-sigma parameterisation
. That is the "caveat" deliverable of
ep_scale_collapse_basin_cure_or_caveat.md, and it is now writable from this
evidence.

Acceptance

  • Unit tests: (a) on a two-variable Gaussian factor with known tilted precision,
    the projected covariance equals the analytic inverse Hessian to 1e-8 and is
    independent of np.random state and of prior ids; (b) a forced line-search
    failure returns the unchanged last_dist with updated=False and the mean
    field is byte-identical before and after the update.
  • autofit_workspace_test/scripts/graphical/analytic_gaussian.py, leg A,
    "closed form vs autofit EP": the mu cell PASS with std within tolerance of
    4.11 (currently 3.76 / 4.09 / 3.75 / 4.26 depending on K), and the result is
    identical to every digit across K = 1, 3, 6; ep_history.csv shows 0
    BAD_PROJECTION for the hierarchical factor on leg A.
  • analytic_gaussian.py leg B sigma row and analytic_gaussian_collapse.py
    per-seed verdicts: report the after-numbers; PASS is not required here (the
    finding above says Laplace on sigma stays biased), but "documented collapse"
    must replace every "SILENT" verdict.

Links

Activity

  1. Jammy2211 commented on Sep 2, 2026

    @Jammy2211
    CollaboratorAuthor

    Library PR Created

    PR: #1562 (feature/ep-laplace-hessian, label pending-release)

    API summary: LaplaceOptimiser gains keyword arguments hessian="fd"|"quasi" (default "fd"), fd_step=1e-2 (× model std), fd_min_step=1e-8, hessian_max_size=64; n_refine now accepts 0. Default Laplace projections change numerically (they are now the inverse Hessian at the mode) and are deterministic — no np.random draw on the default path. Failed or non-concave updates return the previous message with updated=False instead of overwriting it; MeanField.from_opt_state projects through inv_hessian_blocks(). New public helper autofit.graphical.laplace.newton.finite_difference_hessian. Workspace/tutorial prose numbers produced by Laplace EP (autofit_workspace features/expectation_propagation.py, HowToFit chapter 3 EP tutorials) may shift; no signature they use changes.

    Next: no linked workspace edit is required — the referee scripts in autofit_workspace_test are unchanged; the phase-2 close-out (un-parking and the cure decision) follows as its own workspace task.

  2. added a commit that references this issue on Sep 2, 2026
  3. Jammy2211 commented on Sep 2, 2026

    @Jammy2211
    CollaboratorAuthor

    Shipped

    PR #1562 — merged 5375f4d631547bc946687cf3645d3689654e510d (CI green: unittest 3.12 / 3.13 / nojax, docs).

    What changed

    • D2 — the Laplace projection now uses a central finite-difference Hessian of the tilted gradient at the mode (LaplaceOptimiser(hessian="fd"), the default; Cholesky-factorised as a full matrix, marginal blocks via inv_hessian_blocks()); the default path draws no random numbers. hessian="quasi" keeps the old path (secants chained, n_refine=0 allowed); factors above hessian_max_size=64 fall back to it.
    • D3 — failed line searches and non-finite / non-concave Hessians skip the update instead of writing it: the previous message is returned with updated=False and the flag preserved. The per-variable check_valid/update_invalid backstop is kept and now names each reverted variable with precision(q*) and precision(cavity). The STALE FACTORS warning now covers always-skipped factors as well as raising ones.
    • autofit/graphical/README.md: §3.2 / §3.4 describe the shipped behaviour; new §3.5 documents the hierarchical-scatter caveat (a mode-based projection of σ has no valid Gaussian to write).

    Evidence

    • pytest test_autofit: 2440 passed, 2 skipped (new test_laplace_hessian.py, 10).
    • Referee leg A 18/18 PASS and byte-identical across prior ids (K = 1, 3, 6); collapse configuration RECOVER 5/5 seeds; leg B sigma 9.37 ± 3.57 inside the exact interval, mu PASS.

    Closing as completed. Phase-2 close-out (un-parking the autofit parity scripts and the moment-matching cure decision) follows as its own workspace task.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions