Search

Search papers and lessons

Variational Inference with Normalizing Flows

Danilo Jimenez Rezende, Shakir Mohamed · 2015

Rezende and Mohamed (2015) replace the simple Gaussian guess in variational inference with a normalizing flow, a chain of invertible maps whose exact density is cheap to track, and show that this gives tighter bounds.

On this page

  • Colour = topic mix
  • Probability
  • Linear algebra
  • Calculus
  • Discrete math
  • Inference
  • Neural network basics
  • ReadReady to readNot yet

TL;DR

Variational inference replaces an impossible posterior with a simple guess and tunes the guess to fit. The usual guesses are independent Gaussians or mean-field families, and they cannot match the true posterior even with unlimited training. Rezende and Mohamed propose building the guess as a normalizing flow: start from a simple density and push samples through a sequence of invertible maps, keeping track of how each map stretches space so the final density is still exact. Their planar and radial flows are cheap to evaluate, and in deep latent Gaussian models the flows gave tighter bounds on the marginal likelihood than diagonal Gaussians or NICE-style flows.

Builds on: Normalizing Flow, Reparameterization Trick, Amortized Inference, Variational Lower Bound (ELBO) · Leads to: Variational Autoencoder

Why it mattered

Variational autoencoders became a default way to fit latent-variable generative models, and their encoders output a diagonal Gaussian. That choice is convenient, but it bounds how good the approximation can be. The paper gives a concrete fix that stays inside the same training loop: keep the Amortized Inference encoder and the Reparameterization Trick, then add a flow on top of the encoder's Gaussian sample. It is a concrete demonstration that a richer posterior can be made scalable, and it is the reference point for the question "how flexible must the posterior be?" in later Variational Autoencoder and Normalizing Flow work.

The paper also set out an organising idea. It groups finite flows, infinitesimal flows such as the Langevin and Hamiltonian flows from Markov chain Monte Carlo, and volume-preserving flows such as NICE, under one definition. That view made it easier to compare posterior approximations that had been developed separately.

History: before this paper, most variational methods used mean-field families. Structured mean-field and mixture approximations improved on them but were either still restricted or too expensive, as the introduction explains. The paper builds on earlier work by Tabak and Turner and by Tabak and Vanden-Eijnden on transforming densities for density estimation, and it cites NICE (Dinh et al., 2014) as the closest volume-preserving alternative. Its contribution was to put flows inside amortized variational inference with a cheap determinant, and to give a unified view of the approaches it drew on. It appeared as an arXiv preprint in 2015.

The problem

Suppose a model has observed data x\mathbf{x}, hidden variables z\mathbf{z} and parameters θ\boldsymbol{\theta}. The marginal likelihood pθ(x)=∫pθ(x∣z)p(z) dzp_\theta(\mathbf{x}) = \int p_\theta(\mathbf{x} \mid \mathbf{z}) p(\mathbf{z})\, d\mathbf{z} is usually intractable, so the method maximises a lower bound on it. The bound uses an approximate posterior qϕ(z∣x)q_\phi(\mathbf{z} \mid \mathbf{x}), and it is tight only when qϕq_\phi equals the true posterior pθ(z∣x)p_\theta(\mathbf{z} \mid \mathbf{x}).

Two problems have to be solved to make this work at scale. The first is computing gradients of the expected log-likelihood, which the paper handles with Monte Carlo estimates and reparameterisation. The second, which this paper addresses, is choosing a family for qϕq_\phi that is both rich enough and cheap to use. The paper's own argument is that the optimal qq would equal the true posterior, but independent Gaussians and mean-field families cannot represent the posterior's multiple modes, periodicity and correlations. Even when training is perfect, the bound stays loose. The paper cites evidence that limited posteriors cause under-estimated posterior variance and biased parameter estimates in time-series models.

Mixture posteriors are a natural alternative, but each extra component adds a full likelihood evaluation and gradient per update, which is expensive at scale. The paper needs a family whose density is computed in time that grows only linearly with the dimension.

How it works

