Foundations to Frontier
Tests
H. Generative Models › H6 Energy-Based and Score-Based Models

Energy-based models and contrastive divergence

An energy-based model (EBM) assigns every input a scalar energy E_θ(x) and defines the density p_θ(x) = exp(−E_θ(x))/Z_θ. Any network can be the energy, which makes EBMs the most flexible likelihood models, but the normaliser Z_θ is an integral over all inputs and cannot be computed. The maximum-likelihood gradient is still simple: lower the energy of data, raise the energy of model samples. Contrastive divergence (Hinton, 2002) gets those model samples cheaply by running a few MCMC steps started at the data. This page covers the Boltzmann density, the two-phase gradient, CD-k, persistent CD, Langevin-based training of modern deep EBMs (Du and Mordatch, 2019) and where EBMs are used today. The RBM-specific version (block Gibbs, free energy) is on the RBM page. In the exercises you build the pieces on 1-D energies, then train a 49-feature EBM on four 2-D blobs with weights 0.4, 0.3, 0.2 and 0.1. Exact maximum likelihood (the negative phase computed on a grid) reached a test NLL of 2.024 against 2.009 for the true density and found the mode weights (total-variation error 0.021). CD-1 and CD-10 were worse (2.111 and 2.170) and got the weights wrong (TV 0.114 and 0.208), because short chains started at the data never move mass between modes. Ten steps did not help. Persistent CD collapsed onto a single blob at the same learning rate (NLL 3.734); a 5× smaller rate brought it back to 2.305.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

A landscape whose valleys are the data

Picture a landscape over all possible inputs: valleys where realistic data live, hills everywhere else. An energy-based model learns that landscape. Low energy means likely, and the probability of a point is proportional to exp(−energy), so a valley twice as deep is far more than twice as likely. Training digs the valleys under the data and raises the ground where the model’s own samples land but no data are. The catch is that turning energies into probabilities requires adding up exp(−energy) over every possible input, which is impossible for images. The demo shows a 1-D double well: change the barrier, tilt and temperature and watch how the probability shifts between the two valleys.

Score lab
Dashed: the energy E(x) = 2(x² − 1)² + 0.5·x. Solid: p(x) = exp(−E/T)/Z with log Z = 0.448. Mass in the right well: 0.295. Z needs a sum over every x: easy on a 1-D grid, hopeless in 784 dimensions.
Why engineers care

Energy-based thinking runs through robotics and control: implicit behavioural cloning (Florence et al., 2021) represents a robot policy as an energy over actions and picks the action with the lowest energy, which handles multimodal and discontinuous behaviour far better than regressing one action. Energies are also used as out-of-distribution scores for perception systems.

📝 Quick check (Level 0)
0/3 answered
  1. 1. In an EBM, the probability of x is proportional to…
  2. 2. The hard part of an EBM is…
  3. 3. Training lowers the energy of…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

The density, its gradient and contrastive divergence

  • Model: p_θ(x) = exp(−E_θ(x))/Z_θ with Z_θ = ∫ exp(−E_θ(x)) dx. E can be any network; it only has to make Z finite (LeCun et al., 2006, “A tutorial on energy-based learning”).
  • Gradient of the NLL: ∇_θ [−log p_θ(x)] = ∇θ E_θ(x) − E(x′∼p_θ)[∇_θ E_θ(x′)]. The positive phase pushes data energies down; the negative phase pushes model samples up. At the optimum the two expectations match (moment matching for exponential families E = −θ·φ).
  • The problem: the negative phase needs samples from p_θ, i.e. MCMC on a landscape that changes at every step.
  • CD-k (Hinton, 2002): start the chains at the data and run k MCMC steps; use those samples for the negative phase. Cheap and low-variance, but biased, and not the gradient of any objective in general (Sutskever and Tieleman, 2010).
  • Persistent CD (Tieleman, 2008): keep the chains between parameter updates, so they can, in principle, travel to the whole model distribution; needs a small learning rate so the landscape changes slower than the chains mix.
  • Deep EBMs: sample with Langevin dynamics on the energy gradient ∇_x E: Du and Mordatch (2019) used a replay buffer of past samples; Nijkamp et al. (2019) used short-run chains started from noise; Du et al. (2021) added a KL term that the plain CD gradient ignores.
  • Other estimators: score matching (next page) and noise-contrastive estimation (Gutmann and Hyvärinen, 2010) avoid sampling altogether.
  • Classifiers are EBMs: JEM (Grathwohl et al., 2020) reads the logits of a classifier as energies, E(x) = −log Σ_y exp f(x)[y].
📝 Quick check (Level 1)
0/3 answered
  1. 1. The negative phase requires…
  2. 2. CD-k starts its chains…
  3. 3. Persistent CD keeps…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

Energies, partition functions and CD in code

