Course contents 25 / 34

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.

On this page 14

Take a small convolutional network that reads a 28×2828 \times 28 image and outputs one number, Eθ(x)E_\theta(x), 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: e−Eθ(x)e^{-E_\theta(x)} 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 θ\theta. How do we fit a density whose likelihood we cannot evaluate?

An energy defines a density#

An energy-based model (EBM) is a network Eθ:Rd→RE_\theta: \mathbb R^d \to \mathbb R with parameters θ\theta together with the density

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

ZθZ_\theta is the partition function. Low energy means high probability. ZθZ_\theta must be finite: the energy grows fast enough at infinity, or the domain is bounded, as for pixels in [−1,1][-1, 1]. The energy E(x)=x2/2E(x) = x^2/2 gives Z=2πZ = \sqrt{2\pi} and p=N(0,1)p = \mathcal N(0, 1); 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:

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

Adding a constant cc to the energy multiplies ZθZ_\theta by e−ce^{-c} and leaves pθp_\theta unchanged. This freedom returns later as the offset problem.

Why not compute ZθZ_\theta? A grid with only 10 points per pixel of an MNIST image has 1078410^{784} nodes. Inference y^=arg⁡min⁡yEθ(x,y)\hat y = \arg\min_y E_\theta(x, y) 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 PP, which equals the KL divergence from the data to the model up to a constant (entropy note). Since log⁡pθ(x)=−Eθ(x)−log⁡Zθ\log p_\theta(x) = -E_\theta(x) - \log Z_\theta,

L(θ)=−Ex∼Plog⁡pθ(x)=Ex∼P Eθ(x)+log⁡Zθ.\begin{aligned} \mathcal L(\theta) &= -\mathbb E_{x \sim P} \log p_\theta(x) \\ &= \mathbb E_{x \sim P}\, E_\theta(x) + \log Z_\theta . \end{aligned}

The gradient of the first term averages ∇θEθ\nabla_\theta E_\theta over the data. The second term is the difficulty:

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

Line by line: the chain rule for the logarithm; differentiation under the integral sign, allowed when EθE_\theta is differentiable in θ\theta and the gradient of the integrand is bounded by an integrable function of xx; the chain rule for the exponential; the definition of pθp_\theta, with 1/Zθ1/Z_\theta moved inside; the definition of an expectation.

For a single data point this gives the gradient of the log-likelihood,

∇θlog⁡pθ(x)=−∇θEθ(x)+Ex′∼pθ ∇θEθ(x′),\nabla_\theta \log p_\theta(x) = -\nabla_\theta E_\theta(x) + \mathbb E_{x' \sim p_\theta}\, \nabla_\theta E_\theta(x') ,

and averaging over the data gives the gradient of the loss in two phases (Song and Kingma, 2021, Section 3):

∇θL(θ)=Ex+∼P ∇θEθ(x+)⏟positive phase−Ex−∼pθ ∇θEθ(x−)⏟negative phase.\begin{aligned} \nabla_\theta \mathcal L(\theta) = {}& \underbrace{\mathbb E_{x^+ \sim P}\, \nabla_\theta E_\theta(x^+)}_{\text{positive phase}} \\ &- \underbrace{\mathbb E_{x^- \sim p_\theta}\, \nabla_\theta E_\theta(x^-)}_{\text{negative phase}} . \end{aligned}

Data points x+x^+ are the positive examples, model samples x−x^- the negative ones. A step θ←θ−η ∇θL\theta \leftarrow \theta - \eta\, \nabla_\theta \mathcal L lowers the energy at the data and raises it where the model puts its mass, until the two averages of ∇θEθ\nabla_\theta E_\theta agree.

Worked example: three states. Let x∈{a,b,c}x \in \{a, b, c\} and let the energy be a table, θ=(Ea,Eb,Ec)=(0,1,2)\theta = (E_a, E_b, E_c) = (0, 1, 2), with data frequencies P=(0.5,0.3,0.2)P = (0.5, 0.3, 0.2). For a table, ∂Eθ(x)/∂Ej\partial E_\theta(x)/\partial E_j is 1 if x=jx = j and 0 otherwise, so the positive phase is P(j)P(j) and the negative phase is pθ(j)p_\theta(j):

