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:
If 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 , you draw samples from and compute the average:
By the law of large numbers, this approximation converges to the true value as .
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.

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 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 (which may be hard to sample from or inefficient), you draw from a proposal distribution that's easier, and correct with a weight:
The ratio is the importance weight. If concentrates its samples where 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 whose form you know (up to a constant) but can't draw from directly. Typically: the posterior .
The MCMC idea
Instead of drawing independent samples (impossible), you build a Markov chain whose stationary distribution is . By letting the chain evolve long enough, the visited states form a (correlated) sample from .
Metropolis-Hastings
The most classic algorithm:
- Start from a point
- Propose a new point (for example, a small Gaussian step)
- Compute the acceptance ratio:
- Accept with probability , otherwise stay
- Repeat
The beauty of this algorithm is that you only need the ratio , not the normalized . 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:
The first term requires sampling from . But a random sample is not differentiable with respect to the encoder parameters . How do you backpropagate the gradient through a random draw?
The solution
Instead of drawing , you write:
The randomness is moved to , which doesn't depend on . Now is a deterministic and differentiable function of and , and the gradient can flow freely.

Analogy
Imagine you want to adjust the temperature of a shower (parameter ) 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 () from the faucet setting (). 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 over the entire vocabulary. You apply softmax with a temperature :
Then you sample a token from this distribution.
Effect of temperature
- (in practice, argmax): always the most probable token. Deterministic, but repetitive and boring.
- : a good tradeoff between coherence and creativity. The most common choice.
- : the "natural" distribution learned by the model.
- : 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 most probable tokens
- Top-p (nucleus): only consider the tokens whose cumulative probability reaches
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.