lesson depth
Mastery
not started · 0%

Probabilistic Graphical Models & Exact Inference

Bayesian networks, conditional independence, d-separation, exact inference via Variable Elimination, factor marginalization, Markov models, and MDP foundations of RLHF/GRPO.

Freshness: current•16 min read•Computer Science and Programming

Key Learning Outcomes

  • ✓Decompose joint probability distributions using directed acyclic graph factorizations and verify conditional independence via d-separation.
  • ✓Execute exact inference via Variable Elimination using pointwise factor products and marginalization summations.
  • ✓Connect Markov Decision Processes (MDPs) and Bellman optimality equations to modern policy optimization algorithms (PPO and GRPO).

Mental model

In complex real-world engineering systems, deterministic logic is insufficient: sensors are noisy, model predictions are imperfect, and environmental dynamics are stochastic. If an agent attempts to model uncertainty by storing a full joint probability distribution over $n$ boolean variables, it must store $2^n - 1$ floating-point numbers—an exponential impossibility for $n > 30$.

Probabilistic Graphical Models (PGMs), pioneered by Judea Pearl (1988), resolve this curse of dimensionality by uniting probability theory with graph theory. A Directed Acyclic Graph (DAG) encodes conditional independence assertions between variables: a node is conditionally independent of its non-descendants given its parents.

In modern AI systems, graphical models provide the foundational mathematical framework for:

  1. Calibrated uncertainty quantification across multi-agent sensor networks and evaluation pipelines.
  2. Markov Decision Processes (MDPs), which serve as the exact theoretical formulation underpinning post-training alignment (RLHF, PPO, and GRPO in reasoning models like DeepSeek-R1).
Directed Acyclic Graph (DAG) Topology
Conditional Probability Factor Tables
Evidence Instantiation & Factor Restriction
Variable Elimination Sum-Product Inference
Normalized Posterior Distribution Marginals
Conceptual teaching model synthesized from:aima-search-planning,pearl-pgm-1988

Learning outcomes

  • Decompose full joint probability distributions using Bayesian Network DAG factorizations.
  • Evaluate conditional independence assertions ($A \perp B \mid C$) across chains, forks, and colliders using the d-separation criterion.
  • Execute exact inference using the Variable Elimination algorithm with pointwise factor multiplication and marginalization.
  • Formulate sequential decision-making as a Markov Decision Process (MDP) and trace the Bellman optimality equations to modern policy optimization algorithms (PPO and GRPO).

Theory

Bayesian Network Factorization

A Bayesian network represents a joint probability distribution over a set of random variables $X = \{X_1, X_2, \dots, X_n\}$ using a DAG where vertices represent variables and directed edges represent direct conditional dependencies.

By the chain rule of probability combined with conditional independence:

text(2 lines)
1P(X_1, X_2, ..., X_n) = prod_{i=1}^n P(X_i | Parents(X_i))

If each node has at most $k$ parents, the total number of parameters required to specify the complete distribution drops from $O(2^n)$ to $O(n \cdot 2^k)$—a monumental exponential reduction.

Conditional Independence & d-Separation