Here is the method on one tiny one-dimensional example, step by step. The full model uses many layers and many flow steps, but each step works exactly like this.

  1. Start with a simple density. Let z0z_0 be a random number drawn from a standard Normal, z0∼N(0,1)z_0 \sim \mathcal{N}(0, 1). Its density at 1 is about 0.2420. We want a more flexible density than this one.
  2. Apply one invertible map. Use the planar map f(z)=z+u tanh⁡(wz+b)f(z) = z + u\,\tanh(w z + b) with w=1w = 1, u=1u = 1, b=0b = 0. Then z1=f(z0)=z0+tanh⁡(z0)z_1 = f(z_0) = z_0 + \tanh(z_0). Check: at z0=0z_0 = 0 the map returns 00, and at z0=1z_0 = 1 it returns 1.76161.7616. The map pushes points away from zero: positive points move right and negative points move left.
  3. Track how the map stretches space. The derivative f′(z)=1+u w (1−tanh⁡2z)f'(z) = 1 + u\,w\,(1 - \tanh^2 z) is the local stretch factor. At z0=1z_0 = 1 it is 1.42001.4200, so the map has expanded that neighbourhood by about 42 percent. A stretch greater than one spreads the probability thinner there, so the density must drop.
  4. Update the density. The change-of-variables rule says the new density equals the old density divided by the stretch: q1(z1)=q0(z0)/∣f′(z0)∣q_1(z_1) = q_0(z_0) / |f'(z_0)|. At the point z1=1.7616z_1 = 1.7616, this gives 0.2420/1.4200=0.17040.2420 / 1.4200 = 0.1704. The density is lower because the map spread the mass.
  5. Repeat with more maps. Feed z1z_1 into a second map f2f_2 and multiply the stretch factors. After KK maps the log-density is the starting log-density minus the sum of the log stretch factors. This is the one bookkeeping rule the whole method depends on.
  6. Use the flow inside the bound. The approximate posterior is qKq_K. The bound needs log⁡qK(zK)\log q_K(\mathbf{z}_K) and log⁡p(x,zK)\log p(\mathbf{x}, \mathbf{z}_K). Expectations can be taken under the simple q0q_0 by sampling z0\mathbf{z}_0 and pushing it through the maps, so the flow adds one extra term per map, which is cheap to compute for the planar family.
−3−2−10123−4−2024zf(z)
  • f(x) = x + tanh(x)
  • identity (no change)
One planar map with w = 1, u = 1, b = 0. The curve bends the identity line; points at z = 0 and z = 1 match steps 2 and 3 of the walkthrough.
flowchart LR
  A["z0 ~ q0 (simple Gaussian)"] --> B["f1: planar map"]
  B --> C["z1, density q1"]
  C --> D["f2: planar map"]
  D --> E["zK, density qK = approximate posterior"]

Worked examples

Example
1. Tiny case: the map at zero

Use the one-dimensional planar map f(z)=z+tanh⁡(z)f(z) = z + \tanh(z), so w=1w = 1, u=1u = 1, b=0b = 0, and start at z0=0z_0 = 0.

  1. Compute the image: z1=0+tanh⁡(0)=0z_1 = 0 + \tanh(0) = 0.
  2. Compute the derivative h′(z)=1−tanh⁡2zh'(z) = 1 - \tanh^2 z. At z=0z = 0, tanh⁡0=0\tanh 0 = 0, so h′(0)=1h'(0) = 1.
  3. Stretch factor: f′(0)=1+u w h′(0)=1+1=2f'(0) = 1 + u\,w\,h'(0) = 1 + 1 = 2.
  4. Base density: q0(0)=12π≈0.3989q_0(0) = \frac{1}{\sqrt{2\pi}} \approx 0.3989.
  5. Flow density: q1(0)=q0(0)/2≈0.1995q_1(0) = q_0(0) / 2 \approx 0.1995.

Interpretation: the map doubles the length of the segment around zero, so the same probability is spread over twice the length and the density halves.

Example
2. Standard case: the walkthrough point

