Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Introduction to sampling

Introduction

The fundamental objective of Bayesian statistics is to compute the posterior distribution of a random variable θΘ\theta \in \Theta given data D\mathcal{D}. In the context of supervised learning, where the data D={X,Y}\mathcal{D}=\{X,Y\} comprises features/inputs XX and responses/labels YY, Bayes’ formula for the parameter posterior distribution takes the following form

p(θD)=p(Yθ,X)p(θ)Θp(Yθ,X)p(θ)dθ,p(\theta \mid \mathcal{D}) = \frac{p(Y \mid \theta,X)p(\theta)} {\int_{\Theta}p(Y \mid \theta,X)p(\theta) \rm{d} \theta} \, ,

where p(Yθ,X)p(Y \mid \theta,X) denotes the likelihood of NN observations for the target Y={y1,,yN}Y=\{y_1,\dots,y_N\} given inputs X={x1,,xN}X=\{x_1,\dots,x_N\}, p(θ)p(\theta) is the density of the prior distribution for θ\theta, and

p(D)=Θp(Yθ,X)p(θ)dθ,p(\mathcal{D}) = \int_{\Theta}p(Y \mid \theta,X)p(\theta) \rm{d} \theta,

denotes the model evidence of the data. Note that, in general the posterior is often only known up-to a normalizing constant, because, aside from simple models, calculating the integral in the model evidence is not feasible for high-dimensional θ\theta nor is it often available in closed form. Therefore, it is more common to work with the unnormalized posterior p(θD)p(Yθ,X)p(θ)p(\theta \mid \mathcal{D}) \propto p(Y \mid \theta, X) p(\theta).

We note that the ultimate goal in solving (1) is estimating the posterior predictive for new inputs xx^*, i.e. the pushforward of the posterior through the test likelihood:

p(yx,θ),forθp(θD).p(y^* \mid x^*, \theta) \, , \quad {\rm for} \quad \theta \sim p(\theta \mid \mathcal{D}) \, .

This is a distributed quantity that incorporates both epistemic and aleatoric uncertainty (uncertainty caused by a lack of data or knowledge, respectively), but often we content ourselves with its expectation as a point estimator p^\hat{p}:

p^(yx,D)=EθD[p(yx,θ)]=Θp(yx,θ)p(θD)dθ.\hat{p}(y^* \mid x^* , \mathcal{D} ) = \mathbb{E}_{\theta \mid \mathcal{D}}\left[ p(y^* \mid x^*, \theta) \right] = \int_\Theta p(y^* \mid x^*, \theta) p(\theta \mid \mathcal{D}) \rm{d}\theta \, .

Simulating or sampling from p(yx,θ)p(y^* \mid x^*, \theta), or from p^(yx)\hat{p}(y^* \mid x^* ), or p(yx,θ^)p(y^* \mid x^* , \hat{\theta}) for some point estimator θ^\hat{\theta} is not considered explicitly in this chapter, although it is worth noting that the posterior predictive is often better behaved than the parameter posterior. One primary reason for this may be that it eliminates the non-identifiability arising from exchangeability of the weights on a given layer.

For the remainder of this chapter, we will consider sampling from a generic target distribution π(θ)=κ(θ)/Z\pi(\theta) = {\kappa}(\theta)/Z, where Z=Θκ(θ)dθZ=\int_\Theta \kappa(\theta) \rm{d}\theta may or may not be known. The reader can think of π(θ):=p(θD)\pi(\theta):=p(\theta \mid \mathcal{D}) as the posterior already introduced in (1), but where we drop the data D\mathcal{D} for notational convenience.

Monte Carlo

The most fundamental sampling algorithm is the Monte Carlo algorithm Robert & Casella, 1999, and it is the basis for many other sampling schemes. Monte Carlo works as follows. Suppose we have a random variable θΘ\theta \in \Theta from a distribution which is continuous on RP\mathbb{R}^P. Let π\pi be the probability density function for θ\theta and assume that we are able to simulate independent and identically distributed (i.i.d.) samples from π\pi. Note that we may refer to π\pi as the distribution itself. For some function of interest hh, which is integrable with respect to π\pi, we wish to estimate an expectation

E[h(θ)]=h(θ)π(θ)dθ,\mathbb{E}[h(\theta)] = \int h(\theta)\pi(\theta)\rm{d}\theta,

which is often not available in closed form. Quadrature methods Davis & Rabinowitz, 1984 are suitable in low parameter dimension P5P \leq 5, and with tricks up to P20P \approx 20 Genz & Malik, 1980 or even P100P \approx 100 Bungartz & Griebel, 2004. However, for large PP, Monte Carlo reigns supreme due to its remarkable ability to achieve a mean square error (MSE), defined as MSE=E[(h^ME[h(θ)])2]\text{MSE} = \mathbb{E}\left[(\hat{h}_M - \mathbb{E}[h(\theta)])^2\right], that decays at the canonical rate O(1/M)\mathcal{O}(1/M) in the number of samples MM, regardless of dimension or smoothness of the quantity of interest hh.

The Monte Carlo method is extremely simple to use. We wish to generate MM independent samples θ1,θ2,,θM\theta_1,\theta_2,\ldots,\theta_M as shown in Algorithm 1.

Using the Monte Carlo samples {θi}i=1M\{\theta_i\}_{i=1}^M from π\pi, we can estimate the expectation as follows

E[h(θ)]h^M:=1Mi=1Mh(θi).\mathbb{E}[h(\theta)] \approx \hat{h}_M := \frac1M \sum_{i=1}^M h(\theta_i) \, .

This beautiful equation has remarkable convergence properties, and it is this gold standard that we aim to achieve with other sampling algorithms. Since the samples θ1,,θM\theta_1,\dots,\theta_M are i.i.d. from π\pi, and writing hi=h(θi)h_i = h(\theta_i), we have