Quantityaabbcc
model pθ=e−E/Zp_\theta = e^{-E}/Z, with Z=1.503Z = 1.5030.6650.6650.2450.2450.0900.090
gradient P(j)−pθ(j)P(j) - p_\theta(j)−0.165-0.1650.0550.0550.1100.110
energy after a step of size 10.1650.1650.9450.9451.8901.890
model after the step0.6110.6110.2800.2800.1090.109

The step raises EaE_a, where the model has too much mass, and the model moves towards PP; the fixed point is Ej=−log⁡P(j)+constE_j = -\log P(j) + \text{const}. 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 pθp_\theta, which changes after every update and has an unknown normalizer. Importance sampling would need a proposal close to pθp_\theta in 784 dimensions, as hard as the original problem. What remains is Markov chain Monte Carlo, which needs only the score:

∇xlog⁡pθ(x)=−∇xEθ(x)−∇xlog⁡Zθ⏟= 0.\nabla_x \log p_\theta(x) = -\nabla_x E_\theta(x) - \underbrace{\nabla_x \log Z_\theta}_{=\,0} .

Langevin dynamics, the Euler step of the MALA section without the accept test, is the usual choice for images:

xk+1=xk−ε2 ∇xEθ(xk)+ε zk,x_{k+1} = x_k - \frac{\varepsilon}{2}\, \nabla_x E_\theta(x_k) + \sqrt{\varepsilon}\, z_k ,

with fresh noise zk∼N(0,I)z_k \sim \mathcal N(0, I). Each step costs one input gradient of the network, a forward and a backward pass, and the distribution of xKx_K approaches pθp_\theta as ε→0\varepsilon \to 0 and K→∞K \to \infty (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-kk, Hinton, 2002) starts each chain at a data point, runs only kk steps of an MCMC kernel TT that leaves pθp_\theta invariant, and uses the endpoints as negative examples. Write P0=PP_0 = P for the data, P1P_1 for the distribution after one step and P∞=pθP_\infty = p_\theta for the equilibrium. CD-1 follows approximately the gradient of

DKL(P0 ∥ P∞)−DKL(P1 ∥ P∞).D_{\mathrm{KL}}(P_0 \,\|\, P_\infty) - D_{\mathrm{KL}}(P_1 \,\|\, P_\infty) .

Differentiating both divergences (below), the intractable averages over pθp_\theta cancel. What remains is EP0∇θEθ−EP1∇θEθ\mathbb E_{P_0} \nabla_\theta E_\theta - \mathbb E_{P_1} \nabla_\theta E_\theta, which needs only data and one-step samples, minus a term from the dependence of P1P_1 on θ\theta. 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 θ\theta through P∞=pθP_\infty = p_\theta, and the second also through P1P_1, because the kernel TT depends on θ\theta. 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 ∑xP1log⁡(P1/pθ)\sum_x P_1 \log(P_1/p_\theta) through P1P_1, where the extra ∑x∇θP1(x)\sum_x \nabla_\theta P_1(x) is zero because P1P_1 sums to one:

∇θDKL(P0 ∥ pθ)=EP0∇θEθ−Epθ∇θEθ,∇θDKL(P1 ∥ pθ)=EP1∇θEθ−Epθ∇θEθ+∑x∇θP1(x) log⁡P1(x)pθ(x).\begin{aligned} \nabla_\theta D_{\mathrm{KL}}(P_0 \,\|\, p_\theta) &= \mathbb E_{P_0} \nabla_\theta E_\theta - \mathbb E_{p_\theta} \nabla_\theta E_\theta , \\ \nabla_\theta D_{\mathrm{KL}}(P_1 \,\|\, p_\theta) &= \mathbb E_{P_1} \nabla_\theta E_\theta - \mathbb E_{p_\theta} \nabla_\theta E_\theta \\ &\quad + \textstyle\sum_x \nabla_\theta P_1(x)\, \log \dfrac{P_1(x)}{p_\theta(x)} . \end{aligned}

The difference is never negative: one step of a chain cannot move a distribution farther from its stationary distribution. Take the joint distributions P0(x0) T(x1∣x0)P_0(x_0)\,T(x_1 \mid x_0) and P∞(x0) T(x1∣x0)P_\infty(x_0)\,T(x_1 \mid x_0); their marginals of x1x_1 are P1P_1 and P∞P_\infty, since P∞P_\infty is stationary. The chain rule of the KL divergence splits their divergence in two ways:

DKLjoint=DKL(P0 ∥ P∞)+0=DKL(P1 ∥ P∞)+Ex1∼P1DKL(P0(⋅∣x1) ∥ P∞(⋅∣x1)).\begin{aligned} D_{\mathrm{KL}}^{\text{joint}} &= D_{\mathrm{KL}}(P_0 \,\|\, P_\infty) + 0 \\ &= D_{\mathrm{KL}}(P_1 \,\|\, P_\infty) \\ &\quad + \mathbb E_{x_1 \sim P_1} D_{\mathrm{KL}}\big(P_0(\cdot \mid x_1) \,\|\, P_\infty(\cdot \mid x_1)\big) . \end{aligned}

The first split conditions on x0x_0, where both conditionals are TT; in the second the last term is not negative. Hence DKL(P1 ∥ P∞)≤DKL(P0 ∥ P∞)D_{\mathrm{KL}}(P_1 \,\|\, P_\infty) \le D_{\mathrm{KL}}(P_0 \,\|\, P_\infty). When every transition has positive probability, equality holds only for P0=P∞P_0 = P_\infty, 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: P0(x0∣x1)=P∞(x0∣x1)P_0(x_0 \mid x_1) = P_\infty(x_0 \mid x_1) for every x1x_1 that P1P_1 reaches. When every transition has positive probability, write both sides by Bayes’ rule, P0(x0) T(x1∣x0)/P1(x1)=P∞(x0) T(x1∣x0)/P∞(x1)P_0(x_0)\, T(x_1 \mid x_0)/P_1(x_1) = P_\infty(x_0)\, T(x_1 \mid x_0)/P_\infty(x_1), and cancel TT. Then P0(x0)/P∞(x0)=P1(x1)/P∞(x1)P_0(x_0)/P_\infty(x_0) = P_1(x_1)/P_\infty(x_1) for all x0x_0 and x1x_1, 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 pθp_\theta, 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 N(0,1)\mathcal N(0, 1) and the energy Ev(x)=x2/(2v)E_v(x) = x^2/(2v), so that pv=N(0,v)p_v = \mathcal N(0, v) and the right answer is v=1v = 1. Since ∂Ev/∂v=−x2/(2v2)\partial E_v/\partial v = -x^2/(2v^2), the CD gradient is

∂LCD∂v=−12v2(E (x+)2−E (x−)2).\frac{\partial \mathcal L_{\text{CD}}}{\partial v} = -\frac{1}{2v^2}\Big(\mathbb E\,(x^+)^2 - \mathbb E\,(x^-)^2\Big) .

Training stops where E (x−)2=1\mathbb E\,(x^-)^2 = 1, the data’s second moment, whatever vv that takes. Let the negatives come from KK Langevin steps started at U(−3,3)U(-3, 3), whose variance is 3. Each step multiplies xx by a=1−ε/(2v)a = 1 - \varepsilon/(2v) and adds independent noise of variance ε\varepsilon, so after KK steps the variance is a geometric sum:

Var⁡x−=3 a2K+ε 1−a2K1−a2.\operatorname{Var} x^- = 3\,a^{2K} + \varepsilon\, \frac{1 - a^{2K}}{1 - a^2} .
Steps KKwhere CD stops, v∗v^*model standard deviation
100.0880.0880.300.30
1000.580.580.760.76
10000.9970.9970.9990.999

