Type at least 2 letters. Enter opens the first result, Esc closes.

    Generative Models · Lesson 6 · Adversarial and energy-based models

    Energy-based models, score matching and Langevin dynamics

    Advanced 100 min 5 interactive figures 4 videos Colab notebook

    Before this lesson: lesson 01 (maximum likelihood as a KL divergence) and lesson 05 (critics that learn unnormalized density ratios). Gradient descent (optimization lesson 01). From the probability track: Gaussians, Markov chains and the Metropolis–Hastings algorithm. Stochastic differential equations (SDEs) and the Fokker–Planck equation are explained here as far as we need them; the ML for science track treats them in full. Time: about 100 minutes, plus the notebook.


    Why this matters #

    An energy-based model (EBM) is the most general way to write a density: no invertible layers (as in flows), no ordering of the variables (as in autoregressive models). The ideas of this lesson appear in many places:

    • Diffusion models learn the score of noisy data with denoising score matching, and sample with steps that look like Langevin dynamics. NCSN (Song and Ermon 2019) is annealed Langevin dynamics; predictor–corrector samplers add Langevin "corrector" steps.
    • Bayesian deep learning uses stochastic gradient Langevin dynamics (SGLD): SGD plus the right amount of noise samples a posterior over weights.
    • Physics and chemistry. The Boltzmann distribution p∝e−U/(kBT)p \propto e^{-U/(k_B T)} is an EBM with a known energy, and Langevin dynamics is Brownian dynamics. Slow crossing of energy barriers is the rare-event problem of molecular simulation.
    • Inverse problems. A posterior p(x∣y)∝p(y∣x) p(x)p(x \mid y) \propto p(y \mid x)\,p(x) is an EBM whose energy is the data misfit plus the prior energy. Its score is the sum of two scores, and the unknown p(y)p(y) drops out.

    1. Predict first #

    2. The picture #

    2.1 An energy is a landscape #

    An energy E(x)E(x) is a landscape over the data space. The model density is

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

    Valleys of EE are regions of high probability (modes). Hills are regions of low probability.

    • E(x)=x2/2E(x) = x^2/2 gives p(x)∝e−x2/2p(x) \propto e^{-x^2/2}: the standard normal N(0,1)\mathcal N(0, 1), with Z=2πZ = \sqrt{2\pi}.
    • With a parameter, Eθ(x)=θx2/2E_\theta(x) = \theta x^2/2 with θ>0\theta > 0 gives Zθ=2π/θZ_\theta = \sqrt{2\pi/\theta} and pθ=N(0,1/θ)p_\theta = \mathcal N(0, 1/\theta).
    • The double well E(x)=x4/4−x2E(x) = x^4/4 - x^2 has two valleys at x=±2x = \pm\sqrt 2 with E=−1E = -1, and a hill at x=0x = 0 with E=0E = 0. The density has two modes, and the barrier between them has height E(0)−E(±2)=1E(0) - E(\pm\sqrt2) = 1.

    Only differences of energy matter. Adding a constant cc to EE multiplies e−Ee^{-E} and ZZ by the same factor e−ce^{-c}, so pp does not change. The ratio p(x)/p(x′)=eE(x′)−E(x)p(x)/p(x') = e^{E(x') - E(x)} needs no ZZ.

    Langevin dynamics is noisy gradient descent. The update

    x←x−h ∇E(x)+2h ξ,ξ∼N(0,I),x \leftarrow x - h\,\nabla E(x) + \sqrt{2h}\,\xi, \qquad \xi \sim \mathcal N(0, I),

    is a gradient-descent step on the energy with step size hh, plus a random kick. Without the kick, xx falls into the nearest valley and stops: you get a mode, not a sample. With the kick of size 2h\sqrt{2h}, falling and kicking balance, and the points visit each region in proportion to e−Ee^{-E}. Picture a ball in the landscape that is shaken by heat.

    Interactive figure: loading…

    Press Play. 2000 particles start at x=2.5x = 2.5 and move with Langevin steps. The top chart compares the orange histogram of the particles with the exact blue density e−E/Ze^{-E}/Z. The bottom chart shows the energy and 80 of the particles on it. Then choose the Gaussian target and make hh large: with ULA (plain Langevin steps) the histogram is too wide, and the readout gives the theory 1/(1−h/2)1/(1 - h/2). Switch to MALA: the bias disappears, but fewer steps are accepted.

    The figure shows two facts that section 3 proves. First, the particles settle to the right density for small hh. Second, a finite step hh gives a slightly wrong density (a bias); a Metropolis–Hastings correction (MALA) removes it.

    2.2 Learning pushes the energy down at the data and up at model samples #

    How do we fit EθE_\theta to data? Maximum likelihood (as in lesson 01) makes log⁡pθ(x)\log p_\theta(x) large on the data. Section 3.2 shows that its gradient has two parts:

    • the positive phase lowers the energy at the data points;
    • the negative phase raises the energy at samples from the model.

    If the model puts probability where there are no data, its samples land there, and the negative phase raises the energy there. Learning stops when the two pushes balance: the model samples look like the data, as far as the features of EθE_\theta can tell.

    Interactive figure: loading…

    Press "1 update" a few times. The energy is Eθ(x)=θ1x4/4−θ2x2/2E_\theta(x) = \theta_1 x^4/4 - \theta_2 x^2/2, and the blue data come from two bumps. At the start (θ=(1,0)\theta = (1, 0)) the model has one bump at 0. The orange chain samples go there, and the arrows show that the update pushes the energy up where there are more chain samples and down where there are more data. Run 100 updates: a double well appears, the moments of data and chains become equal, and θ\theta reaches the exact maximum-likelihood value (dashed lines in the small chart).

    Quick check

    During maximum-likelihood training of an EBM, the model puts a lot of probability in a region with no data. What does the negative phase do there?

    2.3 The score field and many noise levels #

    The score of a density is the vector field s(x)=∇xlog⁡p(x)s(x) = \nabla_x \log p(x). It points in the direction where the density grows fastest. For an EBM, log⁡p=−E−log⁡Z\log p = -E - \log Z, and log⁡Z\log Z does not depend on xx, so

    s(x)=−∇xE(x).s(x) = -\nabla_x E(x) .

    So Langevin dynamics needs only the score: x←x+h s(x)+2h ξx \leftarrow x + h\,s(x) + \sqrt{2h}\,\xi. If we can learn the score directly (section 3.7), we never need ZZ or even an energy.

    Noise smooths the data. Let x=x0+σεx = x_0 + \sigma\varepsilon with x0x_0 from the data and ε∼N(0,I)\varepsilon \sim \mathcal N(0, I). The density pσp_\sigma of xx is the data density blurred with a Gaussian of width σ\sigma. For small σ\sigma it is close to the data. For large σ\sigma the modes merge into one wide bump.

    The figure uses the 8 Gaussians of this track: means μk=2(cos⁡2πk8,sin⁡2πk8)\mu_k = 2(\cos\frac{2\pi k}{8}, \sin\frac{2\pi k}{8}), standard deviation s=0.15s = 0.15. After noising, each component has variance s2+σ2s^2 + \sigma^2, so the score of pσp_\sigma is known in closed form. The arrows are the exact score, not a learned one.

    Interactive figure: loading…

    Move the σ slider. At small σ, each violet arrow points to the nearest blue mode; between modes the arrows are almost zero. At large σ, all arrows point to the centre. Now compare two runs from the same uniform start: Langevin at this σ (with σ small) and Annealed Langevin (σ goes from 3 down to 0.05). Mode 1 has weight 0.4 and the others 0.086. The bar chart shows the fraction of particles near each mode: at fixed small σ every mode gets about 1/8; the annealed run gets close to 0.4 for mode 1.

    The figure shows the two problems of a single noise level, and the fix:

    1. The score does not see the mixture weights. Near a mode, the score points to that mode, whatever its weight. Particles go to the closest mode and stay there.
    2. Particles do not cross between modes. At small σ the region between modes has almost no probability, and Langevin needs an exponentially long time to cross it (section 3.9).
    3. The fix: start with large noise. At large σ the modes overlap, particles move freely, and they split according to the weights. As σ shrinks, each particle stays in the mode it chose.
    Quick check

    The target is p=0.9 N(−4,0.52)+0.1 N(4,0.52)p = 0.9\,\mathcal N(-4, 0.5^2) + 0.1\,\mathcal N(4, 0.5^2). What is the score at x=3.5x = 3.5, to two decimals?

    3. Definitions and main results #

    3.1 Energy-based models #

    An energy-based model is a density of the form

    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 ,

    where Eθ:Rd→RE_\theta: \R^d \to \R is any function with parameters θ\theta (often a neural network). The partition function (normalizing constant) ZθZ_\theta must be finite: EθE_\theta must grow fast enough as ∥x∥→∞\|x\| \to \infty, or xx must live in a bounded set. For Eθ(x)=θx2/2E_\theta(x) = \theta x^2/2 this needs θ>0\theta > 0.

    In high dimension, ZθZ_\theta is an integral that we cannot compute. So log⁡pθ(x)\log p_\theta(x) is known only up to the unknown constant log⁡Zθ\log Z_\theta. We can compare two points (pθ(x)/pθ(x′)p_\theta(x)/p_\theta(x')), but we cannot evaluate the likelihood itself.

    3.2 The gradient of the log-likelihood #

    Theorem (EBM log-likelihood gradient). For one data point,

    ∇θ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}\big[\nabla_\theta E_\theta(x')\big].

    For the average log-likelihood L(θ)=Ex∼pdata[log⁡pθ(x)]L(\theta) = \mathbb E_{x \sim p_{\text{data}}}[\log p_\theta(x)]:

    ∇θL(θ)=− Ex∼pdata[∇θEθ(x)]⏟positive phase  +  Ex′∼pθ[∇θEθ(x′)]⏟negative phase.\nabla_\theta L(\theta) = \underbrace{-\,\mathbb E_{x \sim p_{\text{data}}}[\nabla_\theta E_\theta(x)]}_{\text{positive phase}} \;+\; \underbrace{\mathbb E_{x' \sim p_\theta}[\nabla_\theta E_\theta(x')]}_{\text{negative phase}} .

    Proof.

    1. Take the log: log⁡pθ(x)=−Eθ(x)−log⁡Zθ\log p_\theta(x) = -E_\theta(x) - \log Z_\theta.
    2. Differentiate log⁡Zθ\log Z_\theta. Use ∇θlog⁡Z=∇θZ/Z\nabla_\theta \log Z = \nabla_\theta Z / Z and move the gradient inside the integral (this needs a mild regularity condition, as for dominated convergence):
    ∇θlog⁡Zθ=1Zθ∫(−∇θEθ(x′)) e−Eθ(x′) dx′=−∫∇θEθ(x′) pθ(x′) dx′=−Epθ[∇θEθ].\nabla_\theta \log Z_\theta = \frac{1}{Z_\theta}\int \big(-\nabla_\theta E_\theta(x')\big)\,e^{-E_\theta(x')}\,dx' = -\int \nabla_\theta E_\theta(x')\,p_\theta(x')\,dx' = -\mathbb E_{p_\theta}[\nabla_\theta E_\theta].
    1. Combine steps 1 and 2 for one xx, then average over the data. ■\blacksquare

    Reading the result. Gradient ascent on LL moves θ\theta in the direction of −∇θEθ-\nabla_\theta E_\theta at the data, which lowers the energy there, and of +∇θEθ+\nabla_\theta E_\theta at model samples, which raises the energy there. The gradient is zero when

    Epdata[∇θEθ]=Epθ[∇θEθ].\mathbb E_{p_{\text{data}}}[\nabla_\theta E_\theta] = \mathbb E_{p_\theta}[\nabla_\theta E_\theta] .

    Exponential families. If the energy is linear in θ\theta, Eθ(x)=θ⊤ϕ(x)E_\theta(x) = \theta^\top \phi(x) with fixed features ϕ\phi, then ∇θEθ=ϕ(x)\nabla_\theta E_\theta = \phi(x) and the condition is moment matching: Edata[ϕ]=Epθ[ϕ]\mathbb E_{\text{data}}[\phi] = \mathbb E_{p_\theta}[\phi]. The Hessian of log⁡Zθ\log Z_\theta is Cov⁡pθ[ϕ]⪰0\operatorname{Cov}_{p_\theta}[\phi] \succeq 0, so LL is concave and the optimum is unique when the covariance is positive definite. The widget of section 2.2 is this case with ϕ(x)=(x4/4,−x2/2)\phi(x) = (x^4/4, -x^2/2): at the end, x2‾\overline{x^2} and x4‾\overline{x^4} of the chains equal those of the data.

    In code. Draw model samples x~1,…,x~M\tilde x_1, \dots, \tilde x_M with an MCMC sampler and detach them from the computation graph. Then minimize the surrogate loss

    ℓ(θ)=1N∑i=1NEθ(xi)−1M∑j=1MEθ(x~j).\ell(\theta) = \frac1N \sum_{i=1}^N E_\theta(x_i) - \frac1M \sum_{j=1}^M E_\theta(\tilde x_j) .

    Its gradient is a Monte Carlo estimate of −∇θL-\nabla_\theta L. The value of ℓ\ell is not a log-likelihood; only its gradient matters.

    3.3 Langevin dynamics #

    To get model samples, we need a sampler that uses only ∇E\nabla E. A stochastic differential equation (SDE) dXt=b(Xt) dt+2 dWtdX_t = b(X_t)\,dt + \sqrt 2\,dW_t describes a point that moves with velocity bb and is kicked by Brownian motion WtW_t: over a time hh, the kick Wt+h−WtW_{t+h} - W_t is N(0,h I)\mathcal N(0, h\,I) and independent of the past. The simplest way to simulate it is the Euler–Maruyama step:

    Xk+1=Xk+h b(Xk)+2h ξk,ξk∼N(0,I).X_{k+1} = X_k + h\,b(X_k) + \sqrt{2h}\,\xi_k, \qquad \xi_k \sim \mathcal N(0, I).

    The noise scales with h\sqrt h, not hh: the variance of a sum of independent kicks grows linearly with time.

    The (overdamped) Langevin SDE for a target pp uses b=∇log⁡pb = \nabla \log p:

    dXt=∇log⁡p(Xt) dt+2 dWt=−∇E(Xt) dt+2 dWt.dX_t = \nabla \log p(X_t)\,dt + \sqrt 2\,dW_t = -\nabla E(X_t)\,dt + \sqrt 2\,dW_t .

    Theorem (stationarity). If X0∼pX_0 \sim p, then Xt∼pX_t \sim p for all tt: pp is a stationary density of the Langevin SDE. Moreover, if ρt\rho_t is the density of XtX_t, then KL(ρt ∥ p)\mathrm{KL}(\rho_t \,\|\, p) never increases.

    Why this is true (intuition). The density of XtX_t changes for two reasons: the drift moves probability uphill toward the modes, and the noise spreads it out (diffusion). At ρ=p\rho = p the two flows of probability cancel exactly at every point.

    The Fokker–Planck argument
    1. For dX=b dt+2 dWdX = b\,dt + \sqrt 2\,dW, the density ρt\rho_t of XtX_t solves the Fokker–Planck equation ∂tρ=−∇⋅(ρ b)+Δρ\partial_t \rho = -\nabla\cdot(\rho\, b) + \Delta\rho. The first term moves probability with velocity bb; the second term (the Laplacian Δ=∇⋅∇\Delta = \nabla\cdot\nabla) spreads it like heat.
    2. Write Δρ=∇⋅(∇ρ)=∇⋅(ρ ∇log⁡ρ)\Delta\rho = \nabla\cdot(\nabla\rho) = \nabla\cdot(\rho\,\nabla\log\rho), because ∇ρ=ρ ∇log⁡ρ\nabla \rho = \rho\,\nabla\log\rho. With b=∇log⁡pb = \nabla\log p:
    ∂tρ=∇⋅(ρ ∇log⁡ρ−ρ ∇log⁡p)=∇⋅(ρ ∇log⁡ρp).\partial_t\rho = \nabla\cdot\big(\rho\,\nabla\log\rho - \rho\,\nabla\log p\big) = \nabla\cdot\Big(\rho\,\nabla\log\frac{\rho}{p}\Big).
    1. At ρ=p\rho = p the term log⁡(ρ/p)\log(\rho/p) is 0, so ∂tρ=0\partial_t\rho = 0: pp is stationary.
    2. ddtKL(ρt ∥ p)=∫∂tρ (log⁡ρp+1) dx\frac{d}{dt}\mathrm{KL}(\rho_t\,\|\,p) = \int \partial_t\rho\,\big(\log\frac{\rho}{p} + 1\big)\,dx. The "+1+1" part integrates to 0, because the total mass stays 1. Insert step 2 and integrate by parts (the boundary terms vanish when ρ\rho decays fast):
    ddtKL(ρt ∥ p)=−∫ρ ∥∇log⁡ρp∥2dx≤0,\frac{d}{dt}\mathrm{KL}(\rho_t\,\|\,p) = -\int \rho\,\Big\|\nabla\log\frac{\rho}{p}\Big\|^2 dx \le 0,

    with equality only when ρ∝p\rho \propto p, that is, ρ=p\rho = p. ■\blacksquare

    Only ∇log⁡p\nabla \log p appears, so the dynamics never need ZZ. The theorem says nothing about speed. For a target with separated modes, the KL can decrease very slowly (section 3.9).

    3.4 ULA is biased; MALA removes the bias #

    The unadjusted Langevin algorithm (ULA) is the Euler–Maruyama step of the Langevin SDE with a fixed step hh:

    xk+1=xk+h ∇log⁡p(xk)+2h ξk.x_{k+1} = x_k + h\,\nabla\log p(x_k) + \sqrt{2h}\,\xi_k .

    The continuous SDE has stationary density pp. The discrete chain does not: it has an error of order hh. A Gaussian target shows this exactly.

    Theorem (ULA bias for a Gaussian). For the target N(μ,σ2)\mathcal N(\mu, \sigma^2) in 1D, ULA is stable for 0<h<2σ20 < h < 2\sigma^2, its stationary distribution is Gaussian with mean μ\mu, and its stationary variance is

    v=σ21−h/(2σ2)>σ2.v = \frac{\sigma^2}{1 - h/(2\sigma^2)} > \sigma^2 .

    Proof.

    1. The score is ∇log⁡p(x)=−(x−μ)/σ2\nabla\log p(x) = -(x - \mu)/\sigma^2. So xk+1−μ=a (xk−μ)+2h ξkx_{k+1} - \mu = a\,(x_k - \mu) + \sqrt{2h}\,\xi_k with a=1−h/σ2a = 1 - h/\sigma^2.
    2. This is a linear (AR(1)) chain. It forgets its start when ∣a∣<1|a| < 1, that is, 0<h<2σ20 < h < 2\sigma^2.
    3. Taking means: E[xk+1]−μ=a (E[xk]−μ)→0\mathbb E[x_{k+1}] - \mu = a\,(\mathbb E[x_k] - \mu) \to 0. No bias in the mean.
    4. Taking variances, with ξk\xi_k independent of xkx_k: vk+1=a2vk+2hv_{k+1} = a^2 v_k + 2h. At the fixed point, v=a2v+2hv = a^2 v + 2h, so
    v=2h1−a2=2h(2h/σ2)−(h/σ2)2=σ21−h/(2σ2).■v = \frac{2h}{1 - a^2} = \frac{2h}{(2h/\sigma^2) - (h/\sigma^2)^2} = \frac{\sigma^2}{1 - h/(2\sigma^2)} . \qquad \blacksquare

    For N(0,1)\mathcal N(0, 1) and h=0.1h = 0.1: v=1/0.95=1.0526v = 1/0.95 = 1.0526, about 5% too large. The bias is ≈h/(2σ2)\approx h/(2\sigma^2) for small hh. A smaller hh reduces the bias but makes the chain slower: a=1−h/σ2a = 1 - h/\sigma^2 is close to 1, so successive samples are strongly correlated.

    Several dimensions and conditioning

    For a target N(μ,Σ)\mathcal N(\mu, \Sigma), the same computation holds in each eigendirection of Σ\Sigma, with σ2\sigma^2 replaced by the eigenvalue λi\lambda_i. Stability needs h<2λmin⁡h < 2\lambda_{\min}, the bias is largest in the narrowest direction, and the widest direction needs about λmax⁡/h\lambda_{\max}/h steps to mix. So the cost grows with the condition number λmax⁡/λmin⁡\lambda_{\max}/\lambda_{\min}, as for gradient descent (optimization lesson 02). Example: Σ=diag⁡(1.75,0.25)\Sigma = \operatorname{diag}(1.75, 0.25) and h=0.1h = 0.1 give ULA variances 1.80151.8015 (+2.9%) and 0.31250.3125 (+25%); stability needs h<0.5h < 0.5; the wide direction has a=0.943a = 0.943.

    MALA. The Metropolis-adjusted Langevin algorithm uses the ULA step as a proposal, q(x′∣x)=N(x′; x+h∇log⁡p(x), 2h I)q(x' \mid x) = \mathcal N\big(x';\ x + h\nabla\log p(x),\ 2h\,I\big), and accepts x′x' with probability

    α(x,x′)=min⁡{1, p(x′) q(x∣x′)p(x) q(x′∣x)}.\alpha(x, x') = \min\Big\{1,\ \frac{p(x')\,q(x \mid x')}{p(x)\,q(x' \mid x)}\Big\}.

    If it rejects, the chain stays at xx. This is the Metropolis–Hastings rule, so detailed balance makes pp exactly stationary for every hh: the bias is gone. Three facts:

    • p(x′)/p(x)=eE(x)−E(x′)p(x')/p(x) = e^{E(x) - E(x')}: ZZ cancels.
    • MALA needs the energy EE itself, not only its gradient. A network that outputs only a score gives no acceptance ratio.
    • Large steps are often rejected, so the chain moves less. In high dimension, hh must shrink like d−1/3d^{-1/3} to keep a good acceptance rate (Roberts and Rosenthal 1998).
    Quick check

    ULA on the target N(0,4)\mathcal N(0, 4) with step h=1h = 1. What is the stationary variance of the chain?

    3.5 Contrastive divergence and persistent chains #

    The negative phase needs samples from pθp_\theta, and θ\theta changes at every update. Running a chain to equilibrium after each update is too expensive. Two approximations are common.

    • Contrastive divergence (CD-kk) (Hinton 2002): start the chains at the data batch, run kk MCMC steps (often k=1k = 1), and use the end points as negative samples. It is cheap but biased: after kk steps the chains are still close to the data, not distributed as pθp_\theta. Low-energy regions far from the data (spurious modes) are never visited, so they are never corrected. In general, CD-kk is not the gradient of any objective.
    • Persistent CD (PCD; Tieleman 2008): keep the chains from one update to the next instead of restarting them at the data. θ\theta changes slowly, so the chains stay close to the current pθp_\theta and the bias is smaller. The widget of section 2.2 uses persistent chains.
    • Deep EBMs (Du and Mordatch 2019) run tens of Langevin steps per update, started from a replay buffer of earlier samples (about 95%) or from fresh noise (about 5%), and add a small penalty on the size of the energies. In practice the step size and the noise scale are often tuned separately, with much less noise than 2h\sqrt{2h}. The chains are then close to noisy gradient descent, and the samples are not exact samples of pθp_\theta.

    Two methods avoid negative samples altogether: score matching (section 3.7), and noise-contrastive estimation, which trains a logistic classifier to separate data from a known noise distribution and learns log⁡Z\log Z as one more parameter.

    3.6 The score needs no partition function #

    Definition. The score of a density pp on Rd\R^d is s(x)=∇xlog⁡p(x)s(x) = \nabla_x \log p(x), a vector field. (Do not confuse it with the score-function estimator of lesson 02, which uses ∇ϕlog⁡qϕ\nabla_\phi \log q_\phi, the gradient with respect to parameters.)

    For an EBM, log⁡pθ(x)=−Eθ(x)−log⁡Zθ\log p_\theta(x) = -E_\theta(x) - \log Z_\theta, and log⁡Zθ\log Z_\theta does not depend on xx:

    ∇xlog⁡pθ(x)=−∇xEθ(x).\nabla_x \log p_\theta(x) = -\nabla_x E_\theta(x) .

    More generally, if p=p~/Zp = \tilde p / Z for any unnormalized p~\tilde p, then ∇xlog⁡p=∇xlog⁡p~\nabla_x \log p = \nabla_x \log \tilde p. Examples: the score of N(μ,σ2I)\mathcal N(\mu, \sigma^2 I) is −(x−μ)/σ2-(x - \mu)/\sigma^2; the score of a mixture ∑kπkpk\sum_k \pi_k p_k is ∑kwk(x) ∇log⁡pk(x)\sum_k w_k(x)\,\nabla\log p_k(x), where wk(x)=πkpk(x)/p(x)w_k(x) = \pi_k p_k(x)/p(x) are the responsibilities (compute them with log-sum-exp).

    So a score model sθ(x)≈∇xlog⁡p(x)s_\theta(x) \approx \nabla_x \log p(x) can be trained and used for Langevin sampling without ever touching ZZ, or even an energy.

    Quick check

    pθ=e−Eθ/Zθp_\theta = e^{-E_\theta}/Z_\theta and ZθZ_\theta is unknown. Which quantity can you NOT compute exactly?

    3.7 Score matching #

    We want sθ≈∇log⁡ps_\theta \approx \nabla \log p from samples of pp. In this lesson every score-matching loss has the factor 12\tfrac12 (as in Hyvärinen 2005 and Vincent 2011); the minimizers do not depend on this choice.

    Explicit score matching (ESM) minimizes the Fisher divergence

    JESM(θ)=12 Ex∼p ∥sθ(x)−∇log⁡p(x)∥2.J_{\text{ESM}}(\theta) = \tfrac12\,\mathbb E_{x \sim p}\,\big\|s_\theta(x) - \nabla\log p(x)\big\|^2 .

    We cannot compute it: the target ∇log⁡p\nabla\log p is unknown. Two tricks remove the target.

    Implicit score matching (Hyvärinen 2005). Integration by parts gives

    JESM(θ)=Ex∼p[tr⁡(∇xsθ(x))+12 ∥sθ(x)∥2]+C,J_{\text{ESM}}(\theta) = \mathbb E_{x \sim p}\Big[\operatorname{tr}\big(\nabla_x s_\theta(x)\big) + \tfrac12\,\|s_\theta(x)\|^2\Big] + C,

    where C=12E∥∇log⁡p∥2C = \tfrac12\mathbb E\|\nabla \log p\|^2 does not depend on θ\theta. Proof in 1D: expand the square; the cross term is E[sθ (log⁡p)′]=∫sθ p′ dx=−∫sθ′ p dx=−E[sθ′]\mathbb E[s_\theta\,(\log p)'] = \int s_\theta\,p'\,dx = -\int s_\theta'\,p\,dx = -\mathbb E[s_\theta'], when sθp→0s_\theta p \to 0 at ±∞\pm\infty. In dd dimensions, do this for each coordinate. The loss needs only samples of pp. But the trace of the Jacobian ∇xsθ\nabla_x s_\theta costs dd backward passes, which is too slow for images.

    Sliced score matching

    Sliced score matching (Song, Garg, Shi and Ermon 2019) replaces the trace by a random projection: tr⁡(J)=Ev[v⊤Jv]\operatorname{tr}(J) = \mathbb E_v[v^\top J v] for a random vv with E[vv⊤]=I\mathbb E[vv^\top] = I, the same idea as Hutchinson's estimator in lesson 04. The loss EvEx[v⊤∇xsθ(x) v+12∥sθ(x)∥2]\mathbb E_v \mathbb E_{x}\big[v^\top \nabla_x s_\theta(x)\, v + \tfrac12 \|s_\theta(x)\|^2\big] needs one Jacobian-vector product per vv, not dd backward passes.

    Denoising score matching (Vincent 2011). Add Gaussian noise: x=x0+σεx = x_0 + \sigma\varepsilon, with x0∼pdatax_0 \sim p_{\text{data}} and ε∼N(0,I)\varepsilon \sim \mathcal N(0, I). The noising kernel is q(x∣x0)=N(x; x0, σ2I)q(x \mid x_0) = \mathcal N(x;\ x_0,\ \sigma^2 I), and its score is known:

    ∇xlog⁡q(x∣x0)=−x−x0σ2=−εσ.\nabla_x \log q(x \mid x_0) = -\frac{x - x_0}{\sigma^2} = -\frac{\varepsilon}{\sigma} .

    The DSM loss regresses the model on this known target:

    JDSM(θ)=12 Ex0, ε ∥sθ(x0+σε)+εσ∥2.J_{\text{DSM}}(\theta) = \tfrac12\,\mathbb E_{x_0,\ \varepsilon}\,\Big\|s_\theta(x_0 + \sigma\varepsilon) + \frac{\varepsilon}{\sigma}\Big\|^2 .

    The noisy point xx has the density pσ(x)=∫pdata(x0) q(x∣x0) dx0p_\sigma(x) = \int p_{\text{data}}(x_0)\,q(x \mid x_0)\,dx_0, the data density blurred with N(0,σ2I)\mathcal N(0, \sigma^2 I).

    Theorem (DSM = ESM + constant). Assume E∥sθ(x)∥2<∞\mathbb E\|s_\theta(x)\|^2 < \infty for x∼pσx \sim p_\sigma. Then

    JDSM(θ)=12 Ex∼pσ∥sθ(x)−∇log⁡pσ(x)∥2+C,J_{\text{DSM}}(\theta) = \tfrac12\,\mathbb E_{x \sim p_\sigma}\big\|s_\theta(x) - \nabla\log p_\sigma(x)\big\|^2 + C,

    where CC does not depend on θ\theta. So DSM trains sθs_\theta toward the score of the noisy density pσp_\sigma, not of the clean data.

    Why this is true (intuition). One noisy point xx can come from many clean points x0x_0. Each of them gives a different target −ε/σ=(x0−x)/σ2-\varepsilon/\sigma = (x_0 - x)/\sigma^2. A least-squares regression learns the average target at each xx. That average is exactly the score of pσp_\sigma (step 3 below).

    Proof.

    1. Expand both squared norms with ∥s−y∥2=∥s∥2−2⟨s,y⟩+∥y∥2\|s - y\|^2 = \|s\|^2 - 2\langle s, y\rangle + \|y\|^2.
    2. The terms 12E∥sθ(x)∥2\tfrac12\mathbb E\|s_\theta(x)\|^2 are the same in both losses, because in both xx has the density pσp_\sigma.
    3. Key identity. Differentiate pσ(x)=∫pdata(x0) q(x∣x0) dx0p_\sigma(x) = \int p_{\text{data}}(x_0)\,q(x \mid x_0)\,dx_0 under the integral and use ∇q=q ∇log⁡q\nabla q = q\,\nabla\log q:
    ∇pσ(x)=∫pdata(x0) q(x∣x0) ∇xlog⁡q(x∣x0) dx0.\nabla p_\sigma(x) = \int p_{\text{data}}(x_0)\,q(x \mid x_0)\,\nabla_x\log q(x \mid x_0)\,dx_0 .

    Divide by pσ(x)p_\sigma(x). The factor pdata(x0) q(x∣x0)/pσ(x)p_{\text{data}}(x_0)\,q(x \mid x_0)/p_\sigma(x) is the posterior p(x0∣x)p(x_0 \mid x), so

    ∇log⁡pσ(x)=E[∇xlog⁡q(x∣x0) ∣ x]=E[−εσ ∣ x].\nabla\log p_\sigma(x) = \mathbb E\big[\nabla_x\log q(x \mid x_0)\,\big|\,x\big] = \mathbb E\Big[-\frac{\varepsilon}{\sigma}\,\Big|\,x\Big].

    The marginal score is the posterior mean of the conditional score. 4. The cross terms are equal. By step 3 and the tower property, E⟨sθ(x),∇log⁡pσ(x)⟩=E⟨sθ(x),E[−ε/σ∣x]⟩=E⟨sθ(x),−ε/σ⟩\mathbb E\langle s_\theta(x), \nabla\log p_\sigma(x)\rangle = \mathbb E\big\langle s_\theta(x), \mathbb E[-\varepsilon/\sigma \mid x]\big\rangle = \mathbb E\langle s_\theta(x), -\varepsilon/\sigma\rangle. 5. The remaining terms do not contain θ\theta. So C=12(E∥ε/σ∥2−E∥∇log⁡pσ(x)∥2)=12(d/σ2−E∥∇log⁡pσ(x)∥2)C = \tfrac12\big(\mathbb E\|\varepsilon/\sigma\|^2 - \mathbb E\|\nabla\log p_\sigma(x)\|^2\big) = \tfrac12\big(d/\sigma^2 - \mathbb E\|\nabla\log p_\sigma(x)\|^2\big). ■\blacksquare

    Consequences.

    • Over all functions, the minimizer is the conditional mean of the target: s∗(x)=E[−ε/σ∣x]=∇log⁡pσ(x)s^*(x) = \mathbb E[-\varepsilon/\sigma \mid x] = \nabla\log p_\sigma(x). This is the general rule "the best least-squares prediction is the conditional mean".
    • The loss does not go to 0. Its minimum is C=12E ∥ε/σ−E[ε/σ∣x]∥2≥0C = \tfrac12\mathbb E\,\|\varepsilon/\sigma - \mathbb E[\varepsilon/\sigma \mid x]\|^2 \ge 0, the conditional variance of the target. No function of xx can predict the part of the noise that xx does not reveal. Do not judge a score model by how close its loss is to 0.
    • Noise prediction. Multiply the loss by σ2\sigma^2: σ2∥sθ+ε/σ∥2=∥σsθ+ε∥2\sigma^2\|s_\theta + \varepsilon/\sigma\|^2 = \|\sigma s_\theta + \varepsilon\|^2. So a network ε^θ(x)\hat\varepsilon_\theta(x) that predicts the added noise gives the score sθ=−ε^θ/σs_\theta = -\hat\varepsilon_\theta/\sigma. The DDPM loss of lesson 07 is this loss over many noise levels.
    Interactive figure: loading…

    Add samples. Each aqua dot is one noisy point x=x0+σεx = x_0 + \sigma\varepsilon with its DSM target −ε/σ-\varepsilon/\sigma. The targets are very noisy, but their average in each small bin settles on the exact score of pσp_\sigma. The last readout shows that even the exact score has a positive DSM loss, equal to the constant CC. Make σ small: the targets spread more (their standard deviation is 1/σ1/\sigma), and you need more samples.

    Quick check

    A clean point x0=1x_0 = 1 is noised with σ=0.5\sigma = 0.5 and ε=−0.4\varepsilon = -0.4, so x=0.8x = 0.8. What is the DSM regression target for sθ(0.8)s_\theta(0.8)?

    3.8 Tweedie's formula #

    The DSM optimum also gives a denoiser. From x0=x−σεx_0 = x - \sigma\varepsilon and step 3 of the proof:

    E[x0∣x]=x−σ E[ε∣x]=x+σ2 ∇log⁡pσ(x).\mathbb E[x_0 \mid x] = x - \sigma\,\mathbb E[\varepsilon \mid x] = x + \sigma^2\,\nabla\log p_\sigma(x) .

    This is Tweedie's formula (Robbins 1956, Efron 2011). The score at a noisy point, times σ2\sigma^2, is the step back to the average clean point. So "learn the score of pσp_\sigma" and "learn the best denoiser at noise level σ\sigma" are the same task. The same formula gives the posterior covariance: Cov⁡[x0∣x]=σ2(I+σ2∇2log⁡pσ(x))\operatorname{Cov}[x_0 \mid x] = \sigma^2\big(I + \sigma^2\nabla^2\log p_\sigma(x)\big).

    Check with a Gaussian. Data N(m,s2)\mathcal N(m, s^2) in 1D. Then pσ=N(m,s2+σ2)p_\sigma = \mathcal N(m, s^2 + \sigma^2) and Tweedie gives E[x0∣x]=x−σ2(x−m)/(s2+σ2)=(s2x+σ2m)/(s2+σ2)\mathbb E[x_0 \mid x] = x - \sigma^2 (x - m)/(s^2 + \sigma^2) = (s^2 x + \sigma^2 m)/(s^2 + \sigma^2). This is the posterior mean from Gaussian conditioning: a weighted average of the observation and the prior mean.

    3.9 Two problems of a single score, and many noise levels #

    A score learned from clean data (or from pσp_\sigma with small σ\sigma), used in Langevin dynamics, fails in three ways (Song and Ermon 2019).

    1. Inaccurate scores in low-density regions. The score is trained only where there are data. Between modes and far from the data, the learned score can be wrong, and the chains start exactly there.

    2. The score does not see the mixture weights. Let p=πp1+(1−π) p2p = \pi p_1 + (1 - \pi)\,p_2, where p1p_1 and p2p_2 have disjoint supports. On the support of p1p_1, log⁡p=log⁡π+log⁡p1\log p = \log\pi + \log p_1, so

    ∇log⁡p=∇log⁡p1(the weight π disappears).\nabla\log p = \nabla\log p_1 \qquad \text{(the weight } \pi \text{ disappears)}.

    Langevin chains that cannot cross between the supports keep whatever split they started with. Nearly disjoint supports (well-separated modes) behave almost the same.

    3. Slow mixing. To leave a mode, a chain must climb a barrier of height ΔE=E(saddle)−E(mode)\Delta E = E(\text{saddle}) - E(\text{mode}). For overdamped Langevin at unit temperature, the mean time to cross grows like eΔEe^{\Delta E} (the Arrhenius law). Kramers' formula makes this precise for a 1D double well: the mean time to go from one well to the other is about

    T≈2πE′′(mode) ∣E′′(saddle)∣  eΔE.T \approx \frac{2\pi}{\sqrt{E''(\text{mode})\,|E''(\text{saddle})|}}\;e^{\Delta E} .
    Interactive figure: loading…

    Raise the barrier. The energy is E(x)=a(x2−1)2E(x) = a(x^2 - 1)^2, so the barrier height is aa. The trajectory hops between the wells often for small aa and rarely for large aa. The lower chart has a log scale: the exact mean crossing time is close to a straight line, so it grows exponentially in aa, and Kramers' formula (dashed) is close for high barriers. Press Simulate at a few heights: the simulated averages fall on the exact curve.

    The fix: many noise levels. Let pσ=p∗N(0,σ2I)p_\sigma = p * \mathcal N(0, \sigma^2 I). For large σ\sigma:

    • the noised data fill space, so a learned score is accurate where the chains start;
    • the modes overlap, the barriers are low, and the chains move freely between modes;
    • the score far from the data now depends on the weights, so the chains split correctly.

    Example: for 12N(−4,0.52)+12N(4,0.52)\tfrac12\mathcal N(-4, 0.5^2) + \tfrac12\mathcal N(4, 0.5^2), the barrier log⁡pσ(4)−log⁡pσ(0)\log p_\sigma(4) - \log p_\sigma(0) is 31.3131.31 at σ=0\sigma = 0, 5.715.71 at σ=1\sigma = 1, 1.191.19 at σ=2\sigma = 2, 0.210.21 at σ=3\sigma = 3, and 00 at σ=4\sigma = 4 (one mode).

    Annealed Langevin dynamics (NCSN, Song and Ermon 2019) uses noise levels σ1>σ2>⋯>σL\sigma_1 > \sigma_2 > \dots > \sigma_L (geometric), and one network sθ(x,σ)s_\theta(x, \sigma) trained with DSM at all of them.

    1. Start from a broad distribution (uniform or a wide Gaussian).
    2. For i=1,…,Li = 1, \dots, L: set the step hi=ϵ σi2h_i = \epsilon\,\sigma_i^2 (proportional to the variance at that level) and run TT Langevin steps x←x+hi sθ(x,σi)+2hi ξx \leftarrow x + h_i\,s_\theta(x, \sigma_i) + \sqrt{2h_i}\,\xi.
    3. Each level starts from the samples of the previous level. Return the samples of the last level.

    At large σ\sigma the chains find the right mode weights; small σ\sigma then sharpens the samples. Diffusion models do the same with a continuous noise level and a better-designed sampler (lessons 07–09); predictor–corrector samplers still add Langevin corrector steps at each level.

    Answers to section 1. (1) Larger: 1/(1−0.1/2)=1.05261/(1 - 0.1/2) = 1.0526, about 5% too large (section 3.4). (2) No: at σ=0\sigma = 0 the barrier is 31.331.3, so the crossing time is of order e31.3≈4×1013e^{31.3} \approx 4 \times 10^{13} time units, times a prefactor. Near +4+4 the score is (4−x)/0.25(4 - x)/0.25 for any weights (section 3.9). (3) It learns the score of the noisy density pσp_\sigma, not of the clean data; the loss does not go to 0, its minimum is the constant C>0C > 0 (section 3.7).

    4. Worked example #

    (a) The likelihood gradient of a Gaussian EBM. Eθ(x)=θx2/2E_\theta(x) = \theta x^2/2, so ∇θEθ(x)=x2/2\nabla_\theta E_\theta(x) = x^2/2 and pθ=N(0,1/θ)p_\theta = \mathcal N(0, 1/\theta). Data: {−1,0.5,2}\{-1, 0.5, 2\}.

    • Second moment of the data: x2‾=(1+0.25+4)/3=1.75\overline{x^2} = (1 + 0.25 + 4)/3 = 1.75.
    • Positive phase: −x2‾/2=−0.875-\overline{x^2}/2 = -0.875.
    • Negative phase at θ=1\theta = 1: Epθ[x2/2]=1/(2θ)=0.5\mathbb E_{p_\theta}[x^2/2] = 1/(2\theta) = 0.5.
    • ∇θL=−0.875+0.5=−0.375<0\nabla_\theta L = -0.875 + 0.5 = -0.375 < 0: decrease θ\theta, that is, make the model wider.
    • The gradient −x2‾/2+1/(2θ)-\overline{x^2}/2 + 1/(2\theta) is zero at θ^=1/1.75=0.5714\hat\theta = 1/1.75 = 0.5714. The model variance 1/θ^=1.751/\hat\theta = 1.75 equals the second moment of the data: moment matching.

    (b) ULA on the fitted model N(0,1.75)\mathcal N(0, 1.75).

    • With h=0.7h = 0.7: a=1−0.7/1.75=0.6a = 1 - 0.7/1.75 = 0.6, and the update is x′=0.6 x+1.4 ξ=0.6 x+1.1832 ξx' = 0.6\,x + \sqrt{1.4}\,\xi = 0.6\,x + 1.1832\,\xi.
    • Stationary variance: 1.4/(1−0.36)=2.1875=1.75/0.81.4/(1 - 0.36) = 2.1875 = 1.75/0.8, so 25% too large. Stable for h<2⋅1.75=3.5h < 2 \cdot 1.75 = 3.5.
    • With h=0.07h = 0.07: a=0.96a = 0.96, the variance is 0.14/(1−0.9216)=1.78570.14/(1 - 0.9216) = 1.7857, only 2% too large.
    • The price: the integrated autocorrelation time of an AR(1) chain is (1+a)/(1−a)(1 + a)/(1 - a). It grows from 1.6/0.4=41.6/0.4 = 4 steps to 1.96/0.04=491.96/0.04 = 49 steps. About twelve times less bias costs about twelve times more steps per independent sample.

    (c) One MALA step. Target N(0,1)\mathcal N(0, 1), h=0.5h = 0.5, current point x=1x = 1, noise ξ=1.5\xi = 1.5.

    • Proposal: x′=x−h x+2h ξ=1−0.5+1⋅1.5=2x' = x - h\,x + \sqrt{2h}\,\xi = 1 - 0.5 + 1 \cdot 1.5 = 2.
    • Target ratio: log⁡p(x′)−log⁡p(x)=−42+12=−1.5\log p(x') - \log p(x) = -\tfrac{4}{2} + \tfrac{1}{2} = -1.5.
    • Proposal densities (both have variance 2h=12h = 1, so the constants cancel): log⁡q(x′∣x)=−12(2−0.5)2=−1.125\log q(x' \mid x) = -\tfrac12(2 - 0.5)^2 = -1.125 and log⁡q(x∣x′)=−12(1−(2−1))2=0\log q(x \mid x') = -\tfrac12\big(1 - (2 - 1)\big)^2 = 0.
    • log⁡α=−1.5+0−(−1.125)=−0.375\log\alpha = -1.5 + 0 - (-1.125) = -0.375, so α=e−0.375=0.687\alpha = e^{-0.375} = 0.687. The move is accepted with probability 0.687.

    (d) Score, Tweedie and the DSM floor for Gaussian data. Data N(2,1)\mathcal N(2, 1), noise σ=1\sigma = 1. Then pσ=N(2,2)p_\sigma = \mathcal N(2, 2).

    • Score at x=4x = 4: −(4−2)/2=−1-(4 - 2)/2 = -1.
    • Tweedie: E[x0∣x=4]=4+1⋅(−1)=3\mathbb E[x_0 \mid x = 4] = 4 + 1 \cdot (-1) = 3. Gaussian conditioning gives the same: (1⋅4+1⋅2)/(1+1)=3(1 \cdot 4 + 1 \cdot 2)/(1 + 1) = 3.
    • Posterior variance: σ2(1+σ2⋅(−12))=12\sigma^2(1 + \sigma^2 \cdot (-\tfrac12)) = \tfrac12, which is s2σ2/(s2+σ2)s^2\sigma^2/(s^2 + \sigma^2) with s2=1s^2 = 1.
    • DSM floor: E[(∇log⁡pσ)2]=E[(x−2)2]/4=2/4=12\mathbb E[(\nabla\log p_\sigma)^2] = \mathbb E[(x - 2)^2]/4 = 2/4 = \tfrac12, so C=12(1/σ2−12)=0.25C = \tfrac12(1/\sigma^2 - \tfrac12) = 0.25. Even the exact score has JDSM=0.25J_{\text{DSM}} = 0.25.

    (e) A mixture. Data 12N(−2,0.52)+12N(2,0.52)\tfrac12\mathcal N(-2, 0.5^2) + \tfrac12\mathcal N(2, 0.5^2) (the "narrow" data of the DSM figure), σ=0.5\sigma = 0.5. Noising adds σ2\sigma^2 to each variance: pσ=12N(−2,0.5)+12N(2,0.5)p_\sigma = \tfrac12\mathcal N(-2, 0.5) + \tfrac12\mathcal N(2, 0.5). At x=1x = 1:

    • The two component scores are −(1−2)/0.5=2-(1 - 2)/0.5 = 2 and −(1+2)/0.5=−6-(1 + 2)/0.5 = -6.
    • The responsibility of the right component: the ratio of the two densities is e−(1−2)2/1/e−(1+2)2/1=e8e^{-(1-2)^2/1} / e^{-(1+2)^2/1} = e^{8}, so w+=1/(1+e−8)=0.999665w_+ = 1/(1 + e^{-8}) = 0.999665.
    • The score is the responsibility-weighted average: 0.999665⋅2+0.000335⋅(−6)=1.997320.999665 \cdot 2 + 0.000335 \cdot (-6) = 1.99732.
    • Tweedie: E[x0∣x=1]=1+0.25⋅1.99732=1.4993\mathbb E[x_0 \mid x = 1] = 1 + 0.25 \cdot 1.99732 = 1.4993. This is almost the posterior mean inside the right component alone, (0.25⋅1+0.25⋅2)/0.5=1.5(0.25 \cdot 1 + 0.25 \cdot 2)/0.5 = 1.5.

    5. In code #

    NumPy and SciPy check the numbers of sections 3 and 4. The notebook has these cells and the exercises.

    import numpy as np
    from scipy.special import logsumexp
    from scipy.stats import norm
    
    rng = np.random.default_rng(0)
    
    # (a) EBM gradient for E_theta(x) = theta x^2 / 2: positive + negative phase
    data = np.array([-1.0, 0.5, 2.0])
    theta = 1.0
    grad = -np.mean(data**2 / 2) + 1 / (2 * theta)       # E_p[x^2/2] = 1/(2 theta)
    print(round(grad, 3), round(1 / np.mean(data**2), 4))   # -0.375 0.5714
    
    # (b) ULA on N(0, 1.75) with h = 0.7: run 20000 chains for 200 steps
    s2, h = 1.75, 0.7
    x = np.zeros(20_000)
    for _ in range(200):
        x = x - h * x / s2 + np.sqrt(2 * h) * rng.standard_normal(x.size)
    print(round(x.var(), 3), s2 / (1 - h / (2 * s2)))  # 2.172 2.1875 (sampling error about 0.02)
    
    # (c) one MALA step: target N(0, 1), h = 0.5, from x = 1 to x' = 2
    x0, x1, h = 1.0, 2.0, 0.5
    log_alpha = (norm.logpdf(x1) - norm.logpdf(x0)
                 + norm.logpdf(x0, x1 - h * x1, np.sqrt(2 * h))    # log q(x | x')
                 - norm.logpdf(x1, x0 - h * x0, np.sqrt(2 * h)))   # log q(x' | x)
    print(round(log_alpha, 3), round(np.exp(log_alpha), 3))         # -0.375 0.687
    
    # (d) DSM on Gaussian data N(2, 1) with sigma = 1: p_sigma = N(2, 2)
    sigma = 1.0
    x0 = 2 + rng.standard_normal(1_000_000)
    eps = rng.standard_normal(x0.size)
    xs = x0 + sigma * eps
    exact_score = -(xs - 2) / 2
    print(round(np.mean(0.5 * (exact_score + eps / sigma) ** 2), 3))   # 0.25: the DSM floor
    print(4 + sigma**2 * (-(4 - 2) / 2))                               # Tweedie at x = 4: 3.0
    
    # (e) mixture 0.5 N(-2, 0.25) + 0.5 N(2, 0.25), sigma = 0.5: score at x = 1
    def log_p(x, sigma, w=0.5, m=2.0, s=0.5):
        sd = np.sqrt(s**2 + sigma**2)
        return logsumexp([np.log(w) + norm.logpdf(x, -m, sd),
                          np.log(1 - w) + norm.logpdf(x, m, sd)], axis=0)
    d = 1e-6
    score = (log_p(1 + d, 0.5) - log_p(1 - d, 0.5)) / (2 * d)
    print(round(score, 5), round(1 + 0.25 * score, 4))   # 1.99732 1.4993
    
    # (f) barrier of 0.5 N(-4, 0.25) + 0.5 N(4, 0.25) after noising with sigma
    grid = np.linspace(0, 8, 80_001)
    for sg in [0, 1, 2, 3, 4]:
        lp = log_p(grid, sg, m=4.0)
        print(sg, round(lp.max() - log_p(0.0, sg, m=4.0), 2))
    # 0 31.31 / 1 5.71 / 2 1.19 / 3 0.21 / 4 0.0
    

    The mixture log-density uses logsumexp: far from both components, each Gaussian density underflows to 0 in floating point, and the responsibilities would become 0/00/0.

    6. Where it shows up #

    • Score-based diffusion models. NCSN (Song and Ermon 2019) trains sθ(x,σ)s_\theta(x, \sigma) with DSM and samples with annealed Langevin dynamics. Score SDEs and DDPM use the same DSM (noise-prediction) loss with a continuous noise level (lessons 07–09). Predictor–corrector samplers add Langevin corrector steps.
    • Denoisers as priors. By Tweedie's formula, any good denoiser gives a score. "Plug-and-play" and "regularization by denoising" methods for image restoration use this, and diffusion posterior sampling (lesson 15) adds a likelihood score: ∇xlog⁡p(x∣y)=∇xlog⁡p(x)+∇xlog⁡p(y∣x)\nabla_x\log p(x \mid y) = \nabla_x\log p(x) + \nabla_x\log p(y \mid x), where p(y)p(y) drops out.
    • Bayesian deep learning. SGLD (Welling and Teh 2011) adds Langevin noise to mini-batch SGD with a decreasing step size to sample a posterior over network weights.
    • Classifiers as EBMs. The logits f(x)f(x) of a classifier define an energy E(x)=−log⁡∑yef(x)yE(x) = -\log\sum_y e^{f(x)_y} (JEM, Grathwohl et al. 2020). Such energies are also used for out-of-distribution detection.
    • Physics and chemistry. Overdamped Langevin dynamics is Brownian dynamics, and the score of a Boltzmann density is the force divided by kBTk_B T. Slow crossing of barriers is the rare-event problem (protein folding, phase transitions). Boltzmann generators use normalizing flows to sample all modes without crossing barriers.
    • Data assimilation. With a Gaussian likelihood, the posterior energy is E(x)=∥y−Ax∥2/(2s2)+Eprior(x)E(x) = \|y - Ax\|^2/(2s^2) + E_{\text{prior}}(x). 4D-Var minimizes this energy (the MAP estimate); Langevin with a learned prior score samples it. Score-based data assimilation (Rozet and Louppe 2023) uses a few Langevin corrector steps per noise level.

    7. Common mistakes #

    • Noise h\sqrt h instead of 2h\sqrt{2h}. The update x+h∇log⁡p+h ξx + h\nabla\log p + \sqrt h\,\xi samples p2p^2 (half the temperature): a Gaussian target comes out with half its variance as h→0h \to 0.
    • No noise at all. Then it is gradient descent on EE: it returns a mode, not samples.
    • Ignoring the ULA bias. Test a sampler on a Gaussian with known variance. Steps above 2λmin⁡2\lambda_{\min} diverge.
    • MH with a score network. The MALA ratio needs E(x)−E(x′)E(x) - E(x'); a score field alone does not give it.
    • Sign errors in the EBM loss. Minimize E(xdata)‾−E(x~)‾\overline{E(x_{\text{data}})} - \overline{E(\tilde x)}, with the negative samples x~\tilde x detached from the graph.
    • Trusting short-run chains. CD-1 or 20 Langevin steps from noise do not sample pθp_\theta. The learned energy can work well with its own sampler and still be a poor density.
    • Thinking DSM learns the clean score. It learns the score of pσp_\sigma. The clean score is only the limit σ→0\sigma \to 0, where the targets have variance d/σ2d/\sigma^2 and the regression is hopeless.
    • Expecting the DSM loss to reach 0. Its minimum is C(σ)>0C(\sigma) > 0, which depends on σ\sigma and on the data. Compare with a closed-form score when you can.
    • One chain on a multimodal target. A chain stuck in one mode looks converged. Run many chains from spread-out starts, and anneal the noise level.
    • Confusing the two "scores". ∇xlog⁡p(x)\nabla_x\log p(x) (this lesson) is a gradient with respect to the data. The score function of statistics and of REINFORCE, ∇θlog⁡pθ(x)\nabla_\theta\log p_\theta(x), is a gradient with respect to the parameters.

    8. Check yourself #

    1. Eθ(x)=θ∣x∣E_\theta(x) = \theta|x| with θ>0\theta > 0. Compute ZθZ_\theta and ∇θlog⁡Zθ\nabla_\theta \log Z_\theta, check the theorem of section 3.2, and give the maximum-likelihood θ\theta.
      AnswerZθ=2∫0∞e−θx dx=2/θZ_\theta = 2\int_0^\infty e^{-\theta x}\,dx = 2/\theta, so ∇θlog⁡Zθ=−1/θ\nabla_\theta\log Z_\theta = -1/\theta. The theorem says ∇θlog⁡Zθ=−Epθ[∣x∣]\nabla_\theta \log Z_\theta = -\mathbb E_{p_\theta}[|x|], and for this Laplace density E∣x∣=1/θ\mathbb E|x| = 1/\theta. ✓ The gradient of LL is −∣x∣‾+1/θ-\overline{|x|} + 1/\theta, which is zero at θ^=1/∣x∣‾\hat\theta = 1/\overline{|x|}.
    2. ULA on N(0,4)\mathcal N(0, 4) with h=1h = 1: write the update, the stationary variance and the largest stable step.
      Answerx′=0.75 x+2 ξx' = 0.75\,x + \sqrt2\,\xi. v=2/(1−0.5625)=4.571=4/(1−1/8)v = 2/(1 - 0.5625) = 4.571 = 4/(1 - 1/8), about 14% too large. Stable for h<2σ2=8h < 2\sigma^2 = 8.
    3. Show that dX=∇log⁡p dt+2T dWdX = \nabla\log p\,dt + \sqrt{2T}\,dW has a stationary density proportional to p1/Tp^{1/T}. Which TT does the "noise h\sqrt h" mistake correspond to?
      AnswerThe Fokker–Planck equation is ∂tρ=∇⋅(ρ (T∇log⁡ρ−∇log⁡p))\partial_t\rho = \nabla\cdot\big(\rho\,(T\nabla\log\rho - \nabla\log p)\big). It is 0 when T∇log⁡ρ=∇log⁡pT\nabla\log\rho = \nabla\log p, that is, ρ∝p1/T\rho \propto p^{1/T}. Noise h=2Th\sqrt h = \sqrt{2Th} means T=12T = \tfrac12: the chain samples p2p^2.
    4. For p=N(0,1)p = \mathcal N(0, 1) and the model sa(x)=−axs_a(x) = -ax, compute the implicit score-matching loss E[sa′(x)+12sa(x)2]\mathbb E[s_a'(x) + \tfrac12 s_a(x)^2] and its minimizer.
      Answersa′=−as_a' = -a and 12sa2=12a2x2\tfrac12 s_a^2 = \tfrac12 a^2x^2, so the loss is −a+12a2-a + \tfrac12 a^2 (using E[x2]=1\mathbb E[x^2] = 1). It is minimal at a=1a = 1, the true score −x-x. Check: JESM=12E[(1−a)2x2]=12(1−a)2=(−a+12a2)+12J_{\text{ESM}} = \tfrac12\mathbb E[(1 - a)^2x^2] = \tfrac12(1 - a)^2 = (-a + \tfrac12 a^2) + \tfrac12, so C=12C = \tfrac12.
    5. Data N(0,4)\mathcal N(0, 4) in 1D and noise σ=3\sigma = 3. What is the minimum value of the DSM loss (with the factor 12\tfrac12)? Which function reaches it?
      Answerpσ=N(0,13)p_\sigma = \mathcal N(0, 13) and E[(∇log⁡pσ)2]=1/13\mathbb E[(\nabla\log p_\sigma)^2] = 1/13. So C=12(1/9−1/13)=2/117≈0.0171C = \tfrac12(1/9 - 1/13) = 2/117 \approx 0.0171. It is reached by the exact score s(x)=−x/13s(x) = -x/13.
    6. Why can you not use MALA with the score network of a diffusion model? What could you do instead?
      AnswerMALA needs log⁡p(x′)−log⁡p(x)\log p(x') - \log p(x), and the network gives only ∇log⁡p\nabla\log p. You could parameterize the model as an energy and take its gradient (then the energy gives the ratio), integrate the score along the segment from xx to x′x' (costly, and a learned field need not be a true gradient), or accept the ULA bias with a small step.
    7. For the mixture of section 1, why does annealed Langevin recover the 50/50 weights when plain Langevin started near +4+4 does not?
      AnswerAt σ=0\sigma = 0 the barrier is 31.3, so chains never cross, and the score near each mode does not contain the weights. At σ≥4\sigma \ge 4 the noised mixture has one mode (barrier 0), so the chains mix and split according to the weights. Lowering σ\sigma slowly keeps each chain in the mode it chose, so the split survives as the modes separate.
    Recall cardsAnswer in your head first, then reveal. Add the cards to your review deck to see them again just before you would forget.
    1. Write the gradient of log⁡pθ(x)\log p_\theta(x) for an energy-based model.

    2. Write one step of the unadjusted Langevin algorithm.

    3. Stationary variance of ULA for the target N(μ,σ2)\mathcal N(\mu, \sigma^2) with step hh?

    4. How does MALA remove the bias of ULA, and what does it need that ULA does not?

    5. Why does the score of an EBM not depend on ZθZ_\theta?

    6. Write the denoising score matching loss and its target.

    7. What does DSM learn at its optimum, and why?

    8. State Tweedie's formula for x=x0+σεx = x_0 + \sigma\varepsilon.

    9. Why does contrastive divergence (CD-kk) give a biased gradient?

    10. Why does Langevin with many noise levels (annealing) work better than one small noise level?

    Open the review →

    9. Interview angle #

    • "Why are EBMs hard to train?" — ZθZ_\theta is intractable, so the likelihood gradient needs model samples from MCMC; short chains are biased, long chains are expensive, and mixing between modes is slow.
    • "What is the score, and why do diffusion models learn it instead of the density?" — ∇xlog⁡p(x)\nabla_x\log p(x); it does not contain ZZ, and it can be learned by denoising (DSM).
    • "Langevin versus gradient descent?" — The same step plus noise 2h ξ\sqrt{2h}\,\xi; the noise turns mode finding into sampling. Without noise you get a mode.
    • "What is the bias of ULA and how do you remove it?" — O(h)O(h); for N(0,σ2)\mathcal N(0, \sigma^2) the variance is σ2/(1−h/(2σ2))\sigma^2/(1 - h/(2\sigma^2)). Remove it with MALA or a decreasing step size.
    • "Prove that denoising score matching works." — The marginal score is the posterior mean of the conditional score (differentiate under the integral); so the cross terms of DSM and ESM agree, and the losses differ by a constant.
    • "Why many noise levels?" — Scores are accurate only where noised data have mass; large noise merges modes, so Langevin can cross and find the weights; small noise sharpens.
    • "Contrastive divergence in one sentence?" — Approximate the negative phase with kk MCMC steps started at the data: cheap, biased, and not the gradient of a fixed objective in general.

    10. Practice #

    The notebook for this lesson has five exercises, each with a check cell and a folded solution. All of them use NumPy and exact formulas; no network is trained.

    1. ULA on N(0,1)\mathcal N(0, 1): measure the variance for several hh, compare with 1/(1−h/2)1/(1 - h/2), then write MALA and check that the bias disappears.
    2. Crossing time against barrier height on the double well a(x2−1)2a(x^2 - 1)^2: simulate and compare with the exact formula and Kramers' approximation.
    3. Denoising score matching with a model that is linear in fixed features, fitted by least squares on 1D mixture data; compare with the exact noised score.
    4. Annealed versus fixed-σ Langevin on the 8 Gaussians with unequal weights, with exact scores: compare the mode proportions.
    5. Persistent contrastive divergence for a 1D Gaussian EBM; compare with the closed-form maximum likelihood estimate.

    11. Watch and read #

    A deep EBM trained with contrastive divergence, Langevin sampling and a replay buffer.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    The likelihood gradient of an EBM, Langevin sampling and contrastive divergence, step by step.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    Scores of noisy distributions, denoising score matching and Langevin dynamics, in the notation of modern diffusion models.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    The author of NCSN explains score matching, the problems of a single noise level and annealed Langevin dynamics.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play