Skip to content

Hierarchical EP: parent scale hyperparameter collapses to ~0 with over-confident error (+ init-crash) #1405

Open

Description

@Jammy2211

Summary

A hierarchical EP fit of a parent scale hyperparameter (the sigma of a
HierarchicalFactor parent Gaussian) is unstable: repeated fits of an identical,
known-answer
problem land in three qualitatively different outcomes. On a clean CPU toy
(no JAX, no lensing, parent scatter truth σ=10 — far from the σ→0 boundary):

outcome freq parent scatter (truth 10)
RECOVER ~70% 9–13, sane errors; matches a joint nested-sampler fit
COLLAPSE ~7% 0.003–0.80 with an over-confident ~0 error
CRASH ~23% InitializerException hard-aborts mid-EP

Measured over 30 identical-problem runs across max_steps ∈ {20,25,30,50,60}:
21 RECOVER / 2 COLLAPSE / 7 CRASH. Both COLLAPSEs were at the shortest setting
(max_steps=20); none at 25–60. CRASH appears at every max_steps.

The joint fit — Dynesty on factor_graph.global_prior_model for the same graph — is
stable and correct every run (scatter 12.8 [9.9, 16.3]). The graph and data are fine; EP
is the sole source of the instability.
This is on main including the #1383 projection
fix — it is a distinct, deeper issue.

The COLLAPSE outcome is the exact readout that a downstream hierarchical science fit hit
(parent scatter 4–12× too low, errors ~1000× too tight); this toy shows it is a framework
property, reproduced off-boundary and off-lensing.

Two distinct defects

1. Scale-hyperparameter COLLAPSE (over-shrinkage basin). When it collapses, the
per-group drawn-variable posterior means cluster far tighter than truth (spread ~0.6 vs
true ~±10); the parent factor then sees near-identical draws and infers a tiny scatter,
tightening the shrinkage further — positive feedback to a fixed point at scatter ≈ 0 with
~0 reported error. Not a delta-method/boundary artefact: truth σ=10, the base-space
scatter message is unbounded (TruncatedNormal(mean≈0, lower=-inf, upper=inf)), so
TransformedMessage.variance faithfully reads a genuinely over-confident posterior.
ep_history.csv shows recurring BAD_PROJECTION on the HierarchicalFactor and wildly
swinging log-evidence during collapse. The F10 sigma-collapse guard does not flag it.

2. InitializerException CRASH. ~1-in-4 runs hard-abort when EP drives a factor to a
degenerate all-equal-likelihood state its per-factor DynestyStatic cannot initialise
(autofit/non_linear/initializer.py:185). Should degrade to a flagged BAD_PROJECTION /
skipped update, not kill the whole fit.

Triage questions

  • Is COLLAPSE curable by a more robust / damped HierarchicalFactor scale
    moment-match
    (or a deterministic per-factor optimiser to cut the sampler noise that
    drives basin selection)? Note: naive damping (delta=0.5) made a real downstream fit
    worse — the standing "consider damping, delta < 1" diagnostics hint likely
    mis-diagnoses this mode.
  • Should the F10 sigma-collapse guard fire on a scatter≈0 / error≈0 parent? It
    currently passes silently.
  • Should the InitializerException be caught inside the EP loop and recorded as a bad
    projection rather than aborting the fit?

Minimal repro

Self-contained, numpy-only, runs from the HowToFit repo root in minutes on CPU. Builds
the HowToFit chapter-3 hierarchical toy (5 low-SNR 1-D Gaussians, centre ~ N(50, 10)),
runs EP and a joint Dynesty fit on the same graph, prints an OUTCOME: tag. Loop it ~10×
at TOY_MAX_STEPS=20 to see the recover/collapse/crash split.

