Search

Search papers and lessons

Density estimation using Real NVP

Laurent Dinh, Jascha Sohl-Dickstein, Samy Bengio · 2016

Dinh, Sohl-Dickstein and Bengio (2016) build an image model from affine coupling layers, so that exact likelihood, exact sampling and exact latent inference all cost about one network pass.

On this page

  • Colour = topic mix
  • Linear algebra
  • Probability
  • Calculus
  • Discrete math
  • Generative models
  • Inference
  • ReadReady to readNot yet

TL;DR

Most image models either have a fast likelihood but slow, sequential sampling, or have fast sampling but only approximate likelihoods. Real NVP is a model that gets all of it at once: the likelihood, the sampling and the inference of latent variables are each exact and cost about one pass through the network. It is built from affine coupling layers, each of which changes half of its input by a scale and a shift that depend on the other half. Stacked and arranged in a multi-scale design, these layers model 32 by 32 to 64 by 64 natural images with competitive bits per dimension, and their latent space is as large as the input.

Builds on: Change of Variables Formula, Normalizing Flow, Affine Coupling Layer, NICE: Non-linear Independent Components Estimation · Leads to: Glow: Generative Flow with Invertible 1x1 Convolutions, which replaces the fixed channel masks with invertible 1x1 convolutions

Why it mattered

Image generation in 2016 was dominated by three families. Autoregressive models such as PixelRNN gave exact likelihoods but sampled one pixel at a time. Variational autoencoders gave a latent space but only a bound on the likelihood, and their samples tended to look blurry under a fixed reconstruction cost. GANs gave sharp samples but no likelihood at all. The paper argues that a model with exact likelihood and parallel sampling could sit between these, and its experiments on four image datasets show it can. It introduced the Affine Coupling Layer, which later flow models reused, and it showed that exact-likelihood image models could produce sharp samples.

The problem

A model that maps a latent vector z\mathbf{z} to data x\mathbf{x} by an invertible function gg has an exact density through the change of variables rule. Maximum likelihood then trains the model directly, with no discriminator and no approximate inference. The catch is that for a general gg on images, the Jacobian determinant is a matrix determinant of size equal to the number of pixels, which is far too expensive, and the inverse of a general neural network is hard to compute. The earlier NICE model solved this with volume-preserving maps, which avoid the determinant but are less flexible. The paper's question is how to keep both exact likelihood and a cheap, flexible determinant on high-dimensional image data.

How it works

Here is one affine coupling layer on a tiny two-dimensional input, traced step by step. The full model stacks many such layers on image tensors, but each layer works exactly like this.

  1. Split the input. Take x=(x1,x2)\mathbf{x} = (x_1, x_2) with x1x_1 in the first d=1d = 1 dimension and x2x_2 in the remaining one. The first part is copied to the output unchanged.
  2. Compute a scale and a shift from the copied part. Two networks ss and tt take x1x_1 as input and return s(x1)s(x_1) and t(x1)t(x_1). These networks can be as complicated as needed, because they never need to be inverted. Take a simple example: s(x1)=0.5 x1s(x_1) = 0.5\,x_1 and t(x1)=x1t(x_1) = x_1.
  3. Scale and shift the other part. The output is y2=x2exp⁡(s(x1))+t(x1)y_2 = x_2 \exp(s(x_1)) + t(x_1). Using x=(1,3)x = (1, 3): s(1)=0.5s(1) = 0.5, so exp⁡(0.5)=1.6487\exp(0.5) = 1.6487; t(1)=1t(1) = 1; so y2=3×1.6487+1=5.9461y_2 = 3 \times 1.6487 + 1 = 5.9461. The output is y=(1,5.9461)\mathbf{y} = (1, 5.9461).
  4. Read off the Jacobian determinant. The Jacobian is triangular, so its determinant is the product of its diagonal. The diagonal is 11 for the copied part and exp⁡(s(x1))\exp(s(x_1)) for the other. The log-determinant is therefore just s(x1)s(x_1), which is 0.50.5 here.
  5. Invert the layer. Since y1=x1y_1 = x_1, the inverse can recompute ss and tt from y1y_1 and undo the step: x2=(y2−t(y1))exp⁡(−s(y1))=(5.9461−1)×0.6065=3.0000x_2 = (y_2 - t(y_1))\exp(-s(y_1)) = (5.9461 - 1) \times 0.6065 = 3.0000. Recovering x2=3x_2 = 3 confirms the layer is invertible.
  6. Stack layers so that every part changes. A single layer leaves x1x_1 unchanged. Alternating which part is copied in successive layers lets every dimension be transformed. Images use two masks (checkerboard and channel-wise), a squeeze that trades width for channels, and a multi-scale recursion that sends half the dimensions straight to the output at each level.
