Repository navigation
Description
Overview
Found by the analytic Gaussian benchmark (autofit_workspace_test#91 / PR #92): on an exactly Gaussian hierarchical graph, autofit's EP leaves the parent mean at its starting mean field (50.0000 ± 20.6 vs closed form 50.86 ± 4.11) because every multi-variable factor gradient is corrupted whenever the process's first prior has id 0 — that prior compares equal to the FactorValue sentinel, so the VJP seed is overwritten. Umbrella symptom: #1405. First of three fixes in the EP campaign's fix wave (D1 → D4/D5 → D2/D3); the Mind prompt carries the root cause, repro and control test.
Plan
- Give
FactorValuean identity that cannot collide with a prior id, and makePrior.__eq__type-aware (hash kept consistent). - Stop merging the free-variable cavity gradient into the Jacobian VJP seed; add it after the VJP instead (the control-test form).
- Unit test: a two-variable factor whose first prior has id 0 matches central finite differences on every variable;
GaussianPrior(...) != FactorValue. - Measure the referee:
analytic_gaussian.pyleg Amumean turns PASS andep_history.csvshows SUCCESS hierarchical updates; report the after-numbers on this issue.
Detailed implementation plan
Affected Repositories
- PyAutoFit (primary)
Branch Survey
| Repository | Current Branch | Dirty? |
|---|---|---|
| ./PyAutoFit | main | clean (other claims are web sessions on disjoint files: resampling-info-summary-section; autofit-prodigy-49 PR #1555 merged) |
Suggested branch: feature/ep-prior-id-zero
Worktree: ~/Code/PyAutoLabs-wt/ep-prior-id-zero/
Implementation Steps
autofit/mapper/variable.py:142-149—FactorValuegets a sentinel identity (e.g.id = -1) that noVariable.__init__-assigned id can equal;autofit/mapper/prior/abstract.py:249-259—Prior.__eq__returnsNotImplemented/False for non-Prioroperands;__hash__unchanged (hash(self.id)).autofit/graphical/factor_graphs/jacobians.py:97-99— the VJP seed carries only theFactorValue(and deterministic-variable) cotangents;autofit/graphical/mean_field.py:652—FactorApproximation.func_gradientcomputesfjac.grad() + grad_cavity(add the free-variable cavity gradient after the VJP).- New test (e.g.
test_autofit/graphical/functionality/test_gradient_id_zero.py): reset the id counter (or otherwise construct a prior with id 0), build a two-variable factor (HierarchicalFactoron a drawnGaussianPrior, or a hand-builtFactor), assertFactorApproximation.func_gradient== central FD to 1e-6 on every variable, assertaf.GaussianPrior(0, 1) != FactorValueand thatVariableData({FactorValue: 1.0})is not overwritten by a prior-0 key. pytest test_autofit/graphical -qandpytest test_autofit/mapper -qin the worktree; runautofit_workspace_test/scripts/graphical/analytic_gaussian.pyfrom the worktree (itsactivate.shputs this PyAutoFit first onPYTHONPATH) and paste the leg A table.
Key Files
autofit/mapper/variable.py—FactorValuesentinel (:142-149),Variable.__init__id/hash (:99-100)autofit/mapper/prior/abstract.py—Prior.__eq__/__hash__(:249-259)autofit/graphical/factor_graphs/jacobians.py—AbstractJacobian.gradseed (:97-99)autofit/graphical/mean_field.py—FactorApproximation.func_gradient(:640-654)autofit_workspace_test/scripts/graphical/analytic_gaussian.py— acceptance harness (leg Amurow)
Original Prompt
Click to expand starting prompt
EP: the first prior of a process (id 0) collides with the FactorValue sentinel, corrupting every multi-variable factor gradient
Type: bug
Target: PyAutoFit
Repos:
- PyAutoFit
Themes: - graphical-ep
Difficulty: small
Autonomy: safe
Priority: high
Status: formalised
Consequence: glance
Witness: on a graph whose first prior has id 0,FactorApproximation.func_gradientmatches central finite differences ofFactorApproximation.__call__to 1e-6 on every variable;analytic_gaussian.pyleg Amucell moves from 50.0000 +/- 20.6457 (FAIL) to 50.8596 +/- 3.76 (ref 50.8595 +/- 4.11)
Review-minutes: 5
Unattended: ready
Epic: graphical-ep
Filed: 2026-09-02
Found by the analytic Gaussian benchmark (autofit_workspace_test#91, phase (b)).
Sibling of ep_laplace_covariance_and_failed_update_projection.md (D2/D3) — D1 is
the reason leg A never moves at all; D2/D3 are what remains once it is fixed.
Why
Leg A of the benchmark (exactly Gaussian hierarchical graph, sigma fixed, Laplace
should be exact) reproduces with the benchmark wiring: mu 50.0000 +/- 20.6457
against the closed form 50.8595 +/- 4.11. ep_history.csv for the hierarchical
factor: BAD_PROJECTION=54 / FAILURE=36, no SUCCESS. All 90 hierarchical updates
end Line search failed, iter=0 or BAD_PROJECTION; mu never leaves its start, and
its mean field ends wider than its prior (sigma 20.6 > prior 10).
The gradient of every multi-variable factor is wrong whenever the process's first
prior has id 0. Measured at (mu=48, x=55): state.gradient = (0.0214, -0.0139);
central finite differences of the same FactorApproximation.__call__ give
(0.0900, -0.0825). The factor Jacobian alone is correct (+0.07 / -0.07).
One-variable factors are unaffected (dataset_0: -4.55987 vs FD -4.55987), which is
why the analysis factors converge and only the hierarchical factor stalls.
Root cause (deepest frame last)
FactorApproximation.func_gradient,autofit/graphical/mean_field.py:652—
grad = fjac.grad(grad_cavity)passes the cavity gradient (keyed by the
factor's input priors) into the Jacobian's VJP.AbstractJacobian.grad,autofit/graphical/factor_graphs/jacobians.py:97-99—
seed = VariableData({FactorValue: 1.0}); seed.update(values): the input-keyed
entries land in the VJP seed dict, which is keyed byFactorValue.FactorValueis a class-as-Variable (autofit/mapper/variable.py:142-149)
whoseVariable.__init__gives itid == 0,hash == 0(variable.py:99-100).Prior.__eq__(autofit/mapper/prior/abstract.py:249-253) compares
self.id == other.idwith no type check;Prior.__hash__ishash(self.id)
(:258-259). SoGaussianPrior(id=0) == FactorValueisTrue.
Net effect: the seed's FactorValue slot is overwritten by prior-0's cavity
gradient (0.02), the factor Jacobian is scaled by it, and prior-0's own gradient
entry is added onto the FactorValue key and discarded.
Control test: patching func_gradient to fjac.grad() + grad_cavity gives
mu 50.8596 +/- 3.76, all x_i means to a ~ 0.000 — bit-identical to the untouched
library when one throwaway prior is created first (so id 0 is never a graph prior).
Minimal repro
import numpy as np, autofit as af
from autofit.mapper.variable import FactorValue, VariableData
mu = af.GaussianPrior(50, 10) # FIRST prior of the process -> id 0
print(mu.id, FactorValue.id, mu == FactorValue, hash(mu) == hash(FactorValue)) # 0 0 True True
d = VariableData({FactorValue: 1.0}); d.update({mu: 0.02}); print(dict(d)) # {FactorValue: 0.02}
class Level:
def __init__(self, x): self.x = x
class A(af.Analysis):
def log_likelihood_function(self, i): return -0.5 * (51.0 - i.x) ** 2 / 0.5 ** 2
m = af.Model(Level); m.x = af.GaussianPrior(50, 20)
hf = af.HierarchicalFactor(af.GaussianPrior, mean=mu, sigma=10.0); hf.add_drawn_variable(m.x)
fg = af.FactorGraphModel(af.AnalysisFactor(m, A()), hf)
hfac = [f for f in fg.graph.factors if f.name.startswith("Hierarchical")][0]
fa = fg.mean_field_approximation().factor_approximation(hfac)
vals = {mu: np.float64(48.0), m.x: np.float64(55.0)}
_, g = fa.func_gradient(vals); eps = 1e-5
fd = lambda v: float(fa({**vals, v: vals[v] + eps}) - fa({**vals, v: vals[v] - eps})) / (2 * eps)
print({v.name: round(float(g[v]), 5) for v in vals}, {v.name: round(fd(v), 5) for v in vals})
# {'gaussianprior_0': 0.0214, 'gaussianprior_1': -0.0139} vs FD {'gaussianprior_0': 0.09, 'gaussianprior_1': -0.0825}Fix sketch
- Give
FactorValuean id that cannot collide with a prior: negative, or an
object()-based identity; and/or makePrior.__eq__/Variable.__hash__
type-aware so aPriornever compares equal to a non-Priorvariable. - Independently,
AbstractJacobian.gradshould not merge the free-variable cavity
gradient into the VJP seed — only deterministic-variable cotangents belong
there. Add the free-variable terms afterwards (the control-test form
fjac.grad() + grad_cavity), which is also what makes the fix robust to any
future id collision.
Acceptance
- Unit test: build a graph whose first prior has id 0 (fresh process, or reset
the id counter) and a two-variable factor; assertfunc_gradientagainst
central finite differences on every variable to 1e-6, and assert
GaussianPrior(...) != FactorValue. autofit_workspace_test/scripts/graphical/analytic_gaussian.py, leg A,
"closed form vs autofit EP" column: themucell turns PASS (was
50.0000 +/- 20.6457 FAIL); everyx_imean lands at a ~ 0.000. (Themustd
is still ~8% low until D2 lands — see the sibling prompt; do not loosen the
tolerance.)ep_history.csvfor leg A: the hierarchical factor records SUCCESS updates
instead of 54 BAD_PROJECTION / 36 FAILURE.
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
- Campaign ledger:
draft/research/graphical_ep/ep_campaign.md(phase 1) - Siblings:
draft/bug/autofit/ep_laplace_covariance_and_failed_update_projection.md,
draft/bug/autofit/ep_message_support_and_transform_lost_in_projection.md,
draft/bug/autofit/samples_errors_at_sigma_instance_prior_valued_model.md,
draft/bug/autofit/ep_scale_collapse_basin_cure_or_caveat.md(phase 2) - 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
feature/ep-prior-id-zero,pending-release)API summary: Internal: Prior/Variable equality now type-aware; FactorValue sentinel id −1; AbstractJacobian.grad seeds the VJP only from cotangent variables and adds free-variable terms after the pull-back.
Next: none — no workspace follow-up expected (parity scripts in autofit_workspace_test are re-run per fix; un-parking happens at the end of the wave).
Merge pull request #1558 from PyAutoLabs/feature/ep-prior-id-zero
Jammy2211 commentedon Sep 2, 2026
Shipped
809b4fd85ce308cb7bcd18b58e1202ad73d82fba(CI green: unittest 3.12 / 3.13 / nojax, docs-build).The fix. The
FactorValuesentinel now carriesSENTINEL_ID = -1so noVariableinstance id can collide with it, andVariable.__eq__/Prior.__eq__are type-aware in both directions (hashes unchanged). Independently,AbstractJacobian.gradno longer merges the free-variable cavity gradient into the VJP seed — it seeds only fromcotangent_variablesand adds the input-keyed terms after the pull-back, so the gradient stays right even if a future sentinel collides. Newtest_autofit/graphical/functionality/test_gradient_id_zero.py(4 tests, all fail on the old main);pytest test_autofit: 2391 passed, 2 skipped.Referee (leg A,
analytic_gaussian.py).mumean 50.8596 — exact (a = 0.000; was stuck at 50.0000), everyx_imean a = 0.000, hierarchical SUCCESS = 20 (was 0). The remaining leg A miss is the std (3.76 vs 4.11, −8.5 %), which is the Laplace-covariance defect D2 (ep_laplace_covariance_and_failed_update_projection.md), next in the fix wave.Mind record:
PyAutoMind/complete/2026/09/ep-prior-id-zero.md.