E[h^M]=E[1Mi=1Mhi]=1Mi=1ME[hi]=E[h(θ)].\mathbb{E}[\hat{h}_M] = \mathbb{E}\Bigl[ \tfrac1M\sum_{i=1}^M h_i\Bigr] = \tfrac1M\sum_{i=1}^M \mathbb{E}[h_i] = \mathbb{E}[h(\theta)].

Thus h^M\hat{h}_M is an unbiased estimator of the target integral. Moreover, we can increase the accuracy of our estimator by increasing the number of samples MM. By the strong law of large numbers, if Eh(θ)<\mathbb{E}|h(\theta)|<\infty, we can guarantee that the Monte Carlo estimator converges almost surely to the true value as the number of samples grows without bound. Formally,

1Mi=1Mh(θi)    E[h(θ)]almost surely as M.\frac{1}{M} \sum_{i=1}^M h(\theta_i) \;\to\; \mathbb{E}[h(\theta)] \quad \text{almost surely as } M\to\infty.

That is, with probability one the estimator will eventually get arbitrarily close to the truth. If we invoke the central limit theorem, then we can also quantify how accurate h^M\hat{h}_M is for a given finite MM. Define the variance

V  =  {h(θ)E[h(θ)]}2π(θ)dθ,V \;=\; \int \{h(\theta)-\mathbb{E}[h(\theta)]\}^2 \,\pi(\theta)\,\mathrm{d}\theta,

and assume V<V<\infty. Then as MM\to\infty,

M(h^ME[h(θ)]V)  D  N(0,1).\sqrt{M}\,\left(\frac{\hat{h}_M - \mathbb{E}[h(\theta)]}{\sqrt{V}}\right) \;\xrightarrow{\mathsf{D}}\; \mathcal{N}(0,1).

Equivalently, for large MM,

h^M    N(E[h(θ)],V/M),\hat{h}_M \;\sim\; \mathcal{N}\Bigl(\mathbb{E}[h(\theta)],\,V/M\Bigr),

so that the standard error of the Monte Carlo estimator is V/M\sqrt{V/M} and its MSE decays at the canonical rate O(M1)O(M^{-1}) (i.e. root‐MSE O(M1/2)O(M^{-1/2})). This M1/2M^{-1/2} convergence is independent of the dimension PP or smoothness of hh, and is the benchmark against which all more advanced sampling methods are compared.

Often, a challenge is that we cannot sample from our target probability distribution π\pi directly, and can only evaluate or sample from a non-negative unbiased estimator of κ\kappa. Addressing these challenges has led to the development of the algorithms presented in the remainder of this chapter.

Rejection Sampling

Suppose that q(θ)q(\theta) is a probability density function from which we can sample relatively easily and that π(θ)\pi(\theta) is the target density from which we would like to sample. Suppose in addition that there exists a constant, c>0c > 0, such that

π(θ)q(θ)c,\frac{\pi(\theta)}{q(\theta)} \leq c,

whenever π(θ)>0\pi(\theta)>0. Then, we can formulate an algorithm for simulating MM samples from π(θ)\pi(\theta) as given in Algorithm 2.

Rejection sampling from a Beta(2,2) target \pi(y) using a uniform proposal q(y). Left: q alone does not dominate \pi, but the envelope c q with c=3/2 does. Right: the acceptance probability k(y)=\pi(y)/(c q(y)), shown also for a Beta(3,3) target (c=15/8), for which acceptance is lower.

Figure 1:Rejection sampling from a Beta(2,2)(2,2) target π(y)\pi(y) using a uniform proposal q(y)q(y). Left: qq alone does not dominate π\pi, but the envelope cqc q with c=3/2c=3/2 does. Right: the acceptance probability k(y)=π(y)/(cq(y))k(y)=\pi(y)/(c q(y)), shown also for a Beta(3,3)(3,3) target (c=15/8c=15/8), for which acceptance is lower.

This algorithm is referred to as rejection sampling. We can see that this recipe will be very computationally efficient if the densities q(θ)q(\theta) and π(θ)\pi(\theta) are approximately equal and the constant cc can be chosen close to 1. In this case, the acceptance probability will generally be close to 1. On the other hand, if π(θ)\pi(\theta) and q(θ)q(\theta) are very different, then many runs of the algorithm may be required before a value is finally accepted.

Despite its attraction of ease of implementation and simulation, the efficiency of rejection sampling relies on (i) having a good proposal distribution and (ii) a bound cc. Note that it can easily be modified to work with only κ\kappa, but these difficulties remain.

Importance Sampling

The importance sampling estimator of Eπ[h(θ)]\mathbb{E}_\pi[h(\theta)] begins by re-writing the integral as follows

Θh(θ)π(θ)dθ=π(θ)q(θ)h(θ)q(θ)dθ,\int_\Theta h(\theta)\pi(\theta){\rm d}\theta = \int \frac{\pi(\theta)}{q(\theta)}h(\theta)q(\theta){\rm d}\theta \, ,

where qq is a density such that q(θ)>0q(\theta)>0, whenever π(θ)h(θ)0\pi(\theta)h(\theta)\neq 0. We now produce i.i.d. samples (θ1,,θM)(\theta_1,\ldots,\theta_M) from qq, and estimate

h^=1Mi=1Mπ(θi)q(θi)h(θi)=1Mi=1Mw(θi)h(θi).\hat{h} = \frac{1}{M}\sum^M_{i=1}\frac{\pi{(\theta_i)}}{q{(\theta_i)}}h(\theta_i) = \frac{1}{M}\sum^M_{i=1}w(\theta_i)h(\theta_i) \, .

We call this procedure importance sampling. The density qq is called the proposal or instrumental density and w(θi)=π(θi)q(θi)w(\theta_i)=\frac{\pi{(\theta_i)}}{q{(\theta_i)}} are the* importance weights*. Note that h^\hat{h} is an unbiased Monte Carlo estimator of Eπ[h(θ)]\mathbb{E}_\pi[h(\theta)], as shown in Equation (7). There are two reasons why we might be interested in performing importance sampling:

Recalling the results of Section Monte Carlo, the effective test function is now (π/q)h(\pi/q)h, and so its regularity dictates the convergence behaviour. Hence, if possible, we should choose a proposal density qq such that the variance of (π/q)h(\pi/q)h is small. It can be shown that the optimal proposal distribution is qπhq \propto \pi |h|, however that does little good by itself, since we are back to the same problem of approximating qq. However, it can provide useful guidance.

Suppose that we only know how to evaluate κ\kappa. It is easy to see that an unbiased estimator of the normalizing constant can be built using the following identity

Z=Θκ(θ)dθ=Θκ(θ)q(θ)q(θ)dθ.Z = \int_\Theta \kappa(\theta) {\rm d}\theta = \int_\Theta \frac{\kappa(\theta)}{q(\theta)} q(\theta) {\rm d}\theta \, .

It is left as an exercise to the reader to build a consistent (but biased) self-normalized importance sampling estimator using only κ\kappa. Unlike rejection sampling, importance sampling does not waste samples through the rejection step, which could be a high amount depending on the application at hand.

As alluded to already, a major disadvantage of importance sampling is that it can result in high variance. There are numerous methods beyond what has been introduced here to alleviate such issues, including the sequential importance sampling and resampling methods which will be introduced later in Section Sequential Monte Carlo.

Markov chain Monte Carlo

The preceding sections have introduced Monte Carlo integration and two classical approaches—rejection sampling and importance sampling—for drawing samples from a target distribution π(θ)\pi(\theta), typically the posterior in Bayesian inference. While these methods are simple to use and theoretically well-founded, they suffer significant limitations in high-dimensional settings. Rejection sampling becomes increasingly inefficient as the dimension grows, due to the difficulty of finding proposal distributions that tightly bound the target. Importance sampling, although more flexible, tends to suffer from high variance unless the proposal distribution is well matched to the target Agapiou et al., 2017Chatterjee & Diaconis, 2018—a condition that is notoriously hard to satisfy in practice, especially in the multimodal, heavy-tailed, and high-dimensional posteriors encountered in Bayesian deep learning Papamarkou et al., 2024.

Markov Chain Monte Carlo (MCMC) provides a powerful and general framework to overcome these challenges. Rather than attempting to generate independent samples from π(θ)\pi(\theta), MCMC constructs a Markov chain whose stationary distribution is π\pi itself. By simulating a trajectory through parameter space in such a way that, asymptotically, the empirical distribution of visited states converges to the target, MCMC transforms the task of independent sampling into one of designing a suitable transition mechanism that ensures both* ergodicity* and* invariance* with respect to π\pi Tierney, 1994.

In practical terms, MCMC methods produce a correlated sequence of samples {θ1,θ2,,θM}\{\theta_1, \theta_2, \ldots, \theta_M\}, which, under suitable conditions, can still be used to approximate expectations under π\pi using ergodic averages. The canonical estimator takes the form:

h^M=1Mi=1Mh(θi),\hat{h}_M = \frac{1}{M} \sum_{i=1}^M h(\theta_i),

which, despite the dependence between samples, converges to the true posterior expectation Eπ[h(θ)]\mathbb{E}_\pi[h(\theta)] under mild regularity assumptions Geyer, 2011.

In what follows, we introduce several fundamental MCMC algorithms, starting with the Metropolis–Hastings algorithm, which provides a generic recipe for constructing π\pi-invariant Markov chains from arbitrary proposal distributions Metropolis et al., 1953Hastings, 1970. We then examine key special cases—random-walk Metropolis, the Metropolis-adjusted Langevin algorithm (MALA), and Hamiltonian Monte Carlo (HMC)—that are particularly relevant in the context of high-dimensional posterior inference in Bayesian deep learning. Throughout, we pay close attention to algorithmic trade-offs, scaling behaviour Roberts et al., 1997Roberts & Rosenthal, 1998Fearnhead et al., 2025, and diagnostic tools for assessing convergence and sampling efficiency Brooks & Gelman, 1998.

Metropolis–Hastings

Markov chain Monte Carlo (MCMC) proceeds by generating a Markov chain θ1θ2\theta_1 \to \theta_2\to\ldots with transition kernel M\mathcal{M}, described by a density p(θ,θ)p(\theta,\theta') on Θ2\Theta^2, which is invariant with respect to the target posterior π\pi:

Θπ(θ)p(θ,θ)dθ=π(θ).\int_{\Theta}\pi(\theta')\,p(\theta',\theta)\,\mathrm{d}\theta' =\pi(\theta).

The Metropolis–Hastings (MH) algorithm achieves this invariance by first choosing an arbitrary proposal density q(θ,θ)q(\theta,\theta') that proposes θ\theta' given the current iterate of the Markov chain θ\theta, and then accepting or rejecting each proposed move so that detailed balance—and hence (19)—holds.

Concretely, we can define the MH transition kernel as

p(θ,θ)=q(θ,θ)α(θ,θ),p(\theta,\theta') = q(\theta,\theta')\alpha(\theta,\theta'),

where the acceptance probability is

α(θ,θ)=min{1,π(θ)q(θ,θ)π(θ)q(θ,θ)}.\alpha(\theta,\theta') = \min\left\{ 1,\, \frac{\pi(\theta')\,q(\theta',\theta)} {\pi(\theta)\,q(\theta,\theta')} \right\}.

Because π(θ)κ(θ)\pi(\theta)\propto\kappa(\theta), any unknown normalisation cancels and only the unnormalized density κ\kappa is needed. See Algorithm 3 for a full implementation.

Invariance with respect to π\pi is a necessary condition for building convergent estimators from a Markov chain. The chain also needs to have certain other stability properties, collectively known as ergodicity, to ensure empirical averages (6) built from its output converge. A desirable and achievable property is called* geometric ergodicity*, which essentially guarantees linear convergence, i.e. the dependence on the initial condition vanishes geometrically.

Random walk Metropolis

A particularly simple—and historically important—special case of the Metropolis–Hastings algorithm is the random–walk Metropolis (RWM) proposal, in which one sets

q(θ,θ)=q(θθ),q(\theta,\theta') = q(\theta' - \theta),

where qq is any symmetric density, q(θ)=q(θ)q(\theta)=q(-\theta). The canonical choice is

θ=θ+ϵ,ϵN(0,  λ2IP),\theta' = \theta + \epsilon, \qquad \epsilon\sim \mathcal{N}\bigl(0,\;\lambda^{2}I_{P}\bigr),

so that θN(θ,λ2IP)\theta' \sim \mathcal{N}\left(\theta,\lambda^{2}I_{P}\right), i.e. q(θ,)=N(θ,λ2IP)q(\theta,\cdot) =\mathcal{N}\left(\theta,\lambda^{2}I_{P}\right). Due to symmetry, the Metropolis acceptance probability simplifies to

α(θ,θ)=min{1,  κ(θ)κ(θ)}.\alpha(\theta,\theta') = \min\left\{1,\; \frac{\kappa(\theta')} {\kappa(\theta)}\right\}.