−2−1.5−1−0.500.511.5200.511.522.53x1scale factor
  • scale exp(s(x1)) with s = 0.5 x1
  • no scaling (identity)
How much the copied input x1 stretches the other coordinate. At x1 = 1 the scale is 1.6487, which is the factor used in step 3.
flowchart LR
  X1["x1 (copied unchanged)"] --> S["network s"]
  X1 --> T["network t"]
  X2["x2"] --> M["multiply by exp(s)"]
  S --> M
  M --> ADD["add t"]
  T --> ADD
  X1 --> Y1["y1 = x1"]
  ADD --> Y2["y2"]

Worked examples

Example
1. Tiny case: the layer at zero

Take x=(0,0)x = (0, 0) with d=1d = 1, and let s(x1)=0s(x_1) = 0 and t(x1)=0t(x_1) = 0 for every input.

  1. Compute y1=x1=0y_1 = x_1 = 0.
  2. Compute y2=x2exp⁡(0)+0=0×1+0=0y_2 = x_2 \exp(0) + 0 = 0 \times 1 + 0 = 0.
  3. The log-determinant is s(x1)=0s(x_1) = 0, so the determinant is 11.
  4. The layer is the identity, so the density is unchanged.

Interpretation: a coupling layer with zero scale and zero shift does nothing and preserves volume. Any learned change comes from ss and tt being non-zero.

Example
2. Standard case: the walkthrough layer

Use x=(1,3)x = (1, 3), s(x1)=0.5x1s(x_1) = 0.5 x_1 and t(x1)=x1t(x_1) = x_1, as in the walkthrough.

  1. Forward: y1=1y_1 = 1.
  2. Forward: y2=3×exp⁡(0.5)+1=3×1.6487+1=5.9461y_2 = 3 \times \exp(0.5) + 1 = 3 \times 1.6487 + 1 = 5.9461.
  3. Log-determinant: ln⁡∣det⁡∣=s(1)=0.5\ln|\det| = s(1) = 0.5.
  4. Inverse step one: y1=1y_1 = 1 gives s(y1)=0.5s(y_1) = 0.5 and t(y1)=1t(y_1) = 1.
  5. Inverse step two: x2=(5.9461−1)/exp⁡(0.5)=4.9461/1.6487=3.0000x_2 = (5.9461 - 1)/\exp(0.5) = 4.9461 / 1.6487 = 3.0000.
  6. Check: the recovered input is (1,3)(1, 3), the original.

Interpretation: the forward and inverse passes cost the same, and the determinant is read directly from ss. This is the property that lets the model sample and evaluate likelihoods with equal ease.

Example
3. Realistic case: the bits per dimension on CIFAR-10

The paper reports bits per dimension, the code length per pixel channel, where lower is better. On CIFAR-10 test images, PixelRNN scores 3.003.00 and Real NVP scores 3.493.49. A 32 by 32 colour image has 32×32×3=307232 \times 32 \times 3 = 3072 dimensions, so the two models' ideal code lengths for one image are:

  1. PixelRNN: 3072×3.00=92163072 \times 3.00 = 9216 bits, which is 9216/8=11529216 / 8 = 1152 bytes.
  2. Real NVP: 3072×3.49=10,721.33072 \times 3.49 = 10{,}721.3 bits, which is 10,721.3/8=1340.210{,}721.3 / 8 = 1340.2 bytes.
  3. Gap per dimension: 3.49−3.00=0.493.49 - 3.00 = 0.49 bits.
  4. Relative gap: 0.49/3.00=16.30.49 / 3.00 = 16.3 percent more code length for Real NVP on this dataset.
  5. On Imagenet at 32 by 32, the same gap is 4.28−3.86=0.424.28 - 3.86 = 0.42 bits per dimension.

