Search

Search papers and lessons

Langevin Dynamics

Level 4 · 11 min read

Langevin dynamics draws samples by repeatedly stepping uphill on a log-density and adding a little noise, so the walk settles into the distribution itself.

On this page

  • Colour = topic mix
  • Probability
  • Calculus
  • Linear algebra
  • Discrete math
  • Sampling
  • Stochastic processes
  • Sign in to see your progress

TL;DR

Langevin dynamics is a way to draw samples from a probability distribution when you can only evaluate its score, the gradient of its log-density. You repeat one simple move: take a small step uphill along the score, then add a small amount of Gaussian noise. The steps alone would carry the walk to the nearest peak and stop there. The noise keeps it moving, so over time its positions spread out according to the distribution itself.

The discrete version is the unadjusted Langevin algorithm. Adding an accept-or-reject test turns it into the Metropolis-adjusted Langevin algorithm, which removes the bias from the step size.

Where you'll see it: in Bayesian inference on large datasets (stochastic gradient Langevin dynamics), in molecular simulations that keep a system at a fixed temperature, and as the sampler inside score-based generative models, where it runs at a sequence of decreasing noise levels.

Intuition

A marble on a bumpy floor, shaken

Think of the log-density as a landscape. High ground is where the distribution puts most of its probability. The score is the arrow at each point that points uphill, toward the peaks.

If you only follow the arrows, you climb to the nearest peak and stop. That is optimisation: it finds one best answer. A sampler has a different job. It must spend time in every region in proportion to its probability, including the lower foothills, so that averages along the walk match averages under the distribution.

Langevin dynamics does this by shaking the marble. Each step has two parts. The push uphill keeps the walk on the high ground. The random kick knocks it off the peak and sends it into the foothills. The two balance out. Once the walk has settled, it is found in a spread-out cloud, densest where the landscape is highest.

Why not sample directly? For a Bayesian posterior you usually know the density only up to a constant, and the normalising constant is an integral you cannot compute. The score does not care about that constant, because taking the log turns a constant multiplier into an additive constant that disappears under the gradient. Random-walk samplers also waste effort proposing blind moves. Langevin uses the slope, so its proposals point toward likely regions, which matters a great deal in high dimensions.

−3−2−10123−2−1012xvalue
  • density of N(0, 1)
  • score -x
For a standard Gaussian, the score is -x. It is zero at the peak and points back toward the peak on either side.
flowchart LR
  A[Current position] --> B[Compute the score there]
  B --> C[Step uphill by a small amount]
  C --> D[Add a small random kick]
  D --> E[New position]
  E --> A

The math

The continuous-time equation

Let p(x)p(x) be the target density and s(x)=∇xlog⁡p(x)s(x) = \nabla_x \log p(x) its score. Langevin dynamics is the stochastic differential equation

dXt=∇xlog⁡p(Xt) dt+2 dWt.dX_t = \nabla_x \log p(X_t)\, dt + \sqrt{2}\, dW_t.

Here XtX_t is the position at time tt, and WtW_t is a Brownian motion, so each increment dWtdW_t is an independent Gaussian with mean zero and variance dtdt. The first term is the drift, the deterministic push uphill. The second term is diffusion, the random kick. Writing it as an equation with dtdt and dWtdW_t is the subject of stochastic differential equations; you do not need that machinery to follow the rest.

Why the walk settles into p

Let qt(x)q_t(x) be the probability density of XtX_t at time tt. For a process dXt=b(Xt) dt+σ dWtdX_t = b(X_t)\, dt + \sigma\, dW_t it satisfies the Fokker-Planck equation

∂tqt=−∇⋅(qt b)+σ22 ∇2qt.\partial_t q_t = -\nabla \cdot \big(q_t\, b\big) + \frac{\sigma^2}{2}\, \nabla^2 q_t.

