Foundations to Frontier
Tests

Exact and approximate inference

Inference means answering questions of a probabilistic model: a marginal P(x_i | evidence), a most likely explanation, or the normalizing constant Z (the evidence). Exact inference sums the joint efficiently by exploiting the graph: variable elimination, belief propagation on trees and the junction tree algorithm. The cost grows exponentially with the treewidth, so grids, dense networks and continuous non-Gaussian models need approximations. These are deterministic ones (mean-field variational inference, loopy belief propagation and the Bethe free energy, expectation propagation, Laplace) or Monte Carlo ones (importance sampling, Gibbs, MCMC). This page puts the whole map in one place and compares the methods on a model where the exact answer is known. In the exercise a 4×4 Ising grid with random fields is solved exactly by enumerating 65536 states. At weak coupling loopy BP was essentially exact (marginal error below 0.0001) and mean field nearly so (0.003). Near the phase transition (J = 0.5) mean field was badly overconfident (marginal error 0.24, magnetization 0.84 against a true 0.38), while loopy BP erred by 0.06 and Gibbs sampling by 0.008. At strong coupling (J = 1) Gibbs chains got trapped in one phase and became the worst method (0.18).

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Asking questions of a model

A graphical model is only useful if you can ask it questions: given that the alarm fired, how likely is a panel fault? Answering means adding up the probability of every combination of the other variables, and the number of combinations explodes. Exact methods organise that sum cleverly and are fast when the graph is close to a tree. When it is not, you approximate: either replace the distribution with a simpler one you can handle (variational methods, message passing on loops) or draw random samples from it (Monte Carlo). The demo compares exact answers on a tiny grid with two approximations; push the coupling up to see where they break.

Uncertainty lab
P(sᵢ = +1) for the 9 nodes: grey exact (enumerating 512 states), red mean field, blue loopy BP. Mean absolute error: mean field 0.210, loopy BP 0.005. Strong coupling makes mean field overconfident; loopy BP is usually far closer on this small loopy graph.
Why engineers care

Every Bayesian filter, SLAM back-end, fault diagnoser and Bayesian neural network is an inference engine. Knowing when an approximation is overconfident (mean field), when it is biased but stable (loopy BP, EP) and when it is unbiased but slow to mix (MCMC) is what lets you trust its error bars.

📝 Quick check (Level 0)
0/3 answered
  1. 1. Exact inference is cheap when the graph is…
  2. 2. Mean-field variational inference tends to be…
  3. 3. MCMC is asymptotically exact but can be…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

The map of inference methods

  • Tasks: marginals p(x_i | e), MAP / most probable explanation argmax p(x | e), and the evidence (partition function) Z = Σ_x p̃(x), whose log is what model comparison and learning need.
  • Variable elimination: push sums inside products, eliminating one variable at a time. On a chain of n binary spins this is a product of 2×2 transfer matrices: O(n) instead of 2ⁿ. For a 10-spin chain with J = 0.8, log Z = 9.9650 either way.
  • Belief propagation (sum-product): on a tree, messages m_(i→j)(x_j) = Σ_(x_i) ψ_i ψ_ij Π_(k≠j) m_(k→i) give exact marginals after two sweeps (forward–backward on a chain, Kalman smoothing for Gaussians). Max-product gives MAP (Viterbi).
  • Junction tree: cluster the graph into a tree of cliques; exact but exponential in the clique size. Treewidth of an L×L grid is L: a 20×20 grid needs tables with 2²¹ entries per clique.
  • Approximate, deterministic:
    • Mean field: q(x) = Π q_i(x_i); for the Ising model m_i = tanh(h_i + J Σ m_j). Its ELBO is a lower bound on log Z. Two spins with J = 0.5, h = 0.2: mean field m = 0.365, exact 0.283.
    • Loopy BP: run BP on a graph with cycles anyway (Pearl; Murphy, Weiss and Jordan, 1999). Its fixed points are stationary points of the Bethe free energy (Yedidia, Freeman and Weiss, 2001).
    • Expectation propagation (Minka, 2001) and Laplace (Gaussian at the mode) for continuous models; both are used in GP classification (I2-5).
  • Approximate, stochastic: importance sampling (ESS = (Σw)²/Σw²), Gibbs sampling (update each variable from p(x_i | Markov blanket); for Ising P(up) = σ(2(h_i + J Σ s_j)), e.g. 0.881 with three of four neighbours up at J = 0.5), Metropolis–Hastings, HMC, sequential Monte Carlo.
  • Two spins, no field: Z = 4 cosh J, so log Z = 1.386 at J = 0 and 1.820 at J = 1.