Interpretation: the paper is honest that Real NVP does not beat PixelRNN on bits per dimension. Its advantage is elsewhere: sampling is parallel, the latent space is exact, and the model is trained only by maximum likelihood.

Try it: on Imagenet at 64 by 64, the Real NVP and PixelRNN scores are 3.983.98 and 3.633.63. How many bytes more does Real NVP need to code one 64 by 64 colour image? Answer: the dimension is 64×64×3=1228864 \times 64 \times 3 = 12288. The gap is 3.98−3.63=0.353.98 - 3.63 = 0.35 bits, so the extra code length is 12288×0.35=4300.812288 \times 0.35 = 4300.8 bits, which is about 537.6537.6 bytes.

Common mistakes and tradeoffs

It is tempting to think that the functions ss and tt must be invertible. In fact they never need to be inverted, because the inverse of the layer only uses ss and tt evaluated on the copied part, which is available at inverse time. That is why they can be deep convolutional networks.

It is tempting to think that a coupling layer preserves volume. In fact its determinant is exp⁡(∑jsj)\exp(\sum_j s_j), which equals 1 only when ss is zero. Volume preservation is the NICE special case, and Real NVP's advantage over NICE is the learned scale.

It is tempting to think that exact likelihood means the samples are good. The paper notes that maximum likelihood values diversity, so a limited-capacity model sometimes outputs improbable samples, especially on CelebA. Exact likelihood is a training objective and says nothing about how sharp a sample looks; the paper's claim is only that its samples are sharper than VAE samples in its experiments.

It is tempting to think that sampling is slow because the model is deep. In fact sampling runs in parallel over the input dimensions, which is the main contrast with autoregressive models. Each layer's inverse costs the same as its forward pass.

When to use this approach: you need exact likelihoods, exact latent inference, and parallel sampling on continuous data, and you can afford networks whose size grows with the image. When not to use it: you only need the best bits per dimension on images, where autoregressive models were stronger in this paper, or you need a discrete data model, where the change of variables rule does not apply directly. Alternatives include PixelRNN for exact likelihoods with slow sampling, VAEs for a learned latent space with approximate likelihoods, and GANs for sharp samples without any likelihood.

The math

Definition: Affine coupling layer

Given x∈RD\mathbf{x} \in \mathbb{R}^D and a split index d<Dd < D, the layer outputs y1:d=x1:d\mathbf{y}_{1:d} = \mathbf{x}_{1:d} and yd+1:D=xd+1:D⊙exp⁡(s(x1:d))+t(x1:d)\mathbf{y}_{d+1:D} = \mathbf{x}_{d+1:D} \odot \exp\big(s(\mathbf{x}_{1:d})\big) + t(\mathbf{x}_{1:d}), where ss and tt map Rd\mathbb{R}^d to RD−d\mathbb{R}^{D-d} and ⊙\odot is element-wise multiplication.

Step 2 in symbols

The scale ss and the shift tt are arbitrary functions of the copied part x1:d\mathbf{x}_{1:d}. In the walkthrough they were s(x1)=0.5x1s(x_1) = 0.5 x_1 and t(x1)=x1t(x_1) = x_1. In the paper they are deep convolutional networks, with the scale given as a hyperbolic tangent times a learned scale and the shift as an affine output.

Step 4 in symbols

The Jacobian of the layer is block triangular:

∂y∂x⊤=[Id0∂yd+1:D∂x1:d⊤diag(exp⁡[s(x1:d)])].\frac{\partial \mathbf{y}}{\partial \mathbf{x}^\top} = \begin{bmatrix} \mathbb{I}_d & 0 \\ \frac{\partial \mathbf{y}_{d+1:D}}{\partial \mathbf{x}_{1:d}^\top} & \mathrm{diag}\big(\exp[s(\mathbf{x}_{1:d})]\big) \end{bmatrix}.

The determinant of a triangular matrix is the product of its diagonal, so