Local moves and tuning. RWM proposals are inherently local: each candidate θ\theta' lies in a neighbourhood of θ\theta. If λ\lambda is too small, the chain makes only tiny steps and mixes very slowly; if λ\lambda is too large, most proposals fall in low-density regions and are rejected. Optimal scaling results show that, for a wide class of PP-dimensional targets, the stationary acceptance rate tends to 0.234\approx0.234 as PP\to\infty when λP1/2\lambda\propto P^{-1/2} Roberts et al., 1997. In practice, one therefore adapts λ\lambda so that the empirical acceptance rate lies between about 20%20\% and 30%30\%.

Preconditioning. When components of θ\theta have very different scales or strong correlations, one can replace λ2IP\lambda^2 I_{P} by λ2V\lambda^2 V, where VV is a positive-definite “preconditioning” matrix (often an estimate of the posterior covariance). This preconditioned RWM retains symmetry and thus the same simplified acceptance probability, but can yield orders-of-magnitude improvements in computational efficiency, i.e. less samples required to sample the target, because the proposed parameters θ\theta' will be more closely aligned with the posterior distribution, and thus less likely to be rejected.

Gibbs Sampler

Given a multi-variate θ=(θ1,θ2θn)\theta = (\theta_1, \theta_2 \dots \theta_n), it may be intractable to sample all at once. However if the full conditional distributions for each coordinate are known, then it becomes possible to apply Gibbs sampling.

The Gibbs sampling algorithm is fairly straightforward. Given the proposals are known, the Gibbs algorithm updates the sample by updating each coordinate one at a time, i.e. θiP(θiθ¬i)\theta_i' \sim P(\theta_i \mid \theta_{\neg i}), where θ¬i\theta_{\neg i} denotes all coordinates except ii. While it may be tempting to update all coordinates at the same time, this would not properly preserve the joint distribution as all coordinates would be updated independently. We include a simple formulation in Algorithm 4.

Given that the Gibbs sampler is drawing from the correct proposal, the typical Metropolis-Hastings acceptance step is not needed in this case. However, this sampler suffers from slow and highly correlated samples due to the nature of the single coordinate update approach.