Here b=∇log⁡pb = \nabla \log p and σ2=2\sigma^2 = 2, so σ2/2=1\sigma^2/2 = 1. Test whether q=pq = p is unchanged over time. Since p∇log⁡p=∇pp \nabla \log p = \nabla p, the drift term becomes −∇⋅∇p=−∇2p-\nabla \cdot \nabla p = -\nabla^2 p. The diffusion term is +∇2p+\nabla^2 p. They cancel, so ∂tp=0\partial_t p = 0. The target is a fixed point of the dynamics. Under mild smoothness and growth conditions on pp, the walk also converges to pp from any starting point, which is the ergodicity you need for sampling.

The argument uses only ∇log⁡p\nabla \log p. Adding a constant to log⁡p\log p changes nothing, so the normalising constant of pp is never needed.

The discrete algorithm

A computer cannot run continuous time, so we use the Euler-Maruyama scheme with step size ϵ>0\epsilon \gt 0:

xk+1=xk+ϵ ∇xlog⁡p(xk)+2ϵ ξk,ξk∼N(0,I).x_{k+1} = x_k + \epsilon\, \nabla_x \log p(x_k) + \sqrt{2\epsilon}\, \xi_k, \qquad \xi_k \sim \mathcal{N}(0, I).

Here xkx_k is the kk-th sample, and ξk\xi_k is fresh standard Gaussian noise at each step. This is the unadjusted Langevin algorithm (ULA). Its samples are biased: the chain settles into a distribution close to pp but not equal to it. The bias shrinks as ϵ\epsilon shrinks. The worked example below measures it.

Metropolis adjustment

The bias can be removed. Treat the ULA move as a proposal yy from a Gaussian q(y∣x)q(y \mid x) with mean x+ϵ∇log⁡p(x)x + \epsilon \nabla \log p(x) and variance 2ϵ2\epsilon. Accept it with probability

α(x,y)=min⁡(1,p(y) q(x∣y)p(x) q(y∣x)),\alpha(x, y) = \min\left(1, \frac{p(y)\, q(x \mid y)}{p(x)\, q(y \mid x)}\right),

and otherwise stay at xx. This is the Metropolis-adjusted Langevin algorithm (MALA). It is an instance of Metropolis-Hastings, so its stationary distribution is exactly pp, at the cost of computing the acceptance test.

Stochastic gradient Langevin dynamics

Suppose the log-density is a prior plus a sum over NN data points, log⁡p(θ)=log⁡π(θ)+∑i=1Nlog⁡p(di∣θ)\log p(\theta) = \log \pi(\theta) + \sum_{i=1}^{N} \log p(d_i \mid \theta). Computing the full gradient on every step costs NN operations. Welling and Teh proposed replacing it with a minibatch estimate of size mm:

g^(θ)=∇log⁡π(θ)+Nm∑i∈B∇log⁡p(di∣θ),\hat g(\theta) = \nabla \log \pi(\theta) + \frac{N}{m} \sum_{i \in B} \nabla \log p(d_i \mid \theta),

where BB is a random batch of mm data points. Plugging g^\hat g into the ULA update gives stochastic gradient Langevin dynamics (SGLD). It is the sampling counterpart of stochastic gradient descent: the batch adds noise to the drift on top of the kick. For this reason the step size is usually decreased over time, so that the injected noise is small compared to the Langevin kick.

Annealed Langevin

For a very multimodal density, Song and Ermon ran Langevin on a sequence of smoothed versions of pp, with noise levels σ1>σ2>⋯>σL\sigma_1 \gt \sigma_2 \gt \dots \gt \sigma_L. At each level they started from where the previous level ended. Large smoothing flattens the valleys between modes, so the chain crosses between them. Small smoothing then sharpens the distribution toward the real one.

Worked examples

Example
One step on a standard Gaussian

