πŸŽ‰ 75% of content is free forever β€” Unlock Premium from $10/mo β†’
CW
NEWSLIVESearch All Content
πŸ’Ό Servicesℹ️ Aboutβœ‰οΈ ContactView Pricing Plansfrom $10

Energy-Based Models and Score Matching

🟒 Free Lesson

Energy-Based Models and Score Matching

Most generative models commit to a tractable probability: an autoregressive model factorizes it, a VAE bounds it, a normalizing flow computes it exactly. Energy-based models (EBMs) refuse the commitment. They assign an energy value to every possible configuration and interpret low energy as high probability β€” without ever computing the normalizing constant that would turn energies into probabilities.

That refusal is the source of both their flexibility and their difficulty. Because the model only needs to score configurations relative to each other, the same architecture can model images, molecular configurations, structured labels, and joint distributions over variables that other families cannot factor cleanly. But the partition function β€” the sum over all configurations β€” is intractable for continuous, high-dimensional data, so exact maximum likelihood is off the table.

The field's answer, developed through score matching, noise-contrastive estimation, and Langevin sampling, is to stop fitting probabilities and start fitting the score: the gradient of the log density with respect to the input. This lesson builds that story from the energy function outward, with working implementations of denoising score matching and Langevin dynamics, and a clear picture of where EBMs sit in modern generative AI.

The energy function as the whole model

An EBM defines p(x) proportional to exp(βˆ’E(x)) where E is a neural network mapping an input to a scalar. Low-energy regions are where the model believes data lives. Everything else β€” geometry of the distribution, modes, correlations β€” is encoded in the landscape that network draws.

python
import torch
import torch.nn as nn

class EnergyNet(nn.Module):
    def __init__(self, input_dim: int, hidden: int = 256, depth: int = 3):
        super().__init__()
        layers = []
        dim = input_dim
        for _ in range(depth):
            layers += [nn.Linear(dim, hidden), nn.SiLU()]
            dim = hidden
        layers.append(nn.Linear(dim, 1))
        self.net = nn.Sequential(*layers)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return self.net(x).squeeze(-1)

class JointEnergyModel(nn.Module):
    """Energy over (x, y) pairs β€” useful for structured prediction."""

    def __init__(self, x_dim: int, y_dim: int, hidden: int = 256):
        super().__init__()
        self.features = nn.Sequential(
            nn.Linear(x_dim + y_dim, hidden), nn.ReLU(),
            nn.Linear(hidden, hidden), nn.ReLU(),
        )
        self.energy_head = nn.Linear(hidden, 1)
        self.classifier = nn.Linear(hidden, y_dim)

    def forward(self, x: torch.Tensor, y: torch.Tensor):
        h = self.features(torch.cat([x, y], dim=-1))
        return self.energy_head(h).squeeze(-1), self.classifier(h)

The joint variant illustrates why EBMs attract researchers: modeling energy over input-label pairs yields a predictor that can be refined at inference time by searching for low-energy labels, rather than committing to a single forward pass. The catch is always the same β€” you can compare energies pointwise, but converting them to a normalized probability requires the intractable partition function Z = ∫ exp(βˆ’E(x)) dx.

Fitting the score instead of the density

The score is the gradient of log p with respect to x: for our model it is exactly βˆ’βˆ‡E(x). Score matching trains the model to match the data's score without ever computing Z, because Z differentiates to a constant and cancels out of the objective.

The catch: the data score is unknown (it would require knowing p). Denoising score matching solves this with a clean trick β€” add known Gaussian noise to data, then train the model's score on the noisy samples to point toward the clean original. Since the corruption kernel's score is analytically known, the target is computable:

python
import torch
import torch.nn as nn

class DenoisingScoreTrainer:
    def __init__(self, energy: EnergyNet, sigma: float = 0.1,
                 lr: float = 1e-3):
        self.energy = energy
        self.sigma = sigma
        self.opt = torch.optim.Adam(energy.parameters(), lr=lr)

    def score(self, x: torch.Tensor) -> torch.Tensor:
        x = x.detach().requires_grad_(True)
        e = self.energy(x)
        return torch.autograd.grad(e.sum(), x, create_graph=True)[0]

    def loss(self, batch: torch.Tensor) -> torch.Tensor:
        noise = torch.randn_like(batch) * self.sigma
        noisy = batch + noise
        predicted = self.score(noisy)
        target = -noise / (self.sigma ** 2)
        return 0.5 * ((predicted - target) ** 2).mean()

    def step(self, batch: torch.Tensor) -> float:
        loss = self.loss(batch)
        self.opt.zero_grad()
        loss.backward()
        self.opt.step()
        return loss.item()

trainer = DenoisingScoreTrainer(EnergyNet(input_dim=784), sigma=0.1)

Two features make this practical. The target βˆ’noise/σ² is the score of the Gaussian corruption kernel, which is known in closed form; no reference to the true data density appears anywhere. And because the target is a regression signal, training is a stable least-squares problem β€” a world away from the adversarial balance that plagues GANs. Using several noise scales, from tiny to large, teaches the score across the whole range of the data-to-noise spectrum; this multi-scale variant is the direct ancestor of diffusion models, which are best understood as EBMs trained by denoising score matching at every timestep.

Sampling with Langevin dynamics

If you can evaluate βˆ‡ log p(x), you can sample from p(x) by Langevin dynamics: initialize at random noise, then repeatedly take a small step down the energy landscape while adding a fresh noise injection. The noise keeps the chain from settling into a single local minimum and, under appropriate step-size conditions, guarantees convergence to the correct distribution.