ep_toy_diagnostic.py
"""
Toy hierarchical EP diagnostic
==============================

Cheap CPU reproduction of the slope_hierarchy goal-2 pathology:
EP recovers the parent MEAN but reports a parent SCATTER that is too low with
error bars that are orders-of-magnitude too tight.

Known-answer toy (HowToFit chapter 3 hierarchical dataset):
  - N Gaussians, each centre drawn from parent N(mean=50, sigma=10)
  - TRUE parent mean   = 50.0
  - TRUE parent scatter= 10.0   <-- FAR from the sigma->0 boundary (the key contrast
                                     with slope_hierarchy whose truth was 0.1)
  - per-Gaussian normalization = 0.5, sigma = 5.0 (fixed at truth to keep the joint
    nested-sampler fit cheap and to isolate the parent-scatter question)

Run from the HowToFit repo root.
"""
import os
import sys
import numpy as np
from os import path

import autofit as af
from autofit.graphical import mean_field_summary, check_sigma_collapse

# ---- config ---------------------------------------------------------------
TOTAL_DATASETS = int(os.environ.get("TOY_N", "5"))
MAX_STEPS = int(os.environ.get("TOY_MAX_STEPS", "20"))
RUN_JOINT = os.environ.get("TOY_JOINT", "1") == "1"
OUT_TAG = os.environ.get("TOY_TAG", f"ep_toy_n{TOTAL_DATASETS}_s{MAX_STEPS}")

TRUE_MEAN = 50.0
TRUE_SCATTER = 10.0

print(f"=== TOY EP DIAGNOSTIC  N={TOTAL_DATASETS}  max_steps={MAX_STEPS} ===")
print(f"TRUE parent: mean={TRUE_MEAN}  scatter={TRUE_SCATTER}")

# ---- data -----------------------------------------------------------------
data_list, noise_map_list = [], []
for i in range(TOTAL_DATASETS):
    dp = path.join("dataset", "example_1d", "gaussian_x1__hierarchical", f"dataset_{i}")
    data_list.append(af.util.numpy_array_from_json(file_path=path.join(dp, "data.json")))
    noise_map_list.append(af.util.numpy_array_from_json(file_path=path.join(dp, "noise_map.json")))

analysis_list = [af.ex.Analysis(data=d, noise_map=n) for d, n in zip(data_list, noise_map_list)]

# ---- per-dataset models: only `centre` free (nuisances fixed at truth) -----
model_list = []
for _ in range(TOTAL_DATASETS):
    g = af.Model(af.ex.Gaussian)
    g.centre = af.TruncatedGaussianPrior(mean=50.0, sigma=20.0, lower_limit=0.0, upper_limit=100.0)
    g.normalization = 0.5
    g.sigma = 5.0
    model_list.append(g)

# ---- EP fit ---------------------------------------------------------------
dynesty = af.DynestyStatic(nlive=100, sample="rwalk")
analysis_factor_list = [
    af.AnalysisFactor(prior_model=m, analysis=a, optimiser=dynesty, name=f"dataset_{i}")
    for i, (m, a) in enumerate(zip(model_list, analysis_list))
]

hierarchical_factor = af.HierarchicalFactor(
    af.GaussianPrior,
    mean=af.TruncatedGaussianPrior(mean=50.0, sigma=10.0, lower_limit=0.0, upper_limit=100.0),
    sigma=af.TruncatedGaussianPrior(mean=10.0, sigma=5.0, lower_limit=0.0, upper_limit=100.0),
)
for m in model_list:
    hierarchical_factor.add_drawn_variable(m.centre)

factor_graph = af.FactorGraphModel(*analysis_factor_list, hierarchical_factor)

laplace = af.LaplaceOptimiser()
try:
    ep_result = factor_graph.optimise(
        laplace,
        paths=af.DirectoryPaths(name=path.join("ep_toy_diagnostic", OUT_TAG)),
        ep_history=af.EPHistory(kl_tol=0.05),
        max_steps=MAX_STEPS,
    )
except Exception as e:
    print(f"\nOUTCOME: CRASH  ({type(e).__name__}: {str(e).splitlines()[0][:80]})")
    print("DONE-SENTINEL")
    sys.exit(0)

mean_field = ep_result.updated_ep_mean_field.mean_field
ep_mean = mean_field.mean[hierarchical_factor.mean]
ep_mean_err = float(np.sqrt(mean_field.variance[hierarchical_factor.mean]))
ep_sigma = mean_field.mean[hierarchical_factor.sigma]
ep_sigma_err = float(np.sqrt(mean_field.variance[hierarchical_factor.sigma]))

