Energy-Based Models
Unnormalized densities, contrastive divergence and score matching.
Write down any function of the input, call it an energy, and you have a probability model: . The freedom is total, and so is the difficulty, because the normalizer is an integral over all of input space. This lesson derives what maximum likelihood then demands, the Markov chains that try to supply it and the biases they bring, and three ways to train without sampling at all: score matching, the denoising version that diffusion models are built on, and noise-contrastive estimation.
What you’ll learn
- Derive the log-likelihood gradient of an energy-based model as the difference between the data and model expectations of .
- Prove that is stationary for the Langevin diffusion, compute the bias of its unadjusted discretization, and explain why score-driven chains misjudge the weights of separated modes.
- Explain contrastive divergence, persistent chains and the short-run samplers of deep EBMs, and what their biases do to the learned model.
- Derive score matching by integration by parts and denoising score matching by the tower property, explain why noise-contrastive estimation is consistent, and read any classifier as an energy-based model.
The likelihood gradient and the missing samples
The log-density is minus the energy, minus a constant that depends on the parameters:
Differentiate the log-partition function under the integral. The integrand turns into the model density itself:
Average over the training set. The gradient of the log-likelihood is a difference of two expectations of the same quantity, under the data and under the model:
Ascent lowers the energy of the data (the positive phase) and raises it wherever the model puts its mass (the negative phase). It stops when the two expectations agree; for an exponential family, , that is the classic moment matching .
Everything hinges on samples from , a distribution known only up to and changing with every update. Given exact samples , the stochastic gradient is unbiased, and it is the gradient of the surrogate loss with a data point and held fixed, with no gradient through the sampler. That is how deep EBMs are implemented, and Du & Mordatch (2019) noted its resemblance to the critic objective of a Wasserstein GAN, with a Markov chain in place of a generator (Generative Adversarial Networks). The rest of this lesson is about where comes from, or how to do without it.
Langevin dynamics: sampling with the score
Since involves no normalizer, gradient-based Markov chains can sample an EBM. The basic one is the overdamped Langevin diffusion: gradient descent on the energy plus Brownian noise.
The density of obeys the Fokker–Planck equation, a continuity equation whose flux has a drift part and a diffusion part:
For we have , so the flux vanishes at every point, not just on average: the drift toward low energy exactly balances the spreading by noise. Hence .
Run the unadjusted Langevin algorithm with step on , a standard normal. What is the variance of the chain's stationary distribution?
Show the answer
1.14
The update is , so the stationary variance solves , giving : too wide by 14%, and with no stationary distribution at all for . The bias vanishes only as . A Metropolis–Hastings accept–reject step (the Metropolis-adjusted Langevin algorithm, MALA) removes it at any step size.
Separated modes. Langevin chains find mass by following local gradients, and that is their weakness on multimodal targets. Take with components that barely overlap. Inside the support of , : the score hardly depends on at all. To learn the weights a chain must cross the low-density gap, and for high energy barriers the expected crossing time grows exponentially with the barrier's height, roughly like for a barrier of height (the Eyring–Kramers law), so in practice the share of chains in each mode is set by where they started. Song & Ermon (2019) showed this with exact scores on a two-Gaussian mixture, and showed that annealing, running Langevin on the scores of less and less noised versions of the data, recovers the weights: under heavy noise the modes overlap, so the score depends on both of them and on their weights. That ladder of noise levels became the diffusion model (Diffusion Models).
Contrastive divergence and short-run samplers
Restricted Boltzmann machines made EBMs practical first. Binary visible units and hidden units interact only across the two layers, , so each layer is conditionally independent given the other: and , and block Gibbs sampling alternates between them. The likelihood gradient for is , with drawn given in the first term.
Contrastive divergence (CD-; Hinton, 2002) replaces the model expectation by the statistics after only Gibbs steps, often one, of a chain started at the training data:
Hinton motivated it as approximately minimizing a difference of two divergences, , where is the data distribution and the distribution after steps, while dropping a term for how itself moves with . The shortcut has costs. CD is biased: its fixed points generally differ from those of maximum likelihood, although the bias is typically small (Carreira-Perpiñán & Hinton, 2005). The CD-1 update for binary RBMs is not the gradient of any function, and with a suitably chosen regularizer CD learning can cycle forever (Sutskever & Tieleman, 2010). And because its chains start at the data and run briefly, CD rarely explores low-energy regions far from the data, so it does little to raise their energy.
Persistent CD (Tieleman, 2008) keeps a set of chains running across parameter updates instead of restarting them at the data; when the parameters change slowly, the chains stay close to the current model and can wander far from the data. Deep EBMs carried the recipe to images. Du & Mordatch (2019) ran Langevin dynamics on a convolutional energy, starting each chain from a replay buffer of earlier samples 95% of the time and from uniform noise otherwise, with spectral normalization and a small penalty on energy magnitudes for stability. Their models produced good samples, could be composed by adding energies, and detected out-of-distribution inputs. Their CIFAR-10 chains took 60 steps of size 10 with noise of standard deviation 0.005, hundreds of times smaller than a Langevin step of that size requires. Such samplers are noisy gradient descent, biased on purpose for speed.
An EBM is trained with 60-step Langevin chains started from noise, with far less noise than Langevin requires, and the chains' samples look excellent. What does this establish?
- That is an accurate density model of the data
- That the short-run sampler is a good generator; the density itself may put its mass elsewhere
- That the chains have mixed, since otherwise the samples would look poor
- Nothing: samples from an EBM are never informative
Show the answer
B. That the short-run sampler is a good generator; the density itself may put its mass elsewhere
Training matched the data to whatever the biased sampler produces, so sampler and data agree, but nothing forces long-run Langevin on to give the same distribution. Checking the energy itself takes long chains or a likelihood estimate.
Training without sampling
Sampling inside the training loop can be avoided by matching something other than the likelihood. The Fisher divergence compares scores, which do not involve . With the model's score ,
Two log-densities with the same gradient everywhere differ by a constant, and normalization forces the constant to be zero, so only when the model matches the data. The data's score is unknown, but it can be eliminated.
Expand the square. The last term involves only the data and is the constant :
In the cross term, the density cancels against the derivative of its logarithm, :
Integrate by parts. The boundary term vanishes by the decay assumption, and what remains is an expectation under the data of something the model can compute:
So . In dimensions the same step, applied coordinate by coordinate, gives the trace. Under further identifiability conditions Hyvärinen also proved that minimizing the sample version of is a consistent estimator.
The trace is the bottleneck. needs the diagonal of a matrix of second derivatives of the energy, about backward passes. Sliced score matching (Song, Garg, Shi & Ermon, 2019) projects onto random directions, , the trick of Hutchinson's estimator in Continuous Flows & Flow Matching. Denoising score matching (Vincent, 2011) removes the trace altogether by changing the target: corrupt each data point, , and fit the score of the corrupted density .
Differentiate the mixture under the integral and divide by it. The score of the mixture is the posterior average of the components' scores:
Expand both squares. The terms agree, the cross terms agree by the tower property, and the rest does not involve . This is the argument of conditional flow matching, with a score in place of a velocity.
The price is that the model learns the score of the noised data, which approaches the data score only as , where the target becomes very noisy. Learning it at many noise levels at once and sampling by descending through them is how diffusion models work; Diffusion Models shows that their noise-prediction loss is this objective at every noise level, up to a weight per level.
Noise-contrastive estimation (NCE; Gutmann & Hyvärinen, 2010) keeps the energy and replaces sampling by classification. Treat the log-normalizer as one more parameter , so ; draw noise samples per data point from a density that can be evaluated; and train a logistic classifier to tell data from noise with the logit
The Bayes-optimal classifier has logit , the density-ratio fact behind the optimal GAN discriminator (Generative Adversarial Networks). If the model family contains the data distribution and wherever the data are, the optimum therefore has , which is normalized, so converges to ; Gutmann & Hyvärinen proved the estimator consistent. NCE works best when the noise resembles the data, since an easy discrimination gives little signal (Song & Kingma, 2021, review variants that adapt the noise). Contrastive representation learning borrowed the idea and the name (Self-Supervised Learning).
Classifiers are energy-based models
Any classifier with logits already defines an EBM over inputs and labels. Grathwohl et al. (2020) called the result a joint energy-based model (JEM):
JEM trained this model on : the first term by ordinary cross-entropy, the second by the likelihood gradient with short-run sampling. Its chains took 20 steps from a replay buffer, reinitialized from noise with probability 5%, with step size 1 and noise of standard deviation 0.01, again about a hundred times less noise than Langevin requires. The authors reported better calibration, out-of-distribution detection and adversarial robustness than comparable classifiers, and samples rivaling contemporary GANs. They were candid about the cost: the gradient estimates were unstable, and their models "regularly diverged throughout training", needing restarts with lower learning rates or more regularization.
In a JEM, add the same constant to all logits at one input . What changes?
- The predicted class probabilities
- Nothing at all
- The energy falls by , so the unnormalized density at grows by the factor , while is unchanged
- Every class probability grows by the factor
Show the answer
C. The energy falls by , so the unnormalized density at grows by the factor , while is unchanged
, so drops by . The softmax is invariant to a common shift, which is why an ordinary classifier never pins this direction down and JEM can spend it on density.
Key takeaways
- An EBM's log-likelihood gradient is : push the energy down on data and up on model samples, which must come from MCMC.
- The Langevin diffusion leaves invariant because its probability flux vanishes; the unadjusted algorithm is biased (stationary variance for a standard normal), and score-driven chains cannot learn the weights of separated modes in reasonable time, which annealing through noise levels repairs.
- Contrastive divergence starts short chains at the data: biased, and for binary RBMs not the gradient of any function. Persistent chains and replay buffers keep chains running; with the short, low-noise samplers of deep EBMs, the sampler rather than may be what matches the data.
- Score matching turns the Fisher divergence into by integration by parts; denoising score matching regresses on and learns the noised score, the objective of diffusion models; NCE classifies data against noise with as a parameter.
- A classifier's logits define an EBM with ; trained as one (JEM), it gained calibration and out-of-distribution detection at the price of unstable training.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
In the log-likelihood gradient of an EBM, what does the second term do during gradient ascent, and why is it hard to compute?
- It lowers the energy of the data; it is hard because the data set is large
- It raises the energy wherever the model currently puts its mass, and it needs samples from the model, which is known only up to
- It normalizes the density exactly at every step
- It is a regularizer that can be dropped once training has converged
Show the answer
B. It raises the energy wherever the model currently puts its mass, and it needs samples from the model, which is known only up to
The second term is of , an expectation under . It pushes the energy up on the model's own samples, which keeps the density from piling up away from the data. Estimating it takes samples from , usually by MCMC.
Langevin dynamics with the exact score is run on a mixture of two well-separated Gaussians with weights 0.7 and 0.3, from chains started uniformly over a region containing both. After a moderate number of steps, what fraction of the chains sits in the heavier mode?
- About 0.7, because the score encodes the weights
- About 1, because chains drift toward the heavier mode
- Roughly the fraction that started in its basin of attraction: the local score does not depend on the weights, and crossing the gap takes exponentially long
- About 0.5, because Langevin dynamics treats modes symmetrically
Show the answer
C. Roughly the fraction that started in its basin of attraction: the local score does not depend on the weights, and crossing the gap takes exponentially long
Inside a mode's support, , whatever is. Chains settle in the basin they start in, so the split reflects the initialization until the chain mixes, which takes a time exponential in the barrier height. Annealing through noise levels (Song & Ermon, 2019) repairs this.
Denoising score matching with Gaussian noise of standard deviation regresses on . At the optimum, equals:
- The score of the noised data, , which approaches the data's score only as
- The score of the data, , for any
- The target of each training pair, which it memorizes
- Minus the energy,
Show the answer
A. The score of the noised data, , which approaches the data's score only as
The regression's minimizer is the conditional mean of the target given , and that posterior average of the components' scores is exactly . Diffusion models exploit this at every noise level instead of trying to make tiny.
In noise-contrastive estimation the log-normalizer is a free parameter , with . If the model family contains the data distribution, what does converge to?
- , the log of the noise-to-data ratio
- The entropy of the noise distribution
- , so that is normalized
Show the answer
D. , so that is normalized
The optimal classifier needs , hence , a normalized density. With that forces .
Further reading
- G. E. Hinton, "Training products of experts by minimizing contrastive divergence," Neural Computation 14(8), 1771–1800 (2002).
- A. Hyvärinen, "Estimation of non-normalized statistical models by score matching," Journal of Machine Learning Research 6, 695–709 (2005).
- P. Vincent, "A connection between score matching and denoising autoencoders," Neural Computation 23(7), 1661–1674 (2011).
- M. Gutmann & A. Hyvärinen, "Noise-contrastive estimation: A new estimation principle for unnormalized statistical models," AISTATS (2010).
- Y. Song & D. P. Kingma, "How to train your energy-based models," arXiv:2101.03288 (2021).