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
100 changes: 90 additions & 10 deletions autofit/graphical/laplace/optimiser.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import logging
from operator import attrgetter
from typing import Optional, Dict, Tuple, Any, Union

import numpy as np
Expand All @@ -8,7 +9,7 @@
from autofit.graphical.factor_graphs.factor import Factor
from autofit.graphical.laplace import newton
from autofit.graphical.mean_field import MeanField, FactorApproximation
from autofit.graphical.utils import Status, StatusFlag
from autofit.graphical.utils import FlattenArrays, Status, StatusFlag
from autofit.mapper.variable_operator import VariableData, VariableFullOperator

FactorApprox = Union[EPMeanField, FactorApproximation, Factor]
Expand Down Expand Up @@ -163,19 +164,19 @@ def optimise_state(
kws = {**self.default_kws, **kwargs}
return newton.optimise_quasi_newton(state, old_state, **kws)

def make_mode_hessian(
def fd_steps(
self, state: newton.OptimisationState, mean_field: MeanField
) -> Tuple[Optional[VariableFullOperator], str]:
) -> VariableData:
"""
The negative finite-difference Hessian of the tilted log-density at
`state`, as a Cholesky-factorised full operator over the free variables.

Returns ``(operator, "")`` or ``(None, reason)`` when the Hessian is not
finite or not negative definite.
The central-difference step for each free parameter: a fixed fraction
`fd_step` of the mean field's standard deviation, floored at
`fd_min_step`. Shared by every finite difference this optimiser takes,
so the mode Hessian and the deterministic Jacobian are differenced on
the same scale.
"""
# `variance` rather than `std`: TransformedMessage exposes only the former
variance = MeanField.variance.fget(mean_field)
step = VariableData(
return VariableData(
{
v: np.maximum(
self.fd_step
Expand All @@ -185,7 +186,20 @@ def make_mode_hessian(
for v in state.parameters
}
)
H, shapes = newton.finite_difference_hessian(state, step)

def make_mode_hessian(
self, state: newton.OptimisationState, mean_field: MeanField
) -> Tuple[Optional[VariableFullOperator], str]:
"""
The negative finite-difference Hessian of the tilted log-density at
`state`, as a Cholesky-factorised full operator over the free variables.

Returns ``(operator, "")`` or ``(None, reason)`` when the Hessian is not
finite or not negative definite.
"""
H, shapes = newton.finite_difference_hessian(
state, self.fd_steps(state, mean_field)
)
if not np.all(np.isfinite(H)):
return None, "non-finite Hessian at mode (mode on a limit / outside support)"
try:
Expand All @@ -198,6 +212,63 @@ def make_mode_hessian(
f"tilted log-density not concave at mode (min eig {min_eig:.3g})",
)

def make_deterministic_hessian(
self,
state: newton.OptimisationState,
hessian: VariableFullOperator,
mean_field: MeanField,
) -> VariableFullOperator:
"""
The precision of the factor's deterministic outputs implied by the free
variables' mode covariance, ``diag(J Sigma J.T) ** -1``.

`J` is the central-difference Jacobian of the factor's deterministic
outputs with respect to the free parameters, differenced on the same
steps as the mode Hessian (`fd_steps`); ``Sigma`` is the inverse of
`hessian`.

Only the diagonal is written. ``J Sigma J.T`` is rank deficient whenever
there are more deterministic outputs than free parameters — the common
case, e.g. a regression factor with 50 outputs and 3 parameters — so the
full block is not a valid precision, and `MeanField.from_mode` reads only
the per-variable marginals in any case. A deterministic output the free
parameters do not move (an all-zero Jacobian row, so zero or non-finite
variance) keeps the cavity curvature it came in with, rather than being
handed an infinite precision.
"""
deterministic = state.value.deterministic_values
det_variables = sorted(deterministic.keys(), key=attrgetter("id"))
det_shapes = FlattenArrays(
{v: np.shape(deterministic[v]) for v in det_variables}
)

shapes = hessian.param_shapes
x = shapes.flatten(state.parameters)
step = shapes.flatten(self.fd_steps(state, mean_field))

jacobian = np.empty((det_shapes.splits[-1], x.size))
for i in range(x.size):
offset = np.zeros(x.size)
offset[i] = step[i]
plus = state.update(
parameters=shapes.unflatten(x + offset)
).value.deterministic_values
minus = state.update(
parameters=shapes.unflatten(x - offset)
).value.deterministic_values
jacobian[:, i] = (
det_shapes.flatten(plus) - det_shapes.flatten(minus)
) / (2 * step[i])

covariance = hessian.inv().operator.to_dense()
variance = np.einsum("ij,jk,ik->i", jacobian, covariance, jacobian)

moved = np.isfinite(variance) & (variance > 0)
cavity = det_shapes.flatten(state.det_hessian.diagonal())
precision = np.where(moved, 1.0 / np.where(moved, variance, 1.0), cavity)

return VariableFullOperator.from_diagonal(det_shapes.unflatten(precision))

def optimise_approx(
self,
factor_approx: FactorApprox,
Expand Down Expand Up @@ -235,6 +306,15 @@ def optimise_approx(
),
)
next_state.hessian = hessian
if next_state.det_hessian is not None:
# The fd branch never reaches `newton.quasi_deterministic_update`
# (that runs in the line search and in `refine_state`, both of
# which live in the `else` below), so without this the
# deterministic variables would be projected at the cavity
# precision `prepare_state` built — PyAutoFit#1570.
next_state.det_hessian = self.make_deterministic_hessian(
next_state, hessian, mean_field
)
else:
if self.hessian == "fd":
logger.info(
Expand Down
56 changes: 56 additions & 0 deletions test_autofit/graphical/functionality/test_laplace_hessian.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

import numpy as np
import pytest
from scipy import stats

from autofit import graphical as graph
from autofit.graphical.laplace import newton
Expand Down Expand Up @@ -220,3 +221,58 @@ def spy(state1, state, **kwargs):
def test__hessian_option_validated():
with pytest.raises(ValueError):
LaplaceOptimiser(hessian="exact")


def _deterministic_ep_run(hessian):
"""
z = 2x with a Gaussian prior and likelihood on x, so the posterior is
analytic: Var(x) = 1 / (1/1^2 + 1/0.5^2) = 0.2 and Var(z) = 4 Var(x) = 0.8.
The deterministic variable starts far wider than that, at N(0, 10), so a
projection that never refreshes it is visible in the returned variance.
"""
x_, z_ = Variable("x"), Variable("z")

def prior(x):
return float(stats.norm(0.0, 1.0).logpdf(x).sum())

def likelihood(x):
return float(stats.norm(0.0, 0.5).logpdf(x).sum())

def double(x):
return 2.0 * x

model = (
graph.Factor(prior, x_)
* graph.Factor(likelihood, x_)
* graph.Factor(double, x_, factor_out=z_)
)
approx = graph.EPMeanField.from_approx_dists(
model, {x_: NormalMessage(0.0, 10.0), z_: NormalMessage(0.0, 10.0)}
)

np.random.seed(1)
optimiser = graph.EPOptimiser(
approx.factor_graph,
default_optimiser=LaplaceOptimiser(hessian=hessian),
)
mean_field = optimiser.run(approx, max_steps=10).mean_field
return mean_field, x_, z_, optimiser


@pytest.mark.parametrize("hessian", ["fd", "quasi"])
def test__deterministic_variance_follows_the_free_variable(hessian):
# The fd branch used to write only the free-variable Hessian, leaving the
# deterministic variable at the cavity precision `prepare_state` built: it
# returned Var(z) = 100, its starting variance, with success (PyAutoFit#1570).
mean_field, x_, z_, optimiser = _deterministic_ep_run(hessian)

assert float(mean_field[x_].variance) == pytest.approx(0.2, rel=1.0e-2)
assert float(mean_field[z_].variance) == pytest.approx(0.8, rel=1.0e-2)
# the free variable's own factors report success throughout, which is why a
# deterministic variable left at its cavity covariance was silent
assert all(
status.success
for factor, history in optimiser.ep_history.history.items()
for _, status in history.history
if not factor.deterministic_variables
)
Loading