Two variables $X$ and $Y$ are conditionally independent given evidence variables $E$ ($X \perp Y \mid E$) if all undirected paths between $X$ and $Y$ are blocked according to the three fundamental connection topologies:

  1. Causal Chain ($X \to Z \to Y$): Blocked if and only if intermediate node $Z$ is in evidence set $E$.
  2. Common Cause / Fork ($X \leftarrow Z \to Y$): Blocked if and only if intermediate node $Z$ is in evidence set $E$.
  3. Common Effect / Collider / V-Structure ($X \to Z \leftarrow Y$): Inactive (blocked) by default when neither $Z$ nor any of its descendants are in $E$. Crucially, observing $Z$ (or any descendant of $Z$) activates the path, inducing a dependency between $X$ and $Y$. This phenomenon is known as explaining away (Berkson's paradox).

Exact Inference via Variable Elimination

To compute the posterior probability $P(Q \mid E = e)$ of a query variable $Q$ given evidence $E = e$, we sum over all hidden (nuisance) variables $H$:

text(2 lines)
1P(Q, e) = sum_{h in H} prod_{i=1}^n P(X_i | Parents(X_i))

Instead of summing the full product directly, Variable Elimination exploits the distributive law ($a \cdot b + a \cdot c = a \cdot (b + c)$), pushing summations inside factor products.

python(55 lines)
1from typing import Dict, List, Set
2
3class Factor:
4 def __init__(self, variables: List[str], values: Dict[tuple, float]):
5 self.variables = variables # Variable names
6 self.values = values # Mapping: tuple of values -> probability
7
8def point_wise_product(f1: Factor, f2: Factor) -> Factor:
9 """Multiplies two factors by joining matching variable assignments."""
10 joined_vars = list(dict.fromkeys(f1.variables + f2.variables))
11 new_values = {}
12 # Cross-product multiplication over shared and distinct variable assignments
13 # (Simplified illustration of factor multiplication)
14 return Factor(joined_vars, new_values)
15
16def sum_out(var: str, factor: Factor) -> Factor:
17 """Marginalizes out a variable by summing over all its domain values."""
18 remaining_vars = [v for v in factor.variables if v != var]
19 new_values = {}
20 # Sum over all instances of var in factor.values
21 return Factor(remaining_vars, new_values)
22
23def variable_elimination(
24 query_var: str,
25 evidence: Dict[str, any],
26 factors: List[Factor],
27 elimination_order: List[str]
28) -> Dict[any, float]:
29 # 1. Restrict factors by given evidence
30 current_factors = [restrict_evidence(f, evidence) for f in factors]
31
32 # 2. Sequentially eliminate nuisance variables
33 for var in elimination_order:
34 if var == query_var or var in evidence:
35 continue
36 # Collect all factors containing var
37 matching = [f for f in current_factors if var in f.variables]
38 remaining = [f for f in current_factors if var not in f.variables]
39
40 # Multiply matching factors together
41 prod_factor = matching[0]
42 for f in matching[1:]:
43 prod_factor = point_wise_product(prod_factor, f)
44
45 # Marginalize out the variable
46 marginalized = sum_out(var, prod_factor)
47 current_factors = remaining + [marginalized]
48
49 # 3. Final product and normalization
50 final_factor = current_factors[0]
51 for f in current_factors[1:]:
52 final_factor = point_wise_product(final_factor, f)
53
54 return normalize(final_factor)
35 lines hidden

Computational Complexity: Exact inference is $O(n \cdot d^{w^*})$, where $w^*$ is the tree-width of the graph induced by the chosen elimination ordering. Finding the optimal elimination order is NP-hard.

Markov Decision Processes (MDPs) to Modern RLHF / GRPO

An MDP is a sequential probabilistic model defined by $\langle S, A, T, R, \gamma \rangle$. The agent's goal is to find a policy $\pi(a \mid s)$ that maximizes the expected discounted cumulative return:

text(2 lines)
1V^*(s) = max_{a in A} [ R(s, a) + gamma * sum_{s'} T(s, a, s') * V^*(s') ]

In modern LLM alignment (RLHF, PPO, and DeepSeek-R1's Group Relative Policy Optimization - GRPO):

  • State $s_t$: Prompt and generated tokens up to step $t$.
  • Action $a_t$: Next token sampled from vocabulary $V$.
  • Policy $\pi_\theta(a_t \mid s_t)$: The autoregressive neural network weights.
  • Reward $R$: Computed by an automated verifier (for math/code) or a trained Reward Model (for safety).

In GRPO, instead of training an auxiliary value network Critic (which consumes significant GPU memory), the model samples a group of $G$ outputs for each prompt, evaluates their empirical rewards $\{r_1, \dots, r_G\}$, and computes normalized advantages:

text(2 lines)
1A_i = (r_i - mean(r)) / std(r)

The policy gradient is updated directly using the advantage estimate:

text(2 lines)
1Loss = - (1/G) * sum_{i=1}^G [ (pi_theta / pi_ref) * A_i - beta * KL(pi_theta || pi_ref) ]

Classical MDP principles provide the exact mathematical foundation for this gradient optimization.

Trade-offs

| Probabilistic Model | Representation Expressiveness | Inference Complexity | Learning Complexity | Ideal Application | |---|---|---|---|---| | Naïve Bayes | Strict mutual independence given class | $O(n)$ linear | Closed-form counting | High-throughput spam/sentiment classification | | Bayesian Networks (Exact) | Factored DAG conditional dependencies | $O(n \cdot d^{w^*})$ (exponential in tree-width) | Maximum Likelihood / EM | Medical diagnosis, fault isolation, causal analysis | | Approximate Sampling (MCMC / Gibbs)| Full graphical models | Asymptotically exact; slow convergence | Not applicable | Physics simulations, Bayesian parameter estimation | | Markov Decision Processes (MDP) | Sequential stochastic control | Polynomial via Dynamic Programming | Value/Policy Iteration | Robotics, resource scheduling | | Policy Optimization (PPO / GRPO)| Deep continuous parameterized policies | Neural forward pass | Stochastic gradient descent on GPUs | LLM post-training alignment, reasoning model self-play |

Failure modes and misconceptions

  1. Explaining Away Confusion: Assuming that two independent causes remain independent after observing their common effect. If an alarm sounds ($Z=1$), observing that an earthquake occurred ($X=1$) reduces the posterior probability that a burglary occurred ($Y=1$), even though burglary and earthquake are unconditionally independent.
  2. Ignoring Induced Tree-Width: A poorly chosen variable elimination ordering can introduce intermediate factors with dozens of variables, causing out-of-memory crashes on networks with fewer than 100 nodes.
  3. Correlation vs. Causation in Directed Edges: Directing an edge from $A \to B$ implies conditional dependence, but without interventional data (Pearl's $do$-calculus), a statistical DAG cannot distinguish between causal effects and unobserved confounders.
  4. Treating LLM Softmax Logits as True Probabilities: Deep neural networks are notoriously uncalibrated. Output token logits reflect training frequency and temperature scaling rather than true Bayesian posterior probabilities.
Reflect before revealing the guide

Decision scenario

You are architecting an automated fraud detection engine for high-value financial wires. The system aggregates 12 noisy signals (IP geolocation mismatch, device fingerprint changes, historical transaction velocity, recipient risk score, biometric typing cadence). The compliance department requires both an explainable risk calculation and transparent confidence intervals.

  • Option A: Train an uncalibrated black-box deep multi-layer perceptron that outputs a single scalar fraud score between 0.0 and 1.0.
  • Option B: Feed all 12 signals into an LLM prompt and ask it to output: "Low, Medium, or High Risk with an explanation."
  • Option C: Build a Bayesian Network modeling the causal generation of fraud indicators from latent risk states, executing Variable Elimination to compute exact posterior probability $P(\text{Fraud} \mid \text{Evidence})$ alongside marginal sensitivity analyses for human audit.

Recommendation: Choose Option C. Option A fails regulatory auditability mandates because the black-box embeddings cannot explain why a specific wire was flagged. Option B suffers from non-deterministic variance and hallucinations on borderline cases. Option C provides mathematically grounded posterior probabilities, robust handling of missing sensor telemetry, and auditable causal explanations required by financial regulators.

Prerequisites & Related Concepts (2)

Private notes

0 words
Next