Use the same map and start at z0=1z_0 = 1, with the density values from the walkthrough.

  1. Compute the image: z1=1+tanh⁡1=1+0.7616=1.7616z_1 = 1 + \tanh 1 = 1 + 0.7616 = 1.7616.
  2. Compute tanh⁡21=0.5800\tanh^2 1 = 0.5800, so h′(1)=1−0.5800=0.4200h'(1) = 1 - 0.5800 = 0.4200.
  3. Stretch factor: f′(1)=1+0.4200=1.4200f'(1) = 1 + 0.4200 = 1.4200.
  4. Base density: q0(1)=e−1/22π=0.2420q_0(1) = \frac{e^{-1/2}}{\sqrt{2\pi}} = 0.2420.
  5. Flow density at the image: q1(1.7616)=0.2420/1.4200=0.1704q_1(1.7616) = 0.2420 / 1.4200 = 0.1704.
  6. Check with logs: ln⁡q0(1)=−1.4189\ln q_0(1) = -1.4189 and ln⁡1.4200=0.3507\ln 1.4200 = 0.3507, so ln⁡q1=−1.4189−0.3507=−1.7696\ln q_1 = -1.4189 - 0.3507 = -1.7696, and e−1.7696=0.1704e^{-1.7696} = 0.1704.

Interpretation: the density at the new point is lower than the base density at the old point, because the map stretched the neighbourhood. The log form in step 6 is the one the bound actually uses.

Example
3. Realistic case: reading the MNIST table

The paper reports upper bounds on the negative log-probability −ln⁡p(x)-\ln p(\mathbf{x}) of binarised MNIST test digits. Lower is better. The relevant entries are: diagonal Gaussian posterior ≤89.9\leq 89.9; planar flow with K=10K = 10: ≤87.5\leq 87.5; K=80K = 80: ≤85.1\leq 85.1; NICE with K=10K = 10: ≤88.6\leq 88.6; NICE with K=80K = 80: ≤87.2\leq 87.2.

  1. Gain from the diagonal Gaussian to the planar flow at K=80K = 80: 89.9−85.1=4.889.9 - 85.1 = 4.8.
  2. Gain from K=10K = 10 to K=80K = 80 for planar flows: 87.5−85.1=2.487.5 - 85.1 = 2.4.
  3. Gap between NICE and planar flows at K=10K = 10: 88.6−87.5=1.188.6 - 87.5 = 1.1.
  4. Gap between NICE and planar flows at K=80K = 80: 87.2−85.1=2.187.2 - 85.1 = 2.1.
  5. The planar-flow advantage over NICE is larger at the longer flow. The paper's explanation is that every planar parameter is learned, whereas NICE relies on a randomly initialised mixing step that is not learned.

Interpretation: a longer flow is better, and a learned planar map beats a fixed volume-preserving map at the same length. The comparison holds the model fixed, so the gaps are attributable to the posterior family.

Try it: using the planar-flow entries only, how much does the bound improve going from K=20K = 20 to K=40K = 40? Answer: 86.5−85.7=0.886.5 - 85.7 = 0.8. The gain is smaller than the gain from K=10K = 10 to K=20K = 20 (87.5−86.5=1.087.5 - 86.5 = 1.0), so the returns diminish as the flow grows.

Common mistakes and tradeoffs

It is tempting to think that a normalizing flow is a generative model that replaces the encoder. In fact, in this paper the flow is a posterior approximation inside variational inference. It is trained through the same bound as the encoder, and it is used to approximate p(z∣x)p(\mathbf{z} \mid \mathbf{x}), not to model the data directly.

It is tempting to think that more flow steps always help. The paper shows steady gains up to K=80K = 80 on MNIST, but each step adds parameters and compute, and the gains get smaller. The right length depends on the budget.

It is tempting to think that the determinant has to be computed in full. In fact the planar and radial families are chosen so that the determinant reduces to one inner product or one scalar, which is why the method is scalable. A general invertible network would need the O(LD3)O(LD^3) cost the paper warns about.

It is tempting to think that a volume-preserving flow is strictly worse. The NICE comparison shows that it can reach similar asymptotic quality when the flow is long, but it needs a random mixing step and more parameters. Its advantage is that its Jacobian determinant is exactly one, so no determinant has to be computed and the log-density correction is zero.

When to use this approach: the posterior is clearly non-Gaussian, you need an amortized encoder, and you can afford a few extra layers. When not to use it: the posterior is close to Gaussian and the extra flexibility would not change decisions, or the model is small enough that exact MCMC is cheaper. Alternatives include mixtures of Gaussians (which need one likelihood evaluation per component), structured mean-field families, and MCMC-style flows such as Langevin and Hamiltonian flows, which need likelihood gradients at each step.

