From 17945499dbb68aeac501fc182446f9fad3001476 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Wed, 2 Sep 2026 17:34:48 -0400 Subject: [PATCH] fix(graphical): prior id 0 no longer collides with the FactorValue sentinel; cavity gradient added after the VJP (#1557) The first prior of a process took id 0, the same id Variable.__init__ gave the FactorValue class-as-variable, and Prior.__eq__ compared ids with no type check: the prior compared and hashed equal to the sentinel, so its cavity gradient overwrote the VJP seed in AbstractJacobian.grad and every multi-variable factor gradient was wrong (analytic Gaussian benchmark leg A: the parent mean never left its starting mean field). - FactorValue takes a negative sentinel id no prior or variable can equal. - Prior.__eq__ is type-aware and Variable.__eq__ mirrors it (same id counter and same id), so the comparison is symmetric; hashes unchanged. - AbstractJacobian.grad seeds the VJP only with the cotangents of the factor's outputs (cotangent_variables: out_variables for the VJP, left_variables for the JVP) and adds input-keyed entries afterwards; FactorApproximation.func_gradient splits the cavity gradient the same way. - Regression test: prior id 0 vs FactorValue, gradient vs central finite differences, and a three-group hierarchical EP run that moves the parent. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01C49DeRHoKss4xBnz5F7gUm --- autofit/graphical/factor_graphs/jacobians.py | 37 ++++- autofit/graphical/mean_field.py | 16 +- autofit/mapper/prior/abstract.py | 10 +- autofit/mapper/variable.py | 24 ++- .../functionality/test_gradient_id_zero.py | 152 ++++++++++++++++++ 5 files changed, 231 insertions(+), 8 deletions(-) create mode 100644 test_autofit/graphical/functionality/test_gradient_id_zero.py diff --git a/autofit/graphical/factor_graphs/jacobians.py b/autofit/graphical/factor_graphs/jacobians.py index 447b36402..a356d665e 100644 --- a/autofit/graphical/factor_graphs/jacobians.py +++ b/autofit/graphical/factor_graphs/jacobians.py @@ -93,14 +93,43 @@ def _full_repr(self) -> str: cls_name = type(self).__name__ return f"{cls_name}({out_var} โ†’ โˆ‚({in_var})แต€ {out_var})" + @property + def cotangent_variables(self): + """ + The variables whose cotangents ``self(seed)`` accepts: the factor's + outputs, i.e. ``FactorValue`` and its deterministic variables. + + ``VectorJacobianProduct`` exposes these as ``out_variables``; + ``JacobianVectorProduct`` (a ``RectVariableOperator`` mapping its + ``left_variables`` onto its ``right_variables``) names the same set + ``left_variables`` and uses ``out_variables`` for the inputs, so it + overrides this property. + """ + return self.out_variables + def grad(self, values=None): + """ + The gradient of the factor value with respect to its input variables, + pulled back through this Jacobian. + + Parameters + ---------- + values + Optional cotangents. Entries keyed by the factor's output variables + (``FactorValue`` and its deterministic variables) seed the + vector-Jacobian product; entries keyed by the input variables + themselves (e.g. the cavity gradient of the free variables) are not + part of the seed and are added to the result after the pull-back. + """ seed = VariableData({FactorValue: 1.0}) + grad = VariableData(values) if values else VariableData() if values: - seed.update(values) + for v in self.cotangent_variables: + if v in values: + seed[v] = values[v] jac = self(seed) - grad = VariableData(values) if values else VariableData() for v, g in jac.items(): if v is not FactorValue: grad[v] = grad.get(v, 0) + g @@ -119,6 +148,10 @@ def variables(self): def out_variables(self): return self.right_variables + @property + def cotangent_variables(self): + return self.left_variables + @property def factor_out(self): return tuple(self.out_variables) diff --git a/autofit/graphical/mean_field.py b/autofit/graphical/mean_field.py index 9ae2f1548..c91f76ccf 100755 --- a/autofit/graphical/mean_field.py +++ b/autofit/graphical/mean_field.py @@ -649,7 +649,21 @@ def func_gradient( ) logl = np.sum(fval) + np.sum(log_cavity) - grad = fjac.grad(grad_cavity) + + # Only the cavity gradient of the factor's deterministic variables is a + # cotangent of one of its outputs and so belongs in the VJP seed; the + # cavity gradient of the free variables is added after the pull-back. + deterministic_grad = VariableData( + { + v: grad_cavity[v] + for v in self.deterministic_variables + if v in grad_cavity + } + ) + grad = fjac.grad(deterministic_grad) + for v, g in grad_cavity.items(): + if v not in deterministic_grad: + grad[v] = grad.get(v, 0) + g return logl, grad diff --git a/autofit/mapper/prior/abstract.py b/autofit/mapper/prior/abstract.py index b3048021f..57a05cff9 100644 --- a/autofit/mapper/prior/abstract.py +++ b/autofit/mapper/prior/abstract.py @@ -247,10 +247,12 @@ def __getattr__(self, item): return getattr(self.message, item) def __eq__(self, other): - try: - return self.id == other.id - except AttributeError: - return False + # Priors are numbered from their own counter (``Prior._ids``), so an id + # only identifies a prior among other priors: a non-``Prior`` operand + # (a plain ``Variable``, the ``FactorValue`` sentinel, ...) is never + # equal, whatever its id. ``Variable.__eq__`` applies the same rule in + # the other direction so the comparison is symmetric. + return isinstance(other, Prior) and self.id == other.id def __ne__(self, other): return not self.__eq__(other) diff --git a/autofit/mapper/variable.py b/autofit/mapper/variable.py index f2ed79c4d..2d0b67e4e 100644 --- a/autofit/mapper/variable.py +++ b/autofit/mapper/variable.py @@ -96,6 +96,21 @@ def __repr__(self): args = ", ".join(chain([self.name], map(repr, self.plates))) return f"{self.__class__.__name__}({args})" + def __eq__(self, other): + """ + Two variables are the same variable only when they were drawn from the + same id sequence with the same id. ``Prior`` numbers its instances from + its own counter (``Prior._ids``), every other ``Variable`` from + ``ModelObject._ids``, so a prior and a plain variable that happen to + share an integer id are distinct objects, not equal ones. This is the + mirror image of ``Prior.__eq__`` so the comparison is symmetric. + """ + return ( + isinstance(other, Variable) + and type(self)._ids is type(other)._ids + and self.id == other.id + ) + def __hash__(self): return self.id @@ -140,9 +155,16 @@ def variables(*vals): # that allows us to keep track of the FactorValue vs deterministic # values when calculating gradients and jacobians class VariableMetaClass(type, Variable): + # The sentinel takes a negative id so that no ``Variable`` (or ``Prior``, + # which numbers its instances from a separate counter that also starts at + # 0) can ever hash or compare equal to it. Before this the first prior of + # a process (id 0) collided with ``FactorValue`` (id 0), and a ``dict`` + # keyed by ``FactorValue`` was silently overwritten by that prior's entry. + SENTINEL_ID = -1 + def __new__(cls, clsname, bases, attrs): newcls = super().__new__(cls, clsname, bases, attrs) - Variable.__init__(newcls, clsname) + Variable.__init__(newcls, clsname, id_=cls.SENTINEL_ID) return newcls diff --git a/test_autofit/graphical/functionality/test_gradient_id_zero.py b/test_autofit/graphical/functionality/test_gradient_id_zero.py new file mode 100644 index 000000000..e1d328a23 --- /dev/null +++ b/test_autofit/graphical/functionality/test_gradient_id_zero.py @@ -0,0 +1,152 @@ +""" +Regression tests for PyAutoFit#1557: the first prior of a process (id 0) used to +compare (and hash) equal to the ``FactorValue`` sentinel, so its cavity gradient +overwrote the VJP seed and every multi-variable factor gradient was wrong. +""" +import itertools + +import numpy as np +import pytest + +import autofit as af +from autofit.graphical import LaplaceOptimiser +from autofit.graphical.utils import StatusFlag +from autofit.mapper.prior.abstract import Prior +from autofit.mapper.variable import FactorValue, Variable, VariableData + + +class Level: + def __init__(self, x): + self.x = x + + +class Analysis(af.Analysis): + def log_likelihood_function(self, instance): + return -0.5 * (51.0 - instance.x) ** 2 / 0.5**2 + + +@pytest.fixture(autouse=True) +def fresh_prior_ids(monkeypatch): + # Number priors as a fresh process would, so the first one takes id 0 + monkeypatch.setattr(Prior, "_ids", itertools.count()) + + +@pytest.fixture(name="mu") +def make_mu(): + mu = af.GaussianPrior(50.0, 10.0) + assert mu.id == 0 + return mu + + +@pytest.fixture(name="hierarchical_approx") +def make_hierarchical_approx(mu): + model = af.Model(Level) + model.x = af.GaussianPrior(50.0, 20.0) + + hierarchical = af.HierarchicalFactor(af.GaussianPrior, mean=mu, sigma=10.0) + hierarchical.add_drawn_variable(model.x) + + graph = af.FactorGraphModel(af.AnalysisFactor(model, Analysis()), hierarchical) + factor = next(f for f in graph.graph.factors if f.name.startswith("Hierarchical")) + approx = graph.mean_field_approximation().factor_approximation(factor) + return approx, mu, model.x + + +def test_prior_id_zero_is_not_the_factor_value_sentinel(mu): + assert FactorValue.id < 0 + + assert mu != FactorValue + assert FactorValue != mu + assert not (mu == FactorValue) + assert not (FactorValue == mu) + assert hash(mu) != hash(FactorValue) + + seed = VariableData({FactorValue: 1.0}) + seed.update({mu: 0.02}) + assert seed[FactorValue] == 1.0 + assert seed[mu] == 0.02 + assert len(seed) == 2 + + +def test_prior_and_variable_with_the_same_id_are_distinct(mu): + variable = Variable("x", id_=mu.id) + + assert variable != mu + assert mu != variable + assert not (variable == mu) + assert not (mu == variable) + + # Equality by id among priors is unchanged + assert mu == af.GaussianPrior(0.0, 1.0, id_=mu.id) + assert af.GaussianPrior(0.0, 1.0, id_=mu.id) == mu + + +def test_gradient_matches_finite_differences(hierarchical_approx): + approx, mu, x = hierarchical_approx + values = {mu: np.float64(48.0), x: np.float64(55.0)} + + _, gradient = approx.func_gradient(values) + + eps = 1e-5 + for variable in values: + plus = {**values, variable: values[variable] + eps} + minus = {**values, variable: values[variable] - eps} + finite_difference = float(approx(plus) - approx(minus)) / (2 * eps) + + assert abs(finite_difference) > 1e-2 + assert float(gradient[variable]) == pytest.approx(finite_difference, abs=1e-6) + + +class GroupAnalysis(af.Analysis): + def __init__(self, y, noise): + self.y = y + self.noise = noise + + def log_likelihood_function(self, instance): + return float(-0.5 * np.sum((self.y - instance.x) ** 2) / self.noise**2) + + +def test_hierarchical_ep_updates_the_parent_mean(tmp_path): + """ + With the corrupted gradient the parent mean never left its starting mean + field (50.0 +/- 15) and the hierarchical factor never recorded a SUCCESS. + """ + # The Laplace optimiser's refinement step samples the global numpy RNG + np.random.seed(0) + rng = np.random.default_rng(0) + mu = af.GaussianPrior(50.0, 10.0) + assert mu.id == 0 + + hierarchical = af.HierarchicalFactor(af.GaussianPrior, mean=mu, sigma=10.0) + analysis_factors = [] + for truth in (45.0, 52.0, 58.0): + model = af.Model(Level) + model.x = af.GaussianPrior(50.0, 20.0) + y = truth + 2.0 * rng.standard_normal(20) + analysis_factors.append(af.AnalysisFactor(model, GroupAnalysis(y, 2.0))) + hierarchical.add_drawn_variable(model.x) + + graph = af.FactorGraphModel(*analysis_factors, hierarchical) + result = graph.optimise( + af.LaplaceOptimiser(), + paths=af.DirectoryPaths(name="ep", path_prefix=str(tmp_path)), + max_steps=5, + ) + mean_field = result.updated_ep_mean_field.mean_field + + # The x_i are pinned by their data, so the exact parent posterior is + # mu | x ~ N(m, 1 / p) with p = 1 / 10^2 (prior) + n / 10^2 (hierarchical) + x_means = [float(mean_field[f.prior_model.x].mean) for f in analysis_factors] + precision = (1 + len(x_means)) / 10.0**2 + mu_mean = (50.0 + sum(x_means)) / 10.0**2 / precision + + assert float(mean_field[mu].mean) == pytest.approx(mu_mean, abs=0.1) + assert float(mean_field[mu].sigma) == pytest.approx(precision**-0.5, rel=0.1) + + flags = [ + status.flag + for factor in graph.graph.factors + if factor.name.startswith("Hierarchical") + for _, status in result.ep_history[factor].history + ] + assert StatusFlag.SUCCESS in flags, flags