print("\n================ EP RESULT ================")
print(f"parent mean    : {ep_mean:.4f} +/- {ep_mean_err:.4g}   (truth {TRUE_MEAN})")
print(f"parent scatter : {ep_sigma:.4f} +/- {ep_sigma_err:.4g}   (truth {TRUE_SCATTER})")
# outcome tag: COLLAPSE if scatter << truth, else RECOVER
_tag = "COLLAPSE" if ep_sigma < 0.4 * TRUE_SCATTER else "RECOVER"
print(f"OUTCOME: {_tag}  scatter={ep_sigma:.4f}  err={ep_sigma_err:.4f}  mean={ep_mean:.3f}")
print("\n--- mean_field_summary ---")
try:
    print(mean_field_summary(mean_field))
except Exception as e:
    print("mean_field_summary failed:", e)
print("\n--- check_sigma_collapse ---")
try:
    print(check_sigma_collapse(mean_field))
except Exception as e:
    print("check_sigma_collapse failed:", e)

# base-space (untransformed) sigma message: is it near the sigma->0 boundary?
try:
    base_msg = mean_field[hierarchical_factor.sigma]
    print("\n--- parent-sigma message (base space) ---")
    print("  repr:", repr(base_msg))
    for attr in ("mean", "sigma", "scale", "variance", "natural_parameters"):
        v = getattr(base_msg, attr, None)
        if callable(v):
            try:
                v = v()
            except Exception:
                continue
        if v is not None:
            print(f"  {attr}: {v}")
except Exception as e:
    print("base sigma message introspection failed:", e)

# ---- JOINT nested-sampler fit of the SAME graph ---------------------------
def weighted_percentiles(values, weights, qs=(0.16, 0.5, 0.84)):
    order = np.argsort(values)
    v = np.asarray(values)[order]
    w = np.asarray(weights)[order]
    cw = np.cumsum(w)
    cw = cw / cw[-1]
    return np.interp(qs, cw, v)

if RUN_JOINT:
    print("\n================ JOINT NESTED-SAMPLER FIT (SAME graph) ================")
    joint_model = factor_graph.global_prior_model
    print("joint dims (prior_count):", joint_model.prior_count)
    search = af.DynestyStatic(
        name=path.join("ep_toy_diagnostic", OUT_TAG + "_joint"),
        nlive=150,
        sample="rwalk",
    )
    joint_result = search.fit(model=joint_model, analysis=factor_graph)
    samples = joint_result.samples

    ordered = samples.model.priors_ordered_by_id
    params = np.array(samples.parameter_lists)
    weights = np.array(samples.weight_list)

    def marg(prior):
        col = [i for i, p in enumerate(ordered) if p.id == prior.id][0]
        lo, med, hi = weighted_percentiles(params[:, col], weights)
        return med, lo, hi

    jm_med, jm_lo, jm_hi = marg(hierarchical_factor.mean)
    js_med, js_lo, js_hi = marg(hierarchical_factor.sigma)
    print("\n---------------- JOINT RESULT (percentile 16/50/84) ----------------")
    print(f"parent mean    : {jm_med:.4f}  [{jm_lo:.4f}, {jm_hi:.4f}]   (truth {TRUE_MEAN})")
    print(f"parent scatter : {js_med:.4f}  [{js_lo:.4f}, {js_hi:.4f}]   (truth {TRUE_SCATTER})")

    # ---- side-by-side verdict table ----
    print("\n================ EP vs JOINT ================")
    print(f"{'param':10s} {'truth':>7s} {'EP':>22s} {'JOINT':>26s}")
    print(f"{'mean':10s} {TRUE_MEAN:7.2f} {ep_mean:8.4f}+/-{ep_mean_err:<10.3g} "
          f"{jm_med:8.4f} [{jm_lo:.3f},{jm_hi:.3f}]")
    print(f"{'scatter':10s} {TRUE_SCATTER:7.2f} {ep_sigma:8.4f}+/-{ep_sigma_err:<10.3g} "
          f"{js_med:8.4f} [{js_lo:.3f},{js_hi:.3f}]")
    joint_sigma_err = 0.5 * (js_hi - js_lo)
    ratio = joint_sigma_err / ep_sigma_err if ep_sigma_err > 0 else float("inf")
    print(f"\nscatter error ratio JOINT/EP = {ratio:.1f}x  "
          f"(EP err {ep_sigma_err:.4g}  vs  JOINT half-CI {joint_sigma_err:.4g})")