The math

Definition: Normalizing flow

A normalizing flow is a sequence of invertible, differentiable maps f1,…,fKf_1, \ldots, f_K applied to a random variable z0\mathbf{z}_0 with density q0q_0. Set zk=fk(zk−1)\mathbf{z}_k = f_k(\mathbf{z}_{k-1}). The resulting density qKq_K satisfies ln⁡qK(zK)=ln⁡q0(z0)−∑k=1Kln⁡∣det⁡∂fk∂zk−1∣\ln q_K(\mathbf{z}_K) = \ln q_0(\mathbf{z}_0) - \sum_{k=1}^{K} \ln \left|\det \frac{\partial f_k}{\partial \mathbf{z}_{k-1}}\right|.

Step 2 in symbols

The one-map case uses the change-of-variables rule q(z′)=q(z)∣det⁡∂f∂z∣−1q(\mathbf{z}') = q(\mathbf{z}) \left|\det \frac{\partial f}{\partial \mathbf{z}}\right|^{-1}, where z′=f(z)\mathbf{z}' = f(\mathbf{z}). The paper's planar family is

f(z)=z+u h(w⊤z+b),f(\mathbf{z}) = \mathbf{z} + \mathbf{u}\, h(\mathbf{w}^\top \mathbf{z} + b),

where w\mathbf{w} and u\mathbf{u} are vectors in RD\mathbb{R}^D, bb is a scalar and hh is a smooth element-wise non-linearity, here tanh⁡\tanh. The walkthrough used D=1D = 1, w=1\mathbf{w} = 1, u=1\mathbf{u} = 1, b=0b = 0.

Step 3 in symbols

The stretch factor is the determinant of the Jacobian ∂f/∂z\partial f / \partial \mathbf{z} (see Jacobian Matrix and Determinant). For the planar map the matrix determinant lemma reduces it to a single number:

ψ(z)=h′(w⊤z+b) w,∣det⁡∂f∂z∣=∣1+u⊤ψ(z)∣.\psi(\mathbf{z}) = h'(\mathbf{w}^\top \mathbf{z} + b)\, \mathbf{w}, \qquad \left|\det \frac{\partial f}{\partial \mathbf{z}}\right| = \left|1 + \mathbf{u}^\top \psi(\mathbf{z})\right|.

Here h′h' is the derivative of hh. In the walkthrough h′(z)=1−tanh⁡2zh'(z) = 1 - \tanh^2 z, so at z=1z = 1 the stretch is ∣1+1⋅(1−tanh⁡21)∣=1.4200|1 + 1 \cdot (1 - \tanh^2 1)| = 1.4200, as before. The cost is one inner product, so it is O(D)O(D) rather than the O(D3)O(D^3) of a general Jacobian determinant.

Step 4 in symbols

For KK maps, the log-density is the sum of the log stretch factors:

ln⁡qK(zK)=ln⁡q0(z0)−∑k=1Kln⁡∣1+uk⊤ψk(zk−1)∣.\ln q_K(\mathbf{z}_K) = \ln q_0(\mathbf{z}_0) - \sum_{k=1}^{K} \ln \left|1 + \mathbf{u}_k^\top \psi_k(\mathbf{z}_{k-1})\right|.

Step 6 in symbols

Start from the bound, which the paper writes as log⁡pθ(x)≥−F(x)\log p_\theta(\mathbf{x}) \geq -\mathcal{F}(\mathbf{x}) with F(x)=Eq[log⁡qϕ(z∣x)−log⁡p(x,z)]\mathcal{F}(\mathbf{x}) = \mathbb{E}_{q}[\log q_\phi(\mathbf{z} \mid \mathbf{x}) - \log p(\mathbf{x}, \mathbf{z})] (see Variational Lower Bound (ELBO)). Substitute the flow density and change the expectation to the base distribution q0q_0:

F(x)=Eq0 ⁣[ln⁡q0(z0)]−Eq0 ⁣[log⁡p(x,zK)]−Eq0 ⁣[∑k=1Kln⁡∣1+uk⊤ψk(zk−1)∣].\mathcal{F}(\mathbf{x}) = \mathbb{E}_{q_0}\!\left[\ln q_0(\mathbf{z}_0)\right] - \mathbb{E}_{q_0}\!\left[\log p(\mathbf{x}, \mathbf{z}_K)\right] - \mathbb{E}_{q_0}\!\left[\sum_{k=1}^{K} \ln \left|1 + \mathbf{u}_k^\top \psi_k(\mathbf{z}_{k-1})\right|\right].

The first term is the entropy-like term of the base Gaussian, the second is the usual reconstruction term evaluated at the end of the flow, and the third is the new correction from the flow. The paper shows that the third term needs only the linear-time quantities above.

The paper's other map, the radial flow f(z)=z+β h(α,r)(z−z0)f(\mathbf{z}) = \mathbf{z} + \beta\, h(\alpha, r)(\mathbf{z} - \mathbf{z}_0) with r=∥z−z0∥r = \|\mathbf{z} - \mathbf{z}_0\| and h(α,r)=1/(α+r)h(\alpha, r) = 1/(\alpha + r), also has a linear-time determinant. It expands or contracts space around a reference point z0\mathbf{z}_0 instead of across a hyperplane.

The paper also gives a volume-preserving comparison family. The NICE map f(zA,zB)=(zA,zB+hλ(zA))f(\mathbf{z}_A, \mathbf{z}_B) = (\mathbf{z}_A, \mathbf{z}_B + h_\lambda(\mathbf{z}_A)) has Jacobian determinant exactly 1, so it contributes nothing to the log-density correction. Its inverse is easy to compute. The paper's result is that planar maps reach the same kind of flexibility with far fewer parameters, because all of their parameters are learned.

Invertibility needs a constraint. For planar maps with h=tanh⁡h = \tanh, a sufficient condition is w⊤u≥−1\mathbf{w}^\top \mathbf{u} \geq -1, and the paper enforces it by adjusting u\mathbf{u} along w\mathbf{w}. The walkthrough satisfies it, since w⊤u=1\mathbf{w}^\top \mathbf{u} = 1.

Results

The paper reports four kinds of evidence.

Representational power on 2D densities. The authors define four unnormalised 2D energy functions with multi-modality and periodicity, and approximate each with a flow of length 2, 8 or 32 starting from a diagonal Gaussian. Figure 3 shows that approximation quality improves as the flow length grows, and that the planar flow reaches the same asymptotic quality as NICE but with far fewer parameters. The paper states these comparisons qualitatively in the text.

MNIST, binarised. The model is a deep latent Gaussian model with 40 latent variables, trained for 500,000 updates. Table 2 gives the bounds quoted in the Worked examples above. The paper's own planar-flow entries are ≤87.5\leq 87.5 for K=10K = 10, ≤86.5\leq 86.5 for K=20K = 20, ≤85.7\leq 85.7 for K=40K = 40 and ≤85.1\leq 85.1 for K=80K = 80. The table also lists results from other papers, including HVI with 1, 4 and 8 leapfrog steps (88.08, 86.40, 85.51) and DARN with 500 hidden units (84.71), which the authors attribute to different models and so are only indicative.

CIFAR-10 patches. The model uses 3 by 8 by 8 patches, 30 latent variables and a logit-normal observation model. Table 3 reports, under the heading −ln⁡p(x)-\ln p(\mathbf{x}), the values −293.7-293.7 at K=0K = 0, −308.6-308.6 at K=2K = 2, −317.9-317.9 at K=5K = 5 and −320.7-320.7 at K=10K = 10. The paper's text says increasing KK systematically improves the test log-likelihood. The table does not explain its sign convention, so read the numbers with the paper's own description.

What the results do not show. Each comparison is a single model class with one optimiser setting (RMSprop, learning rate 1×10−51 \times 10^{-5}, momentum 0.9, mini-batches of 100), and the paper uses an annealed bound with an inverse temperature that rises from 0.01 to 1 over 10,000 iterations. The model comparisons against other papers use different architectures. The paper also notes that a Maxout non-linearity (a unit that takes the maximum over small groups of its inputs) was used in the deterministic layers. The results support the claim that a richer posterior helps in these experiments. They do not establish how much a flow helps on other tasks, and the paper does not claim that they do.

Reading guide

  • Abstract and Section 1 (Introduction). Needs Variational Lower Bound (ELBO) and the idea of a posterior family. Read for the motivation: mean-field posteriors cannot match the true posterior.
  • Section 2 (Amortized Variational Inference). Needs Amortized Inference, Reparameterization Trick and Stochastic Gradient Descent. Skip the MCCV discussion on first read.
  • Section 2.3 (Deep Latent Gaussian Models). Needs Latent Variable Model and the idea of an encoder and decoder from Variational Autoencoder.
  • Section 3 (Normalizing Flows). Needs Change of Variables Formula, Jacobian Matrix and Determinant. Equations (5) to (7) are the core of the method; work the walkthrough above alongside them.
  • Section 3.2 (Infinitesimal Flows). Optional on first read. It needs the partial differential equation that describes how a density changes over time, and it names the Langevin and Hamiltonian flows as examples.
  • Section 4 (Inference with Normalizing Flows). The planar and radial families, the flow-based bound, and the algorithm. Needs everything above.
  • Section 5 (Alternative Flow-based Posteriors). Needs the volume-preserving idea. Read it for the comparison with NICE.
  • Section 6 (Results) and the Appendix. Read the figure and table captions first, then the numbers. The appendix proves when the planar and radial maps are invertible; it uses only the calculus already introduced.

Recap

  • A variational posterior is only as good as its family; Gaussian and mean-field families cannot match a multi-modal true posterior.
  • A normalizing flow pushes a simple density through invertible maps and updates the density with the log stretch factor at each step (Change of Variables Formula).
  • Planar and radial maps have determinants that cost O(D)O(D), so a flow of length KK costs about KK times that.
  • Inside the bound, the flow adds one log-determinant term to the usual reconstruction and prior terms, and training uses the reparameterised Monte Carlo gradient from Reparameterization Trick.
  • In deep latent Gaussian models, longer planar flows gave steadily tighter bounds than diagonal Gaussians or NICE.

Read next: Variational Autoencoder for the model this paper plugs into, and Normalizing Flow for the broader family of flows and their uses in density estimation.

Check yourself

QuestionRecall: why is a mean-field Gaussian posterior limited even with perfect training?Show answer

Its family cannot represent the true posterior. Mean-field and independent Gaussian posteriors cannot capture multiple modes, periodicity or strong correlations, so the best member of the family stays a poor match. The bound is then loose however well the parameters are optimised.

QuestionCompute: for the planar map f(z)=z+tanh⁡(z)f(z) = z + \tanh(z) at z0=0z_0 = 0, what is the flow density q1(0)q_1(0) if q0(0)=0.3989q_0(0) = 0.3989?Show answer

The stretch factor at zero is f′(0)=1+h′(0)=1+1=2f'(0) = 1 + h'(0) = 1 + 1 = 2. Then q1(0)=q0(0)/2=0.3989/2=0.19945q_1(0) = q_0(0)/2 = 0.3989/2 = 0.19945, or about 0.1995.

QuestionWhy does the paper prefer a planar flow over a general invertible neural network as the flow?Show answer

A general invertible network has a Jacobian determinant that costs about O(LD3)O(LD^3) to compute, and its gradients involve matrix inverses that can be numerically unstable. The planar map's determinant is a single inner product, so each step costs O(D)O(D). That makes long flows affordable inside a training loop that runs hundreds of thousands of updates.

QuestionApplied: a researcher uses a planar flow of length 10 and sees the bound on a binarised MNIST-like task go from 89.9 (diagonal Gaussian) to 87.5. Using the paper's table, what would the length-80 planar flow be expected to give, and what is the total gain?Show answer

The paper's own length-80 planar bound is ≤85.1\leq 85.1, so the expected result is about 85.1. The total gain from the diagonal Gaussian is 89.9−85.1=4.889.9 - 85.1 = 4.8, and the gain from length 10 to length 80 is 87.5−85.1=2.487.5 - 85.1 = 2.4. The researcher should expect a similar pattern on their own data, but the paper's numbers apply to its model and training setup, not to a different task.

Sources

Read the full paper

Danilo Jimenez Rezende, Shakir Mohamed, 2015. arXiv:1505.05770