∣det⁡∂y∂x⊤∣=exp⁡ ⁣[∑js(x1:d)j],log⁡∣det⁡∂y∂x⊤∣=∑js(x1:d)j.\left|\det \frac{\partial \mathbf{y}}{\partial \mathbf{x}^\top}\right| = \exp\!\left[\sum_j s(\mathbf{x}_{1:d})_j\right], \qquad \log\left|\det \frac{\partial \mathbf{y}}{\partial \mathbf{x}^\top}\right| = \sum_j s(\mathbf{x}_{1:d})_j.

The derivatives of ss and tt do not appear, which is why those functions can be arbitrarily complex. In the walkthrough the log-determinant was s(1)=0.5s(1) = 0.5.

Step 5 in symbols

The inverse is

x1:d=y1:d,xd+1:D=(yd+1:D−t(y1:d))⊙exp⁡(−s(y1:d)).\mathbf{x}_{1:d} = \mathbf{y}_{1:d}, \qquad \mathbf{x}_{d+1:D} = \big(\mathbf{y}_{d+1:D} - t(\mathbf{y}_{1:d})\big) \odot \exp\big(-s(\mathbf{y}_{1:d})\big).

Because y1:d=x1:d\mathbf{y}_{1:d} = \mathbf{x}_{1:d}, the same ss and tt are available in both directions.

Masked form

The two partitions can be written with a binary mask b\mathbf{b}:

y=b⊙x+(1−b)⊙(x⊙exp⁡(s(b⊙x))+t(b⊙x)).\mathbf{y} = \mathbf{b} \odot \mathbf{x} + (1 - \mathbf{b}) \odot \Big(\mathbf{x} \odot \exp\big(s(\mathbf{b} \odot \mathbf{x})\big) + t(\mathbf{b} \odot \mathbf{x})\Big).

The checkerboard mask has value 1 where the sum of the two spatial coordinates is odd. The channel-wise mask has value 1 for the first half of the channels.

Composition

For two layers faf_a and fbf_b, the determinant of the composition is the product of determinants, det⁡(A⋅B)=det⁡(A)det⁡(B)\det(\mathbf{A} \cdot \mathbf{B}) = \det(\mathbf{A}) \det(\mathbf{B}). The log-determinants therefore add across layers, and the inverse of a composition runs the layers in reverse order, (fb∘fa)−1=fa−1∘fb−1(f_b \circ f_a)^{-1} = f_a^{-1} \circ f_b^{-1}.

Batch normalization inside the flow

A batch normalisation step x↦(x−μ~)/σ~2+ϵ\mathbf{x} \mapsto (\mathbf{x} - \tilde{\mu}) / \sqrt{\tilde{\sigma}^2 + \epsilon} is a linear rescaling of each dimension. Its Jacobian determinant is (∏i(σ~i2+ϵ))−1/2\left(\prod_i (\tilde{\sigma}_i^2 + \epsilon)\right)^{-1/2}, so it adds one more term to the log-density and the model stays exact.

Squeezing and factoring out

The squeeze operation turns an s×s×cs \times s \times c tensor into an s2×s2×4c\frac{s}{2} \times \frac{s}{2} \times 4c tensor. The multi-scale model applies it between groups of coupling layers and factors out half the dimensions at each level. Writing z(i)\mathbf{z}^{(i)} for the factored-out part at level ii, the final latent is the concatenation z=(z(1),…,z(L))\mathbf{z} = (\mathbf{z}^{(1)}, \ldots, \mathbf{z}^{(L)}), and the prior is the unit Gaussian described in the walkthrough.

Results

The paper reports bits per dimension on four datasets. Table 1 gives test results for CIFAR-10 and validation results for the rest, with training results in parentheses.

DatasetPixelRNNReal NVPConv DRAWIAF-VAE
CIFAR-103.003.49bound 3.59bound 3.28
Imagenet 32 by 323.86 (3.83)4.28 (4.26)bound 4.40 (4.35)
Imagenet 64 by 643.63 (3.57)3.98 (3.75)bound 4.10 (4.04)
LSUN bedroom2.72 (2.70)
LSUN tower2.81 (2.78)
LSUN church outdoor3.08 (2.94)
CelebA3.02 (2.97)