It is possible to extend the initial Gibbs sampler to a block-style approach in the case where the joint distribution over multiple coordinates is known. Instead of the single-coordinate marginal, if we know the joint distribution over one-set of coordinates conditioned on another set, it is possible to quickly sample by alternative sampling from each joint distribution. This is known as the Block-Gibbs sampler. More formally, if we have two sets of coordinates I,JI, J, the block Gibbs sampler proceeds by sampling θIP(θIθJ)\theta'_I \sim P(\theta_I \mid \theta_J), and then sampling θJP(θJθI)\theta'_J \sim P(\theta_J \mid \theta'_I). This sampling algorithm avoids the pitfalls of the typical Gibbs sampler. However, it is only possible to use this in cases where the conditional distributions over blocks of coordinates is known.

Metropolis-adjusted Langevin Algorithm

The random-walk Metropolis ignores gradient information about π\pi. The Metropolis–Adjusted Langevin Algorithm (MALA) rectifies this by using an Euler–Maruyama discretisation of the overdamped Langevin diffusion

dθt=12 ⁣logπ(θt)dt+dWt,\mathrm{d}\theta_{t} = \tfrac12\nabla\!\log\pi(\theta_{t})\,\mathrm{d}t + \mathrm{d}W_{t},

where {Wt}t0\{W_t\}_{t\geq 0} is standard Brownian motion on RP\mathbb{R}^{P}, and whose stationary law is π\pi. Concretely, the MALA proposal is

θθN(θ+λ22logκ(θ),λ2IP).\theta' | \theta \sim \mathcal{N}\left( \theta +\tfrac{\lambda^{2}}{2}\,\nabla\log\kappa(\theta), \lambda^{2}I_{P} \right).

This drift term logκ(θ)\nabla\log\kappa(\theta) biases proposed moves towards regions of higher posterior density, enabling larger step-sizes than RWM and better acceptance rates. The MALA proposal also forms the basis for many other wonderful Monte Carlo algorithms, including the stochastic gradient Langevin dynamics (SGLD) Welling & Teh, 2011 and all other stochastic gradient MCMC (SG-MCMC) algorithms, which will be the focus of the next chapter.

Gradient-based tuning. Under regularity conditions, choosing λP1/6\lambda\propto P^{-1/6} yields an optimal stationary acceptance rate of approximately 0.574 as PP\to\infty Roberts & Rosenthal, 1998. In applications, one often adapts λ\lambda to target an acceptance rate of about 50%50\% to 60%60\%. This can be done by monitoring the acceptance rate and adjusting λ\lambda accordingly, or by using more sophisticated adaptive schemes that adjust the step size based on the empirical gradient information.

Preconditioned MALA and robustness. Analogous to RWM, one can introduce a symmetric preconditioning matrix VV, replacing IPI_{P} by VV both in the covariance and in the drift:

θN(θ+λ22Vlogκ(θ),λ2V).\theta' \sim \mathcal{N}\left( \theta + \tfrac{\lambda^{2}}{2}\,V\,\nabla\log\kappa(\theta), \lambda^{2}V \right).

Preconditioning often dramatically accelerates convergence on anisotropic posteriors. However, because MALA relies on logκ\nabla\log\kappa, it can be sensitive to regions where the gradient is large or ill-behaved (e.g. lighter-than-Gaussian tails). Common mitigations include gradient clipping or fallback to RWM outside of a “trust region.”

Monitoring Performance

Assessing the quality of an MCMC run is essential to ensure that empirical averages h^M=1Mi=1Mh(θi)\hat{h}_{M}=\tfrac1M\sum_{i=1}^M h(\theta_i) reliably approximates Eπ[h(θ)]\mathbb{E}_{\pi}[h(\theta)]. Three widely used diagnostics are:

1. Autocorrelation and Integrated Autocorrelation Time. For a scalar summary of h(θ)h(\theta), define the lag-kk autocorrelation

ρk=Cov[h(θi),h(θi+k)]Varπ[h(θ)].\rho_k = \frac{\mathrm{Cov}\bigl[h(\theta_i),\,h(\theta_{i+k})\bigr]} {\mathrm{Var}_{\pi}\bigl[h(\theta)\bigr]}.

As the Markov chain is stationary, ρ0=1\rho_0=1, and ρk0\rho_k\to0 as kk\to\infty. The slower ρk\rho_k decays, the more correlated is the chain. One can show that, via the Markov-chain central limit theorem,

M(h^MEπ[h])DN(0,Veff),whereVeff=Varπ[h](1+2k=1ρk).\sqrt{M}\bigl(\hat{h}_{M}-\mathbb{E}_{\pi}[h]\bigr) \xrightarrow{\mathcal{D}} \mathcal{N}\bigl(0,V_{\mathrm{eff}}\bigr), \quad \mathrm{where} \quad V_{\mathrm{eff}} = \mathrm{Var}_{\pi}[h]\,\Bigl(1 + 2\sum_{k=1}^\infty \rho_k\Bigr).

The quantity τint=1+2k=1ρk\tau_{\mathrm{int}}=1+2\sum_{k=1}^\infty\rho_k is the integrated autocorrelation time, and the* effective sample size* ESS=M/τint\mathrm{ESS}=M/\tau_{\mathrm{int}} measures the number of independent draws represented by MM correlated samples. Figure Figure 3 illustrates autocorrelation decay. A related metric is the* expected squared jumping distance* (ESJD) E[θi+1θi2]\mathbb{E}[\|\theta_{i+1}-\theta_i\|^2], which balances move size against acceptance rate. Larger moves will reduce the correlation between elements of the Markov chain, however, larger moves are also less likely to be accepted, which means that the chain does not evolve. Therefore, the challenge for practitioners, is to balance between small moves (high correlation and high acceptance rate) and large moves (low correlation and low acceptance rate).

2. Trace Plots. Plotting the sequence {h(θi)}i=1M\{h(\theta_i)\}_{i=1}^M versus iteration ii provides a simple-to-interpret visual representation of mixing and stationarity. Well‐mixed chains rapidly traverse the bulk of the posterior, showing no apparent trends or “stickiness” (see Left Panel Figure Figure 2). Conversely, slow mixing or multimodality is signalled by long periods of drift or entrapment in subregions of the posterior (see Right Panel Figure Figure 2). Trace plots are a useful visual tool for diagnosing the efficiency of an MCMC algorithm, however, they tend to be most useful for low-dimensional posteriors as it is easier to visualise all of the parameters θ\theta, whereas, for high-dimensional posteriors, visualising all of the parameters in the Markov chain individually is often impractical.

3. Potential Scale Reduction (Gelman–Rubin) Diagnostic. When multiple chains {θi(c)}\{\theta_i^{(c)}\} are run from overdispersed starting points, one can compare the between-chain variance BB to the* within-chain variance* WW. The* potential scale reduction factor*

R^=M1MW+1MBW\widehat{R} = \sqrt{\frac{\tfrac{M-1}{M}W + \tfrac{1}{M}B}{W}}

tends to 1 as all chains converge to the same target distribution Gelman & Rubin, 1992. Values of R^<1.1\widehat{R}<1.1 are commonly taken to indicate satisfactory convergence, after which samples from all chains may be pooled to produce an approximation to the posterior π\pi.

In practice, one would usually employ a combination of these diagnostics: trace plots for qualitative assurance, autocorrelation and ESS for quantitative accuracy, and R^\widehat{R} to guard against failure to explore multimodal targets.

Trace plots for \lambda=0.9 (left) and \lambda=0.01 (right).

(a)

Trace plots for \lambda=0.9 (left) and \lambda=0.01 (right).

(b)

Figure 2:Trace plots for λ=0.9\lambda=0.9 (left) and λ=0.01\lambda=0.01 (right).

Corresponding ACFs for \lambda=0.9 (left) and \lambda=0.01 (right).

(a)

Corresponding ACFs for \lambda=0.9 (left) and \lambda=0.01 (right).

(b)

Figure 3:Corresponding ACFs for λ=0.9\lambda=0.9 (left) and λ=0.01\lambda=0.01 (right).

Hamiltonian Monte Carlo

Random–walk Metropolis (RWM) requires proposal steps of size λ=O(d1/2)\lambda=O(d^{-1/2}) to maintain a non–degenerate acceptance rate in dimension dd, whereas MALA can take steps of size O(d1/6)O(d^{-1/6}). Hamiltonian Monte Carlo (HMC) goes a step further: with an integration step size ϵ=O(d1/4)\epsilon=O(d^{-1/4}) it still enjoys an acceptance rate bounded away from 0 while exploring much larger regions of parameter space between consecutive accept–reject decisions Beskos et al., 2013Duane et al., 1987Neal, 2011Cobb & Jalaian, 2021. The key is to embed the dd‐dimensional parameter θ\theta in a 2d2d-dimensional* phase space* and simulate approximate Hamiltonian dynamics that preserve a surrogate “total energy”.

Extended target and Hamiltonian. Introduce an auxiliary momentum variable zRdz\in\mathbb{R}^d and a positive–definite* mass matrix* M0M_0. Define the Hamiltonian

H(θ,z)=U(θ)+K(z):=logπ(θ)+12zM01z,H(\theta,z)=U(\theta)+K(z) := -\log\pi(\theta)+\tfrac12 z^{\top}M_0^{-1}z,

so that the joint density π~(θ,z)exp[H(θ,z)]\widetilde\pi(\theta,z)\propto\exp[-H(\theta,z)] has marginal π(θ)\pi(\theta) and independent zN(0,M0)z\sim\mathcal{N}(0,M_0).

Hamiltonian dynamics. The continuous equations of motion are

dθdt=M01z,dzdt=θlogπ(θ),\frac{\mathrm{d}\theta}{\mathrm{d}t}=M_0^{-1}z, \qquad \frac{\mathrm{d}z}{\mathrm{d}t}=\nabla_{\theta}\log\pi(\theta),

which conserve HH exactly and therefore move along surfaces of constant joint density. Exact simulation is impossible for general targets π\pi, so HMC uses the second–order, symplectic leapfrog integrator Leimkuhler & Reich, 2005 with step size Δt\Delta t:

zt+12Δt=zt+Δt2θ ⁣logπ(θt),θt+Δt=θt+ΔtM01zt+12Δt,zt+Δt=zt+12Δt+Δt2θ ⁣logπ(θt+Δt).\begin{align} z_{t+\tfrac12\Delta t} &=z_t+\tfrac{\Delta t}{2}\nabla_{\theta}\!\log\pi(\theta_t), \notag\\ \theta_{t+\Delta t} &=\theta_t+\Delta t\,M_0^{-1}z_{t+\tfrac12\Delta t}, \\ z_{t+\Delta t} &=z_{t+\tfrac12\Delta t}+\tfrac{\Delta t}{2} \nabla_{\theta}\!\log\pi(\theta_{t+\Delta t}). \notag \end{align}

One repeats this map LL times, with ϵ=Δt\epsilon=\Delta t and T=LϵT=L\,\epsilon is the integration time.

HMC kernel. Starting from θi1\theta_{i-1}:

  1. Draw momentum zN(0,M0)z\sim\mathcal{N}(0,M_0).

  2. Apply LL leapfrog steps (36) to obtain (θ,z)(\theta',z').

  3. Accept (θ,z)(\theta',z') with probability

    α=min{1,exp[H(θi1,z)H(θ,z)]}.\alpha = \min\Bigl\{1,\, \exp\bigl[H(\theta_{i-1},z)-H(\theta',z')\bigr]\Bigr\}.
  4. Set θi=θ\theta_{i}=\theta' if accepted, otherwise θi=θi1\theta_{i}=\theta_{i-1}; discard zz'.

Because the leapfrog map is volume–preserving (i.e. the Jacobian =1=1) and symmetric (its inverse is obtained by (θ,z)(θ,z)(\theta,z)\mapsto(\theta,-z) and running the LL steps backward), the Metropolis correction guarantees π~\widetilde\pi is invariant; the posterior π\pi is therefore stationary for the marginal chain on θ\theta.

High‐dimensional scaling. For product targets π(θ)=i=1df(θi)\pi(\theta)=\prod_{i=1}^d f(\theta^i) with M0=IdM_0=I_d, one can show Fearnhead et al., 2025 that to keep a well-behaved acceptance rate, one must scale ϵ=O(d1/4)\epsilon = O(d^{-1/4}), hence L=O(d1/4)L=O(d^{1/4}). The computational cost per effectively independent draw is therefore O(d1/4)O(d^{1/4}), compared with O(d1/3)O(d^{1/3}) for MALA and O(d)O(d) for RWM.

Practical tuning.

Because HMC combines long, momentum‐driven proposals with high acceptance probabilities, it has become the default sampler in many Bayesian deep‐learning applications, where posteriors are high‐dimensional, strongly correlated and feature narrow valleys that thwart simpler MCMC methods.

Sequential Monte Carlo

Sequential Monte Carlo (SMC) methods are a set of Monte Carlo algorithms designed to sample from a sequence of target probability densities {πn(θ1:n)}\{\pi_n(\theta_{1:n})\} of increasing dimension, where each one is defined on the product space Θn=i=1nΘ\Theta^n = \prod_{i=1}^n \Theta Doucet et al., 2001Del Moral, 2004. This is referred to as the smoothing distribution in the context of state-space models. Often one may be interested only in the time nn marginal πn(θn)\pi_n(\theta_n), which is known as the* filtering distribution*. Suppose

πn(θ1:n)=κn(θ1:n)Zn,\begin{align} \pi_n(\theta_{1:n}) = \frac{\kappa_n(\theta_{1:n})}{Z_n} \, , \end{align}

where the un-normalized density admits the decomposition

κn(θ1:n)=κn(θnθ1:n1)κn1(θ1:n1),\kappa_n(\theta_{1:n}) = \kappa_n(\theta_n | \theta_{1:n-1}) \kappa_{n-1}(\theta_{1:n-1}) \, ,

and κn(θnθ1:n1)\kappa_n(\theta_n | \theta_{1:n-1}) and κ1(θ1)\kappa_1(\theta_1) can be evaluated, and ZnZ_n is the unknown normalizing constant given by

Zn=κn(θ1:n)dθ1:n.\begin{align} Z_n = \int \kappa_n(\theta_{1:n}) \mathrm{d}\theta_{1:n}. \end{align}

Note that we write

dθ1:n which is equivalent to ΘΘΘdθ1dθ2dθn.\int \mathrm{d}\theta_{1:n} \quad \text{ which is equivalent to }\quad \int_{\Theta} \int_{\Theta} \cdots \int_{\Theta} \mathrm{d}\theta_1 \mathrm{d}\theta_2 \cdots \mathrm{d}\theta_n.

SMC provides an approximation of π1(θ1)\pi_1(\theta_1) and an estimate of Z1Z_1 at time 1 then an approximation of π2(θ1:2)\pi_2(\theta_{1:2}) and an estimate of Z2Z_2 at time 2 and so on. The approximations are done sequentially in time:

Consider another probability density qn(θ1:n)=qn(θnθ1:n1)qn1(θ1:n1)q_n(\theta_{1:n}) = q_n(\theta_n | \theta_{1:n-1})q_{n-1}(\theta_{1:n-1}) that is easy to sample from, and such that the support of qn(θ1:n)q_n(\theta_{1:n}) includes the support of πn(θ1:n)\pi_n(\theta_{1:n}). Then, we have the following importance sampling (IS) identities

πn(θ1:n)=κn(θ1:n)Zn=wn(θ1:n)qn(θ1:n)Zn,Zn=wn(θ1:n)qn(θ1:n)dθ1:n,\begin{align} \pi_n(\theta_{1:n}) &= \frac{\kappa_n(\theta_{1:n})}{Z_n} = \frac{w_n(\theta_{1:n}) q_n(\theta_{1:n})}{Z_n},\\ Z_n&=\int w_n(\theta_{1:n})q_n(\theta_{1:n}) \mathrm{d}\theta_{1:n}, \end{align}

where wn(θ1:n)w_n(\theta_{1:n}) is the unnormalized weight function and in light of (39) we have the following recursive definition of the weights

wn(θ1:n)=κn(θ1:n)qn(θ1:n)=κn(θnθ1:n1)qn(θnθ1:n1)wn1(θ1:n1)=:α(θnθ1:n1)wn1(θ1:n1).\begin{align} w_n(\theta_{1:n}) = \frac{\kappa_n(\theta_{1:n})}{q_n(\theta_{1:n})} = \frac{\kappa_n(\theta_n | \theta_{1:n-1})}{q_n(\theta_n | \theta_{1:n-1})} w_{n-1}(\theta_{1:n-1}) =: \alpha(\theta_n | \theta_{1:n-1}) w_{n-1}(\theta_{1:n-1}) \, . \end{align}

Assume we draw, sequentially in time, MM independent samples θ1:n(i)\theta_{1:n}^{(i)}, i=1,,Mi=1,\cdots,M, from qn(θ1:n)q_n(\theta_{1:n}) (see Algorithm 6). We have the following unbiased estimator of ZnZ_n:

Z^n=1Mi=1Mwn(θ1:n(i)).\begin{align} \widehat{Z}_n &= \frac{1}{M} \sum_{i=1}^M w_n(\theta_{1:n}^{(i)}). \end{align}

A consistent self-normalized importance sampling estimator of En(hn)\mathbb{E}_n(h_n), for an arbitrary function hn:ΘnRh_n:\Theta^n\to \mathbb{R}, is given by

En^(hn)=i=1Nwn(θ1:n(i))hn(θ1:n(i))i=1Nwn(θ1:n(i))=i=1MWn(i)hn(θ1:n(i)),\widehat{\mathbb{E}_n}(h_n) =\frac{\sum_{i=1}^N w_n(\theta_{1:n}^{(i)}) h_n(\theta_{1:n}^{(i)}) }{\sum_{i=1}^N w_n(\theta_{1:n}^{(i)})} \nonumber = \sum_{i=1}^M W_n^{(i)} \,\, h_n(\theta_{1:n}^{(i)}) \, ,

where

Wn(i)=wn(θ1:n(i))i=1Mwn(θ1:n(i)).\begin{align} W_n^{(i)} = \frac{w_n(\theta_{1:n}^{(i)})}{\sum_{i=1}^M w_n(\theta_{1:n}^{(i)})} \, . \end{align}

These are the ingredients of the sequential importance sampling (SIS) algorithm, given in Algorithm 6. In Algorithms 6 and 7 we take hn(θ1:n)=θnh_n(\theta_{1:n}) = \theta_n.

As nn grows the weights will degenerate, in the sense that one will dominate the rest. This can be monitored by the effective sample size, which is related to the variance of the weights:

ESS=(i=1Mwn(i))2i=1M(wn(i))2.{\sf ESS} = \frac{\left(\sum_{i=1}^M w_n^{(i)}\right)^2}{\sum_{i=1}^M (w_n^{(i)})^2} \, .

One way to mitigate this somewhat is by resampling, i.e. for i=1,,Mi=1,\dots,M, let

θ1:n(i)θ1:n(j),forj(Wn(1),,Wn(M)),andwn(i)1/M.\theta_{1:n}^{(i)} \leftarrow \theta_{1:n}^{(j)} \, , \quad {\rm for}\quad j \sim (W_n^{(1)},\dots,W_n^{(M)}) \, , \quad {\rm and}\quad w_n^{(i)} \leftarrow 1/M \, .

Resampling slightly increases the variance of the estimator, but the particles are rejuvenated at the filtering end, and under suitable conditions the filter can even remain stable online for infinite time Del Moral, 2004. Note that this branching of the particles forward in time means coalescence backward in time, so the particles still degenerate for small times, which is problematic for the smoother. SIS along with resampling is called sequential importance resampling (SIR) or sequential Monte Carlo (SMC). See Algorithm 7. In the context of a state space model, qnq_n is often chosen as the forward evolution kernel of the hidden process, and in the filtering context this specific choice is often called the bootstrap particle filter. In practice, one resamples when the ESS is less than a threshold (e.g. M/2M/2 or M/4M/4). See Chopin & Papaspiliopoulos (2020) for a recent comprehensive introduction.

Summary

This chapter introduced the Monte Carlo algorithm and a number of methods that develop it. Each addresses the same underlying difficulty: simulating from, or estimating expectations under, a target distribution π(θ)\pi(\theta) that in most applications can only be evaluated up to an unknown normalising constant.

When independent samples from π\pi are available, Monte Carlo integration (Section Monte Carlo) applies directly. When they are not, rejection sampling (Section Rejection Sampling) and importance sampling construct estimators from an accessible proposal distribution. Both are exact in principle, but become inefficient in high dimension unless the proposal closely matches the target.

Markov chain Monte Carlo (Section Markov chain Monte Carlo) removes the need for independent draws by constructing a Markov chain whose stationary distribution is the target. The Metropolis–Hastings algorithm (Section Metropolis–Hastings) provides the general recipe, with the random-walk Metropolis algorithm (Section Random walk Metropolis), the Gibbs sampler, the Metropolis-adjusted Langevin algorithm (Section Metropolis-adjusted Langevin Algorithm), and Hamiltonian Monte Carlo (Section Hamiltonian Monte Carlo) as the special cases treated here. Since the samples are correlated, step-size tuning and the convergence diagnostics of Section Monitoring Performance are essential in practice.

Sequential Monte Carlo (Section Sequential Monte Carlo) extends importance sampling to a sequence of targets on nested product spaces, as in filtering. Sequential importance sampling with resampling propagates weighted particles forward in time, with resampling when the effective sample size drops.

The methods play complementary roles: rejection and importance sampling suit low-dimensional or well-matched problems, MCMC is the standard tool for high-dimensional Bayesian computation, and sequential Monte Carlo is suited to inference along a sequence. These ideas are taken further in the chapters that follow. For example, stochastic gradient MCMC is covered in Chapter Stochastic Gradient MCMC, and sequential Monte Carlo samplers, which applies SMC to an artificial sequence of intermediate targets with MCMC mutations, with tempering and multilevel extensions for neural network posteriors, in Chapter Sequential Monte Carlo samplers.

References
  1. Robert, C. P., & Casella, G. (1999). Monte Carlo statistical methods. Springer.
  2. Davis, P. J., & Rabinowitz, P. (1984). Methods of Numerical Integration (Second Edition). Academic Press.
  3. Genz, A. C., & Malik, A. A. (1980). Remarks on algorithm 006: An adaptive algorithm for numerical integration over an N-dimensional rectangular region. Journal of Computational and Applied Mathematics, 6(4), 295–302.
  4. Bungartz, H.-J., & Griebel, M. (2004). Sparse grids. Acta Numerica, 13, 147–269.
  5. Agapiou, S., Papaspiliopoulos, O., Sanz-Alonso, D., & Stuart, A. M. (2017). Importance Sampling: Intrinsic Dimension and Computational Cost. Statistical Science, 32(3), 405–431.
  6. Chatterjee, S., & Diaconis, P. (2018). The sample size required in importance sampling. The Annals of Applied Probability, 28(2), 1099–1135.
  7. Papamarkou, T., Skoularidou, M., Palla, K., Aitchison, L., Arbel, J., Dunson, D., Filippone, M., Fortuin, V., Hennig, P., Hernández-Lobato, J. M., Hubin, A., Immer, A., Karaletsos, T., Khan, M. E., Kristiadi, A., Li, Y., Mandt, S., Nemeth, C., Osborne, M. A., … Zhang, R. (2024). Position: Bayesian Deep Learning is Needed in the Age of Large-Scale AI. In R. Salakhutdinov, Z. Kolter, K. Heller, A. Weller, N. Oliver, J. Scarlett, & F. Berkenkamp (Eds.), Proceedings of the 41st International Conference on Machine Learning (Vol. 235, pp. 39556–39586). PMLR.
  8. Tierney, L. (1994). Markov Chains for Exploring Posterior Distributions. The Annals of Statistics, 22(4), 1701–1728.
  9. Geyer, C. J. (2011). Introduction to Markov chain Monte Carlo. Handbook of Markov Chain Monte Carlo, 3–48.
  10. Metropolis, N., Rosenbluth, A. W., Rosenbluth, M. N., Teller, A. H., & Teller, E. (1953). Equation of State Calculations by Fast Computing Machines. The Journal of Chemical Physics, 21(6), 1087–1092.
  11. Hastings, W. K. (1970). Monte Carlo sampling methods using Markov chains and their applications. Biometrika, 57(1), 97–109.
  12. Roberts, G. O., Gelman, A., & Gilks, W. R. (1997). Weak convergence and optimal scaling of random walk Metropolis algorithms. The Annals of Applied Probability, 7(1), 110–120.
  13. Roberts, G. O., & Rosenthal, J. S. (1998). Optimal scaling of discrete approximations to Langevin diffusions. Journal of the Royal Statistical Society: Series B (Statistical Methodology), 60(1), 255–268.
  14. Fearnhead, P., Nemeth, C., Oates, C. J., & Sherlock, C. (2025). Scalable Monte Carlo for Bayesian Learning. Cambridge University Press.
  15. Brooks, S. P., & Gelman, A. (1998). General methods for monitoring convergence of iterative simulations. Journal of Computational and Graphical Statistics, 7(4), 434–455.