Skip to content

fix(graphical): prior id 0 collides with the FactorValue sentinel, corrupting multi-variable factor gradients (EP) #1557

Closed

Description

@Jammy2211

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 FactorValue an identity that cannot collide with a prior id, and make Prior.__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.py leg A mu mean turns PASS and ep_history.csv shows 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

  1. autofit/mapper/variable.py:142-149 — FactorValue gets a sentinel identity (e.g. id = -1) that no Variable.__init__-assigned id can equal; autofit/mapper/prior/abstract.py:249-259 — Prior.__eq__ returns NotImplemented/False for non-Prior operands; __hash__ unchanged (hash(self.id)).
  2. autofit/graphical/factor_graphs/jacobians.py:97-99 — the VJP seed carries only the FactorValue (and deterministic-variable) cotangents; autofit/graphical/mean_field.py:652 — FactorApproximation.func_gradient computes fjac.grad() + grad_cavity (add the free-variable cavity gradient after the VJP).
  3. 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 (HierarchicalFactor on a drawn GaussianPrior, or a hand-built Factor), assert FactorApproximation.func_gradient == central FD to 1e-6 on every variable, assert af.GaussianPrior(0, 1) != FactorValue and that VariableData({FactorValue: 1.0}) is not overwritten by a prior-0 key.
  4. pytest test_autofit/graphical -q and pytest test_autofit/mapper -q in the worktree; run autofit_workspace_test/scripts/graphical/analytic_gaussian.py from the worktree (its activate.sh puts this PyAutoFit first on PYTHONPATH) and paste the leg A table.

Key Files

  • autofit/mapper/variable.py — FactorValue sentinel (: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.grad seed (:97-99)
  • autofit/graphical/mean_field.py — FactorApproximation.func_gradient (:640-654)
  • autofit_workspace_test/scripts/graphical/analytic_gaussian.py — acceptance harness (leg A mu row)

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_gradient matches central finite differences of FactorApproximation.__call__ to 1e-6 on every variable; analytic_gaussian.py leg A mu cell 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)

  1. 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.
  2. 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 by FactorValue.
  3. FactorValue is a class-as-Variable (autofit/mapper/variable.py:142-149)
    whose Variable.__init__ gives it id == 0, hash == 0 (variable.py:99-100).
  4. Prior.__eq__ (autofit/mapper/prior/abstract.py:249-253) compares
    self.id == other.id with no type check; Prior.__hash__ is hash(self.id)
    (:258-259). So GaussianPrior(id=0) == FactorValue is True.

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 FactorValue an id that cannot collide with a prior: negative, or an
    object()-based identity; and/or make Prior.__eq__ / Variable.__hash__
    type-aware so a Prior never compares equal to a non-Prior variable.
  • Independently, AbstractJacobian.grad should 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; assert func_gradient against
    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: the mu cell turns PASS (was
    50.0000 +/- 20.6457 FAIL); every x_i mean lands at a ~ 0.000. (The mu std
    is still ~8% low until D2 lands — see the sibling prompt; do not loosen the
    tolerance.)
  • ep_history.csv for leg A: the hierarchical factor records SUCCESS updates
    instead of 54 BAD_PROJECTION / 36 FAILURE.

Links

Activity

  1. Jammy2211 commented on Sep 2, 2026

    @Jammy2211
    CollaboratorAuthor

    Library PR Created

    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).

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

    @Jammy2211
    CollaboratorAuthor

    Shipped

    The fix. The FactorValue sentinel now carries SENTINEL_ID = -1 so no Variable instance id can collide with it, and Variable.__eq__ / Prior.__eq__ are type-aware in both directions (hashes unchanged). Independently, AbstractJacobian.grad no longer merges the free-variable cavity gradient into the VJP seed — it seeds only from cotangent_variables and adds the input-keyed terms after the pull-back, so the gradient stays right even if a future sentinel collides. New test_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). mu mean 50.8596 — exact (a = 0.000; was stuck at 50.0000), every x_i mean 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.

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