The entries marked as bounds in the paper (Conv DRAW and IAF-VAE, printed with a less-than sign) are upper bounds. The paper's own reading is that Real NVP's bits per dimension do not improve on PixelRNN but are competitive with other generative methods, and that performance increases with the number of parameters.

Two other findings are qualitative. Figure 5 shows samples that the paper describes as globally coherent and sharp, in contrast to VAE samples, which it hypothesises comes from not using a fixed-form reconstruction cost. Figure 6 shows a manifold built from four validation examples, which the paper describes as smooth and semantically consistent in latent space. Appendix F also builds a class-conditional variant that uses CelebA attribute labels to define the invertible function's parameters.

What the results do not show: the bits per dimension are not state of the art against PixelRNN, and the suggested use for semi-supervised learning in the conclusion is a possibility the paper does not test. The paper uses data augmentation with horizontal flips, a logit preprocessing step that maps pixels into a bounded range with a margin of α=0.05\alpha = 0.05, and Adam with default settings. Those choices are part of the reported numbers.

Reading guide

Recap

  • The change of variables rule gives an exact density for an invertible map, but a general map on images has an intractable determinant.
  • An affine coupling layer copies half its input and scales and shifts the other half by functions of the copied half, so its determinant is the sum of the scale terms.
  • Its inverse costs the same as its forward pass, so sampling and likelihood evaluation are both one pass.
  • Stacked with alternating masks, squeezing and factoring out, the layers model 32 by 32 to 64 by 64 natural images with competitive bits per dimension.
  • The model is trained by maximum likelihood, so its samples are sharper than VAE samples in the paper's experiments but its bits per dimension do not beat PixelRNN.

Read next: NICE: Non-linear Independent Components Estimation for the volume-preserving predecessor this paper extends, and Variational Inference with Normalizing Flows for the posterior-approximation use of flows.

Check yourself

QuestionRecall: why does an affine coupling layer have a cheap Jacobian determinant?Show answer

The layer leaves one part of the input unchanged and scales the other part by a function of the unchanged part. The Jacobian is block triangular with identity in the copied block, so its determinant is the product of the diagonal scales, which is exp⁡\exp of the sum of ss. The derivatives of ss and tt never appear.

QuestionCompute: a coupling layer has x=(2,1)x = (2, 1), d=1d = 1, s(x1)=0.5x1s(x_1) = 0.5 x_1 and t(x1)=x1t(x_1) = x_1. What is the output y2y_2, and what is the log-determinant?Show answer

The copied part is x1=2x_1 = 2, so s(2)=1s(2) = 1 and t(2)=2t(2) = 2. Then y2=x2exp⁡(s)+t=1×e1+2=2.7183+2=4.7183y_2 = x_2 \exp(s) + t = 1 \times e^1 + 2 = 2.7183 + 2 = 4.7183. The log-determinant is s(2)=1s(2) = 1.

QuestionWhy can the scale and shift networks be deep convolutional networks that cannot be inverted analytically?Show answer

The inverse of the layer recomputes ss and tt on the copied part y1:d\mathbf{y}_{1:d}, which equals x1:d\mathbf{x}_{1:d}. It never inverts ss or tt themselves, so their internal structure can be arbitrary. Only the arithmetic that combines them with the other part must be invertible, and that is a multiply and an add.

QuestionApplied: a team trains a Real NVP style model on 32 by 32 colour images and reports 3.50 bits per dimension, while a PixelRNN baseline reports 3.00. The team says its model is better because it samples in parallel. Is that claim supported by the paper's numbers?Show answer

Parallel sampling is a real property of the model, and the paper says so. But the bits per dimension comparison in the paper shows Real NVP at 3.49 on CIFAR-10 against PixelRNN at 3.00, so the paper itself does not claim the likelihood is better. The team's claim is supported only if it is about sampling speed and exact latent inference, and it should not be presented as a likelihood win.

Sources

Read the full paper

Laurent Dinh, Jascha Sohl-Dickstein, Samy Bengio, 2016. arXiv:1605.08803