25 / 34 · Energy-Based Models
Energy-based models
Any network with one scalar output defines a density up to an unknown constant. How to train it: the likelihood gradient and its negative phase, short Langevin chains with a replay buffer, and the sampling-free NCE and score matching.
Maximum likelihood · Sampling unnormalized densities: MALA, Hamiltonian Monte Carlo and NUTS · Logistic regression
On this page 14
Take a small convolutional network that reads a image and outputs one number, , trained to be low on digits and high on everything else: blank pages, noise, scribbles. Is it a generative model of digits? It is, once we exponentiate: is large exactly where the network says “digit”, and normalizing it gives a density over images. The previous note sampled such a density for a fixed energy. Here the energy is learned from data, and the normalizing constant, which nobody can compute, changes with every update of . How do we fit a density whose likelihood we cannot evaluate?
An energy defines a density#
An energy-based model (EBM) is a network with parameters together with the density
is the partition function. Low energy means high probability. must be finite: the energy grows fast enough at infinity, or the domain is bounded, as for pixels in . The energy gives and ; a network can draw a valley for every mode of the data. Nothing restricts the architecture: no invertibility as in flows, no pixel ordering as in autoregressive models, no encoder as in a VAE (LeCun et al., 2006).
Only differences of energy matter:
Adding a constant to the energy multiplies by and leaves unchanged. This freedom returns later as the offset problem.
Why not compute ? A grid with only 10 points per pixel of an MNIST image has nodes. Inference with an energy of an input and an answer only compares energies and never needs it (LeCun et al., 2006, Section 1.1); sampling, likelihoods and maximum-likelihood training do.
The likelihood gradient: positive and negative phases#
Maximum likelihood minimizes the expected negative log-likelihood over the data distribution , which equals the KL divergence from the data to the model up to a constant (entropy note). Since ,
The gradient of the first term averages over the data. The second term is the difficulty:
Line by line: the chain rule for the logarithm; differentiation under the integral sign, allowed when is differentiable in and the gradient of the integrand is bounded by an integrable function of ; the chain rule for the exponential; the definition of , with moved inside; the definition of an expectation.
For a single data point this gives the gradient of the log-likelihood,
and averaging over the data gives the gradient of the loss in two phases (Song and Kingma, 2021, Section 3):
Data points are the positive examples, model samples the negative ones. A step lowers the energy at the data and raises it where the model puts its mass, until the two averages of agree.
Worked example: three states. Let and let the energy be a table, , with data frequencies . For a table, is 1 if and 0 otherwise, so the positive phase is and the negative phase is :
| Quantity | |||
|---|---|---|---|
| model , with | |||
| gradient | |||
| energy after a step of size 1 | |||
| model after the step |
The step raises , where the model has too much mass, and the model moves towards ; the fixed point is . The gradient components sum to zero, so the mean energy stays at 1: the gradient never moves the overall level of the energies.
Why the negative phase needs samples from the model#
The negative phase averages under , which changes after every update and has an unknown normalizer. Importance sampling would need a proposal close to in 784 dimensions, as hard as the original problem. What remains is Markov chain Monte Carlo, which needs only the score:
Langevin dynamics, the Euler step of the MALA section without the accept test, is the usual choice for images:
with fresh noise . Each step costs one input gradient of the network, a forward and a backward pass, and the distribution of approaches as and (Du and Mordatch, 2019, Section 3). The EBM literature often calls it SGLD, after Welling and Teh (2011).
A long chain after every update is unaffordable, and with many modes Langevin chains mix slowly anyway. The methods below shorten the chains and pay with bias.
Contrastive divergence: stopping the chains early#
Contrastive divergence (CD-, Hinton, 2002) starts each chain at a data point, runs only steps of an MCMC kernel that leaves invariant, and uses the endpoints as negative examples. Write for the data, for the distribution after one step and for the equilibrium. CD-1 follows approximately the gradient of
Differentiating both divergences (below), the intractable averages over cancel. What remains is , which needs only data and one-step samples, minus a term from the dependence of on . CD-1 drops that term, which Hinton found in simulations to be small and seldom opposed to the other two (Hinton, 2002, Section 3).
Derivation
Both divergences depend on through , and the second also through , because the kernel depends on . With sums over a discrete state space (integrals otherwise), the likelihood gradient above, taken at a fixed first argument, gives the first two terms of each line; the last term of the second line differentiates through , where the extra is zero because sums to one:
The difference is never negative: one step of a chain cannot move a distribution farther from its stationary distribution. Take the joint distributions and ; their marginals of are and , since is stationary. The chain rule of the KL divergence splits their divergence in two ways:
The first split conditions on , where both conditionals are ; in the second the last term is not negative. Hence . When every transition has positive probability, equality holds only for , a perfect model (Hinton, 2002, Section 3): CD asks that the chain not walk away from the data.
Derivation
Equality needs the last term to vanish, and a KL divergence is zero only when its arguments are equal: for every that reaches. When every transition has positive probability, write both sides by Bayes’ rule, , and cancel . Then for all and , so the ratio is a constant, and it is 1 because both distributions sum to one.
Image EBMs keep short chains but start them from uniform noise, with about 10 to 100 Langevin steps (Du and Mordatch, 2019; Nijkamp et al., 2019). The endpoints are not samples of , so the gradient estimate is biased (Song and Kingma, 2021, Section 3).
What short chains learn#
A one-parameter toy example shows the direction of the bias exactly. Let the data be and the energy , so that and the right answer is . Since , the CD gradient is
Training stops where , the data’s second moment, whatever that takes. Let the negatives come from Langevin steps started at , whose variance is 3. Each step multiplies by and adds independent noise of variance , so after steps the variance is a geometric sum:
| Steps | where CD stops, | model standard deviation |
|---|---|---|
| 10 | ||
| 100 | ||
| 1000 |
With and the chain has barely contracted its starting noise, so only a steep energy brings its output variance down to 1: a model three times too narrow. Even stops at , the long-run value of unadjusted Langevin with this step. The samples match the data; the density does not. Nijkamp et al. (2019) read such a model as a learned sampler: a fixed number of Langevin steps that turns noise into images.
Short chains learn the wrong density
Persistent chains and the replay buffer#
Restarted chains throw away the previous update’s work. Persistent contrastive divergence (Tieleman, 2008) continues each chain where the last update left it: the parameters change little, so a chain near equilibrium for the old model stays near it for the new one. A replay buffer keeps a pool of past samples instead (Du and Mordatch, 2019, Section 3.2): a chain starts from a stored sample with probability 0.95 and from uniform noise otherwise, runs Langevin steps, and its endpoint goes back into the buffer. Stored samples keep refining, and fresh noise keeps exploring.
In the toy example the buffer makes the age of a sample geometric: it has run rounds of steps with probability , 20 rounds on average. Averaging the variance formula above over these ages and solving for numerically (steps below), CD stops at for and at for , the blue curve in the figure; the fresh 5% keep some bias.
Derivation
With the model held at , a sample of age has run steps from the uniform start, so its variance is the formula above with replaced by , and the buffer is a mixture of these zero-mean distributions. Its second moment averages their variances over the ages; with the geometric series gives
One training step#
A small convolutional energy on MNIST (four stride-2 convolutions with Swish, two linear layers, 76,993 parameters, pixels in ) puts the pieces together:
One EBM training step: buffer, Langevin chains, two phases
- 128 chains start from the buffer (up to 8192 images) with probability 0.95, or from uniform noise on .
- 60 Langevin steps with fixed: noise of standard deviation 0.005, then a step of size 10 against the energy gradient clipped to per component, pixels clamped to .
- The network scores 128 data images and the 128 samples .
- The loss, plus times the mean squared energies (next section), takes an Adam step (, learning rate ).
- The samples go back to the buffer, and the oldest drop out.
New images come from chains started at uniform noise and run longer, for example 256 steps.
The offset problem: why energies drift#
The CD loss depends only on differences between energies. For a network whose last layer has a bias , every energy has derivative 1 in , so the two phases cancel and exactly: nothing holds the overall level, and the other parameters move it freely. Nor is the scale: while the sampler lags behind the model, the network can widen the gap by making all energies larger, and the values drift to numerically unstable sizes (Du and Mordatch, 2019, Section 3.3).
The fix is a small multiple of the mean squared energy of both batches:
When the samples look like the data, the first term vanishes in expectation and the penalty pulls the common level to zero. When they do not, it bounds the gap. Suppose the network could set one energy for all data and one energy for all samples. Setting both derivatives of to zero gives
so : for , a gap of 10, and for . Without the penalty the loss has no minimum. The penalty is not part of the likelihood, so is kept small: 0.1 here, 1 in Du and Mordatch’s CIFAR-10 setting, together with spectral normalization of all layers (Section 3.3).
Where training breaks#
EBM training diverges easily (Grathwohl et al., 2020, Appendix H). In the typical failure the energy surface develops many sharp local minima, and chains from noise fall into the nearest one and stay noise-like. The negative phase keeps raising the energy where they sit and the positive phase keeps lowering it at the data, so the gap grows while the samples stop improving. The warning sign is negative samples with energies much larger than those of the data (Du and Mordatch, 2019, Appendix A.12). The loss settles near zero early and shows nothing; watch the generated images, the buffer and the mean energy of uniform noise instead. What helps, roughly from the cheapest:
- the L2 penalty and spectral normalization, which bound the energies and their gradients;
- smooth activations such as Swish, , which keep the input gradient smooth (Appendix A.12);
- no normalization layers, which hurt sampling (Appendix A.12); with batch normalization an image’s energy even depends on the rest of the batch;
- Adam with , since the loss surface moves with the negative samples and momentum keeps pushing in stale directions;
- a smaller learning rate or more Langevin steps per update (Grathwohl et al., Appendix H);
- restarting from an earlier checkpoint that had not yet diverged.
Evaluating a model without its normalizer#
Without there is no likelihood to report. Annealed importance sampling (Neal, 2001) estimates by moving from a tractable to through , from 0 to 1, with MCMC steps and importance weights along the way; on CIFAR-10 its bounds stayed far apart (Du and Mordatch, 2019, Appendix A.3). Image EBMs are judged by their samples, with FID for example, and by the tasks below.
Noise-contrastive estimation: learning Z by classification#
Two estimators avoid sampling from the model during training. Noise-contrastive estimation (NCE, Gutmann and Hyvärinen, 2010) treats the log-normalizer as one more parameter , an estimate of :
Choose a noise distribution that is easy to sample and to evaluate, such as a Gaussian, draw as many noise samples as data, and train a logistic regression to tell them apart, its logit fixed to the log-ratio of model and noise:
is the log-likelihood of the labels “data” and “noise”. Why does a classifier learn a density? With equal numbers of both, the Bayes-optimal probability that is data is , where is the data density, so the best classifier of the constrained form has , normalization included. Gutmann and Hyvärinen prove that this is the only maximum of over , provided wherever (Theorem 1), and that the estimate is consistent (Theorem 2): if the model family contains the data density, the fitted integrates to one in the large-sample limit, without any constraint. Maximum likelihood cannot learn , since the likelihood grows without bound in it; in NCE a that is too large makes the classifier call noise “data” and pays for it.
Worked example. Data , noise , and an energy with the right shape, , so the only unknown is ; the correct value is . At the true probability of “data” is . With the classifier gives , since . The unnormalized model, , gives , too confident, so the loss lowers ; maximizing numerically returns .
The noise decides how much the model learns. Noise equal to the data gives an asymptotic covariance twice the Cramér–Rao bound (Gutmann and Hyvärinen, 2010, Section 2.4); far noise, such as uniform noise against digits, is told apart by crude features, and the energy learns nothing finer. NCE is the discriminator of a GAN trained against a fixed generator whose density is known, with its logit constrained to ; the constraint turns the discriminator into a density, and there is no minimax game (Ermon, 2023, lecture 12).
Score matching: no samples and no Z#
The score of an EBM, , does not involve . Fitting it to the data’s score by minimizing the Fisher divergence
trains the energy with neither the normalizer nor model samples (Hyvärinen, 2005). The unknown data score is removed in the score matching note by integration by parts, which gives plus a constant, with the Laplacian, and derives the cheaper sliced and denoising versions. Either way the loss contains the input gradient of the energy, so each training step differentiates twice, and generation still needs Langevin dynamics.
Out-of-distribution detection#
An energy trained with a negative phase is low on the data and pushed up wherever its samples went, so can flag unusual inputs: those whose energy exceeds a threshold chosen on held-out data. Likelihood models are not automatically such detectors. Separating CIFAR-10 test images from SVHN house numbers by log-likelihood, PixelCNN++ and Glow reach an area under the ROC curve of 0.32 and 0.24, below the 0.5 of chance, because they give the house numbers higher likelihood; an EBM reaches 0.63 (Du and Mordatch, 2019, Section 4.4). The same EBM scores 0.30 on constant images: only what its sampler visited was pushed up. Energies also have no common scale, so the threshold must be calibrated per model.
JEM: your classifier is secretly an EBM#
A classifier with classes outputs logits and probabilities . Grathwohl et al. (2020) read the same logits as the negative energy of the pair :
Summing over gives a density of the input alone,
with the energy computed by the stable log-sum-exp. Dividing the joint by the marginal cancels and returns the softmax, so the classifier is unchanged. A constant added to all logits of an input leaves the classifier alone but changes ; this freedom, unused by ordinary training, holds the density of a joint energy-based model (JEM).
Worked example. Logits give class probabilities and . Logits give the same probabilities and . The classifier cannot tell the two inputs apart; under the second is times more probable.
JEM trains with : cross-entropy for the second term, the EBM gradient with a replay buffer for the first. On CIFAR-10 the resulting classifier keeps 92.9% accuracy while also generating images (Table 1), and is better calibrated than the same network trained alone (Section 5.2). The cost is the EBM’s: Langevin steps at every update, and frequent divergence.
Composing energies#
Adding energies multiplies densities:
This is a product of experts (Hinton, 2002): large only where both factors are, a logical AND of the constraints the energies encode. The score of the sum is the sum of the scores, so Langevin dynamics on the composed model needs no new training. For example, is and is ; their sum is , the energy of , which sits between the two and is narrower than either. Separately trained energies are in arbitrary units, so a weight on each term changes the result.
What you should remember#
- : only energy differences matter, and is intractable.
- : lower the energy at data, raise it at model samples.
- Short Langevin chains bias the model towards an energy whose -step sampler matches the data.
- A replay buffer (95% old samples, 5% noise) lengthens the chains for free; pins the energy level and caps the gap at about .
- NCE learns and by classifying data against noise; score matching fits . Neither samples during training.
- Any classifier is an EBM with ; adding energies multiplies densities.
Notebook#
The EBM notebook of the HSE-LAMBDA Deep Generative Models course trains the MNIST configuration of this note in PyTorch Lightning, following Lippe’s tutorial. Cell numbers count every cell, markdown included, from 1. No code cell has saved outputs; the network outputs , which it calls a score.
- Model and sampler (cells 8–14): the Swish CNN with 76,993 parameters, a buffer of 8192 images with 5% fresh starts, 60 steps of size 10 with gradients clipped to and noise 0.005.
- Training (cells 15–28): the loss above, Adam with betas , 60 epochs; the checkpoint is the epoch that best separates test digits from noise, not the one with the best samples.
- Generation and outlier checks (cells 35–54): 256 Langevin steps from noise, and energies of a test digit against noisy, flipped and shrunk copies.
Issues: the callbacks override on_epoch_end, which PyTorch Lightning 2.x no longer calls, so nothing is logged; make_grid(..., range=...) must become value_range; flip(dims=(1, 2)) is a 180° rotation, not a mirror image; and cell 3 calls the method contrastive divergence, though it is persistent CD with a buffer.
Next#
An energy-based model is trained with biased short MCMC chains inside every update and is shaped as much by its sampler as by its data. Diffusion models avoid this loop: they fix a process that turns data into noise and learn to undo it step by step, a regression with no sampling in training. The next note builds that forward process; the score matching note shows that the trained network is, up to a known scale, the score of the noised data: the negative gradient of an energy.
References#
- Y. LeCun, S. Chopra, R. Hadsell, M. Ranzato, F. J. Huang. A Tutorial on Energy-Based Learning. In G. Bakır, T. Hofmann, B. Schölkopf, A. Smola, B. Taskar (eds.), Predicting Structured Data, MIT Press, 2006. Section 1.1: inference by energy minimization.
- Y. Song, D. P. Kingma. How to Train Your Energy-Based Models. arXiv:2101.03288, 2021. Section 3: the gradient of the log-normalizer, Langevin MCMC, contrastive divergence and its bias; Section 4: score matching.
- S. Ermon. Deep Generative Models (CS236), Stanford, Fall 2023. Lecture 12: sampling from EBMs, score matching, noise-contrastive estimation and its comparison with GANs.
- G. E. Hinton. Training Products of Experts by Minimizing Contrastive Divergence. Neural Computation, 14(8), 1771–1800, 2002. Section 3: contrastive divergence.
- T. Tieleman. Training Restricted Boltzmann Machines using Approximations to the Likelihood Gradient. ICML, 2008. Persistent contrastive divergence.
- Y. Du, I. Mordatch. Implicit Generation and Modeling with Energy-Based Models. NeurIPS, 2019. Section 3: Langevin sampling, the replay buffer, the L2 term and spectral normalization; Section 4.4: out-of-distribution detection; Appendices A.3 and A.12: likelihood estimates, training tips.
- E. Nijkamp, M. Hill, S.-C. Zhu, Y. N. Wu. Learning Non-Convergent Non-Persistent Short-Run MCMC Toward Energy-Based Model. NeurIPS, 2019.
- M. Welling, Y. W. Teh. Bayesian Learning via Stochastic Gradient Langevin Dynamics. ICML, 2011.
- M. Gutmann, A. Hyvärinen. Noise-contrastive estimation: A new estimation principle for unnormalized statistical models. AISTATS, PMLR 9, 297–304, 2010. Theorems 1 and 2; Section 2.4: the choice of noise.
- A. Hyvärinen. Estimation of Non-Normalized Statistical Models by Score Matching. Journal of Machine Learning Research, 6, 2005.
- R. M. Neal. Annealed Importance Sampling. Statistics and Computing, 11(2), 125–139, 2001.
- W. Grathwohl, K.-C. Wang, J.-H. Jacobsen, D. Duvenaud, M. Norouzi, K. Swersky. Your Classifier is Secretly an Energy Based Model and You Should Treat it Like One. ICLR, 2020. Table 1, Section 5.2 and Appendix H.
- P. Lippe. Tutorial 8: Deep Energy-Based Generative Models. In UvA Deep Learning Tutorials, University of Amsterdam.
- HSE-LAMBDA, Deep Generative Models course repository:
EBM.ipynb.