python
class LangevinSampler:
    def __init__(self, energy: EnergyNet, step_size: float = 0.01,
                 n_steps: int = 200, noise_scale: float = 0.01):
        self.energy = energy
        self.step_size = step_size
        self.n_steps = n_steps
        self.noise_scale = noise_scale

    @torch.no_grad()
    def sample(self, n: int, dim: int, device="cpu") -> torch.Tensor:
        x = torch.randn(n, dim, device=device)
        for step in range(self.n_steps):
            with torch.enable_grad():
                x = x.detach().requires_grad_(True)
                e = self.energy(x)
                score = torch.autograd.grad(e.sum(), x)[0]
            noise = torch.randn_like(x) * self.noise_scale
            x = x - self.step_size * score + noise
        return x.detach()

sampler = LangevinSampler(trained_energy, step_size=0.01, n_steps=300)
samples = sampler.sample(n=32, dim=784)

In practice, plain Langevin is rarely used raw. Annealed Langevin dynamics β€” running the chain through a descending sequence of noise levels, each with its own step size β€” covers the space far more reliably than a single-temperature run, because large noise early on lets the chain jump between modes that would otherwise be separated by high energy barriers. This annealing schedule is, again, exactly the structure diffusion samplers formalize.

Sampling cost is the EBM's recurring bill: every step is a gradient evaluation, and thousands of steps are typical. EBM practitioners pay it willingly for the modeling flexibility; production systems usually distill the learned energy into a cheaper one-step generator.

Noise-contrastive estimation: learning differences instead of gradients

Score matching is not the only escape from the partition function. Noise-contrastive estimation (NCE) reframes density estimation as ordinary binary classification: given a data point and a point drawn from a fixed noise distribution, ask the model to decide which is which. The energy function then learns to assign lower energy to data than to noise, and the normalizing constant becomes just another parameter the classifier absorbs rather than an obstacle it must compute.

NCE's practical advantage is that its training signal comes from comparisons instead of derivatives, so it needs no gradient computation with respect to inputs and no carefully tuned noise levels. Its cost is that quality depends heavily on the noise distribution β€” if the noise is too easy to distinguish from data, the model learns a shallow trick; if it is too close, the task becomes statistically inefficient. The choice of noise distribution is therefore the real hyperparameter, and it requires the same kind of thought that choosing a negative set requires in contrastive representation learning.

The two families sit on a spectrum modern systems freely mix. Diffusion training uses denoising score matching, while contrastive decoding at inference compares candidate continuations as an energy-tilting scheme. Recognizing both as energy-based moves lets you reuse intuitions across otherwise unrelated techniques: what matters is the landscape of relative scores, not the absolute probability anywhere.

Keeping chains stable in practice

Long MCMC chains introduce failure modes that do not exist in gradient-descent training. If the sampler drifts into regions the model has never seen, energies there are meaningless and the chain can wander into degenerate states β€” a problem visible as generation samples that look progressively stranger the more steps you take. Training with the same kind of chain you will sample with (or mixing model-generated samples into training) keeps the energy function well-behaved exactly where inference will visit.

Diagnostics are simple and worth automating: track the mean and variance of energy on real data versus on samples throughout training, and alert if the gap closes in the wrong direction or if sample energies grow without bound. Also check chain convergence by running multiple chains from different initializations and confirming they settle in agreement β€” chains that end in different places indicate modes the sampler is not crossing, which means your sample diversity is lower than your evaluation suggests.

Where EBMs show up today

Pure EBMs remain a research tool, but their ideas are embedded in shipping systems. Diffusion models are score-matching machines: the noise predictor is a parameterized score function, and the sampler is an annealed Langevin variant. Classifier-free guidance is an energy-tilting trick β€” extrapolating between conditional and unconditional scores sharpens the effective distribution the same way adding a term to an energy would. Noise-contrastive estimation, the sibling of score matching, underlies contrastive representation learning and contrastive decoding in language models.

For practitioners, the practical lesson is this: when you need to model a distribution you cannot normalize β€” unstructured outputs, joint constraints, energy-based reranking of candidates β€” you do not need Z. You need relative energies and a gradient, and score matching plus Langevin-style refinement gives you both.

MethodWhat is learnedSampling costRelation to EBMs
Denoising score matchingScore field across noise levelsLangevin / annealedCore EBM training method
Noise-contrastive estimationEnergy differences vs noiseDirect (no chain)Avoids partition function
Diffusion modelsTime-indexed scoreIterative denoisingScore-based EBM specialized to images
Contrastive decodingLogit contrasts at decode timeNone (reranking)Energy tilting over candidates

Common Mistakes

Trying to compute the partition function directly

Fix: Train with score matching or contrastive estimation β€” both objectives cancel Z by construction.

Training the score at a single noise level

Fix: Sample multiple sigmas per batch; a single scale teaches the score only near that corruption level.

Sampling with a large step size and no noise

Fix: Keep the injected noise and anneal the step size; deterministic descent collapses into one mode.

Evaluating samples after too few Langevin steps

Fix: Run until the chain mixes β€” visually plausible early samples often sit in a single basin.

Assuming energy values are comparable across separately trained models

Fix: Only energy differences within one trained model are meaningful; Z differs between runs.

Key Takeaways

  • Energy-based models assign unnormalized densities via a scalar network β€” flexible, but the partition function is intractable.
  • Score matching sidesteps normalization by training the gradient of log density instead of the density itself.
  • Denoising score matching makes targets computable by corrupting data with known Gaussian noise.
  • Langevin dynamics samples by combining gradient descent on energy with fresh noise injection; annealing makes it mix across modes.
  • Diffusion models are the productionized form of this lineage β€” score matching plus annealed sampling.
  • EBM ideas also appear as contrastive objectives and logit tilting in systems you already deploy.
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

β€”
β˜†β˜†β˜†β˜†β˜†
0 ratings

Rate & Feedback

Need Expert Generative AI Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement