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 known only up to its normalizer: Langevin dynamics, MALA and HMC need nothing but . There the energy was given. Here it gets parameters and is learned from data.
Take any network with one scalar output and call it the energy. An energy-based model (EBM) turns it into a density:
Low energy means high density. The normalizer is called the partition function. For it equals , and is .
Nothing restricts . 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 . It is an integral over all of . Even a crude grid with 10 values per pixel on a image has nodes. What survives without it are comparisons. As in the previous topic, the normalizer cancels in a ratio of densities:
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:
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:
The integral became an expectation under the model itself. Put the two terms together:
The first term is the positive phase. A descent step along it lowers the energy of training points . The second is the negative phase. It raises the energy of the model's own samples . When the samples look like the data, the two pulls balance.
In code this is a surrogate loss, , where the samples 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 , , be the parameters themselves, and let the data visit the states with frequencies .
The partition function is a sum of three terms, , and the model probabilities are
Differentiating with respect to gives when and otherwise. So each phase turns into a probability:
State 1 gets . The model puts too much mass there, so the negative phase wins and a descent step raises . One step of size moves the model to , closer to the data on every state.
The negative phase needed the model probabilities, and that is where entered. With three states it is a sum of three terms. In it turns into a demand for samples.
Short chains and contrastive divergence
Every gradient step needs samples from the current . The samplers of Sampling unnormalized densities fit, because the score of an EBM does not involve : . Langevin dynamics with a step size reads
Each step costs one backward pass through 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-, Hinton, 2002) starts each chain at a training point and runs only 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 and the energy with one parameter ; the right answer is . Negatives come from Langevin steps with , started from the uniform distribution on , whose variance is . Since , training stops where the negatives have the same second moment as the data, variance . Where it stops:
| learned |
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 . 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 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 and from uniform noise otherwise, so fresh starting points keep arriving. In the toy model, steps with a buffer give instead of , and gives instead of .
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 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 (, learning rate ) 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 along a clipped energy gradient but noise with standard deviation , which matches a temperature of about . 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 to every energy, say through the bias of the last layer: both averages shift by , 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:
The penalty is not part of the likelihood, so stays small; Lippe's tutorial uses . 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 , a smaller learning rate or more Langevin steps, and a restart from an earlier checkpoint.
There is no likelihood to watch either. Without 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 :
Pick a noise distribution 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:
The loss is ordinary binary cross-entropy. The best possible classifier is the Bayes one, with logit . So at the optimum , including its normalization, and learns . Gutmann and Hyvärinen prove that this optimum is unique and that the estimator is consistent.
A worked case. Data , noise with standard deviation , energy . The correct constant is . At the data density is and the noise density , so with the classifier says "data" with probability , the true answer. With it says : overconfident, and the cross-entropy gradient pushes 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 , fitting only the gradient , comes later in the course in the topic Score matching.
Your classifier is an EBM
Energies hide inside ordinary classifiers. A classifier with logits over the classes can be read as a joint EBM over pairs, with the logits as negative energies (Grathwohl et al., 2020, JEM):
Summing over gives a density of inputs alone, with the energy
Divide the joint by this marginal and 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 . It trains with cross-entropy for plus the EBM gradient with a replay buffer for . 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: and give , the energy of , 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.
Answers are saved on the server and tied to this browser until you sign in.