Factor graphs: compute marginals with local messages
因子图
Expose factor scopes, compute exact tree marginals and distinguish tree guarantees from loopy inference.
factor-graphsDraw the functions as well as the variables
A product such as u(A)f(A,B)g(B,C) says more than “A is connected to B.” It names three different functions and tells us exactly which arguments each one reads. A factor graph makes those functions into nodes: variable nodes connect to factor nodes, and an edge means the variable is an argument of that factor. There are no variable-to-variable or factor-to-factor edges.
For this product, the graph is a tree: u—A—f—B—g—C. A factor may also touch three or more variables. The number of arguments affects computation even if the picture looks small. Read Markov random fields and Bayesian networks first.
Represent a product, then choose the inference operation
For nonnegative factors on finite variables with a finite, positive normalizer Z, the joint and a single-variable marginal are:
N(a) lists the variables touched by factor a. Factors need not be conditional probabilities. A Bayesian-network conditional table can be one factor; an undirected potential can be another. Deep Learning’s structured-models chapter explains these product representations. A particular factorization determines the factor graph; the same distribution can admit different factorizations and different graph shapes.
The Kschischang–Frey–Loeliger 2001 paper, SectionII, develops sum-product on these graphs. A message along an edge is a function of the variable on that edge. Variable-to-factor messages multiply the other incoming messages:
The destination is excluded so a message is not immediately sent back as its own evidence. At a leaf variable, the empty product is 1 for each state. Factor-to-variable messages multiply the factor by the other incoming messages and sum out its other arguments:
At a unary factor this is just its table. Finally, multiply all messages arriving at a variable and normalize the resulting vector.
Why a tree makes the answer exact
Deleting an edge of a tree splits it into two disjoint components. The message toward the other side summarizes the product of all factors on the sending side, summed over every variable there except the shared argument. Starting at leaves proves this interpretation by induction: incoming components are disjoint, so their factors multiply without double counting. At a variable, the incoming components cover the rest of the tree; their product is its unnormalized marginal.
With unnormalized messages, summing that vector gives the same global Z at every variable. If messages are separately rescaled for numerical stability, normalized marginals survive positive rescaling, but recovering Z requires keeping the scale factors. Our exact rational implementation does not discard those scales.
A small tree engine with a visible contract
The complete Python 3.12 program handles 1–8 binary variables, at most 12 factors and factor arity 1–3. Table entries are rational weights in[0,1000], ordered lexicographically by the listed scope’s binary assignments. It validates the connected bipartite tree before recursive messages run, caches both message directions, and rejects an all-zero joint. A single isolated variable is a valid tree with a uniform marginal and Z=2.
from fractions import Fraction as F
from functools import lru_cache
from itertools import product
from math import prod
def tree_marginals(n, factors):
if type(n) is not int or not 1<=n<=8:
raise ValueError('one to eight binary variables required')
factors=list(factors)
if len(factors)>12:raise ValueError('at most twelve factors')
parsed=[];adj=[[] for _ in range(n+len(factors))]
for j,(scope,weights) in enumerate(factors):
scope=tuple(scope);weights=tuple(weights)
if not 1<=len(scope)<=3 or len(set(scope))!=len(scope):
raise ValueError('one to three distinct variables per factor')
if any(type(v) is not int or not 0<=v<n for v in scope):
raise ValueError('variable index outside graph')
if len(weights)!=2**len(scope) or any(type(w) not in (int,F) or not 0<=w<=1000 for w in weights):
raise ValueError('nonnegative rational binary table at most1000 required')
parsed.append((scope,dict(zip(product((0,1),repeat=len(scope)),map(F,weights)))))
for v in scope:adj[v].append(n+j);adj[n+j].append(v)
seen=set();stack=[(0,-1)]
while stack:
node,parent=stack.pop()
if node in seen:raise ValueError('factor graph contains a cycle')
seen.add(node)
stack.extend((other,node) for other in adj[node] if other!=parent)
if len(seen)!=len(adj):raise ValueError('connected tree required')
@lru_cache(None)
def message(node,destination):
if node<n:
return tuple(prod((message(other,node)[x] for other in adj[node] if other!=destination),start=F(1)) for x in (0,1))
scope,table=parsed[node-n];position=scope.index(destination);out=[F(0),F(0)]
for state,weight in table.items():
incoming=prod((message(v,node)[state[k]] for k,v in enumerate(scope) if v!=destination),start=F(1))
out[state[position]]+=weight*incoming
return tuple(out)
marginals=[];partition=None
for v in range(n):
raw=[prod((message(f,v)[x] for f in adj[v]),start=F(1)) for x in (0,1)]
z=sum(raw,F(0))
if z==0:raise ValueError('all configurations have zero weight')
if partition is not None and z!=partition:raise ArithmeticError('inconsistent tree normalization')
partition=z;marginals.append(tuple(x/z for x in raw))
return marginals,partition
if __name__ == '__main__':
factors=[((0,),[1,2]),((0,1),[3,1,1,3]),((1,2),[2,1,1,2])]
marginals,z=tree_marginals(3,factors)
print('partition:',z)
for i,m in enumerate(marginals):print('variable',i,':',*[str(v) for v in m])
observed,z=tree_marginals(3,factors+[((1,),[0,1])])
print('B=1 weight:',z)
for i,m in enumerate(observed):print('conditioned',i,':',*[str(v) for v in m])
parity=[((0,1,2),[1,0,0,1,0,1,1,0])]
print('even-parity normalizer:',tree_marginals(3,parity)[1])
Output:
partition: 36
variable 0 : 1/3 2/3
variable 1 : 5/12 7/12
variable 2 : 17/36 19/36
B=1 weight: 21
conditioned 0 : 1/7 6/7
conditioned 1 : 0 1
conditioned 2 : 1/3 2/3
even-parity normalizer: 4
The first model matches the preceding random-field chapter: Z=36 and the probabilities of A=1,B=1,C=1 are 2/3,7/12,19/36. Adding a unary indicator[0,1] at B conditions on B=1. The new unnormalized total is 21, so the evidence probability under the original normalized model is 21/36; the conditional endpoint probabilities become 6/7 and 2/3.
The parity factor permits only assignments with an even number of ones. It has four legal assignments and Z=4. This is a genuine three-variable factor, not a collection of unnamed pairwise links. Zero entries encode hard constraints; contradictory constraints produce Z=0 and must be reported rather than normalized.
For binary factors of degrees d_a, this direct implementation uses O(Σ_a d_a²2^d_a + Σ_i deg(i)²) arithmetic operations for all cached directed messages, plus table storage and O(E) message entries. It repeats some products to keep the update rule visible. More careful prefix/suffix products can reduce that overhead. These costs exclude rational-number bit growth. Exhaustive enumeration instead visits 2ⁿ global assignments even when every factor is small.
A loop changes the guarantee
A tree in the variable graph does not by itself prove the chosen factor graph is acyclic. Two factors sharing two variables already form a four-edge bipartite cycle. The program rejects such input. Iterating the same local updates on a loopy graph is a separate algorithm: convergence and exactness are not generally guaranteed. SectionV of the original paper makes this distinction.
Marginal inference adds over alternatives; MAP chooses a maximum-weight configuration. Replacing sum by max leads to max-product or max-sum variants with their own reconstruction rules. Taking each marginal’s most likely state independently need not find a jointly legal or maximum-weight configuration, especially with hard constraints.
A graph specifies neither how factor parameters were learned nor whether its assumptions fit the application. Large dense factors can hide exponential work in one node. Choose scopes and approximation methods with the actual state spaces in view.
Trace what crosses one edge
- What message does a leaf variable with no other factors send?
Answer 1: The constant vector(1,1), because the empty product is 1.
- Why must a message exclude the edge it is being sent along?
Answer 2: It summarizes the sending-side component. Including the destination’s message would feed its contribution back and double count.
- In the chain example, what is p(B=1) from the old and new normalizers?
Answer 3: 21/36=7/12. The new total uses the same unnormalized factors plus a B=1 indicator.
- Does a three-variable parity factor necessarily create a cycle?
Answer 4: No. One factor connected to three variables is a star, hence a tree. Factor arity and graph cycles are different properties.
One local rule, several familiar algorithms
The 2001 paper connects sum-product with message-passing algorithms in probabilistic inference and coding. Its exact tree argument is the basis used here; broad application examples in the paper are not performance claims for this small engine. Belief propagation will examine schedules and approximations separately.
Project: translate the collider network’s three conditional tables into factors, add a warning-evidence indicator and compare its posterior with exact joint enumeration. Then deliberately add a cycle and confirm that this tree solver refuses it. Do not relabel refusal as successful approximate inference.
Make a prediction, then check
Do two factors that share two variables form a cycle in the factor graph?
Learning objectives
- Represent a product with distinct variable and factor nodes.
- Compute exact tree marginals and diagnose invalid normalization or cycles.
Prerequisites & connections
Explore related knowledge →References
- Factor Graphs and the Sum-Product Algorithm
Frank R. Kschischang; Brendan J. Frey; Hans-Andrea Loeliger · 2001 - Deep Learning — Chapter16: Structured Probabilistic Models
Ian Goodfellow; Yoshua Bengio; Aaron Courville · 2016
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 locations, mathematical assumptions, original examples, exact/literal and numerical checks, and bilingual review; not independent human or second-agent review.
- Single-agent authored technical review: primary-source locations, explicit assumptions and limits, mathematical derivations, literal/exact reference probabilities, bilingual equations and four matching exercises. Not independent human or second-agent review.
- Four focused CPython3.12.4 tests passed per chapter; strict bilingual MDX/KaTeX rendering gives three display equations, six anchors and four answers. Exact rational inference is separated from floating-point maximum-entropy solving; test scopes and repository results are recorded separately.
- 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.
- Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
- Final English copy edit separates words from adjacent numerals outside code, equations and link destinations; formulas/programs unchanged, final SHA rebound.
- Reader-facing title and summary describe marginal inference; the first definition explicitly requires finite positive Z. Code and equations unchanged; final hashes rebound.
Source locations checked:
- Factor Graphs and the Sum-Product Algorithm · 2001 IEEE47(2), printed498–519: SectionII variable/factor nodes and equations5–6, tree component proof; SectionV warns loopy outputs are not generally exact summaries.
- Deep Learning — Chapter16: Structured Probabilistic Models · Chapter16 Sections16.2.1–16.2.2 product representations and16.2.7 explicit bipartite factor scopes. Original engine checks tree topology itself.
Related topics