AI State of the Art
Math/Probability and Statistics/12 min
Section 329

Sampling: Monte Carlo, Importance Sampling, MCMC

Listen as a podcast →

Why sample?

In machine learning, we constantly encounter integrals that are impossible to compute analytically. For example, to make predictions with a Bayesian model, you'd need to integrate over all possible parameters:

P(y∣x,D)=∫P(y∣x,θ)P(θ∣D) dθP(y | x, \mathcal{D}) = \int P(y | x, \theta) P(\theta | \mathcal{D}) \, d\theta

If θ\theta lives in a space with millions of dimensions (like the weights of a network), this integral is intractable. Sampling is the solution: instead of computing the integral exactly, you draw samples and average.

Basic Monte Carlo

The principle

The idea of Monte Carlo is simple and elegant. To compute Ep(x)[f(x)]=∫f(x)p(x) dxE_{p(x)}[f(x)] = \int f(x) p(x) \, dx, you draw NN samples x1,x2,…,xNx_1, x_2, \ldots, x_N from p(x)p(x) and compute the average:

Ep(x)[f(x)]≈1N∑i=1Nf(xi),xi∼p(x)E_{p(x)}[f(x)] \approx \frac{1}{N} \sum_{i=1}^N f(x_i), \quad x_i \sim p(x)

By the law of large numbers, this approximation converges to the true value as N→∞N \to \infty.

Analogy

To estimate the area of a lake on a map, throw darts randomly at the map. The proportion of darts that land in the lake, multiplied by the area of the map, gives an estimate of the lake's area. The more darts you throw, the more precise the estimate.

On the left, thousands of points drawn at random inside a square, coloured blue if they fall in the inscribed disc and red otherwise. On the right, two curves against the number of samples: the estimate of pi converging to 3.14, and the relative error decreasing.
The canonical dart-throwing picture: the fraction of points landing inside the disc estimates its area, hence pi. On the right, the estimate starts far off with few draws, then settles. That is the law of large numbers at work, and it is exactly how a gradient estimated on a mini-batch behaves.Source : Imad Pasha (Prappleizer), Metropolis-Hastings Tutorial

In ML

  • SGD is a Monte Carlo method: you estimate the gradient over the entire dataset by computing it on a random mini-batch
  • Dropout during inference: averaging multiple forward passes with different masks is Monte Carlo

Limitations

The problem with basic Monte Carlo is efficiency. If the distribution p(x)p(x) is highly concentrated in a small region of space, most samples fall in "uninteresting" areas and contribute little to the estimate. In high dimensions, this problem explodes.

Importance sampling

The idea: sample smarter

Instead of drawing from p(x)p(x) (which may be hard to sample from or inefficient), you draw from a proposal distribution q(x)q(x) that's easier, and correct with a weight:

Ep(x)[f(x)]=∫f(x)p(x)q(x)q(x) dx≈1N∑i=1Nf(xi)p(xi)q(xi),xi∼q(x)E_{p(x)}[f(x)] = \int f(x) \frac{p(x)}{q(x)} q(x) \, dx \approx \frac{1}{N} \sum_{i=1}^N f(x_i) \frac{p(x_i)}{q(x_i)}, \quad x_i \sim q(x)

The ratio wi=p(xi)q(xi)w_i = \frac{p(x_i)}{q(x_i)} is the importance weight. If qq concentrates its samples where f(x)⋅p(x)f(x) \cdot p(x) is large, the estimate is more efficient.

Analogy

To estimate the average size of fish in a lake, instead of fishing randomly (lots of small fish, few big ones), you could fish in the deep areas where big fish concentrate, then correct your estimate to account for your sampling bias.

In ML

  • Off-policy learning in RL: you learn from data collected by an old policy, using importance weights to correct
  • PPO (Proximal Policy Optimization) uses importance sampling with a clipped ratio for stability
  • Log-likelihood estimation in latent variable models

High-dimensional problem

In high dimensions, importance weights can vary by several orders of magnitude, making the estimate very noisy. A few samples with enormous weights dominate, and variance explodes. This is the "curse of dimensionality" of importance sampling.

MCMC: Markov Chain Monte Carlo

The problem

You want to sample from a distribution p(θ)p(\theta) whose form you know (up to a constant) but can't draw from directly. Typically: the posterior P(θ∣D)∝P(D∣θ)P(θ)P(\theta | \mathcal{D}) \propto P(\mathcal{D} | \theta) P(\theta).

The MCMC idea

Instead of drawing independent samples (impossible), you build a Markov chain whose stationary distribution is p(θ)p(\theta). By letting the chain evolve long enough, the visited states form a (correlated) sample from p(θ)p(\theta).

Metropolis-Hastings