📝 Quick check (Level 1)
0/3 answered
  1. 1. BP on a tree gives…
  2. 2. The junction tree's cost is exponential in…
  3. 3. Loopy BP fixed points correspond to…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

Running inference

Exercise 1.

  • Variable elimination (transfer matrices) for log Z of an Ising chain, checked against enumeration.
  • Forward–backward marginals (BP on a tree).
  • Naive importance sampling of log Z and its effective sample size.

Practice.

  • Small discrete models (treewidth up to about 20): exact junction tree (pgmpy, libDAI). Use log-space or rescaling at every step.
  • Gaussian models: exact by linear algebra (Kalman, GTSAM’s sparse Cholesky); exploit sparsity.
  • Loopy discrete models: loopy BP with damping (0.5) as a fast baseline; check convergence; compare with Gibbs on a subset.
  • Continuous Bayesian models: NUTS (Stan, PyMC, NumPyro) as the reference; VI (ADVI, normalizing flows) when you need speed; check VI against MCMC on a subsample.
  • Diagnose MCMC with R-hat below 1.01, effective sample size and multiple chains from dispersed starts; diagnose VI with Pareto-k̂ of importance weights (PSIS; Yao et al., 2018).
import numpyro, numpyro.distributions as dist, jax.numpy as jnp
from numpyro.infer import MCMC, NUTS, SVI, Trace_ELBO, autoguide
def model(x, y=None):                      # Bayesian logistic regression for landing-site safety
    w = numpyro.sample("w", dist.Normal(0, 1).expand([x.shape[1]]).to_event(1))
    numpyro.sample("y", dist.Bernoulli(logits=x @ w), obs=y)
mcmc = MCMC(NUTS(model), num_warmup=500, num_samples=1000, num_chains=4); mcmc.run(key, x, y)
mcmc.print_summary()                       # r_hat, n_eff
guide = autoguide.AutoNormal(model)        # mean-field VI for comparison
svi = SVI(model, guide, numpyro.optim.Adam(0.01), Trace_ELBO()).run(key, 5000, x, y)
🐍 Exercise 1: exact chain inference and naive Monte Carlo
Compute log Z of an Ising chain by elimination and by enumeration, chain marginals by forward–backward, and log Z by uniform importance sampling.
📝 Quick check (Level 2)
0/3 answered
  1. 1. A good MCMC convergence check is…
  2. 2. Damping loopy BP helps…
  3. 3. PSIS Pareto-k̂ diagnoses…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

Why trees are easy. On a tree every variable separates the graph, so the sum over the joint factorizes into independent sums over subtrees. These partial sums are the BP messages, and each is computed once per direction: 2|E| messages, each costing (card)² for pairwise factors.

Variational view. For any q, log Z = ELBO(q) + KL(q ‖ p) with ELBO(q) = E_q[log p̃] + H(q). Mean field maximizes the ELBO over factorized q, so it gives a lower bound on log Z, and minimizing the reverse KL makes q mode-seeking: when the posterior has two phases (all spins up or all down) it picks one, and marginals become overconfident.

Bethe approximation. Replace the entropy with the Bethe entropy Σ_edges H(b_ij) − Σ_i (d_i − 1) H(b_i), exact on trees, and optimize over locally consistent pseudo-marginals. Loopy BP fixed points are exactly its stationary points. For attractive (ferromagnetic) binary models the Bethe partition function is a lower bound on Z (Ruozzi, 2012), consistent with Exercise 2; for general models it is neither bound.

Monte Carlo. Gibbs sampling is unbiased in the limit but its error depends on mixing. In a ferromagnet above the critical coupling (about 0.44 on the infinite square lattice, Onsager 1944) flipping a whole magnetized region needs crossing a barrier that grows with the region’s boundary, so single-site chains stay in one phase. Cluster moves (Swendsen–Wang, 1987), parallel tempering or annealed importance sampling fix this.

Complexity. Computing Z for general binary MRFs is #P-hard, and approximating marginals within a constant is NP-hard (Dagum and Luby, 1993; Roth, 1996): no method is good everywhere.

📝 Quick check (Level 3)
0/3 answered
  1. 1. Mean field gives a…
  2. 2. The Bethe entropy is exact on…
  3. 3. Single-site Gibbs mixes badly in a ferromagnet because…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

How do mean field, loopy BP and Gibbs sampling compare with exact inference as coupling grows?

History.

  • L. Onsager, “Crystal statistics I. A two-dimensional model with an order-disorder transition” (1944).
  • J. Pearl, Probabilistic Reasoning in Intelligent Systems (1988): belief propagation.
  • S. Lauritzen and D. Spiegelhalter (1988): the junction tree.
  • S. Geman and D. Geman, “Stochastic relaxation, Gibbs distributions, and the Bayesian restoration of images” (1984).
  • J. Yedidia, W. Freeman and Y. Weiss, “Generalized belief propagation” (2001) and the Bethe free energy; M. Wainwright and M. Jordan, “Graphical models, exponential families, and variational inference” (2008).

