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 to data by an invertible function 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 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.
- Split the input. Take with in the first dimension and in the remaining one. The first part is copied to the output unchanged.
- Compute a scale and a shift from the copied part. Two networks and take as input and return and . These networks can be as complicated as needed, because they never need to be inverted. Take a simple example: and .
- Scale and shift the other part. The output is . Using : , so ; ; so . The output is .
- Read off the Jacobian determinant. The Jacobian is triangular, so its determinant is the product of its diagonal. The diagonal is for the copied part and for the other. The log-determinant is therefore just , which is here.
- Invert the layer. Since , the inverse can recompute and from and undo the step: . Recovering confirms the layer is invertible.
- Stack layers so that every part changes. A single layer leaves 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.
- scale exp(s(x1)) with s = 0.5 x1
- no scaling (identity)
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
Take with , and let and for every input.
- Compute .
- Compute .
- The log-determinant is , so the determinant is .
- 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 and being non-zero.
Use , and , as in the walkthrough.
- Forward: .
- Forward: .
- Log-determinant: .
- Inverse step one: gives and .
- Inverse step two: .
- Check: the recovered input is , the original.
Interpretation: the forward and inverse passes cost the same, and the determinant is read directly from . This is the property that lets the model sample and evaluate likelihoods with equal ease.
The paper reports bits per dimension, the code length per pixel channel, where lower is better. On CIFAR-10 test images, PixelRNN scores and Real NVP scores . A 32 by 32 colour image has dimensions, so the two models' ideal code lengths for one image are:
- PixelRNN: bits, which is bytes.
- Real NVP: bits, which is bytes.
- Gap per dimension: bits.
- Relative gap: percent more code length for Real NVP on this dataset.
- On Imagenet at 32 by 32, the same gap is 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 and . How many bytes more does Real NVP need to code one 64 by 64 colour image? Answer: the dimension is . The gap is bits, so the extra code length is bits, which is about bytes.
Common mistakes and tradeoffs
It is tempting to think that the functions and must be invertible. In fact they never need to be inverted, because the inverse of the layer only uses and 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 , which equals 1 only when 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
Given and a split index , the layer outputs and , where and map to and is element-wise multiplication.
Step 2 in symbols
The scale and the shift are arbitrary functions of the copied part . In the walkthrough they were and . 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:
The determinant of a triangular matrix is the product of its diagonal, so
The derivatives of and do not appear, which is why those functions can be arbitrarily complex. In the walkthrough the log-determinant was .
Step 5 in symbols
The inverse is
Because , the same and are available in both directions.
Masked form
The two partitions can be written with a binary mask :
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 and , the determinant of the composition is the product of determinants, . The log-determinants therefore add across layers, and the inverse of a composition runs the layers in reverse order, .
Batch normalization inside the flow
A batch normalisation step is a linear rescaling of each dimension. Its Jacobian determinant is , so it adds one more term to the log-density and the model stays exact.
Squeezing and factoring out
The squeeze operation turns an tensor into an tensor. The multi-scale model applies it between groups of coupling layers and factors out half the dimensions at each level. Writing for the factored-out part at level , the final latent is the concatenation , 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.
| Dataset | PixelRNN | Real NVP | Conv DRAW | IAF-VAE |
|---|---|---|---|---|
| CIFAR-10 | 3.00 | 3.49 | bound 3.59 | bound 3.28 |
| Imagenet 32 by 32 | 3.86 (3.83) | 4.28 (4.26) | bound 4.40 (4.35) | |
| Imagenet 64 by 64 | 3.63 (3.57) | 3.98 (3.75) | bound 4.10 (4.04) | |
| LSUN bedroom | 2.72 (2.70) | |||
| LSUN tower | 2.81 (2.78) | |||
| LSUN church outdoor | 3.08 (2.94) | |||
| CelebA | 3.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 , and Adam with default settings. Those choices are part of the reported numbers.
Reading guide
- Abstract and Section 1 (Introduction). Needs Generative Model and the idea of exact likelihood. Read for the motivation: a model with exact likelihood, sampling and latent inference.
- Section 2 (Related work). Needs Autoregressive Model, Variational Autoencoder and Generative Adversarial Network. Read for the three families the paper positions itself between.
- Section 3.1 (Change of variable formula). Needs Change of Variables Formula and Probability Density Function. This is the rule every later step depends on.
- Section 3.2 to 3.3 (Coupling layers and their properties). Needs Affine Coupling Layer and Jacobian Matrix. Work the walkthrough alongside these equations.
- Section 3.4 and 3.5 (Masked convolution and combining layers). Needs Convolutional Neural Network. The masks are the image-specific part.
- Section 3.6 and 3.7 (Multi-scale architecture and batch normalization). Needs Batch Normalization, Weight Normalization and Deep Residual Learning for Image Recognition (ResNet). Read the squeeze operation with figure 3.
- Section 4 (Experiments). Needs Adam Optimizer and Maximum Likelihood Estimation for the training objective. Read Table 1 together with the results above.
- Appendices. Optional. Appendix E describes a batch normalisation variant that averages a moving average of the layer statistics with the current batch statistics; read it when you want to reproduce the training setup.
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 of the sum of . The derivatives of and never appear.
QuestionCompute: a coupling layer has , , and . What is the output , and what is the log-determinant?Show answer
The copied part is , so and . Then . The log-determinant is .
QuestionWhy can the scale and shift networks be deep convolutional networks that cannot be inverted analytically?Show answer
The inverse of the layer recomputes and on the copied part , which equals . It never inverts or 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
- Dinh, L., Sohl-Dickstein, J. and Bengio, S. (2016). Density estimation using Real NVP. arXiv:1605.08803. https://arxiv.org/abs/1605.08803
- Dinh, L., Krueger, D. and Bengio, Y. (2014). NICE: Non-linear Independent Components Estimation. arXiv:1410.8516. https://arxiv.org/abs/1410.8516