Target: p(x)=N(0,1)p(x) = \mathcal{N}(0, 1), so the score is ∇log⁡p(x)=−x\nabla \log p(x) = -x. Take ϵ=0.1\epsilon = 0.1, start at x0=3x_0 = 3, and draw noise ξ0=0.5\xi_0 = 0.5.

  1. Score at the start: −x0=−3-x_0 = -3.
  2. Drift term: ϵ×(−3)=−0.3\epsilon \times (-3) = -0.3.
  3. Noise scale: 2ϵ=0.2≈0.4472\sqrt{2\epsilon} = \sqrt{0.2} \approx 0.4472.
  4. Kick term: 0.4472×0.5≈0.22360.4472 \times 0.5 \approx 0.2236.
  5. New position: x1=3−0.3+0.2236=2.9236x_1 = 3 - 0.3 + 0.2236 = 2.9236.

The drift pulled the walk toward zero by 0.30.3, and the noise pushed it back up by 0.220.22. Without noise, the update would be 2.72.7 every time and the walk would keep converging to the peak. The kick is what makes the walk a sampler.

Example
How big is the step-size bias?

Keep the same target and see where the ULA chain actually settles. Each step is xk+1=(1−ϵ)xk+2ϵ ξkx_{k+1} = (1 - \epsilon) x_k + \sqrt{2\epsilon}\, \xi_k. This is a simple autoregressive process. If its variance is vv at equilibrium, then

v=(1−ϵ)2v+2ϵ.v = (1 - \epsilon)^2 v + 2\epsilon.
  1. Expand: v=v−2ϵv+ϵ2v+2ϵv = v - 2\epsilon v + \epsilon^2 v + 2\epsilon.
  2. Cancel vv on both sides and collect: v(2ϵ−ϵ2)=2ϵv(2\epsilon - \epsilon^2) = 2\epsilon.
  3. Divide by ϵ\epsilon: v(2−ϵ)=2v(2 - \epsilon) = 2, so v=22−ϵv = \dfrac{2}{2 - \epsilon}.
  4. With ϵ=0.1\epsilon = 0.1: v=2/1.9≈1.053v = 2 / 1.9 \approx 1.053.

The chain's variance is about 5%5\% too large compared with the true value of 11. The bias is of order ϵ\epsilon. Halving ϵ\epsilon roughly halves the error, at the cost of twice as many steps. This is why MALA's accept-reject step is useful when the step must be large.

Example
Posterior for a mean, one full-gradient step

Data: x=(2.1,1.9,2.4)x = (2.1, 1.9, 2.4), assumed Gaussian with known variance 11. Prior on the unknown mean μ\mu: N(0,100)\mathcal{N}(0, 100). The log posterior is, up to a constant,

log⁡p(μ∣x)=−12∑i(xi−μ)2−μ2200.\log p(\mu \mid x) = -\tfrac{1}{2}\sum_i (x_i - \mu)^2 - \frac{\mu^2}{200}.

Its gradient is ∑i(xi−μ)−μ/100\sum_i (x_i - \mu) - \mu/100.

  1. Sum of the data: 2.1+1.9+2.4=6.42.1 + 1.9 + 2.4 = 6.4.
  2. At μ0=0\mu_0 = 0 the gradient is 6.4−0=6.46.4 - 0 = 6.4.
  3. Take ϵ=0.01\epsilon = 0.01 and noise ξ0=0.3\xi_0 = 0.3.
  4. Drift: 0.01×6.4=0.0640.01 \times 6.4 = 0.064.
  5. Kick: 0.02×0.3≈0.0424\sqrt{0.02} \times 0.3 \approx 0.0424.
  6. New value: μ1=0+0.064+0.0424≈0.106\mu_1 = 0 + 0.064 + 0.0424 \approx 0.106.

The posterior mode is ∑xi/(n+1/100)=6.4/3.01≈2.13\sum x_i / (n + 1/100) = 6.4 / 3.01 \approx 2.13, and its standard deviation is 1/3.01≈0.581/\sqrt{3.01} \approx 0.58. The first step moved the chain from 00 toward the mode, and it is far from done. Run the chain for many steps and its samples spread around 2.132.13 with spread about 0.580.58, which is the posterior.