With ε=0.01\varepsilon = 0.01 and K=10K = 10 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 K=1000K = 1000 stops at 0.9970.997, 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.

Figure

Short chains learn the wrong density

Where CD stops as a function of chain lengthPanel A: K from 1 to 1000 on a log axis against the model variance. The red curve (restarted from noise) rises from 0.012 at K = 1 to 0.088 at K = 10 and 0.58 at K = 100 and approaches 1 by K = 1000; the blue curve (buffer) lies above it, 0.52 at K = 10. A dashed line marks the data variance 1. Panel B: a narrow red peak for the learned density, the wide thick data curve, a flat-topped red dashed curve for the 10-step samples and a blue curve for the buffer model.A · where CD stops00.511101001000Langevin steps per update, Kmodel variance v*data variance0.0880.52fresh noisebuffer 95% / 5%B · densities at K = 1000.51-202densitydata N(0, 1)model, fresh noiseits 10-step samplesmodel, bufferWhere CD stops as a function of chain lengthPanel A: K from 1 to 1000 on a log axis against the model variance. The red curve (restarted from noise) rises from 0.012 at K = 1 to 0.088 at K = 10 and 0.58 at K = 100 and approaches 1 by K = 1000; the blue curve (buffer) lies above it, 0.52 at K = 10. A dashed line marks the data variance 1. Panel B: a narrow red peak for the learned density, the wide thick data curve, a flat-topped red dashed curve for the 10-step samples and a blue curve for the buffer model.A · where CD stops00.511101001000Langevin steps per update, Kmodel variance v*data variance0.0880.52fresh noisebuffer 95% / 5%B · densities at K = 1000.51-202densitydata N(0, 1)model, fresh noiseits 10-step samplesmodel, buffer
Toy contrastive divergence: data N(0, 1), energy x²/(2v), negatives from K Langevin steps of size ε = 0.01 started at U(−3, 3). (A) The model variance v* where CD stops, against K, for chains restarted from noise (red) and a 95% / 5% replay buffer (blue). (B) At K = 10: the data, the learned N(0, 0.088), its 10-step samples and the buffer model.

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 KK 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 nn rounds of KK steps with probability 0.05⋅0.95 n−10.05 \cdot 0.95^{\,n-1}, 20 rounds on average. Averaging the variance formula above over these ages and solving E (x−)2=1\mathbb E\,(x^-)^2 = 1 for vv numerically (steps below), CD stops at v∗=0.52v^* = 0.52 for K=10K = 10 and at 0.940.94 for K=100K = 100, the blue curve in the figure; the fresh 5% keep some bias.

Derivation

With the model held at vv, a sample of age nn has run nKnK steps from the uniform start, so its variance is the formula above with KK replaced by nKnK, and the buffer is a mixture of these zero-mean distributions. Its second moment averages their variances over the ages; with r=a2Kr = a^{2K} the geometric series gives

E (x−)2=∑n≥10.05⋅0.95 n−1(3rn+ε 1−rn1−a2)=3S+ε 1−S1−a2,S=0.05 r1−0.95 r.\begin{aligned} \mathbb E\,(x^-)^2 &= \sum_{n \ge 1} 0.05 \cdot 0.95^{\,n-1} \Big(3 r^n + \varepsilon\, \frac{1 - r^n}{1 - a^2}\Big) \\ &= 3 S + \varepsilon\, \frac{1 - S}{1 - a^2} , \qquad S = \frac{0.05\, r}{1 - 0.95\, r} . \end{aligned}

One training step#

A small convolutional energy on MNIST (four stride-2 convolutions with Swish, two linear layers, 76,993 parameters, pixels in [−1,1][-1, 1]) puts the pieces together:

Figure

One EBM training step: buffer, Langevin chains, two phases

