Belief propagation: distinguish stable messages from accurate marginals
置信传播
Compare synchronous pairwise messages with exact enumeration and expose a converged but inaccurate loopy example.
belief-propagationA small change in the messages can still leave a wrong answer
A three-node chain has exact marginals obtainable by passing local messages. Close the chain into a triangle and reuse the same update rule: the messages in our example settle to within 10⁻¹², yet one reported marginal is wrong by about 0.0261. The computation has found a stable numerical pattern, not an exact answer to the probability problem.
Belief propagation is a family of local inference procedures. Its guarantees depend on the graph and the update schedule. Read factor graphs for the tree proof and Markov random fields for normalized potentials. This chapter focuses on pairwise updates and what changes when a loop is present.
A message summarizes information from the other neighbors
Take a finite pairwise model with unary weights uᵢ(xᵢ) and positive edge potentials ψᵢⱼ(xᵢ,xⱼ). After absorbing factor nodes into pairwise messages, the update from variable i toward j is:
Normalize each message so its entries sum to one. Its arbitrary positive scale does not affect normalized beliefs. The destination j is excluded from the incoming product, as in sum-product on a factor graph. On a tree, messages summarize disjoint components and can be scheduled from leaves; a final outward pass supplies all marginals. The Kschischang–Frey–Loeliger paper, SectionsII andV, separates exact cycle-free summaries from loopy iterations.
At any iteration, the reported belief is:
On a tree after messages have propagated far enough, this is the true marginal. During a finite transient or on a loop it is generally an approximation. A belief is not automatically a posterior that has been computed exactly.
Specify the update schedule and stopping rule
A synchronous update computes every candidate from the previous iteration’s messages, then replaces them together. An asynchronous schedule uses newly available messages sooner. Damping mixes an old normalized message with its normalized candidate. With η denoting the candidate’s weight, our update and diagnostic are:
η=1 means no damping. Damping can change stability and speed; it does not restore a general tree theorem on loops. A small η also makes the actual step smaller, so the same residual threshold should not be mistaken for a universal measure of inference error. Yedidia, Freeman and Weiss’s report develops the relation between loopy BP and approximate free-energy formulations. We do not use that relation to certify the global optimum of a loopy iteration.
Compare the same local rule with an exact joint
The complete Python 3.12 program supports 1–8 binary variables, finite positive unary and pairwise weights in[10⁻⁶,10], an update rate in(0,1] and up to 1000 synchronous steps. Edge keys use increasing variable indices; the table is read in the corresponding argument order, including when the message travels in reverse. Graphs may contain loops or be disconnected. The exact reference is a separate exhaustive calculation for the valid supplied model.
from fractions import Fraction as F
from itertools import product
from math import isfinite,prod
def belief_propagation(unary, edges, rate=1.0, tolerance=1e-12, max_steps=500):
unary=[list(row) for row in unary];n=len(unary)
if not 1<=n<=8 or any(len(row)!=2 for row in unary):
raise ValueError('one to eight binary unary tables required')
if any(type(v) not in (int,float) or not isfinite(v) or not 1e-6<=v<=10 for row in unary for v in row):
raise ValueError('finite positive potentials in [1e-6,10] required')
adj=[[] for _ in range(n)];tables={}
for key,table in edges.items():
if len(key)!=2 or any(type(v) is not int for v in key) or not 0<=key[0]<key[1]<n:
raise ValueError('edge keys must be increasing valid index pairs')
table=[list(row) for row in table]
if len(table)!=2 or any(len(row)!=2 for row in table) or any(type(v) not in (int,float) or not isfinite(v) or not 1e-6<=v<=10 for row in table for v in row):
raise ValueError('positive binary pair table required')
tables[key]=table;i,j=key;adj[i].append(j);adj[j].append(i)
if type(rate) not in (int,float) or not isfinite(rate) or not 0<rate<=1:
raise ValueError('update rate in (0,1] required')
if type(tolerance) not in (int,float) or not isfinite(tolerance) or not 1e-15<=tolerance<=1e-3:
raise ValueError('tolerance in [1e-15,1e-3] required')
if type(max_steps) is not int or not 1<=max_steps<=1000:
raise ValueError('integer maximum steps in [1,1000] required')
def pair(i,j,xi,xj):
return tables[i,j][xi][xj] if i<j else tables[j,i][xj][xi]
messages={(i,j):[.5,.5] for i in range(n) for j in adj[i]}
for iteration in range(1,max_steps+1):
updated={}
for i,j in messages:
raw=[sum(unary[i][xi]*pair(i,j,xi,xj)*prod(messages[k,i][xi] for k in adj[i] if k!=j) for xi in (0,1)) for xj in (0,1)]
normalizer=sum(raw);candidate=[x/normalizer for x in raw]
updated[i,j]=[(1-rate)*messages[i,j][x]+rate*candidate[x] for x in (0,1)]
residual=max((abs(updated[key][x]-messages[key][x]) for key in messages for x in (0,1)),default=0.0)
messages=updated
if residual<=tolerance:break
beliefs=[]
for i in range(n):
raw=[unary[i][x]*prod(messages[k,i][x] for k in adj[i]) for x in (0,1)]
beliefs.append([x/sum(raw) for x in raw])
return beliefs,iteration,residual,residual<=tolerance
def exact_reference(unary,edges):
n=len(unary);weights={}
for state in product((0,1),repeat=n):
weight=prod((F(unary[i][state[i]]) for i in range(n)),start=F(1))
for (i,j),table in edges.items():weight*=F(table[state[i]][state[j]])
weights[state]=weight
z=sum(weights.values(),F(0))
return [[sum((w for s,w in weights.items() if s[i]==x),F(0))/z for x in (0,1)] for i in range(n)]
if __name__ == '__main__':
unary=[[1,2],[1,1],[1,1]]
chain={(0,1):[[3,1],[1,3]],(1,2):[[2,1],[1,2]]}
triangle={**chain,(0,2):[[3,1],[1,3]]}
for name,edges in [('chain',chain),('triangle',triangle)]:
b,it,res,converged=belief_propagation(unary,edges)
exact=exact_reference(unary,edges)
print(name,'steps:',it,'message residual:',f'{res:.3e}','stopped:',converged)
print('belief P(1):',*[f'{row[1]:.9f}' for row in b])
print('exact P(1):',*[str(row[1]) for row in exact])
print('maximum marginal error:',f'{max(abs(row[1]-float(ref[1])) for row,ref in zip(b,exact)):.9f}')
print('one-step triangle stopped:',belief_propagation(unary,triangle,max_steps=1)[3])
Output:
chain steps: 3 message residual: 0.000e+00 stopped: True
belief P(1): 0.666666667 0.583333333 0.527777778
exact P(1): 2/3 7/12 19/36
maximum marginal error: 0.000000000
triangle steps: 30 message residual: 7.887e-13 stopped: True
belief P(1): 0.692767193 0.618625965 0.618625965
exact P(1): 2/3 47/78 47/78
maximum marginal error: 0.026100527
one-step triangle stopped: False
The chain matches the earlier random-field example: probabilities of state 1 are 2/3,7/12,19/36. Adding an AC edge that favors equal labels by a factor of 3 forms the triangle. Exhaustive enumeration gives 2/3,47/78,47/78; BP instead reports approximately 0.692767,0.618626,0.618626. It stops after 30 iterations with a message residual below 10⁻¹², despite a maximum marginal error above 0.026. These are observations for these inputs and this schedule, not a universal error bound.
max_steps=1 correctly returns a false stopping flag for the triangle. The flag says whether the message-change criterion was met. It does not claim uniqueness of the fixed point, successful global optimization or accurate marginals. The exact reference uses fractions for the represented input values; BP uses floating point.
For binary pairwise graphs, this straightforward implementation costs O(Σᵢdeg(i)²) per iteration because it recomputes incoming products for each outgoing edge. Message storage is O(E); the separate reference visits 2ⁿ configurations and stores their weights. More efficient product caching is possible. Dense or higher-order factors require different cost accounting; this code is deliberately pairwise.
Feedback can recycle information
Removing an edge from a loop does not split the graph into independent components. Messages can bring information back around the loop, so the disjoint-subtree proof no longer applies. Some problems converge to useful approximations, some oscillate, and some have multiple fixed points. The input’s strict positivity avoids zero-message contradictions here, but does not guarantee correctness or convergence.
This implementation normalizes messages and therefore does not recover the original partition function from their final scales. A Bethe approximation to a normalizer would be an additional calculation with a different guarantee. Likewise, replacing sums with maxima creates a MAP-oriented variant rather than preserving marginal inference.
A small test graph permits exact comparison. A large deployment may not, so assess approximation sensitivity across schedules, initializations and stronger reference methods where feasible. Agreement between two similar loopy implementations is weaker evidence than agreement with exact enumeration on a tractable model.
Ask what the stopping flag means
- In a synchronous update, may one message use another message already updated in the same iteration?
Answer 1: No. That would be an asynchronous schedule; all synchronous candidates read the old messages.
- Why does the destination not appear in the incoming product?
Answer 2: The outgoing message summarizes the other neighbors’ contributions, rather than immediately returning the recipient’s own contribution.
- Does a residual below 10⁻¹² certify a marginal error below 10⁻¹²?
Answer 3: No. The triangle has residual below that threshold and marginal error about 0.0261.
- Does η=1/2 mean half the data are ignored?
Answer 4: No. It mixes the old message and the new candidate equally; it changes the numerical update, not the observations.
Keep representation and approximation separate
Belief propagation connects probabilistic inference with decoding and approximate energy methods. Its local appearance is attractive because a large model can be processed through small neighborhoods. The mathematical work lies in the relationship between those local updates and the global quantity being requested.
Project: vary the added triangle potential continuously from all ones to a strong agreement preference. Record the exact marginal error, iteration count and stopping residual separately. Repeat with damping. A smaller residual or more iterations should never be reported as lower inference error unless the exact comparison supports it.
Make a prediction, then check
Does a tiny loopy-BP message residual certify exact marginals?
Learning objectives
- Implement normalized synchronous pairwise updates with explicit damping.
- Distinguish a message residual from exact marginal error.
Prerequisites & connections
Explore related knowledge →References
- Factor Graphs and the Sum-Product Algorithm
Frank R. Kschischang; Brendan J. Frey; Hans-Andrea Loeliger · 2001 - Understanding Belief Propagation and its Generalizations — TR2001-22
Jonathan S. Yedidia; William T. Freeman; Yair Weiss · 2001
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-06 · Codex single-agent authored technical review: cited primary-source scope, explicit assumptions, original calculations and counterexamples, runnable tests and bilingual review; not independent human or second-agent review.
- Single-agent authored technical review: bounded primary-source locations, assumptions, original derivations, exact/literal references and matching bilingual equations/examples/exercises. Not independent human or second-agent review.
- Four focused CPython3.12.4 tests passed per chapter. Markov and MH matrices use exact fractions; EM and BP are floating-point and tested against independent analytic or enumerated references. Seeded MCMC frequencies are an observed run, not a convergence certificate.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
Source locations checked:
- Factor Graphs and the Sum-Product Algorithm · SectionsII/V: exact component summaries on trees versus iterative messages and absent general exactness on cycles.
- Understanding Belief Propagation and its Generalizations — TR2001-22 · MERL cover/abstract: TR2001-22, November2001, connects BP fixed points with Bethe stationary points; inner colophon says final draftJanuary2002. Main body text extraction is garbled; no full-body proof review claimed. Damping convention and triangle are original calculations.
Related topics