Energy-based models, score matching and Langevin dynamics
Before this lesson: lesson 01 (maximum likelihood as a KL divergence) and lesson 05 (critics that learn unnormalized density ratios). Gradient descent (optimization lesson 01). From the probability track: Gaussians, Markov chains and the Metropolis–Hastings algorithm. Stochastic differential equations (SDEs) and the Fokker–Planck equation are explained here as far as we need them; the ML for science track treats them in full. Time: about 100 minutes, plus the notebook.
Why this matters #
An energy-based model (EBM) is the most general way to write a density: no invertible layers (as in flows), no ordering of the variables (as in autoregressive models). The ideas of this lesson appear in many places:
- Diffusion models learn the score of noisy data with denoising score matching, and sample with steps that look like Langevin dynamics. NCSN (Song and Ermon 2019) is annealed Langevin dynamics; predictor–corrector samplers add Langevin "corrector" steps.
- Bayesian deep learning uses stochastic gradient Langevin dynamics (SGLD): SGD plus the right amount of noise samples a posterior over weights.
- Physics and chemistry. The Boltzmann distribution is an EBM with a known energy, and Langevin dynamics is Brownian dynamics. Slow crossing of energy barriers is the rare-event problem of molecular simulation.
- Inverse problems. A posterior is an EBM whose energy is the data misfit plus the prior energy. Its score is the sum of two scores, and the unknown drops out.
1. Predict first #
2. The picture #
2.1 An energy is a landscape #
An energy is a landscape over the data space. The model density is
Valleys of are regions of high probability (modes). Hills are regions of low probability.
- gives : the standard normal , with .
- With a parameter, with gives and .
- The double well has two valleys at with , and a hill at with . The density has two modes, and the barrier between them has height .
Only differences of energy matter. Adding a constant to multiplies and by the same factor , so does not change. The ratio needs no .
Langevin dynamics is noisy gradient descent. The update
is a gradient-descent step on the energy with step size , plus a random kick. Without the kick, falls into the nearest valley and stops: you get a mode, not a sample. With the kick of size , falling and kicking balance, and the points visit each region in proportion to . Picture a ball in the landscape that is shaken by heat.
Press Play. 2000 particles start at and move with Langevin steps. The top chart compares the orange histogram of the particles with the exact blue density . The bottom chart shows the energy and 80 of the particles on it. Then choose the Gaussian target and make large: with ULA (plain Langevin steps) the histogram is too wide, and the readout gives the theory . Switch to MALA: the bias disappears, but fewer steps are accepted.
The figure shows two facts that section 3 proves. First, the particles settle to the right density for small . Second, a finite step gives a slightly wrong density (a bias); a Metropolis–Hastings correction (MALA) removes it.
2.2 Learning pushes the energy down at the data and up at model samples #
How do we fit to data? Maximum likelihood (as in lesson 01) makes large on the data. Section 3.2 shows that its gradient has two parts:
- the positive phase lowers the energy at the data points;
- the negative phase raises the energy at samples from the model.
If the model puts probability where there are no data, its samples land there, and the negative phase raises the energy there. Learning stops when the two pushes balance: the model samples look like the data, as far as the features of can tell.
Press "1 update" a few times. The energy is , and the blue data come from two bumps. At the start () the model has one bump at 0. The orange chain samples go there, and the arrows show that the update pushes the energy up where there are more chain samples and down where there are more data. Run 100 updates: a double well appears, the moments of data and chains become equal, and reaches the exact maximum-likelihood value (dashed lines in the small chart).
During maximum-likelihood training of an EBM, the model puts a lot of probability in a region with no data. What does the negative phase do there?
The gradient of the log-likelihood is . The second term (negative phase) uses samples from the model; ascending it increases the energy where those samples are. That is how spurious modes are removed, but only if the sampler actually visits them.
2.3 The score field and many noise levels #
The score of a density is the vector field . It points in the direction where the density grows fastest. For an EBM, , and does not depend on , so
So Langevin dynamics needs only the score: . If we can learn the score directly (section 3.7), we never need or even an energy.
Noise smooths the data. Let with from the data and . The density of is the data density blurred with a Gaussian of width . For small it is close to the data. For large the modes merge into one wide bump.
The figure uses the 8 Gaussians of this track: means , standard deviation . After noising, each component has variance , so the score of is known in closed form. The arrows are the exact score, not a learned one.
Move the σ slider. At small σ, each violet arrow points to the nearest blue mode; between modes the arrows are almost zero. At large σ, all arrows point to the centre. Now compare two runs from the same uniform start: Langevin at this σ (with σ small) and Annealed Langevin (σ goes from 3 down to 0.05). Mode 1 has weight 0.4 and the others 0.086. The bar chart shows the fraction of particles near each mode: at fixed small σ every mode gets about 1/8; the annealed run gets close to 0.4 for mode 1.
The figure shows the two problems of a single noise level, and the fix:
- The score does not see the mixture weights. Near a mode, the score points to that mode, whatever its weight. Particles go to the closest mode and stay there.
- Particles do not cross between modes. At small σ the region between modes has almost no probability, and Langevin needs an exponentially long time to cross it (section 3.9).
- The fix: start with large noise. At large σ the modes overlap, particles move freely, and they split according to the weights. As σ shrinks, each particle stays in the mode it chose.
The target is . What is the score at , to two decimals?
At the left term is about times the right one, so . The constant disappears under the derivative: . Near a well-separated mode, the score does not depend on the weights.
3. Definitions and main results #
3.1 Energy-based models #
An energy-based model is a density of the form
where is any function with parameters (often a neural network). The partition function (normalizing constant) must be finite: must grow fast enough as , or must live in a bounded set. For this needs .
In high dimension, is an integral that we cannot compute. So is known only up to the unknown constant . We can compare two points (), but we cannot evaluate the likelihood itself.
3.2 The gradient of the log-likelihood #
Theorem (EBM log-likelihood gradient). For one data point,
For the average log-likelihood :
Proof.
- Take the log: .
- Differentiate . Use and move the gradient inside the integral (this needs a mild regularity condition, as for dominated convergence):
- Combine steps 1 and 2 for one , then average over the data.
Reading the result. Gradient ascent on moves in the direction of at the data, which lowers the energy there, and of at model samples, which raises the energy there. The gradient is zero when
Exponential families. If the energy is linear in , with fixed features , then and the condition is moment matching: . The Hessian of is , so is concave and the optimum is unique when the covariance is positive definite. The widget of section 2.2 is this case with : at the end, and of the chains equal those of the data.
In code. Draw model samples with an MCMC sampler and detach them from the computation graph. Then minimize the surrogate loss
Its gradient is a Monte Carlo estimate of . The value of is not a log-likelihood; only its gradient matters.
3.3 Langevin dynamics #
To get model samples, we need a sampler that uses only . A stochastic differential equation (SDE) describes a point that moves with velocity and is kicked by Brownian motion : over a time , the kick is and independent of the past. The simplest way to simulate it is the Euler–Maruyama step:
The noise scales with , not : the variance of a sum of independent kicks grows linearly with time.
The (overdamped) Langevin SDE for a target uses :
Theorem (stationarity). If , then for all : is a stationary density of the Langevin SDE. Moreover, if is the density of , then never increases.
Why this is true (intuition). The density of changes for two reasons: the drift moves probability uphill toward the modes, and the noise spreads it out (diffusion). At the two flows of probability cancel exactly at every point.
The Fokker–Planck argument
- For , the density of solves the Fokker–Planck equation . The first term moves probability with velocity ; the second term (the Laplacian ) spreads it like heat.
- Write , because . With :
- At the term is 0, so : is stationary.
- . The "" part integrates to 0, because the total mass stays 1. Insert step 2 and integrate by parts (the boundary terms vanish when decays fast):
with equality only when , that is, .
Only appears, so the dynamics never need . The theorem says nothing about speed. For a target with separated modes, the KL can decrease very slowly (section 3.9).
3.4 ULA is biased; MALA removes the bias #
The unadjusted Langevin algorithm (ULA) is the Euler–Maruyama step of the Langevin SDE with a fixed step :
The continuous SDE has stationary density . The discrete chain does not: it has an error of order . A Gaussian target shows this exactly.
Theorem (ULA bias for a Gaussian). For the target in 1D, ULA is stable for , its stationary distribution is Gaussian with mean , and its stationary variance is
Proof.
- The score is . So with .
- This is a linear (AR(1)) chain. It forgets its start when , that is, .
- Taking means: . No bias in the mean.
- Taking variances, with independent of : . At the fixed point, , so
For and : , about 5% too large. The bias is for small . A smaller reduces the bias but makes the chain slower: is close to 1, so successive samples are strongly correlated.
Several dimensions and conditioning
For a target , the same computation holds in each eigendirection of , with replaced by the eigenvalue . Stability needs , the bias is largest in the narrowest direction, and the widest direction needs about steps to mix. So the cost grows with the condition number , as for gradient descent (optimization lesson 02). Example: and give ULA variances (+2.9%) and (+25%); stability needs ; the wide direction has .
MALA. The Metropolis-adjusted Langevin algorithm uses the ULA step as a proposal, , and accepts with probability
If it rejects, the chain stays at . This is the Metropolis–Hastings rule, so detailed balance makes exactly stationary for every : the bias is gone. Three facts:
- : cancels.
- MALA needs the energy itself, not only its gradient. A network that outputs only a score gives no acceptance ratio.
- Large steps are often rejected, so the chain moves less. In high dimension, must shrink like to keep a good acceptance rate (Roberts and Rosenthal 1998).
ULA on the target with step . What is the stationary variance of the chain?
The update is , so . The continuous SDE has stationary variance 4; the discrete step adds a bias of about . The last option forgets to square .
3.5 Contrastive divergence and persistent chains #
The negative phase needs samples from , and changes at every update. Running a chain to equilibrium after each update is too expensive. Two approximations are common.
- Contrastive divergence (CD-) (Hinton 2002): start the chains at the data batch, run MCMC steps (often ), and use the end points as negative samples. It is cheap but biased: after steps the chains are still close to the data, not distributed as . Low-energy regions far from the data (spurious modes) are never visited, so they are never corrected. In general, CD- is not the gradient of any objective.
- Persistent CD (PCD; Tieleman 2008): keep the chains from one update to the next instead of restarting them at the data. changes slowly, so the chains stay close to the current and the bias is smaller. The widget of section 2.2 uses persistent chains.
- Deep EBMs (Du and Mordatch 2019) run tens of Langevin steps per update, started from a replay buffer of earlier samples (about 95%) or from fresh noise (about 5%), and add a small penalty on the size of the energies. In practice the step size and the noise scale are often tuned separately, with much less noise than . The chains are then close to noisy gradient descent, and the samples are not exact samples of .
Two methods avoid negative samples altogether: score matching (section 3.7), and noise-contrastive estimation, which trains a logistic classifier to separate data from a known noise distribution and learns as one more parameter.
3.6 The score needs no partition function #
Definition. The score of a density on is , a vector field. (Do not confuse it with the score-function estimator of lesson 02, which uses , the gradient with respect to parameters.)
For an EBM, , and does not depend on :
More generally, if for any unnormalized , then . Examples: the score of is ; the score of a mixture is , where are the responsibilities (compute them with log-sum-exp).
So a score model can be trained and used for Langevin sampling without ever touching , or even an energy.
and is unknown. Which quantity can you NOT compute exactly?
The score is ; the ULA update uses only the score; the MALA ratio uses , where cancels. Only the absolute value needs .
3.7 Score matching #
We want from samples of . In this lesson every score-matching loss has the factor (as in Hyvärinen 2005 and Vincent 2011); the minimizers do not depend on this choice.
Explicit score matching (ESM) minimizes the Fisher divergence
We cannot compute it: the target is unknown. Two tricks remove the target.
Implicit score matching (Hyvärinen 2005). Integration by parts gives
where does not depend on . Proof in 1D: expand the square; the cross term is , when at . In dimensions, do this for each coordinate. The loss needs only samples of . But the trace of the Jacobian costs backward passes, which is too slow for images.
Sliced score matching
Sliced score matching (Song, Garg, Shi and Ermon 2019) replaces the trace by a random projection: for a random with , the same idea as Hutchinson's estimator in lesson 04. The loss needs one Jacobian-vector product per , not backward passes.
Denoising score matching (Vincent 2011). Add Gaussian noise: , with and . The noising kernel is , and its score is known:
The DSM loss regresses the model on this known target:
The noisy point has the density , the data density blurred with .
Theorem (DSM = ESM + constant). Assume for . Then
where does not depend on . So DSM trains toward the score of the noisy density , not of the clean data.
Why this is true (intuition). One noisy point can come from many clean points . Each of them gives a different target . A least-squares regression learns the average target at each . That average is exactly the score of (step 3 below).
Proof.
- Expand both squared norms with .
- The terms are the same in both losses, because in both has the density .
- Key identity. Differentiate under the integral and use :
Divide by . The factor is the posterior , so
The marginal score is the posterior mean of the conditional score. 4. The cross terms are equal. By step 3 and the tower property, . 5. The remaining terms do not contain . So .
Consequences.
- Over all functions, the minimizer is the conditional mean of the target: . This is the general rule "the best least-squares prediction is the conditional mean".
- The loss does not go to 0. Its minimum is , the conditional variance of the target. No function of can predict the part of the noise that does not reveal. Do not judge a score model by how close its loss is to 0.
- Noise prediction. Multiply the loss by : . So a network that predicts the added noise gives the score . The DDPM loss of lesson 07 is this loss over many noise levels.
Add samples. Each aqua dot is one noisy point with its DSM target . The targets are very noisy, but their average in each small bin settles on the exact score of . The last readout shows that even the exact score has a positive DSM loss, equal to the constant . Make σ small: the targets spread more (their standard deviation is ), and you need more samples.
A clean point is noised with and , so . What is the DSM regression target for ?
The target is , which equals : it points from back to . The value has the wrong power of . The exact score of is not needed: DSM replaces it by this known target, and the regression averages the targets.
3.8 Tweedie's formula #
The DSM optimum also gives a denoiser. From and step 3 of the proof:
This is Tweedie's formula (Robbins 1956, Efron 2011). The score at a noisy point, times , is the step back to the average clean point. So "learn the score of " and "learn the best denoiser at noise level " are the same task. The same formula gives the posterior covariance: .
Check with a Gaussian. Data in 1D. Then and Tweedie gives . This is the posterior mean from Gaussian conditioning: a weighted average of the observation and the prior mean.
3.9 Two problems of a single score, and many noise levels #
A score learned from clean data (or from with small ), used in Langevin dynamics, fails in three ways (Song and Ermon 2019).
1. Inaccurate scores in low-density regions. The score is trained only where there are data. Between modes and far from the data, the learned score can be wrong, and the chains start exactly there.
2. The score does not see the mixture weights. Let , where and have disjoint supports. On the support of , , so
Langevin chains that cannot cross between the supports keep whatever split they started with. Nearly disjoint supports (well-separated modes) behave almost the same.
3. Slow mixing. To leave a mode, a chain must climb a barrier of height . For overdamped Langevin at unit temperature, the mean time to cross grows like (the Arrhenius law). Kramers' formula makes this precise for a 1D double well: the mean time to go from one well to the other is about
Raise the barrier. The energy is , so the barrier height is . The trajectory hops between the wells often for small and rarely for large . The lower chart has a log scale: the exact mean crossing time is close to a straight line, so it grows exponentially in , and Kramers' formula (dashed) is close for high barriers. Press Simulate at a few heights: the simulated averages fall on the exact curve.
The fix: many noise levels. Let . For large :
- the noised data fill space, so a learned score is accurate where the chains start;
- the modes overlap, the barriers are low, and the chains move freely between modes;
- the score far from the data now depends on the weights, so the chains split correctly.
Example: for , the barrier is at , at , at , at , and at (one mode).
Annealed Langevin dynamics (NCSN, Song and Ermon 2019) uses noise levels (geometric), and one network trained with DSM at all of them.
- Start from a broad distribution (uniform or a wide Gaussian).
- For : set the step (proportional to the variance at that level) and run Langevin steps .
- Each level starts from the samples of the previous level. Return the samples of the last level.
At large the chains find the right mode weights; small then sharpens the samples. Diffusion models do the same with a continuous noise level and a better-designed sampler (lessons 07–09); predictor–corrector samplers still add Langevin corrector steps at each level.
Answers to section 1. (1) Larger: , about 5% too large (section 3.4). (2) No: at the barrier is , so the crossing time is of order time units, times a prefactor. Near the score is for any weights (section 3.9). (3) It learns the score of the noisy density , not of the clean data; the loss does not go to 0, its minimum is the constant (section 3.7).
4. Worked example #
(a) The likelihood gradient of a Gaussian EBM. , so and . Data: .
- Second moment of the data: .
- Positive phase: .
- Negative phase at : .
- : decrease , that is, make the model wider.
- The gradient is zero at . The model variance equals the second moment of the data: moment matching.
(b) ULA on the fitted model .
- With : , and the update is .
- Stationary variance: , so 25% too large. Stable for .
- With : , the variance is , only 2% too large.
- The price: the integrated autocorrelation time of an AR(1) chain is . It grows from steps to steps. About twelve times less bias costs about twelve times more steps per independent sample.
(c) One MALA step. Target , , current point , noise .
- Proposal: .
- Target ratio: .
- Proposal densities (both have variance , so the constants cancel): and .
- , so . The move is accepted with probability 0.687.
(d) Score, Tweedie and the DSM floor for Gaussian data. Data , noise . Then .
- Score at : .
- Tweedie: . Gaussian conditioning gives the same: .
- Posterior variance: , which is with .
- DSM floor: , so . Even the exact score has .
(e) A mixture. Data (the "narrow" data of the DSM figure), . Noising adds to each variance: . At :
- The two component scores are and .
- The responsibility of the right component: the ratio of the two densities is , so .
- The score is the responsibility-weighted average: .
- Tweedie: . This is almost the posterior mean inside the right component alone, .
5. In code #
NumPy and SciPy check the numbers of sections 3 and 4. The notebook has these cells and the exercises.
import numpy as np
from scipy.special import logsumexp
from scipy.stats import norm
rng = np.random.default_rng(0)
# (a) EBM gradient for E_theta(x) = theta x^2 / 2: positive + negative phase
data = np.array([-1.0, 0.5, 2.0])
theta = 1.0
grad = -np.mean(data**2 / 2) + 1 / (2 * theta) # E_p[x^2/2] = 1/(2 theta)
print(round(grad, 3), round(1 / np.mean(data**2), 4)) # -0.375 0.5714
# (b) ULA on N(0, 1.75) with h = 0.7: run 20000 chains for 200 steps
s2, h = 1.75, 0.7
x = np.zeros(20_000)
for _ in range(200):
x = x - h * x / s2 + np.sqrt(2 * h) * rng.standard_normal(x.size)
print(round(x.var(), 3), s2 / (1 - h / (2 * s2))) # 2.172 2.1875 (sampling error about 0.02)
# (c) one MALA step: target N(0, 1), h = 0.5, from x = 1 to x' = 2
x0, x1, h = 1.0, 2.0, 0.5
log_alpha = (norm.logpdf(x1) - norm.logpdf(x0)
+ norm.logpdf(x0, x1 - h * x1, np.sqrt(2 * h)) # log q(x | x')
- norm.logpdf(x1, x0 - h * x0, np.sqrt(2 * h))) # log q(x' | x)
print(round(log_alpha, 3), round(np.exp(log_alpha), 3)) # -0.375 0.687
# (d) DSM on Gaussian data N(2, 1) with sigma = 1: p_sigma = N(2, 2)
sigma = 1.0
x0 = 2 + rng.standard_normal(1_000_000)
eps = rng.standard_normal(x0.size)
xs = x0 + sigma * eps
exact_score = -(xs - 2) / 2
print(round(np.mean(0.5 * (exact_score + eps / sigma) ** 2), 3)) # 0.25: the DSM floor
print(4 + sigma**2 * (-(4 - 2) / 2)) # Tweedie at x = 4: 3.0
# (e) mixture 0.5 N(-2, 0.25) + 0.5 N(2, 0.25), sigma = 0.5: score at x = 1
def log_p(x, sigma, w=0.5, m=2.0, s=0.5):
sd = np.sqrt(s**2 + sigma**2)
return logsumexp([np.log(w) + norm.logpdf(x, -m, sd),
np.log(1 - w) + norm.logpdf(x, m, sd)], axis=0)
d = 1e-6
score = (log_p(1 + d, 0.5) - log_p(1 - d, 0.5)) / (2 * d)
print(round(score, 5), round(1 + 0.25 * score, 4)) # 1.99732 1.4993
# (f) barrier of 0.5 N(-4, 0.25) + 0.5 N(4, 0.25) after noising with sigma
grid = np.linspace(0, 8, 80_001)
for sg in [0, 1, 2, 3, 4]:
lp = log_p(grid, sg, m=4.0)
print(sg, round(lp.max() - log_p(0.0, sg, m=4.0), 2))
# 0 31.31 / 1 5.71 / 2 1.19 / 3 0.21 / 4 0.0
The mixture log-density uses logsumexp: far from both components, each Gaussian density
underflows to 0 in floating point, and the responsibilities would become .
6. Where it shows up #
- Score-based diffusion models. NCSN (Song and Ermon 2019) trains with DSM and samples with annealed Langevin dynamics. Score SDEs and DDPM use the same DSM (noise-prediction) loss with a continuous noise level (lessons 07–09). Predictor–corrector samplers add Langevin corrector steps.
- Denoisers as priors. By Tweedie's formula, any good denoiser gives a score. "Plug-and-play" and "regularization by denoising" methods for image restoration use this, and diffusion posterior sampling (lesson 15) adds a likelihood score: , where drops out.
- Bayesian deep learning. SGLD (Welling and Teh 2011) adds Langevin noise to mini-batch SGD with a decreasing step size to sample a posterior over network weights.
- Classifiers as EBMs. The logits of a classifier define an energy (JEM, Grathwohl et al. 2020). Such energies are also used for out-of-distribution detection.
- Physics and chemistry. Overdamped Langevin dynamics is Brownian dynamics, and the score of a Boltzmann density is the force divided by . Slow crossing of barriers is the rare-event problem (protein folding, phase transitions). Boltzmann generators use normalizing flows to sample all modes without crossing barriers.
- Data assimilation. With a Gaussian likelihood, the posterior energy is . 4D-Var minimizes this energy (the MAP estimate); Langevin with a learned prior score samples it. Score-based data assimilation (Rozet and Louppe 2023) uses a few Langevin corrector steps per noise level.
7. Common mistakes #
- Noise instead of . The update samples (half the temperature): a Gaussian target comes out with half its variance as .
- No noise at all. Then it is gradient descent on : it returns a mode, not samples.
- Ignoring the ULA bias. Test a sampler on a Gaussian with known variance. Steps above diverge.
- MH with a score network. The MALA ratio needs ; a score field alone does not give it.
- Sign errors in the EBM loss. Minimize , with the negative samples detached from the graph.
- Trusting short-run chains. CD-1 or 20 Langevin steps from noise do not sample . The learned energy can work well with its own sampler and still be a poor density.
- Thinking DSM learns the clean score. It learns the score of . The clean score is only the limit , where the targets have variance and the regression is hopeless.
- Expecting the DSM loss to reach 0. Its minimum is , which depends on and on the data. Compare with a closed-form score when you can.
- One chain on a multimodal target. A chain stuck in one mode looks converged. Run many chains from spread-out starts, and anneal the noise level.
- Confusing the two "scores". (this lesson) is a gradient with respect to the data. The score function of statistics and of REINFORCE, , is a gradient with respect to the parameters.
8. Check yourself #
- with . Compute and , check the
theorem of section 3.2, and give the maximum-likelihood .
Answer
, so . The theorem says , and for this Laplace density . ✓ The gradient of is , which is zero at . - ULA on with : write the update, the stationary variance and the largest
stable step.
Answer
. , about 14% too large. Stable for . - Show that has a stationary density proportional to
. Which does the "noise " mistake correspond to?
Answer
The Fokker–Planck equation is . It is 0 when , that is, . Noise means : the chain samples . - For and the model , compute the implicit score-matching loss
and its minimizer.
Answer
and , so the loss is (using ). It is minimal at , the true score . Check: , so . - Data in 1D and noise . What is the minimum value of the DSM loss (with
the factor )? Which function reaches it?
Answer
and . So . It is reached by the exact score . - Why can you not use MALA with the score network of a diffusion model? What could you do instead?
Answer
MALA needs , and the network gives only . You could parameterize the model as an energy and take its gradient (then the energy gives the ratio), integrate the score along the segment from to (costly, and a learned field need not be a true gradient), or accept the ULA bias with a small step. - For the mixture of section 1, why does annealed Langevin recover the 50/50 weights when plain
Langevin started near does not?
Answer
At the barrier is 31.3, so chains never cross, and the score near each mode does not contain the weights. At the noised mixture has one mode (barrier 0), so the chains mix and split according to the weights. Lowering slowly keeps each chain in the mode it chose, so the split survives as the modes separate.
Write the gradient of for an energy-based model.
(positive phase at the data, negative phase at model samples).
Write one step of the unadjusted Langevin algorithm.
, with .
Stationary variance of ULA for the target with step ?
, stable for . For , : .
How does MALA remove the bias of ULA, and what does it need that ULA does not?
It uses the ULA step as a proposal and accepts it with the Metropolis–Hastings probability, so is exactly stationary. It needs energy differences , not only the score.
Why does the score of an EBM not depend on ?
and does not depend on , so .
Write the denoising score matching loss and its target.
; the target is .
What does DSM learn at its optimum, and why?
The score of the noisy density, : a least-squares fit learns the conditional mean of the target.
State Tweedie's formula for .
.
Why does contrastive divergence (CD-) give a biased gradient?
Its negative samples come from MCMC steps started at the data, so they are close to the data, not samples of ; regions far from the data are never corrected.
Why does Langevin with many noise levels (annealing) work better than one small noise level?
At large the modes overlap, the scores are accurate and depend on the weights, and chains cross easily; lowering keeps each chain in its mode and sharpens the samples.
9. Interview angle #
- "Why are EBMs hard to train?" — is intractable, so the likelihood gradient needs model samples from MCMC; short chains are biased, long chains are expensive, and mixing between modes is slow.
- "What is the score, and why do diffusion models learn it instead of the density?" — ; it does not contain , and it can be learned by denoising (DSM).
- "Langevin versus gradient descent?" — The same step plus noise ; the noise turns mode finding into sampling. Without noise you get a mode.
- "What is the bias of ULA and how do you remove it?" — ; for the variance is . Remove it with MALA or a decreasing step size.
- "Prove that denoising score matching works." — The marginal score is the posterior mean of the conditional score (differentiate under the integral); so the cross terms of DSM and ESM agree, and the losses differ by a constant.
- "Why many noise levels?" — Scores are accurate only where noised data have mass; large noise merges modes, so Langevin can cross and find the weights; small noise sharpens.
- "Contrastive divergence in one sentence?" — Approximate the negative phase with MCMC steps started at the data: cheap, biased, and not the gradient of a fixed objective in general.
10. Practice #
The notebook for this lesson has five exercises, each with a check cell and a folded solution. All of them use NumPy and exact formulas; no network is trained.
- ULA on : measure the variance for several , compare with , then write MALA and check that the bias disappears.
- Crossing time against barrier height on the double well : simulate and compare with the exact formula and Kramers' approximation.
- Denoising score matching with a model that is linear in fixed features, fitted by least squares on 1D mixture data; compare with the exact noised score.
- Annealed versus fixed-σ Langevin on the 8 Gaussians with unequal weights, with exact scores: compare the mode proportions.
- Persistent contrastive divergence for a 1D Gaussian EBM; compare with the closed-form maximum likelihood estimate.
11. Watch and read #
- Song and Kingma, How to Train Your Energy-Based Models (2021): §2 (EBMs), §3 (maximum likelihood with MCMC, Langevin, CD and persistent CD), §4 (score matching, including denoising and sliced score matching).
- Song and Ermon, Generative Modeling by Estimating Gradients of the Data Distribution (NeurIPS 2019): §2 (score matching, Langevin), §3 (the problems of low density and slow mixing), §4 (noise levels and annealed Langevin, Algorithm 1).
- Yang Song, Generative Modeling by Estimating Gradients of the Data Distribution (blog post): a readable tour from scores to score SDEs.
- Vincent, A Connection Between Score Matching and Denoising Autoencoders (2011): the original DSM = ESM + constant result.
- Hyvärinen, Estimation of Non-Normalized Statistical Models by Score Matching (JMLR 2005): implicit score matching.
- Song, Garg, Shi and Ermon, Sliced Score Matching (UAI 2019).
- UvA Deep Learning tutorial 8, Deep Energy-Based Generative Models: a practical EBM with contrastive divergence and a replay buffer.
- Murphy, Probabilistic Machine Learning: Advanced Topics, free PDF: chapter 24 (energy-based models: MCMC training, score matching, noise-contrastive estimation).
Runs in your browser with nothing to install. The notebook repeats the key demos and has exercises with checks; solutions are inside, folded.
No Google account needed: Python runs inside your browser. The first start downloads about 40 MB; your changes are saved in this browser only.