Skip to content
BIASED

Energy-based models

A density from any network through an energy, the likelihood gradient as a tug of war between positive and negative phases, contrastive divergence and the replay buffer, noise-contrastive estimation, and the classifier as a hidden EBM.

An energy defines a density

The topic Sampling unnormalized densities: MALA and HMC sampled a density e−U(x)/Ze^{-U(x)}/Z known only up to its normalizer: Langevin dynamics, MALA and HMC need nothing but ∇U\nabla U. There the energy UU was given. Here it gets parameters and is learned from data.

Take any network Eθ:RD→RE_\theta: \mathbb R^D \to \mathbb R with one scalar output and call it the energy. An energy-based model (EBM) turns it into a density:

pθ(x)=e−Eθ(x)Zθ,Zθ=∫e−Eθ(x) dx.p_\theta(x) = \frac{e^{-E_\theta(x)}}{Z_\theta}, \qquad Z_\theta = \int e^{-E_\theta(x)}\, dx .

Low energy means high density. The normalizer ZθZ_\theta is called the partition function. For E(x)=x2/2E(x) = x^2/2 it equals 2π\sqrt{2\pi}, and pp is N(0,1)\mathcal N(0, 1).

Nothing restricts EθE_\theta. A flow had to be invertible, keep the dimension and have a cheap Jacobian (see The change of variables); an energy can be any convolutional network.

The price is ZθZ_\theta. It is an integral over all of RD\mathbb R^D. Even a crude grid with 10 values per pixel on a 28×2828 \times 28 image has 1078410^{784} nodes. What survives without it are comparisons. As in the previous topic, the normalizer cancels in a ratio of densities:

pθ(x)pθ(y)=eEθ(y)−Eθ(x).\frac{p_\theta(x)}{p_\theta(y)} = e^{E_\theta(y) - E_\theta(x)} .

So the model can say which of two images is more plausible, and by how much. It cannot say how likely one image is on its own, and it cannot produce an image directly.

Positive and negative phases

Train by maximum likelihood, as always. The negative log-likelihood of the data splits into two terms:

L(θ)=−Ex∼P[log⁡pθ(x)]=Ex∼P[Eθ(x)]+log⁡Zθ.\mathcal L(\theta) = -\mathbb E_{x \sim P}\big[\log p_\theta(x)\big] = \mathbb E_{x \sim P}\big[E_\theta(x)\big] + \log Z_\theta .

The first term is an average over training data, easy to estimate. The second looks hopeless, but its gradient is not. Differentiate under the integral:

∇θlog⁡Zθ=1Zθ∫∇θe−Eθ(x) dx=−∫e−Eθ(x)Zθ ∇θEθ(x) dx=−Ex∼pθ[∇θEθ(x)].\nabla_\theta \log Z_\theta = \frac{1}{Z_\theta} \int \nabla_\theta e^{-E_\theta(x)}\, dx = -\int \frac{e^{-E_\theta(x)}}{Z_\theta}\, \nabla_\theta E_\theta(x)\, dx = -\mathbb E_{x \sim p_\theta}\big[\nabla_\theta E_\theta(x)\big] .

The integral became an expectation under the model itself. Put the two terms together:

∇θL=Ex+∼P[∇θEθ(x+)]−Ex−∼pθ[∇θEθ(x−)].\nabla_\theta \mathcal L = \mathbb E_{x^+ \sim P}\big[\nabla_\theta E_\theta(x^+)\big] - \mathbb E_{x^- \sim p_\theta}\big[\nabla_\theta E_\theta(x^-)\big] .

The first term is the positive phase. A descent step along it lowers the energy of training points x+x^+. The second is the negative phase. It raises the energy of the model's own samples x−x^-. When the samples look like the data, the two pulls balance.

In code this is a surrogate loss, 1N∑iEθ(xi+)−1N∑iEθ(xi−)\frac1N \sum_i E_\theta(x_i^+) - \frac1N \sum_i E_\theta(x_i^-), where the samples xi−x_i^- are plain inputs: no gradient flows into the procedure that made them. It resembles the critic loss of Wasserstein GANs and Lipschitz constraints with the sign flipped. But there is no separate generator. The samples come from the energy itself, through MCMC (Du and Mordatch, 2019).

Three states

The two phases are easiest to see on a space with three states. Let the energies E1=0E_1 = 0, E2=1E_2 = 1, E3=2E_3 = 2 be the parameters themselves, and let the data visit the states with frequencies P=(0.5, 0.3, 0.2)P = (0.5,\ 0.3,\ 0.2).

The partition function is a sum of three terms, Z=1+e−1+e−2≈1.503Z = 1 + e^{-1} + e^{-2} \approx 1.503, and the model probabilities are

pθ=(0.665, 0.245, 0.090).p_\theta = \big(0.665,\ 0.245,\ 0.090\big).

Differentiating Eθ(x)E_\theta(x) with respect to EiE_i gives 11 when x=ix = i and 00 otherwise. So each phase turns into a probability:

∂L∂Ei=P(i)−pθ(i).\frac{\partial \mathcal L}{\partial E_i} = P(i) - p_\theta(i) .

State 1 gets 0.5−0.665=−0.1650.5 - 0.665 = -0.165. The model puts too much mass there, so the negative phase wins and a descent step raises E1E_1. One step of size 11 moves the model to (0.611, 0.280, 0.109)(0.611,\ 0.280,\ 0.109), closer to the data on every state.

The negative phase needed the model probabilities, and that is where ZZ entered. With three states it is a sum of three terms. In RD\mathbb R^D it turns into a demand for samples.

Short chains and contrastive divergence

Every gradient step needs samples x−x^- from the current pθp_\theta. The samplers of Sampling unnormalized densities fit, because the score of an EBM does not involve ZθZ_\theta: ∇xlog⁡pθ(x)=−∇xEθ(x)\nabla_x \log p_\theta(x) = -\nabla_x E_\theta(x). Langevin dynamics with a step size η\eta reads

xk+1=xk−η2 ∇xEθ(xk)+η zk,zk∼N(0,I).x_{k+1} = x_k - \frac{\eta}{2}\, \nabla_x E_\theta(x_k) + \sqrt{\eta}\, z_k, \qquad z_k \sim \mathcal N(0, I).

Each step costs one backward pass through EθE_\theta with respect to the input. Running chains to equilibrium after every parameter update would cost thousands of passes per update. So practical methods cut the chains short and accept a biased gradient.

Contrastive divergence (CD-kk, Hinton, 2002) starts each chain at a training point and runs only kk steps. The endpoints serve as negatives: in a few steps a chain already drifts toward where the model is wrong. Image EBMs usually start from uniform noise instead and run 10–100 Langevin steps.

How large is the bias? Take data N(0,1)\mathcal N(0, 1) and the energy Ev(x)=x2/(2v)E_v(x) = x^2/(2v) with one parameter vv; the right answer is v=1v = 1. Negatives come from KK Langevin steps with η=0.01\eta = 0.01, started from the uniform distribution on [−3,3][-3, 3], whose variance is 33. Since ∂Ev/∂v=−x2/(2v2)\partial E_v/\partial v = -x^2/(2v^2), training stops where the negatives have the same second moment as the data, variance 11. Where it stops:

KK 1010 100100 10001000
learned v∗v^* 0.0880.088 0.580.58 0.9970.997

Short chains learn a model that is far too narrow. Its 10-step samples have exactly the right variance, but the density itself has variance 0.0880.088. Nijkamp et al. (2019) describe such a model as a learned short-run sampler rather than a density.

Persistent chains and a replay buffer

Restarting chains from scratch throws work away. Persistent contrastive divergence (Tieleman, 2008) keeps each chain and continues it from where it stopped. One update changes θ\theta only a little, so the old samples are almost samples of the new model, and over training every chain accumulates many steps.

A replay buffer (Du and Mordatch, 2019) does this for images. It stores past negatives. Each new chain starts from a stored sample with probability 0.950.95 and from uniform noise otherwise, so fresh starting points keep arriving. In the toy model, K=10K = 10 steps with a buffer give v∗=0.52v^* = 0.52 instead of 0.0880.088, and K=100K = 100 gives 0.940.94 instead of 0.580.58.

Here is one training step of a small MNIST EBM, following Lippe's tutorial. A batch of 128 chains starts from the buffer, which holds up to 8192 images, or from noise. The chains run 60 Langevin steps while θ\theta stays frozen, because the energy being sampled must not move under them. Only then does the network score the 128 data images and the 128 negatives, and Adam (β1=0\beta_1 = 0, learning rate 10−410^{-4}) takes a step on the surrogate loss. Finally the negatives go back into the buffer, pushing out the oldest entries.

The sampler is "Langevin" only in form. It uses a step of 1010 along a clipped energy gradient but noise with standard deviation 0.0050.005, which matches a temperature of about 10−610^{-6}. In effect it is gradient descent on the energy with a little jitter. New images take 256 such steps from noise.

Why energies drift

The surrogate loss has a blind spot. Add a constant bb to every energy, say through the bias of the last layer: both averages shift by bb, and the loss does not change. Nothing pins the overall energy level, and nothing stops the network from stretching the gap between data and negatives without end. Energies drift.

The common fix adds a small penalty on squared energies of both batches:

L=1N∑i=1N[Eθ(xi+)−Eθ(xi−)]+αN∑i=1N[Eθ(xi+)2+Eθ(xi−)2].\mathcal L = \frac{1}{N} \sum_{i=1}^{N} \big[E_\theta(x_i^+) - E_\theta(x_i^-)\big] + \frac{\alpha}{N} \sum_{i=1}^{N} \big[E_\theta(x_i^+)^2 + E_\theta(x_i^-)^2\big] .

The penalty is not part of the likelihood, so α\alpha stays small; Lippe's tutorial uses α=0.1\alpha = 0.1. Du and Mordatch also add spectral normalization.

Even so, EBM training diverges easily (Grathwohl et al., 2020). Chains get stuck in sharp local minima, the energy gap grows, and samples stop improving while the loss sits calmly near zero. Watch the samples, the buffer and the energy of pure noise instead. The usual remedies, roughly from cheapest: the penalty and spectral normalization, smooth activations such as Swish, no normalization layers, Adam with β1=0\beta_1 = 0, a smaller learning rate or more Langevin steps, and a restart from an earlier checkpoint.

There is no likelihood to watch either. Without ZθZ_\theta it cannot be computed, and annealed importance sampling (Neal, 2001) gives only loose estimates on images. Image EBMs are judged by their samples.

Noise-contrastive estimation

Noise-contrastive estimation (NCE; Gutmann and Hyvärinen, 2010) avoids sampling the model at all. It makes the missing normalizer one more parameter cc:

log⁡pm(x)=−Eθ(x)+c.\log p_m(x) = -E_\theta(x) + c .

Pick a noise distribution pnp_n that we can both sample and evaluate, for example a wide Gaussian. Mix data and noise in equal numbers and train a logistic classifier to tell them apart. Its logit is fixed to the log-ratio of the model and the noise:

Pr⁡(data∣x)=σ(log⁡pm(x)−log⁡pn(x)).\Pr(\text{data} \mid x) = \sigma\big(\log p_m(x) - \log p_n(x)\big).

The loss is ordinary binary cross-entropy. The best possible classifier is the Bayes one, with logit log⁡P(x)−log⁡pn(x)\log P(x) - \log p_n(x). So at the optimum pm=Pp_m = P, including its normalization, and cc learns −log⁡Zθ-\log Z_\theta. Gutmann and Hyvärinen prove that this optimum is unique and that the estimator is consistent.

A worked case. Data N(0,1)\mathcal N(0, 1), noise N(0,4)\mathcal N(0, 4) with standard deviation 22, energy E(x)=x2/2E(x) = x^2/2. The correct constant is c∗=−log⁡2π≈−0.919c^* = -\log\sqrt{2\pi} \approx -0.919. At x=0x = 0 the data density is 0.3990.399 and the noise density 0.1990.199, so with c∗c^* the classifier says "data" with probability 2/32/3, the true answer. With c=0c = 0 it says 0.8340.834: overconfident, and the cross-entropy gradient pushes cc down.

This looks like a GAN discriminator facing a generator that never trains. There is no minimax game, and the choice of noise is the main lever. A third route that never meets ZθZ_\theta, fitting only the gradient −∇xEθ-\nabla_x E_\theta, comes later in the course in the topic Score matching.

Your classifier is an EBM

Energies hide inside ordinary classifiers. A classifier with logits fθ(x)[y]f_\theta(x)[y] over the classes yy can be read as a joint EBM over pairs, with the logits as negative energies (Grathwohl et al., 2020, JEM):

pθ(x,y)=efθ(x)[y]Zθ.p_\theta(x, y) = \frac{e^{f_\theta(x)[y]}}{Z_\theta} .

Summing over yy gives a density of inputs alone, with the energy

Eθ(x)=−log⁡∑yefθ(x)[y].E_\theta(x) = -\log \sum_{y} e^{f_\theta(x)[y]} .

Divide the joint by this marginal and ZθZ_\theta cancels, leaving exactly the softmax: the classifier is unchanged. But the softmax ignores a common shift of all logits, and the energy does not. That spare degree of freedom is where JEM stores pθ(x)p_\theta(x). It trains with cross-entropy for pθ(y∣x)p_\theta(y \mid x) plus the EBM gradient with a replay buffer for pθ(x)p_\theta(x). On CIFAR-10 it keeps 92.9% accuracy, generates images and is better calibrated, at the cost of the sampling and the instability above.

Energies also compose. Adding two energies multiplies the densities, a product of experts: N(0,1)\mathcal N(0, 1) and N(2,1)\mathcal N(2, 1) give x2/2+(x−2)2/2=(x−1)2+1x^2/2 + (x - 2)^2/2 = (x - 1)^2 + 1, the energy of N(1,12)\mathcal N(1, \tfrac12), which keeps only what both experts agree on.

Here is the bill. Training needs model samples in its inner loop, and those samples are short, biased chains. Generation takes hundreds of gradient steps on a landscape with sharp minima and separated modes. Diffusion models keep the walk from noise to data but change what is learned. A fixed process destroys data with many small doses of Gaussian noise, and a network learns to undo one small step at a time. The next topic, DDPM: the forward process, builds that noising process.

Check your understanding

The same questions as in Pulse. Answers are shared between modes.

Full notes

Answers are saved on the server and tied to this browser until you sign in.