Flows, Autoregressive & Energy-Based Models
Exact likelihoods from invertible maps and the chain rule, and unnormalized energies.
A VAE can only bound its likelihood and a GAN has none. Two other families compute it exactly: normalizing flows push noise through an invertible network and pay for every layer with a log-determinant, and autoregressive models multiply one-step predictions. A third, the energy-based model, writes down any density it likes, up to a normalizing constant it cannot compute. This lesson derives all three and the bargain each one strikes.
What you’ll learn
- Derive the change-of-variables formula in one dimension, state it in dimensions, and write a flow's exact log-likelihood as a base log-density plus a sum of log-determinants.
- Build affine coupling layers with triangular Jacobians, implement one with its inverse, and explain Glow's actnorm and invertible convolutions.
- Show that an autoregressive model with Gaussian conditionals is a flow, and compare the network passes that flows and autoregressive models need to train and to sample.
- Define an energy-based model, explain why its partition function blocks maximum likelihood while its score does not, and describe continuous-time flows trained by flow matching.
Densities through invertible maps
A normalizing flow models data with a simple base density and an invertible, differentiable network that maps data to noise, . (In this lesson is that noise vector, a latent variable, never a pre-activation.) Its inverse is the generator: draw and output . The name comes from the data-to-noise direction, which "normalizes" data into a Gaussian. What density does such a model put on ?
Start in one dimension with an increasing . The event is the event , that is , so the two cumulative distribution functions agree:
Differentiate with the chain rule. A decreasing flips the inequality and the sign, and the absolute value absorbs both cases:
In dimensions the same bookkeeping holds box by box: a small box around carries the same probability as its image, and scales the box's volume by , the Jacobian determinant. That gives the change-of-variables formula:
Where stretches the neighborhood of , , the box's probability equals that of a larger region of noise, so the data density at exceeds the noise density at by that factor. In the generator's direction, with , the sign of the correction flips:
One layer of a flow doubles every coordinate of a -dimensional image, . How many nats does its log-determinant add to ?
Show the answer
543 nats
, so nats: exactly one bit per dimension. Scaling alone buys likelihood. On 8-bit pixels this has no limit: a continuous density that squeezes its mass ever closer to the 256 integer values makes the likelihood arbitrarily large. That is why pixel values are dequantized with uniform noise before a flow's likelihood means anything (Evaluating Generative Models).
Coupling layers: cheap determinants by design
For a generic network the log-determinant costs , and inverting it means solving an equation iteratively. Flows are built instead from layers with triangular Jacobians, whose determinants are products of their diagonals. The simplest is the additive coupling layer of NICE (Dinh, Krueger & Bengio, 2015): split into halves , keep , and shift the rest by any network of it, . Its Jacobian has ones on the diagonal, so it preserves volume, and NICE ended with a diagonal scaling layer to let volume change. RealNVP (Dinh, Sohl-Dickstein & Bengio, 2017) made the coupling affine:
Keep the first coordinates; scale and shift the others by functions of them, where are arbitrary networks:
The Jacobian is block lower-triangular. The derivatives of and fill the off-diagonal block, which never enters the determinant:
The inverse costs one more pass, because is available on both sides. Neither nor is ever inverted, so they can be any networks at all:
At some input, an affine coupling layer on computes the log-scales . What is the layer's there?
- , since coupling layers preserve volume
- It needs the full determinant, including the derivatives of and
Show the answer
A.
The log-determinant is the sum of the log-scales, : on net the layer shrinks volume slightly, by the factor .
import math
import torch
import torch.nn as nn
class AffineCoupling(nn.Module):
def __init__(self, d, hidden=256):
super().__init__()
self.k = d // 2
self.net = nn.Sequential(nn.Linear(self.k, hidden), nn.ReLU(),
nn.Linear(hidden, 2 * (d - self.k)))
def forward(self, x): # data -> noise, plus log|det J|
xa, xb = x[:, :self.k], x[:, self.k:]
s, t = self.net(xa).chunk(2, dim=-1)
s = torch.tanh(s) # keeps each scale in (1/e, e)
return torch.cat([xa, xb * torch.exp(s) + t], dim=-1), s.sum(dim=-1)
def inverse(self, z): # noise -> data; s, t never inverted
za, zb = z[:, :self.k], z[:, self.k:]
s, t = self.net(za).chunk(2, dim=-1)
return torch.cat([za, (zb - t) * torch.exp(-torch.tanh(s))], dim=-1)
def log_prob(layers, x): # exact log-likelihood of each row
logdet = torch.zeros(x.shape[0])
for layer in layers:
x, ld = layer(x)
logdet = logdet + ld
x = x.flip(dims=[1]) # reverse the order: |det| = 1
base = -0.5 * (x ** 2).sum(dim=1) - 0.5 * x.shape[1] * math.log(2 * math.pi)
return base + logdetA coupling layer and the exact log-likelihood of a stack. Reversing the coordinates between layers, a permutation, lets every coordinate be transformed by some layer. Train by minimizing -log_prob(layers, x).mean(); to sample, push Gaussian noise through the layers in reverse order, undoing each flip and calling inverse. The tanh bounds the log-scales, a common guard against exploding scales early in training.
Images. RealNVP splits pixels by a checkerboard pattern and channels into halves, and uses a squeeze that turns an tensor into , trading resolution for channels. Its multi-scale architecture factors out half of the dimensions after each scale, so later layers work on fewer of them. Glow (Kingma & Dhariwal, 2018) made each step of the flow three layers:
- actnorm, a per-channel scale and bias initialized from a first minibatch so that each channel starts with zero mean and unit variance, then trained freely; for an feature map its log-determinant is ;
- an invertible convolution, a learned matrix that mixes the channels at every pixel and generalizes the fixed permutations of RealNVP; its log-determinant is , an computation that drops to when is stored in LU form, ;
- an affine coupling layer.
On CIFAR-10 this improved the likelihood from RealNVP's 3.49 bits per dimension to 3.35, while the autoregressive PixelCNN++ had already reached 2.92. Glow's samples were shown at reduced temperature, with the noise scaled by 0.7 before decoding, trading diversity for cleaner images.
Autoregressive models are flows too
The overview lesson wrote every distribution as a product of one-step predictions, . Give each conditional a Gaussian whose mean and standard deviation are networks of the earlier coordinates, and sampling becomes a map from noise to data:
For discrete data no flow is needed. PixelCNN predicts each pixel value, WaveNet each audio sample and a GPT each token with a softmax over the possible values, and the exact log-likelihood is the sum of the log-probabilities given to the true values. What the autoregressive family shares is its cost structure:
- Training and density evaluation take one pass. All of is known, so one network computes every conditional at once, provided its connections respect the ordering: masked weights (MADE), masked or causal convolutions (PixelCNN, WaveNet), or a causal attention mask.
- Sampling takes sequential passes, since must exist before can be predicted: 3,072 for a color image generated one channel value at a time, 16,000 for one second of 16 kHz audio.
| Model | of a given | One sample |
|---|---|---|
| Coupling flow (RealNVP, Glow) | one pass | one pass |
| Autoregressive model (PixelCNN, WaveNet, GPT, masked autoregressive flow) | one pass | sequential passes |
| Inverse autoregressive flow (IAF) | sequential passes | one pass |
Think first Why can a coupling layer be inverted in one pass, while an autoregressive layer of the same Gaussian form is fast in only one direction?
A coupling layer's scales and shifts depend only on the half it leaves unchanged, which is available in both directions. An autoregressive layer's depend on : given data they are all available at once, but when sampling, exists only after has been computed. The coupling layer pays for its speed in flexibility. Half of its outputs condition on nothing, so it takes many layers, with permutations between them, to capture dependencies that one autoregressive layer models directly.
Energy-based models: any network, no normalizer
An energy-based model (EBM) drops invertibility and every other architectural constraint. Any network defines a density that is high where the energy is low:
Without the model cannot report , only the energy, which is up to an unknown constant: enough to rank two inputs, not to compare two models. Maximum likelihood still works in principle. The gradient of the log-likelihood splits into a term at the data point and an expectation under the model itself:
Lower the energy of the data, raise it on the model's own samples; at the optimum the two averages balance. The catch is the second term, which needs samples from , a distribution known only up to . Restricted Boltzmann machines were trained by approximating it with a few steps of Markov chain Monte Carlo started at the data, the contrastive divergence of Hinton (2002).
One quantity escapes entirely: the score, the gradient of the log-density with respect to the input,
That opens two doors. Langevin dynamics samples from by following plus noise, and score matching (Hyvärinen, 2005) fits a model's score to data without ever touching . Learning the scores of noise-blurred data at many noise levels is exactly what diffusion models do (Diffusion Models).
A colleague proposes to train an EBM by minimizing the average energy of the training data, "since is just a constant". What goes wrong?
- Nothing: a constant does not change the gradient
- The energy network would have to be invertible
- The gradient of the energy cannot be computed by backpropagation
- depends on ; without it the network can lower the energy everywhere, so the loss falls without bound while the density learns nothing
Show the answer
D. depends on ; without it the network can lower the energy everywhere, so the loss falls without bound while the density learns nothing
, and moves with every weight. Its gradient, , is what pushes the energy up away from the data. Drop it and nothing stops the network from subtracting an ever larger constant everywhere.
Flows in continuous time
Shrink the steps of a residual flow, , toward zero and the stack becomes an ordinary differential equation, a neural ODE (Chen, Rubanova, Bettencourt & Duvenaud, 2018). Time runs from noise at to data at , the convention of flow matching:
If the velocity field is Lipschitz in (uniformly in ) and continuous in , solutions exist, are unique and can be run backward, so the map from to is invertible whatever the network looks like. The sum of log-determinants becomes an integral of a trace, . Such a continuous normalizing flow has an exact likelihood, up to the accuracy of the ODE solver, but training it by maximum likelihood means solving the ODE, and estimating traces, at every step.
Flow matching (Lipman et al., 2023) and rectified flow (Liu, Gong & Liu, 2023) skip the simulation. Draw noise , a data point and a time , form , and regress on with a squared error. The Emergence lesson Continuous Flows & Flow Matching proves that this simple regression learns a field whose flow carries the noise to the data.
Think first In the two-cluster target, which noise points end up in the left cluster?
Those that start left of the vertical axis. The noise and the target are mirror-symmetric, so on that axis the field has no horizontal component, and since solutions of an ODE with a Lipschitz field are unique, no exact trajectory crosses it. Half of the noise lies on each side, matching the clusters' equal weights. No learned notion of the "nearest" cluster is involved: the noise is carried by a map that must be continuous and invertible.
| Family | Sampling | Architecture | Main cost | |
|---|---|---|---|---|
| Coupling flows (RealNVP, Glow) | exact, one pass | one pass | invertible layers with triangular Jacobians; latent as large as the data | many layers needed; likelihoods behind autoregressive models |
| Autoregressive (PixelCNN, WaveNet, GPT) | exact, one pass | sequential passes | any network that respects an ordering | slow sampling |
| Continuous flows (CNFs, flow matching) | exact via an ODE and a trace | one ODE solve: tens of steps | any velocity network | many network calls per sample |
| Energy-based models | only up to | MCMC: many gradient steps | any scalar network | training needs model samples or a score-based objective |
Key takeaways
- Change of variables: for an invertible from data to noise. Stacked layers add their log-determinants, so a flow is trained by exact maximum likelihood.
- Coupling layers keep half the coordinates and scale and shift the rest by networks of the first half: a triangular Jacobian with and a one-pass inverse. Glow adds actnorm and invertible convolutions.
- An autoregressive model with Gaussian conditionals is a flow with a triangular Jacobian; on discrete data the chain rule gives exact likelihoods directly. Training takes one parallel pass, sampling sequential passes.
- An energy-based model accepts any network but hides : its likelihood gradient needs samples from the model, while its score does not involve at all.
- Continuous flows integrate a learned velocity field from noise to data; flow matching trains them by regression on straight noise-to-data paths, without solving the ODE during training.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
A flow maps data to noise by . Near a data point , doubles volumes: . How does the model's density at compare with the base density at ?
- It is half as large
- It is the same, since invertible maps preserve density
- It is twice as large
- It cannot be determined without the inverse map
Show the answer
C. It is twice as large
. A small box around carries the same probability as its image, which is twice as large in noise space, so the probability per unit volume at is twice the base density at .
A Glow step applies an invertible convolution with a weight matrix to an tensor. What is its log-determinant?
- , since a convolution only permutes channels
Show the answer
B.
The same acts on the channels at each of the pixels, so the full Jacobian is block-diagonal with copies of , and the blocks' log-determinants add.
You need to draw 10,000 samples quickly from a model of color images, and you also want exact test log-likelihoods. Which model fits both needs best?
- A PixelCNN
- An energy-based model
- A coupling flow such as Glow
- A GAN
Show the answer
C. A coupling flow such as Glow
A coupling flow evaluates exactly in one pass and samples in one pass. A PixelCNN gives exact likelihoods but needs 3,072 sequential passes per sample, an energy-based model gives its likelihood only up to a constant and samples by MCMC, and a GAN has no likelihood at all.
Which quantity of an energy-based model can be computed exactly at any without knowing its partition function ?
- The score
- The density
- The parameter gradient
- The log-likelihood ratio between two parameter settings
Show the answer
A. The score
The score is : does not depend on , so its gradient vanishes. Langevin sampling and score matching rely on exactly this.
Go deeper
- Autoregressive Density Models · MADE, PixelCNN, WaveNet and masked autoregressive flows.
- Continuous Flows & Flow Matching · Neural ODE flows, and training them without simulation by regressing velocity fields.
- Energy-Based Models · Unnormalized densities, contrastive divergence and score matching.
Further reading
- L. Dinh, J. Sohl-Dickstein & S. Bengio, "Density estimation using Real NVP," ICLR (2017).
- D. P. Kingma & P. Dhariwal, "Glow: Generative flow with invertible 1×1 convolutions," NeurIPS (2018).
- G. Papamakarios, E. Nalisnick, D. J. Rezende, S. Mohamed & B. Lakshminarayanan, "Normalizing flows for probabilistic modeling and inference," Journal of Machine Learning Research 22(57), 1–64 (2021).
- S. J. D. Prince, Understanding Deep Learning, ch. 16 "Normalizing flows" (MIT Press, 2023), free at udlbook.github.io.