Exercise 1.

  • log Z of a 1-D energy by quadrature (log-sum-exp).
  • The two-phase NLL gradient for E = −θ·φ.
  • An unadjusted Langevin step on the energy.
  • A CD-k gradient whose chains start at the data.

Practice.

  • Regularise energy magnitudes (Du and Mordatch add α(E(x)² + E(x′)²)) and use spectral normalisation or smooth activations, so that Langevin gradients stay bounded.
  • Clip or normalise the sampler’s gradient and tune the step size and noise together; many deep-EBM papers decouple them, which means they are no longer sampling the stated density.
  • Monitor the energy gap E(data) − E(samples): if it explodes, the sampler is failing.
  • Keep a replay buffer (95% old samples, 5% fresh noise) for persistent chains.
  • When you can compute Z (small problems, grids, tractable families), check your CD-trained model against exact maximum likelihood.
import torch
def ebm_step(E, x_data, buffer, opt, k=20, eps=0.01, alpha=0.1):
    x = buffer.sample(len(x_data)).requires_grad_(True)         # persistent / replay-buffer chains
    for _ in range(k):                                           # Langevin on the energy
        g, = torch.autograd.grad(E(x).sum(), x)
        x = (x - eps * g + (2 * eps) ** 0.5 * torch.randn_like(x)).detach().requires_grad_(True)
    buffer.push(x.detach())
    e_pos, e_neg = E(x_data), E(x.detach())
    loss = e_pos.mean() - e_neg.mean() + alpha * (e_pos ** 2 + e_neg ** 2).mean()
    opt.zero_grad(); loss.backward(); opt.step()
🐍 Exercise 1: partition functions, the two-phase gradient and CD-k
Compute log Z by quadrature, write the exponential-family NLL gradient, a Langevin step and a CD-k gradient.
📝 Quick check (Level 2)
0/3 answered
  1. 1. A cheap sanity check for an EBM sampler is…
  2. 2. Replay buffers in deep EBMs mostly hold…
  3. 3. To keep Langevin gradients bounded, EBM energies use…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

The NLL gradient. log p_θ(x) = −E_θ(x) − log Z_θ, and ∇_θ log Z_θ = (1/Z_θ) ∫ −∇_θ E_θ(x′) exp(−E_θ(x′)) dx′ = −E_pθ[∇_θ E_θ]. So ∇_θ NLL = E_data[∇_θ E] − E_pθ[∇_θ E]. For E = −θ·φ the optimum matches feature means, E_data[φ] = E_pθ[φ] (maximum entropy subject to those moments).

What CD actually optimises. Hinton (2002) showed CD-k approximately follows the gradient of KL(p_data ‖ p_θ) − KL(p_k ‖ p_θ), where p_k is the data pushed through k MCMC steps; the dropped term involves the derivative of p_k with respect to θ. If the chains barely move (small k, slow mixing), p_k ≈ p_data near each mode and the gradient only sees local shape. Relative mode weights are a global property: changing them requires the chains to carry mass across low-density barriers, so CD cannot learn them (Carreira-Perpiñán and Hinton, 2005).

Why PCD can collapse. Persistent chains are an MCMC sampler for a moving target. If the parameters change faster than the chains mix, the chains lag behind: the model raises the energy where the chains sit, the chains slide into the remaining valleys, and the procedure can oscillate or concentrate the chains. A smaller learning rate, more chains or fast weights (Tieleman and Hinton, 2009) restore the approximation.

Exercise check. On four blobs with weights 0.4/0.3/0.2/0.1, exact maximum likelihood reached weights 0.414/0.303/0.204/0.079; CD-1 reached 0.383/0.204/0.201/0.213, nearly flattening the three smaller modes.

📝 Quick check (Level 3)
0/3 answered
  1. 1. ∇_θ log Z_θ equals…
  2. 2. CD-k cannot learn relative mode weights because…
  3. 3. PCD fails when…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

How close does contrastive divergence get to exact maximum likelihood on a toy EBM, and does it learn the mode weights?

History.

  • J. J. Hopfield (1982) and D. H. Ackley, G. E. Hinton and T. J. Sejnowski (1985): energy-based networks and the Boltzmann machine.
  • G. E. Hinton, “Training products of experts by minimizing contrastive divergence” (Neural Computation, 2002).
  • Y. LeCun, S. Chopra, R. Hadsell, M. Ranzato and F. J. Huang, “A tutorial on energy-based learning” (2006).
  • T. Tieleman, “Training restricted Boltzmann machines using approximations to the likelihood gradient” (ICML 2008): persistent CD.
  • Y. Du and I. Mordatch, “Implicit generation and generalization in energy-based models” (NeurIPS 2019).
  • W. Grathwohl et al., “Your classifier is secretly an energy based model and you should treat it like one” (ICLR 2020).

