Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 35 additions & 2 deletions autofit/graphical/factor_graphs/jacobians.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
Expand Down
16 changes: 15 additions & 1 deletion autofit/graphical/mean_field.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
10 changes: 6 additions & 4 deletions autofit/mapper/prior/abstract.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
24 changes: 23 additions & 1 deletion autofit/mapper/variable.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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


Expand Down
152 changes: 152 additions & 0 deletions test_autofit/graphical/functionality/test_gradient_id_zero.py
Original file line number Diff line number Diff line change
@@ -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
Loading