The most classic algorithm:

  1. Start from a point θ0\theta_0
  2. Propose a new point θ′∼q(θ′∣θt)\theta' \sim q(\theta' | \theta_t) (for example, a small Gaussian step)
  3. Compute the acceptance ratio: α=min⁡(1,p(θ′)q(θt∣θ′)p(θt)q(θ′∣θt))\alpha = \min\left(1, \frac{p(\theta') q(\theta_t | \theta')}{p(\theta_t) q(\theta' | \theta_t)}\right)
  4. Accept θt+1=θ′\theta_{t+1} = \theta' with probability α\alpha, otherwise stay θt+1=θt\theta_{t+1} = \theta_t
  5. Repeat

The beauty of this algorithm is that you only need the ratio p(θ′)/p(θt)p(\theta')/p(\theta_t), not the normalized pp. The normalization constant (the evidence) cancels in the ratio.

Limitations in ML

MCMC is exact in theory but slow in practice for high-dimensional models. Traversing the parameter space of a neural network with millions of weights would take an astronomical amount of time. That's why Bayesian deep learning uses variational inference instead.

The reparameterization trick

The VAE problem

In a Variational Autoencoder, you want to optimize:

L=Ez∼qϕ(z∣x)[log⁡pθ(x∣z)]−DKL(qϕ(z∣x)∥p(z))\mathcal{L} = E_{z \sim q_\phi(z|x)}[\log p_\theta(x|z)] - D_{KL}(q_\phi(z|x) \| p(z))

The first term requires sampling zz from qϕ(z∣x)q_\phi(z|x). But a random sample is not differentiable with respect to the encoder parameters ϕ\phi. How do you backpropagate the gradient through a random draw?

The solution

Instead of drawing z∼N(μϕ,σϕ2)z \sim \mathcal{N}(\mu_\phi, \sigma_\phi^2), you write:

z=μϕ+σϕ⋅ϵ,ϵ∼N(0,1)z = \mu_\phi + \sigma_\phi \cdot \epsilon, \quad \epsilon \sim \mathcal{N}(0, 1)

The randomness is moved to ϵ\epsilon, which doesn't depend on ϕ\phi. Now zz is a deterministic and differentiable function of μϕ\mu_\phi and σϕ\sigma_\phi, and the gradient can flow freely.

Two computation graphs side by side. On the left, the original form: the node z is random and sits on the path between phi and f. On the right, the reparameterised form: z becomes a deterministic node g(phi, x, epsilon) and the only random node is epsilon, placed off the backpropagation path that runs from f back to phi.
On the left, the random node z (in blue) sits across the path from the parameter phi to the loss, so backpropagation is impossible. On the right, the randomness has been pushed into epsilon, which has no link to phi, and z is a deterministic node again. The red arrow shows the gradient now able to reach phi.Source : Slide by D. P. Kingma (NIPS 2015 workshop), via Lilian Weng (Lil Log)

Analogy

Imagine you want to adjust the temperature of a shower (parameter ϕ\phi) based on the water coming out (sample). If the water is random, you can't tell which faucet to turn. The reparameterization trick amounts to separating the plumbing noise (ϵ\epsilon) from the faucet setting (ϕ\phi). The noise still exists, but you can see how the setting affects the average temperature.

Impact

This trick, introduced simultaneously by Kingma and Welling (VAE) and Rezende et al. in 2014, made it possible to train VAEs by gradient descent. Without it, generative models with continuous latent variables would have remained intractable.

Temperature sampling in LLMs

How an LLM generates text

At each step, the model produces logits z1,…,zVz_1, \ldots, z_V over the entire vocabulary. You apply softmax with a temperature TT:

P(tokeni)=ezi/T∑jezj/TP(\text{token}_i) = \frac{e^{z_i / T}}{\sum_j e^{z_j / T}}

Then you sample a token from this distribution.

Effect of temperature

  • T=0T = 0 (in practice, argmax): always the most probable token. Deterministic, but repetitive and boring.
  • T=0.7T = 0.7: a good tradeoff between coherence and creativity. The most common choice.
  • T=1.0T = 1.0: the "natural" distribution learned by the model.
  • T>1.0T > 1.0: more random, more creative, but also more incoherent.

Top-k and top-p (nucleus) sampling

In practice, temperature is combined with filtering:

  • Top-k: only consider the kk most probable tokens
  • Top-p (nucleus): only consider the tokens whose cumulative probability reaches pp

These techniques prevent the model from choosing very improbable tokens that would make the text incoherent, while preserving diversity.

Key takeaways

  • Sampling solves the problem of intractable integrals in ML
  • Monte Carlo estimates an expectation by averaging random samples
  • Importance sampling enables more efficient sampling with correction weights
  • MCMC builds a Markov chain to sample from complex posteriors
  • The reparameterization trick makes sampling differentiable, which enabled VAEs
  • Temperature and nucleus sampling control the diversity of generation in LLMs

Where this is used. The reparameterization trick is what makes the VAE trainable, and temperature is the dial that steers a language model's creativity: see prompt engineering.