Repository navigation
Description
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, allown_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
mustd → 4.11 and bit-identical across prior-id orderings, 0 BAD_PROJECTION on leg A; leg Bsigmaand 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
autofit/graphical/laplace/newton.py— new purefinite_difference_hessian(state, step) -> (H, shapes): central FD ofstate.gradientover free variables sorted byVariable.id, symmetrised.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 onstatus.success == False; on thefdpath setnext_state.hessianor returnStatus(success=False, updated=False, flag=BAD_PROJECTION, message); abovehessian_max_sizefall back toquasiwith a log line;refine_state/refine_approxchain the secants (next_state.update, notstate.update) and acceptn_refine=0(is None).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_cavityprecision guard before the divide (skipFixedMessageand float cavities), existingcheck_valid/update_invalidbranch kept as backstop.autofit/graphical/expectation_propagation/optimiser.py:398— gate_factors_updated.add(factor)onstatus.updatedso an always-skipping factor is reported by the stale-factor warning.- Tests: new
test_autofit/graphical/functionality/test_laplace_hessian.py(a–d as in the Mind prompt); update the stalen_refinecomment inhierarchical/test_hierarchical.py:296-305; addfinite_difference_hessiantotest_ep_statistics_fixes.py's alive list.pytest test_autofit -q; any moved expectation is reported with before/after numbers, not edited. - Referee from the worktree:
analytic_gaussian.py(leg Amustd, 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_stateautofit/graphical/laplace/newton.py—diag_sr1_update, newfinite_difference_hessianautofit/graphical/mean_field.py—from_opt_state,from_mode_covariance,update_factor_mean_fieldautofit/graphical/laplace/line_search.py—OptimisationState.inv_hessian_blocks,validautofit/graphical/expectation_propagation/optimiser.py—_factors_updated,_check_consecutive_failuresautofit_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 withMeanField.precisionof themodel_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 appliesdiag_sr1_update
(newton.py:60-76) atn_refine=3random samples ofmean_field.sample().
state.update(...)copies the original Hessian each time and
diag_sr1_updatewritesstate1.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.sampledrawsnp.randomin dict order, and that
order comes fromfactor.all_variablessets 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 withrefine_statedisabled: 50.8597 +/- 4.2627 identical to every digit, b 0.001.
n_refine=0cannot 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 curvatureFix sketch
- At the converged mode compute a real Hessian: finite-difference the (now
correct, post-D1) gradient, or use the messages' analytic
_normal_gradient_hessianplus the factor's numerical Hessian. Invert the full
matrix and project the marginal variances. - Make
refine_stateaccumulate across samples, or drop it once a real Hessian
exists; allown_refine=0. - Guard the projection: require
precision(q*) >= precision(cavity)per variable
before dividing, and flag otherwise (a real BAD_PROJECTION, not a secant
artefact). - On
status.success == Falsereturnlast_distwithupdated=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 ofnp.randomstate and of prior ids; (b) a forced line-search
failure returns the unchangedlast_distwithupdated=Falseand 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": themucell 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.csvshows 0
BAD_PROJECTION for the hierarchical factor on leg A.analytic_gaussian.pyleg Bsigmarow andanalytic_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
- autofit_workspace_test#91 — test(graphical): analytic Gaussian benchmark — closed form vs minimal EP vs autofit EP/graphical autofit_workspace_test#91
- PyAutoFit#1405 (umbrella symptom) — Hierarchical EP: parent scale hyperparameter collapses to ~0 with over-confident error (+ init-crash) #1405;
adjacent: research: EP review phase 1 — statistics audit of autofit/graphical #1332 F8/F10 - Campaign ledger:
draft/research/graphical_ep/ep_campaign.md(phases 1-2) - Phase 2 prompt:
draft/bug/autofit/ep_scale_collapse_basin_cure_or_caveat.md - Siblings (same dir):
ep_prior_id_zero_collides_with_factor_value.md(done —complete/2026/09/ep-prior-id-zero.md, PyAutoFit#1558 merged 2026-09-02),
ep_message_support_and_transform_lost_in_projection.md,samples_errors_at_sigma_instance_prior_valued_model.md - Scripts:
autofit_workspace_test/scripts/graphical/analytic_{reference,ep_minimal,autofit,gaussian,gaussian_priors,gaussian_collapse}.py
on branchfeature/analytic-gaussian-benchmark
Activity
Jammy2211 commentedon Sep 2, 2026
Library PR Created
PR: #1562 (
feature/ep-laplace-hessian, labelpending-release)API summary:
LaplaceOptimisergains keyword argumentshessian="fd"|"quasi"(default"fd"),fd_step=1e-2(× model std),fd_min_step=1e-8,hessian_max_size=64;n_refinenow accepts0. Default Laplace projections change numerically (they are now the inverse Hessian at the mode) and are deterministic — nonp.randomdraw on the default path. Failed or non-concave updates return the previous message withupdated=Falseinstead of overwriting it;MeanField.from_opt_stateprojects throughinv_hessian_blocks(). New public helperautofit.graphical.laplace.newton.finite_difference_hessian. Workspace/tutorial prose numbers produced by Laplace EP (autofit_workspacefeatures/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.
Merge pull request #1562 from PyAutoLabs/feature/ep-laplace-hessian
Jammy2211 commentedon Sep 2, 2026
Shipped
PR #1562 — merged
5375f4d631547bc946687cf3645d3689654e510d(CI green: unittest 3.12 / 3.13 / nojax, docs).What changed
LaplaceOptimiser(hessian="fd"), the default; Cholesky-factorised as a full matrix, marginal blocks viainv_hessian_blocks()); the default path draws no random numbers.hessian="quasi"keeps the old path (secants chained,n_refine=0allowed); factors abovehessian_max_size=64fall back to it.updated=Falseand the flag preserved. The per-variablecheck_valid/update_invalidbackstop 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 (newtest_laplace_hessian.py, 10).sigma9.37 ± 3.57 inside the exact interval,muPASS.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.