Exercise 2.

  • Data: four Gaussian blobs (std 0.35) at (±1.5, ±1.5) with weights 0.4, 0.3, 0.2, 0.1; 2000 training and 2000 test points.
  • Model: E_θ(x) = −θ·φ(x) + |x|²/18, with 49 RBF features (7×7 centres on [−3, 3]², width 0.6); the quadratic term keeps Z finite.
  • Training: Adam, learning rate 0.05, batch 200, 300 steps. Negative phase: exact (grid quadrature on a 70×70 grid over [−4.5, 4.5]²), CD-1, CD-10 (Langevin, ε = 0.02, started at the batch), PCD-1 with 200 persistent chains (same rate, and 5× smaller).
  • Evaluation: exact test NLL (Z on the grid), total-variation distance between the model’s quadrant masses and the true weights, and mass where the true density is below 10⁻³ of its peak.
measure seed 0 seed 1 seed 2
true density NLL 2.009 2.017 2.048
exact ML NLL 2.024 2.033 2.071
CD-1 / CD-10 NLL 2.111 / 2.170 2.196 / 2.134 2.150 / 2.149
PCD-1 NLL (lr 0.05 / 0.01) 3.734 / 2.305 3.977 / 2.234 5.643 / 2.188
mode-weight TV: exact / CD-1 / CD-10 0.021 / 0.114 / 0.208 0.035 / 0.231 / 0.193 0.021 / 0.102 / 0.145
mode-weight TV: PCD-1 (lr 0.05 / 0.01) 0.636 / 0.202 0.539 / 0.143 0.588 / 0.108
far-from-data mass: exact / CD-1 / CD-10 0.014 / 0.045 / 0.024 0.014 / 0.050 / 0.026 0.015 / 0.053 / 0.030
  • CD is biased: both CD variants trail exact maximum likelihood by 0.08–0.16 nats and misallocate 10–23% of the probability mass between modes.
  • A null result: CD-10 was not consistently better than CD-1 (better on seed 1, worse on seed 0, equal on seed 2). Ten Langevin steps of size 0.02 still do not cross between blobs 3 units apart.
  • A negative result: PCD-1 at the CD learning rate put 74–99% of its mass into a single blob on every seed (NLL 3.7–5.6). At a 5× smaller rate it recovered (NLL 2.19–2.31), but was no better than CD here.
  • Spurious mass: CD-1 left 3–4× more mass far from the data than exact ML.
  • Caveat: with 49 fixed features and a 2-D grid, exact ML is available; for images it is not, which is why CD, PCD and the score-based methods of the next pages exist.
🐍 Exercise 2 (research): how close does contrastive divergence get to exact maximum likelihood on a toy EBM, and does it learn the mode weights?
Train a feature-based EBM on four weighted blobs with exact maximum likelihood, CD-1, CD-10 and PCD, and compare test NLL and the learned mode weights.

Energy-based models in AI, robotics and aerospace

  • Robot policies: implicit behavioural cloning (Florence et al., 2021) and energy-based diffusion policies score candidate actions and choose the lowest energy, capturing several valid ways to grasp or place an object.
  • Out-of-distribution detection: the free energy −log Σ exp(logits) of a classifier is a better OOD score than the maximum softmax (Liu et al., 2020); useful for flagging unusual sensor frames on spacecraft or drones.
  • Composition: energies add, so independently trained EBMs for different constraints (Du et al., 2020) can be combined into one product model, e.g. “safe” and “goal-reaching” trajectories.
  • Physics: Boltzmann generators and learned force fields share the same exp(−E/kT) form; the energy is the physical potential.

References

  1. G. E. Hinton (2002). “Training products of experts by minimizing contrastive divergence.” Neural Computation 14(8).
  2. Y. LeCun, S. Chopra, R. Hadsell, M. Ranzato and F. J. Huang (2006). “A tutorial on energy-based learning.” In Predicting Structured Data, MIT Press.
  3. T. Tieleman (2008). “Training restricted Boltzmann machines using approximations to the likelihood gradient.” ICML.
  4. M. Á. Carreira-Perpiñán and G. E. Hinton (2005). “On contrastive divergence learning.” AISTATS.
  5. Y. Du and I. Mordatch (2019). “Implicit generation and generalization in energy-based models.” NeurIPS.
  6. E. Nijkamp, M. Hill, S.-C. Zhu and Y. N. Wu (2019). “Learning non-convergent non-persistent short-run MCMC toward energy-based model.” NeurIPS.
  7. W. Grathwohl, K.-C. Wang, J.-H. Jacobsen, D. Duvenaud, M. Norouzi and K. Swersky (2020). “Your classifier is secretly an energy based model and you should treat it like one.” ICLR.
  8. P. Florence et al. (2021). “Implicit behavioral cloning.” CoRL.