Exercise 2. A 4×4 Ising grid p(s) ∝ exp(J Σ s_i s_j + Σ h_i s_i), fields h_i ~ N(0, 0.3²), J = 0.1, 0.3, 0.5, 1.0.

  • Exact: enumerate all 65536 states for log Z and the marginals.
  • Mean field (damped, 500 iterations), loopy BP (damped, converged in every case) with the Bethe estimate of log Z, and checkerboard Gibbs with 50 chains × 200 sweeps (50 burn-in), random starts.
  • Measures: mean absolute error of P(s_i = +1) and the error of the log Z estimate.
J exact mean abs. magnetization mean field (MF) magnetization marginal error MF / loopy BP / Gibbs log Z error MF / Bethe
0.1 0.233 0.24 0.0033 / below 0.0001 / 0.0046 −0.102 / −0.001
0.3 0.309 0.414 0.0524 / 0.0042 / 0.0047 −0.793 / −0.046
0.5 0.378 0.844 0.242 / 0.0614 / 0.0078 −0.996 / −0.247
1.0 0.82 0.99 0.0853 / 0.0819 / 0.182 −0.116 / −0.093
  • Weak coupling: everything works; loopy BP is essentially exact.
  • Near the transition (J = 0.5, above the infinite-lattice critical 0.44) mean field more than doubled the magnetization and missed log Z by almost a full nat. Loopy BP was 4 times better on marginals and Gibbs best of all.
  • Strong coupling: both deterministic methods lock into one phase; Gibbs chains also get stuck (a chain rarely leaves the phase it falls into early), so its estimate depends on how many chains happened to start in each, giving the largest error here.
  • Bounds held: every mean-field and Bethe estimate of log Z was below the truth, as theory predicts for this attractive model.
  • Seeds 1 and 2 (different fields): at J = 0.5 marginal errors MF 0.269 / 0.343, loopy BP 0.129 / 0.101, Gibbs 0.022 / 0.006. At J = 1 Gibbs erred by 0.356 / 0.050. With seed 2 the fields nearly cancel (exact magnetization 0.015), so MF and BP each picked one phase and erred by 0.496 and 0.489.
🐍 Exercise 2 (research): how do mean field, loopy BP and Gibbs sampling compare with exact inference as coupling grows?
Compare mean field, loopy BP (with the Bethe free energy) and Gibbs sampling against exact enumeration on a 4×4 Ising grid at increasing coupling.

Inference in AI, robotics and aerospace

  • Navigation and SLAM: Kalman filters and smoothers are exact Gaussian BP; factor-graph solvers (iSAM2) do incremental exact inference on sparse graphs; particle filters are sequential Monte Carlo.
  • Decoding: turbo and LDPC codes on deep-space links are decoded by loopy BP, the first big success of the method (McEliece, MacKay and Cheng, 1998).
  • Vision and mapping: MRF priors for stereo, segmentation and land-cover maps use loopy BP, graph cuts or mean-field (dense CRF) inference.
  • Bayesian deep learning: mean-field VI, Laplace and MCMC for neural networks (section I3) inherit the trade-offs seen here.

References

  1. S. Geman and D. Geman (1984). “Stochastic relaxation, Gibbs distributions, and the Bayesian restoration of images.” IEEE PAMI, 6.
  2. S. L. Lauritzen and D. J. Spiegelhalter (1988). “Local computations with probabilities on graphical structures and their application to expert systems.” JRSS B, 50.
  3. R. Swendsen and J.-S. Wang (1987). “Nonuniversal critical dynamics in Monte Carlo simulations.” Physical Review Letters, 58.
  4. K. Murphy, Y. Weiss and M. Jordan (1999). “Loopy belief propagation for approximate inference: an empirical study.” UAI.
  5. T. Minka (2001). “Expectation propagation for approximate Bayesian inference.” UAI.
  6. J. S. Yedidia, W. T. Freeman and Y. Weiss (2001). “Generalized belief propagation.” NeurIPS.
  7. M. J. Wainwright and M. I. Jordan (2008). “Graphical models, exponential families, and variational inference.” Foundations and Trends in Machine Learning, 1.
  8. N. Ruozzi (2012). “The Bethe partition function of log-supermodular graphical models.” NeurIPS.
  9. Y. Yao, A. Vehtari, D. Simpson and A. Gelman (2018). “Yes, but did it work?: evaluating variational inference.” ICML.