print("\nDONE-SENTINEL")
cd HowToFit
export NUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib PYAUTO_SKIP_VISUALIZATION=1
for r in $(seq 1 10); do TOY_MAX_STEPS=20 TOY_JOINT=0 TOY_TAG=rep_$r \
  python3 ep_toy_diagnostic.py 2>/dev/null | grep OUTCOME; done

Activity

  1. Jammy2211 commented on Jul 22, 2026

    @Jammy2211
    CollaboratorAuthor

    Diagnostic task wrapped up — this report is final; fix work is split into two follow-ups

    The investigation that produced this report is closed out (report-only: PyAutoFit was
    exercised, not edited). Nothing here is waiting on more diagnosis — the two defects are
    characterised as far as a black-box study can take them, and the fix work is now split so
    the easy half isn't blocked behind the hard one.

    Follow-up 1 — InitializerException should not kill the fit (small, safe, do first)

    Pure robustness, no statistical judgment: catch it at the per-factor update site and record
    a flagged bad projection so the sweep continues. It is 23% of runs — the single most common
    non-recovery outcome — and fixing it makes the harder work cheaper, since gathering
    statistics over repeated identical fits currently loses ~1 run in 4. Watch two things: keep
    it loud (flagged in ep_history.csv, never silent), and add a consecutive-failure
    threshold so a factor that never initialises aborts with a message naming it rather than
    converging on a stale message and reporting success.

    Follow-up 2 — the scale-collapse basin (medium, supervised)

    Ordered deliberately: make F10 fire before attacking the basin. A guard that flags a
    collapsed parent is independently shippable and is the part that actually protects users;
    curing the basin is the stretch goal. The acceptance bar is "a collapsed scale is never
    silently reported as a confident answer"
    , not "collapse never happens".

    Three notes carried over so they aren't rediscovered the hard way:

    • Do not reach for damping. The diagnostics' standing hint "consider damping, delta < 1"
      is counterproductive on this mode — delta=0.5 on the science case gave full collapse, 67
      BAD_PROJECTION, log-evidence to 5e7. That hint needs revising alongside whatever the real
      fix is.
    • "Run longer" is not the fix either. The science case converged to a stable wrong
      fixed point (0.026 vs truth 0.1) and plateaued.
    • One run proves nothing. Collapse is ~7% per run, so any "fixed it" claim needs a loop.

    Repro has moved (the prompt was folded into its completion record):
    PyAutoMind/complete/2026/07/ep_scale_collapse_assets/ — ep_toy_diagnostic.py and
    EP_TOY_FINDINGS.md. Still self-contained, numpy-only, minutes on CPU from the HowToFit
    repo root.

    Leaving this issue open as the umbrella for both defects.

  2. Jammy2211 commented on Aug 5, 2026

    @Jammy2211
    CollaboratorAuthor

    Defect 2 (InitializerException) reproduced on the release leg — and it is not hierarchical-specific

    Recording a second sighting here rather than opening a new issue: the 2026-08-03 nightly release-fidelity leg hit this defect, and the run adds three things worth having before follow-up 1 is started.

    The sighting. PyAutoHeart run 30788224561, job 91606145038 (integrate / run_scripts (3.12, autofit_test, graphical)), against 2026.8.3.1.dev69801 wheels:

    Found 8 scripts
      scripts/graphical/ep.py ...              FAIL (11.4s)
          - The`log_likelihood_function`  is always returning `nan` values.
      scripts/graphical/ep_deterministic.py ...   PASS (1.5s)
      scripts/graphical/ep_exact.py ...           PASS (1.2s)
      scripts/graphical/ep_parity.py ...          PASS (7.4s)
      scripts/graphical/hierarchical.py ...       PASS (5.3s)
      scripts/graphical/shared_state.py ...       PASS (5.2s)
      scripts/graphical/simultaneous.py ...       PASS (4.8s)
    

    1. The nan in the message is a red herring — this is the all-equal-FoM crash

    That text is the InitializerException body, not a nan diagnosis. The guard that raises it is

    if total_points > 1 and np.allclose(a=figures_of_merit_list[0], b=figures_of_merit_list[1:]):

    and np.allclose defaults to equal_nan=False, so an all-nan figure-of-merit list returns False and cannot raise this exception (checked on numpy 2.4.6: np.allclose(np.nan, [np.nan, np.nan]) is False). The condition actually detected is all-equal, finite likelihoods — defect 2 as characterised above, nothing new.

    The wording is worth correcting while follow-up 1 is open: it listed a cause that is impossible for the check, and that cost one round of misdiagnosis downstream (the failure was first written up as an all-nan likelihood bug). Both raise sites carry the same text — samples_from_model (~line 117/120) and samples_jax (~line 182/185); the release profile runs PYAUTO_DISABLE_JAX=0, so the JAX path is live in the leg that caught this.

    2. It is not a HierarchicalFactor property

    The toy that characterised defect 2 is hierarchical, but scripts/graphical/ep.py has no HierarchicalFactor. It shares one centre prior — af.GaussianPrior(mean=50.0, sigma=30.0) — across two AnalysisFactors, each with its own DynestyStatic(nlive=300, maxcall=1000, maxiter=1000), under a LaplaceOptimiser. Meanwhile hierarchical.py passed in the same shard, same wheels, same run.

    So the degenerate all-equal-FoM state is reachable through ordinary shared-prior message passing. Follow-up 1's catch site and its regression test should be scoped to the per-factor update in general, and the test should cover a plain shared-prior graph rather than only a hierarchical one.

    3. Intermittent here too, and release-profile-only

    The shard passed the following night with no change to ep.py — consistent with the ~23%-per-run rate rather than a regression against those wheels. And the per-PR smoke gate runs PYAUTO_TEST_MODE=2, which bypasses the sampler and so never reaches the initializer: this defect can only surface on the release leg (PYAUTO_TEST_MODE=0, config/build/profile_release.yaml). Reproduce with:

    python3 <path>/PyAutoHands/autohands/run_python.py \
      autofit_test scripts/graphical \
      --env-config config/build/profile_release.yaml

    One caveat on the "mid-EP" reading

    That the fit dies after EP has driven a factor into the degenerate state (rather than being degenerate from the first sweep) is inference from the 11.4s runtime against 1.2–7.4s for the siblings, not something the log states. The run artifact that would settle it is behind a network policy I can't reach from here. It matches the mechanism already established above, but treat the sweep index as unconfirmed.

    No new issue filed — this stays folded into follow-up 1, whose PyAutoMind prompt now carries the release-leg evidence. One note carried over from the report that produced it: degrading this crash to a skipped update will turn a red release-leg script green while EP still degenerates underneath, so the "keep it loud" requirement above isn't just hygiene — it is what stops ep.py passes now from quietly meaning EP still fails every fourth run.


    Generated by Claude Code

  3. added 2 commits that reference this issue on Aug 5, 2026
  4. Jammy2211 commented on Sep 2, 2026

    @Jammy2211
    CollaboratorAuthor

    Mechanisms found by the analytic Gaussian benchmark (autofit_workspace_test#91)

    The conjugate benchmark (PyAutoLabs/autofit_workspace_test#91; evidence in phase (a) and phase (b)) isolates six PyAutoFit defects. D1-D4 are the mechanisms under this issue's symptoms (untruncated messages, BAD_PROJECTION churn, parent scale drifting/collapsing). Each is now carried by a PyAutoMind prompt under draft/bug/autofit/.

    D1 — prior id 0 collides with FactorValue. Variable.__init__ gives FactorValue id 0 / hash 0 (autofit/mapper/variable.py:99-100, 142-149) and Prior.__eq__ / __hash__ compare ids with no type check (autofit/mapper/prior/abstract.py:249-259), so the first prior of a process == FactorValue. AbstractJacobian.grad (factor_graphs/jacobians.py:97-99) then merges the cavity gradient into the VJP seed and prior-0's entry overwrites the FactorValue slot. Measured at (mu=48, x=55): gradient (0.0214, -0.0139) vs finite differences (0.0900, -0.0825); one-variable factors unaffected. Leg A: mu 50.0000 +/- 20.6457 (ref 50.8595 +/- 4.11), 54 BAD_PROJECTION / 36 FAILURE, no SUCCESS; patching to fjac.grad() + grad_cavity gives 50.8596 +/- 3.76. -> ep_prior_id_zero_collides_with_factor_value.md

    D2 — the Laplace "covariance" is not a Hessian. make_posdef_hessian (graphical/laplace/optimiser.py:14-15) seeds from MeanField.precision (old message included, no factor curvature); refine_state (optimiser.py:138-146) applies diag_sr1_update (newton.py:60-76) at 3 random samples but the updates do not accumulate, so one random diagonal secant is the "curvature". For the exact tilted precision [[0.02,-0.01],[-0.01,0.0125]] it is indefinite in sign -> var(q*) > var(cavity) -> BAD_PROJECTION (17/40 hierarchical updates even with D1 fixed). The result depends on prior ids through MeanField.sample dict order: mu std 3.76 / 4.09 / 3.75 for K=1/3/6 throwaway priors, 4.26 with refinement off (ref 4.11). -> ep_laplace_covariance_and_failed_update_projection.md

    D3 — a failed line search still projects and overwrites. optimise_approx (laplace/optimiser.py:130-135) projects max(state, next_state) — the start point on failure — and update_factor_mean_field (graphical/mean_field.py:478-517) never reads status.success, so a FAILURE replaces the message with N(old mean, secant variance)/cavity. This is how mu's mean field reached sigma 20.6 > prior sigma 10. -> same prompt as D2

    D4 — truncation limits dropped by every natural-parameter operation. __pow__ and _multiply/_divide -> from_natural_parameters (messages/abstract.py:173-178, 225-234) rebuild via TruncatedNormalMessage.invert_natural_parameters (truncated_normal.py:210), which returns only (mean, sigma); the loss happens at prior.message ** (1/(count-1)) in declarative/abstract.py:82-94, so the leg-B mean field is untruncated from step one. Leg B truncated(10,5,0,100): sigma 3.7348 +/- 0.7527 vs closed form 6.5667 +/- 2.8832, returned limits (-inf, inf); other process histories collapse to sigma ~1e-4. -> ep_message_support_and_transform_lost_in_projection.md

    D5 — TransformedMessage.from_mode skips the Jacobian for scalars. composed_transform.py:406-407 guards on covariance.shape != (); MeanField.from_mode_covariance passes a 0-d DiagonalMatrix (variable_operator.py:305-308), so the physical variance 25.0 is written as the log-space variance (should be 0.25). LogGaussianPrior(log 10, 0.5) leg: log sigma 2.3026 +/- 0.4564 (its start) vs closed form 1.8338 +/- 0.3608; BAD_PROJECTION on all 150 updates. Not the #1498 fingerprint (no-Jacobian reference 1.9692 not matched). -> same prompt as D4

    D6 — errors_at_sigma(as_instance=True) crashes on the hierarchical global model. samples/interface.py:56 calls instance_from_vector on the (lower, upper) tuple list -> prior_model.py:541 -> gaussian.py:52 NormalMessage(mean=(lo, hi)) -> messages/abstract.py:63 broadcast_arrays TypeError. Minor. -> samples_errors_at_sigma_instance_prior_valued_model.md

    Finding for the cure-or-caveat question. The benchmark's minimal EP (analytic_ep_minimal.py) reproduces the scale collapse deterministically under a mode-based projection: the tilted density is proportional to 1/sigma at x_i = mu, so a Laplace projection of the scatter cannot be made exact — moment matching or a log-sigma parameterisation is the cure. D1-D3 make leg A (Gaussian, sigma fixed) exact; the scatter needs the projection change, not another optimiser lever.

    Coverage check: #1332 F1-F10, #1338, #1498, #1500 do not cover D1-D6. Scripts: autofit_workspace_test/scripts/graphical/analytic_{reference,ep_minimal,autofit,gaussian,gaussian_priors,gaussian_collapse}.py on feature/analytic-gaussian-benchmark. Mind commit PyAutoLabs/PyAutoMind@d1024afe.

  5. Jammy2211 commented on Sep 2, 2026

    @Jammy2211
    CollaboratorAuthor

    Status 2026-09-02 — the mechanisms are fixed; the scatter is no longer collapsed

    The three fixes found by the analytic Gaussian benchmark (autofit_workspace_test#91) are merged on main:

    PR Mechanism
    #1558 D1 — prior id 0 collided with the FactorValue sentinel, corrupting every multi-variable factor gradient
    #1560 D4/D5 — truncation limits dropped by natural-parameter ops; TransformedMessage.from_mode skipped the Jacobian
    #1562 D2/D3 — the Laplace "covariance" never contained the factor curvature (random secant, prior-id dependent); failed line searches wrote the start point back

    On the closed-form referee (autofit_workspace_test/scripts/graphical/analytic_gaussian*.py, PyAutoFit main 5375f4d):

    • Exact-Gaussian leg: EP matches the closed form in every cell (mu 50.8596 ± 4.1102 vs 50.8595 ± 4.1104), 0 BAD_PROJECTION, byte-identical across prior-id orderings.
    • The collapse configuration this issue reports (N=5, truncated priors, Laplace, kl_tol 0.05, max_steps 20): RECOVER 5/5 seeds, no silent or stale verdicts — seed 0's scatter reads 9.24 ± 3.61 against the exact 6.57 with 5–95 % interval [2.98, 12.15], where it used to read ~2e-4 ± 0.

    What remains, and why this issue stays open for your call: a hierarchical scatter's tilted density is ∝ 1/σ at x_i = mu, so its mode sits on the boundary; the fixed Laplace path now refuses to write a Gaussian there (or reverts that variable) instead of collapsing it, and the scatter stays near its prior with an honest width. It is not estimated. The caveat is documented in autofit/graphical/README.md §3.5 (trust the parent mean and per-dataset variables; read the scatter from a joint sampler; prefer LogGaussianPrior on the scatter; STALE FACTORS now also warns on always-skipped updates). The cure is a moment-matching projection for the hierarchical factor — the benchmark's hand-rolled EP recovers the exact posterior that way (scatter row |Δmean|/std ≤ 0.08, |std/std_ref − 1| ≤ 0.15 over seeds 0–4). Filed as PyAutoMind/draft/feature/autofit/ep_hierarchical_scatter_moment_matching.md; whether to build it is the human decision this issue now waits on. The leg-1 guard (#1465) is unchanged; its BIASED-TIGHT calibration remains a human decision too.

  6. Jammy2211 commented on Sep 7, 2026

    @Jammy2211
    CollaboratorAuthor

    Codex review of the phase-2 fixes (#1558/#1560/#1562), re-verified on main 2026-09-07 — three findings confirmed, three PRs open: #1572 (coupled-transform covariance, #1560 path, defensive-only), #1573 (P1: deterministic-variable covariance on the fd-Hessian path), #1574 (fully reverted projection counted as updated; README §3.5 wording). Referee analytic_gaussian_collapse.py stays RECOVER 5/5 on each. Partial-revert stale tracking filed as a Mind feature prompt.

  7. Jammy2211 commented on Sep 8, 2026

    @Jammy2211
    CollaboratorAuthor

    D6 (errors_at_sigma(as_instance=True) on a prior-valued model) shipped 2026-09-07 — PyAutoFit#1578 + autofit_workspace_test#99; the phase-1 findings table D1–D6 is now fully shipped; the scatter-estimation cure (moment-matching projection) remains draft/feature/autofit/ep_hierarchical_scatter_moment_matching.md, a human decision; analytic_gaussian.py / analytic_gaussian_priors.py stay parked for it.

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