Tradeoffs and failure modes

Langevin uses gradients, so it is a good default when the score is available and the target is smooth. It is not free of problems.

SituationProblemBetter choice
Several well-separated modesThe chain stays in one mode: the score keeps pushing it back uphill, and the noise rarely carries it across the low-density valleyTempering, annealed Langevin, or several chains from different starts
Step size too largeThe stationary distribution is biased away from the targetMetropolis adjustment (MALA), or a smaller step
Step size too smallThe chain moves slowly and needs many steps to mixAn adaptive step size, or Hamiltonian Monte Carlo
Minibatch gradients with a fixed large stepThe batch noise dominates, and the samples are wider than they should beA decreasing step-size schedule, or full-batch gradients
Log-density has no usable gradientThe score cannot be computedRandom-walk Metropolis, which needs only density evaluations
Parameters on very different scalesThe drift is steep in one direction and flat in another, so the step is slowPreconditioning the step with an estimate of the covariance

The most common practical failure is picking the step size by hand and never checking the bias. Run the chain at two step sizes and compare summary statistics. If they disagree, the step is too large.

History

Paul Langevin introduced his equation in 1908 as a model of Brownian motion. It was a simple force balance: a friction term plus a random force, building on Einstein's 1905 explanation of the same phenomenon. The physics community used it for decades to describe particles in a fluid at a fixed temperature.

Using it as a sampler came later. In the 1990s, Gareth Roberts and Richard Tweedie studied its discrete versions and proved when they converge, which is the theory behind MALA. In 2011, Max Welling and Yee Whye Teh proposed SGLD, which made the method workable for large Bayesian models. The idea returned strongly in 2019, when Yang Song and Stefano Ermon used annealed Langevin to sample from learned score functions, a route that led to the score-based diffusion models that followed.

Check yourself

QuestionWhat is the job of the random kick in the Langevin update, if the drift alone already moves the walk toward high-probability regions?Show answer

Without the kick, the update only follows the score uphill. That is gradient ascent on the log-density, and the walk converges to the nearest peak and stays there, so it cannot represent the spread of the distribution. The kick knocks the walk off the peak and lets it explore lower regions. The balance between drift and kick is what makes the long-run positions follow the density.

QuestionA Langevin chain with step size ϵ=0.05\epsilon = 0.05 is at x=2x = 2 for a standard Gaussian target, and the noise draw is ξ=−1\xi = -1. What is the next position?Show answer

The score is −x=−2-x = -2. The drift is 0.05×(−2)=−0.10.05 \times (-2) = -0.1. The noise scale is 2×0.05=0.1≈0.3162\sqrt{2 \times 0.05} = \sqrt{0.1} \approx 0.3162, so the kick is 0.3162×(−1)=−0.31620.3162 \times (-1) = -0.3162. The new position is 2−0.1−0.3162≈1.5842 - 0.1 - 0.3162 \approx 1.584. The walk moved toward zero, and the negative kick added to that movement.

QuestionWhy does the unadjusted Langevin algorithm give biased samples, and what would make the samples exact?Show answer

The Euler-Maruyama discretisation replaces the continuous-time motion with jumps of finite size. The stationary distribution of the discrete chain is therefore not exactly pp, and the error is of order the step size. Adding a Metropolis accept-reject step to each proposal, which gives MALA, makes the chain's stationary distribution exactly pp for any step size, at the cost of evaluating the density ratio each step.

QuestionYou want to sample from a learned score model of data with several separated clusters. Why is plain Langevin from random noise a poor choice, and how does annealed Langevin help?Show answer

A learned score is unreliable in low-density regions, where there is little training data, and a plain chain starts and travels through exactly those regions. It also rarely crosses the valleys between clusters. At high noise the density is smoothed and the valleys are shallow, so the score is well estimated everywhere and the chain can move between clusters. Each next, less-smoothed level starts from where the previous one ended, and as the noise drops the samples are refined toward the sharp data distribution.

Sources