Monte Carlo & MCMC
Most quantities of interest in a probabilistic model are integrals nobody can compute in closed form: expectations, marginals, partition functions. Monte Carlo replaces the integral with an average over samples; importance sampling reweights samples from a tractable proposal; and when even sampling the target is hard, Markov-chain Monte Carlo builds a chain whose stationary distribution is the target.
╌╌╌╌
A probabilistic model is useful only through the quantities you can read off it, and almost every such quantity is an integral: an expectation , a marginal , a normalizer . For the high-dimensional distributions deep models induce, these integrals have no closed form and a grid quadrature costs , hopeless past a handful of dimensions. Monte Carlo trades the integral for a sample average, and when even sampling the target is intractable, Markov-chain Monte Carlo generates the samples with a chain designed to converge to it.
Monte Carlo estimation
Every quantity below is an expectation of some function under a density :
The Monte Carlo estimator draws independent samples and returns their empirical mean:
Two facts make it the standard tool of probabilistic inference. It is unbiased (its expectation equals the target) and its variance falls as , independent of the dimension .
The decisive consequence is the law: the typical error shrinks like regardless of . The dimension does not appear in the rate; it enters only through . This is why Monte Carlo avoids the curse of dimensionality that makes grid methods intractable.1
| Method | Cost for error | Scaling in dimension |
|---|---|---|
| Grid / deterministic quadrature | exponential in | |
| Monte Carlo | no explicit — only via |
The central limit theorem upgrades the variance bound to a full sampling distribution: for large , which is what justifies the error bars that accompany any honest Monte Carlo estimate.
The geometric picture
The simplest instance is estimating an area (an integral of an indicator). Scatter points uniformly over a bounding box of known area ; the fraction that land in the region estimates . With and uniform on the box, reduces to that landing fraction: Monte Carlo integration with an indicator.
Importance sampling
Often we cannot draw from , or concentrates its mass where rarely puts samples. To address this, sample from a tractable proposal and correct the mismatch by reweighting. Multiply and divide by :
Sampling and averaging gives the importance-sampling estimator with weights :
The estimator is unbiased for any with wherever , but its variance depends sharply on the choice of . Minimizing over yields the optimal proposal.
The optimum is unreachable in practice, since it presupposes the very integral we are after (it needs ). It still dictates the design rule: put proposal mass where is large. The corresponding failure is a proposal with too little mass in those regions.
Markov chains
When the target admits no direct sampler, the typical case for the energy-based models of the next chapter, whose density is with an intractable , we abandon iid draws and build a Markov chain whose long-run distribution is . A chain is governed by a transition kernel , the probability of moving to given the current state . Starting from , the distribution evolves by one matrix–vector product per step:
For example, take three states with the transition matrix below, where entry is the probability of moving from state to state (columns sum to ). One step of the chain is the matrix–vector product ; iterating it drives any starting distribution toward the stationary , the eigenvector of with eigenvalue .
The transition matrix and its fixed point are
The chain forgets its start because every column mixes probability across states; only the eigenvector direction persists under repeated multiplication. MCMC constructs such a so that its fixed point is a distribution chosen in advance.
A convenient sufficient condition for stationarity is detailed balance, which we will use to design kernels with a prescribed stationary distribution.
Stationarity alone does not guarantee the chain reaches from an arbitrary start. That requires ergodicity: the chain must be irreducible (every state reachable from every other) and aperiodic. Under ergodicity the stationary distribution is unique and from any , at a rate set by the second-largest eigenvalue of .3
| Property | Meaning | Why it matters |
|---|---|---|
| Stationary | is a fixed point of | the chain leaves invariant |
| Irreducible | all states communicate | no region is trapped or unreachable |
| Aperiodic | no forced cyclic return | the chain mixes rather than oscillates |
| Ergodic | irreducible aperiodic | uniquely, from any start |
Markov-chain Monte Carlo
MCMC designs a kernel whose stationary distribution equals the target , runs the chain, and treats the visited states as (correlated) samples. Two constructions dominate.
Metropolis–Hastings
Pick any proposal and make every proposed move conditional on an accept/reject test built from the density ratio. The key property is that the test needs only up to its normalizer, since cancels in the ratio.
- 1initialize
- 2for to do
- 3propose
- 4acceptance ratio
- 5draw
- 6if thenaccept
- 7
- 8elsereject, stay put
- 9
- 10record as sample
- 11return
When the proposal is symmetric, (e.g. a Gaussian random walk), the factors cancel and the rule collapses to the original Metropolis acceptance : always accept a move uphill in density, accept a downhill move with probability equal to the density ratio.
For example, suppose a symmetric random walk sits at with and proposes with . The ratio is , so : draw and take the move only if , otherwise stay at and record it again. Had the proposal climbed to , the ratio would clip to and the move would always be taken. The chain therefore spends time in each region in proportion to , satisfying the stationary condition cancelled out of.
Gibbs sampling
When the full conditionals , the distribution of one coordinate given all the others, are tractable, Gibbs sampling dispenses with acceptance entirely: it sweeps the coordinates, resampling each from its conditional. This is the natural sampler for energy-based models, where each unit's conditional is a simple sigmoid of its neighbors.4
- 1initialize
- 2for to do
- 3for to doone sweep over coordinates
- 4sample from
- 5record as sample
- 6return
Each single-coordinate update leaves invariant, and a full sweep (a composition of invariant kernels) therefore does too.
The reason Gibbs sidesteps the acceptance test entirely is that the full conditional, like the M–H ratio, never sees . Write the joint as and condition on the fixed coordinates :
The global normalizer cancels top and bottom, leaving only a sum over the single coordinate — a one-dimensional normalization that is tractable even when the -dimensional is not. For a binary energy-based unit this collapses to a sigmoid: if with , then , which is why Gibbs is the native sampler of Boltzmann machines.
Geometrically, Gibbs moves are axis-aligned: each step slides along one coordinate to a value drawn from the conditional slice, tracing a staircase through the density.
Mixing
MCMC samples are correlated (each state is a perturbation of the last), so the practical question is how many steps separate two effectively independent draws. Two diagnostics govern this.
The variance penalty is the whole cost of correlation. Expanding the variance of the chain average keeps the cross terms that iid sampling would have killed:
where the last step takes so the edge correction drops out and the sum telescopes into the integrated autocorrelation time . Since is geometric, , which blows up as . Thus MCMC steps are worth only iid samples. A chain mixes quickly when is small ( small) and slowly when .
The pathological case is a multimodal target. To travel between two modes of , a local sampler must cross a region where , and hence the acceptance probability, is exponentially small. The chain is trapped in one mode for an exponentially long time: the energy barrier between modes is the geometric cause of slow mixing.
| Symptom | Cause | Remedy |
|---|---|---|
| Long burn-in | near ; poor start | discard early samples; better init |
| High autocorrelation | small proposal steps; strong coupling | thinning; block / reparameterized moves |
| Trapped in one mode | energy barrier between modes | tempering; parallel / annealed chains |
| Slow Gibbs | strongly correlated coordinates | block Gibbs; rotate coordinates |
Heavily correlated coordinates slow Gibbs for the same reason: each axis-aligned move is confined to a thin conditional slice, so the staircase advances in small steps along the ridge of the density.
The partition function
The motivating problem of Goodfellow Ch. 18 is learning an energy-based model , where is tractable but the normalizer is an intractable sum over all configurations. Maximum-likelihood training needs the gradient of , and that gradient splits into two terms: one cheap, one requiring samples from the model itself.
The second term is itself an expectation under the model, which is the crux:
The two phases have a physical reading: the positive phase pushes down the energy of observed data, while the negative phase pushes up the energy of the model's own fantasies, sampled by a Markov chain. Learning halts when the two balance, when the model's samples are statistically indistinguishable from the data.5
Annealed importance sampling
Detecting convergence or comparing two trained models still needs itself: for a held-out likelihood you must normalize. A naive importance-sampling estimate collapses because a tractable never overlaps a sharp model. Annealed importance sampling (AIS) addresses this by bridging from a simple base (with known ) to the target through a sequence of intermediate distributions , typically the geometric path for .
Each rung's two distributions overlap well, so each ratio is low-variance; the anneal schedule converts one intractable importance-sampling problem into many easy ones, the same divide-and-conquer logic that lets simulated annealing cross the energy barriers that trap a single-temperature chain.6
Gradient-guided samplers and the road to diffusion
The random-walk Metropolis of this lesson proposes moves blindly, so in high dimensions its acceptance rate forces tiny steps and the chain moves slowly. The samplers that dominate modern practice fix this by proposing moves along the gradient of the log-density — the same that appears nowhere in Metropolis but everywhere in deep learning.
Hamiltonian Monte Carlo (HMC; Neal, 2011, in the Handbook of MCMC) augments the state with a momentum and simulates physical dynamics under the potential energy : a particle given a random kick coasts along the density's contours for many steps before a single Metropolis accept/reject corrects the numerical error. Because the proposal follows the gradient rather than diffusing, HMC takes long, high-acceptance moves and its autocorrelation time barely grows with dimension. NUTS (the No-U-Turn Sampler; Hoffman & Gelman, 2014, JMLR) removes HMC's one awkward tuning knob — the trajectory length — by running the simulation until it starts to double back, and is the default engine inside probabilistic-programming systems like Stan and PyMC.
Langevin dynamics is the one-step limit of the same idea: propose with — a gradient-ascent step on the log-density plus calibrated noise. This is the bridge to the generative models of the next module. Score-based generative models (Song & Ermon, 2019, NeurIPS) and the equivalent denoising diffusion models (Ho et al., 2020, NeurIPS) learn the score with a neural network and then sample by running exactly this Langevin update, annealed across noise levels in the same spirit as AIS. The negative-phase problem that made energy-based learning hard — needing samples from the model — is answered by learning the score directly and letting gradient-guided Langevin sampling do the rest, which is why diffusion models train stably where Boltzmann machines did not.
Takeaways
- Monte Carlo estimates any expectation by the sample mean : unbiased, with variance and error , a rate independent of dimension, which is why it beats grid quadrature in high .
- Importance sampling draws from a tractable proposal and reweights by ; the optimal proposal is , and a with lighter tails than blows the variance up.
- A Markov chain with kernel converges to a unique stationary when it is ergodic; detailed balance is the design tool that fixes as the stationary distribution.
- MCMC builds such a chain: Metropolis–Hastings accepts a proposed move with probability — cancels; Gibbs resamples each coordinate from its full conditional, leaving invariant.
- Mixing is governed by : burn-in discards the transient, autocorrelation time shrinks the effective sample size to , and multimodal targets mix slowly because energy barriers trap local chains.
- The partition function makes energy-based learning hard: the log-likelihood gradient is a positive phase (data) minus a negative phase (model samples via MCMC); annealed importance sampling estimates itself by bridging from a tractable base. See energy-based and Boltzmann machines.
Footnotes
- Goodfellow, Deep Learning, §17.1 — Sampling and Monte Carlo Methods: the sample-mean estimator, its unbiasedness, and the dimension-free error rate. ↩
- Goodfellow, Deep Learning, §17.2 — Importance Sampling: the reweighting identity, the optimal proposal , and the variance blow-up from light-tailed proposals. ↩
- Goodfellow, Deep Learning, §17.3 — Markov Chain Monte Carlo Methods: transition kernels, stationary distributions, and convergence governed by the second eigenvalue. ↩
- Goodfellow, Deep Learning, §17.4 — Gibbs Sampling: coordinate-wise resampling from full conditionals, the natural sampler for the sigmoid units of an RBM. ↩
- Goodfellow, Deep Learning, §18.1 — The Log-Likelihood Gradient: the positive/negative phase split and the model-expectation term that demands MCMC. ↩
- Goodfellow, Deep Learning, §18.7 — Annealed Importance Sampling: bridging a tractable base to the target through intermediate distributions to estimate . ↩
╌╌ END ╌╌