A training step of an energy-based modelThe buffer B and uniform noise merge into 128 starts x⁰ (95% and 5%); a Langevin block of 60 steps turns them into samples x⁻ using the gradient of the network E_θ. The network E_θ receives the data batch x⁺ and the samples x⁻; its outputs go into the loss, and an Adam step goes from the loss back to E_θ. A dashed path leads from x⁻ back to the buffer.buffer B8192 past samplesU(−1, 1)fresh noise95%5%x⁰128 startsLangevin60 stepsx⁻samples∇ₓEθ, θ fixedEθCNNx⁺data batch, 128positive phasenegative phaseE(x⁺), E(x⁻)L(θ)mean E(x⁺) − mean E(x⁻) + α · mean(E(x⁺)² + E(x⁻)²)Adam, β₁ = 0write back, drop the oldest12345A training step of an energy-based modelThe buffer B and uniform noise merge into 128 starts x⁰ (95% and 5%); a Langevin block of 60 steps turns them into samples x⁻ using the gradient of the network E_θ. The network E_θ receives the data batch x⁺ and the samples x⁻; its outputs go into the loss, and an Adam step goes from the loss back to E_θ. A dashed path leads from x⁻ back to the buffer.buffer B8192 past samplesU(−1, 1)fresh noise95%5%x⁰128 startsLangevin60 stepsx⁻samplesEθCNNx⁺data, 128E(x⁺), E(x⁻)L(θ)E(x⁺) − E(x⁻) + α(E(x⁺)² + E(x⁻)²)Adamwrite back12345
One training step with a replay buffer: chains start from the buffer or fresh noise (1), take 60 Langevin steps with θ fixed (2), the network scores data and samples (3), the loss updates θ (4), and the samples return to the buffer (5). Inputs are green, chain states blue, the network amber, samples red.
  1. 128 chains start from the buffer (up to 8192 images) with probability 0.95, or from uniform noise on [−1,1]784[-1, 1]^{784}.
  2. 60 Langevin steps with θ\theta fixed: noise of standard deviation 0.005, then a step of size 10 against the energy gradient clipped to ±0.03\pm 0.03 per component, pixels clamped to [−1,1][-1, 1].
  3. The network scores 128 data images x+x^+ and the 128 samples x−x^-.
  4. The loss, mean Eθ(x+)−mean Eθ(x−)\text{mean}\, E_\theta(x^+) - \text{mean}\, E_\theta(x^-) plus α=0.1\alpha = 0.1 times the mean squared energies (next section), takes an Adam step (β1=0\beta_1 = 0, learning rate 10−410^{-4}).
  5. 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 bb, every energy has derivative 1 in bb, so the two phases cancel and ∂LCD/∂b=1−1=0\partial \mathcal L_{\text{CD}}/\partial b = 1 - 1 = 0 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 Eθ(x−)−Eθ(x+)E_\theta(x^-) - E_\theta(x^+) 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 α\alpha of the mean squared energy of both batches:

L(θ)=1N∑i=1N[Eθ(xi+)−Eθ(xi−)]+αN∑i=1N[Eθ(xi+)2+Eθ(xi−)2].\begin{aligned} \mathcal L(\theta) = {}& \frac1N \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] . \end{aligned}

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 E+E^+ for all data and one energy E−E^- for all samples. Setting both derivatives of E+−E−+α((E+)2+(E−)2)E^+ - E^- + \alpha\big((E^+)^2 + (E^-)^2\big) to zero gives

1+2αE+=0,−1+2αE−=0,\begin{aligned} 1 + 2\alpha E^+ &= 0 , \\ -1 + 2\alpha E^- &= 0 , \end{aligned}

so E±=∓1/(2α)E^\pm = \mp 1/(2\alpha): ∓5\mp 5 for α=0.1\alpha = 0.1, a gap of 10, and ∓0.5\mp 0.5 for α=1\alpha = 1. Without the penalty the loss has no minimum. The penalty is not part of the likelihood, so α\alpha 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, x σ(x)x\,\sigma(x), 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 β1=0\beta_1 = 0, 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 ZθZ_\theta there is no likelihood to report. Annealed importance sampling (Neal, 2001) estimates Zθ/Z0Z_\theta/Z_0 by moving from a tractable p0p_0 to pθp_\theta through p0(x)1−βe−βEθ(x)p_0(x)^{1-\beta} e^{-\beta E_\theta(x)}, β\beta 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 cc, an estimate of −log⁡Zθ-\log Z_\theta:

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

Choose a noise distribution pnp_n 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:

h(x)=σ(log⁡pm(x)−log⁡pn(x)),J(θ,c)=12 Ex∼Plog⁡h(x)+12 Ey∼pnlog⁡(1−h(y)).\begin{aligned} h(x) &= \sigma\big(\log p_m(x) - \log p_n(x)\big) , \\ J(\theta, c) &= \tfrac12\, \mathbb E_{x \sim P} \log h(x) \\ &\quad + \tfrac12\, \mathbb E_{y \sim p_n} \log\big(1 - h(y)\big) . \end{aligned}

JJ 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 xx is data is p(x)/(p(x)+pn(x))=σ(log⁡p(x)−log⁡pn(x))p(x)/(p(x) + p_n(x)) = \sigma\big(\log p(x) - \log p_n(x)\big), where pp is the data density, so the best classifier of the constrained form has log⁡pm=log⁡p\log p_m = \log p, normalization included. Gutmann and Hyvärinen prove that this is the only maximum of JJ over log⁡pm\log p_m, provided pn>0p_n > 0 wherever p>0p > 0 (Theorem 1), and that the estimate is consistent (Theorem 2): if the model family contains the data density, the fitted e−Eθ+ce^{-E_\theta + c} integrates to one in the large-sample limit, without any constraint. Maximum likelihood cannot learn cc, since the likelihood grows without bound in it; in NCE a cc that is too large makes the classifier call noise “data” and pays for it.

Worked example. Data N(0,1)\mathcal N(0, 1), noise pn=N(0,4)p_n = \mathcal N(0, 4), and an energy with the right shape, E(x)=x2/2E(x) = x^2/2, so the only unknown is cc; the correct value is c∗=−log⁡2π=−0.919c^* = -\log\sqrt{2\pi} = -0.919. At x=0x = 0 the true probability of “data” is 0.399/(0.399+0.199)=0.6670.399/(0.399 + 0.199) = 0.667. With c∗c^* the classifier gives h(0)=σ(−0.919+1.612)=0.667h(0) = \sigma(-0.919 + 1.612) = 0.667, since log⁡pn(0)=−1.612\log p_n(0) = -1.612. The unnormalized model, c=0c = 0, gives h(0)=σ(1.612)=0.834h(0) = \sigma(1.612) = 0.834, too confident, so the loss lowers cc; maximizing JJ numerically returns −0.919-0.919.

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 pnp_n whose density is known, with its logit constrained to log⁡pm−log⁡pn\log p_m - \log p_n; 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, ∇xlog⁡pθ(x)=−∇xEθ(x)\nabla_x \log p_\theta(x) = -\nabla_x E_\theta(x), does not involve ZθZ_\theta. Fitting it to the data’s score by minimizing the Fisher divergence

12 Ex∼P∥∇xlog⁡p(x)+∇xEθ(x)∥2\tfrac12\, \mathbb E_{x \sim P} \big\|\nabla_x \log p(x) + \nabla_x E_\theta(x)\big\|^2

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 EP[12∥∇xEθ∥2−ΔxEθ]\mathbb E_P\big[\tfrac12\|\nabla_x E_\theta\|^2 - \Delta_x E_\theta\big] plus a constant, with Δx\Delta_x 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 Eθ(x)E_\theta(x) 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 CC classes outputs logits fθ(x)∈RCf_\theta(x) \in \mathbb R^C and probabilities pθ(y∣x)=softmax⁡(fθ(x))yp_\theta(y \mid x) = \operatorname{softmax}(f_\theta(x))_y. Grathwohl et al. (2020) read the same logits as the negative energy of the pair (x,y)(x, y):

pθ(x,y)=efθ(x)[y]Zθ,Eθ(x,y)=−fθ(x)[y].\begin{aligned} p_\theta(x, y) &= \frac{e^{f_\theta(x)[y]}}{Z_\theta} , \\ E_\theta(x, y) &= -f_\theta(x)[y] . \end{aligned}

Summing over yy gives a density of the input alone,

pθ(x)=1Zθ∑yefθ(x)[y],Eθ(x)=−logsumexp⁡yfθ(x)[y],\begin{aligned} p_\theta(x) &= \frac{1}{Z_\theta} \sum_y e^{f_\theta(x)[y]} , \\ E_\theta(x) &= -\operatorname{logsumexp}_y f_\theta(x)[y] , \end{aligned}

with the energy computed by the stable log-sum-exp. Dividing the joint by the marginal cancels ZθZ_\theta and returns the softmax, so the classifier is unchanged. A constant added to all logits of an input leaves the classifier alone but changes pθ(x)p_\theta(x); this freedom, unused by ordinary training, holds the density of a joint energy-based model (JEM).

Worked example. Logits (2,0,−1)(2, 0, -1) give class probabilities (0.844,0.114,0.042)(0.844, 0.114, 0.042) and E(x)=−logsumexp⁡=−2.170E(x) = -\operatorname{logsumexp} = -2.170. Logits (3,1,0)(3, 1, 0) give the same probabilities and E(x)=−3.170E(x) = -3.170. The classifier cannot tell the two inputs apart; under pθ(x)p_\theta(x) the second is e≈2.72e \approx 2.72 times more probable.

JEM trains with log⁡pθ(x,y)=log⁡pθ(x)+log⁡pθ(y∣x)\log p_\theta(x, y) = \log p_\theta(x) + \log p_\theta(y \mid x): 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:

EA+B(x)=EA(x)+EB(x),pA+B(x)∝e−EA(x) e−EB(x)∝pA(x) pB(x).\begin{aligned} E_{A+B}(x) &= E_A(x) + E_B(x) , \\ p_{A+B}(x) &\propto e^{-E_A(x)}\, e^{-E_B(x)} \propto p_A(x)\, p_B(x) . \end{aligned}

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, EA(x)=x2/2E_A(x) = x^2/2 is N(0,1)\mathcal N(0, 1) and EB(x)=(x−2)2/2E_B(x) = (x - 2)^2/2 is N(2,1)\mathcal N(2, 1); their sum is x2−2x+2=(x−1)2+1x^2 - 2x + 2 = (x - 1)^2 + 1, the energy of N(1,12)\mathcal N(1, \tfrac12), 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#

  • pθ=e−Eθ/Zθp_\theta = e^{-E_\theta}/Z_\theta: only energy differences matter, and ZθZ_\theta is intractable.
  • ∇θlog⁡pθ(x)=−∇θEθ(x)+Epθ∇θEθ\nabla_\theta \log p_\theta(x) = -\nabla_\theta E_\theta(x) + \mathbb E_{p_\theta}\nabla_\theta E_\theta: lower the energy at data, raise it at model samples.
  • Short Langevin chains bias the model towards an energy whose KK-step sampler matches the data.
  • A replay buffer (95% old samples, 5% noise) lengthens the chains for free; α mean(E2)\alpha\,\text{mean}(E^2) pins the energy level and caps the gap at about 1/α1/\alpha.
  • NCE learns EθE_\theta and log⁡Zθ\log Z_\theta by classifying data against noise; score matching fits −∇xEθ-\nabla_x E_\theta. Neither samples during training.
  • Any classifier is an EBM with E(x)=−logsumexp⁡yfθ(x)[y]E(x) = -\operatorname{logsumexp}_y f_\theta(x)[y]; 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 fθ=−Eθf_\theta = -E_\theta, 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 ±0.03\pm 0.03 and noise 0.005.
  • Training (cells 15–28): the loss above, Adam with betas (0,0.999)(0, 0.999), 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#