RealNVP (real-valued non-volume preserving transformations) is a generative model that stacks many easily invertible transformations (affine coupling layers) to map images to standard normal noise of the same dimension. Because the transformation is invertible and its log-determinant is easy to compute, the log-likelihood of the data can be computed exactly, with no approximation, and maximized directly during training. Generating an image only requires drawing noise from a normal distribution and running the same transformation in reverse.
It was proposed in 2016 by Dinh, Sohl-Dickstein, and Bengio in the paper "Density estimation using Real NVP" (ICLR 2017). It extends NICE (2014) by the same authors and became the basis for later models such as Glow and WaveGlow. Models that build a distribution by stacking invertible transformations in this way are called normalizing flows (flow-based generative models).
Deep generative models of the time each had weaknesses.
Autoregressive models (PixelRNN and others): the likelihood is computed exactly, but pixels are generated one at a time in sequence, so generation is slow.
VAE: generation is fast, but training maximizes a lower bound rather than the log-likelihood itself, and the reconstruction error is measured with a fixed form such as squared error, so images tend to be blurry.
GAN: produces sharp images, but the likelihood cannot be computed, training tends to be unstable, and there is no encoder that maps data to latent variables.
RealNVP has properties that fill the gap between them.
Exact log-likelihood: the log-likelihood of the data is computed and maximized directly, with no approximation or lower bound.
Fast generation and inference: both generation (z→x) and inference (x→z) compute all dimensions in parallel in a single pass.
Meaningful latent space: data is mapped exactly to latent variables of the same dimension as the input.
As an everyday analogy, RealNVP is like kneading and stretching a lump of clay (the normal distribution) into a sculpture (the distribution of images) without tearing or gluing it. Because it records how much each part was stretched, it can compute exactly how densely the clay gathers at any point of the sculpture (the probability density), and kneading in reverse restores the original lump.
Theory
RealNVP maps data x to a latent variable z=f(x) with an invertible transformation f, and assumes a simple distribution pZ (a standard normal) for z.
Change-of-variables formula
If f is invertible, the probability density of the data can be written as follows (Eqs. 2–3).
logpX(x)=logpZ(f(x))+logdet(∂x⊤∂f(x))
The first term measures how likely the mapped point z is under the normal distribution, and the second term (the log-Jacobian, the log of the determinant of the Jacobian matrix) measures how much f expands or contracts volume around that point. To generate, sample z∼pZ and compute x=f−1(z).
For a general invertible function, however, computing the determinant of a high-dimensional Jacobian is very expensive. RealNVP therefore stacks simple transformations whose Jacobian is triangular, because the determinant of a triangular matrix is just the product of its diagonal entries.
Affine coupling layer
For a D-dimensional input x and d<D, the output y of an affine coupling layer is given by the following (Eqs. 4–5; right side of the figure at the top of the article).
The input is split in two: the first part passes through unchanged, and the second part is transformed by a scale exp(s) and a shift t computed from the first part. s (scale) and t (translation) are functions Rd→RD−d, and ⊙ is the element-wise product.
The Jacobian of this transformation is triangular, with the identity matrix in the upper left, zeros in the upper right, and the diagonal matrix diag(exp[s(x1:d)]) in the lower right (Eq. 6). The log-Jacobian is therefore ∑js(x1:d)j, simply the sum of the outputs of s. The inverse is also easy to compute (Eq. 8).
Neither the log-Jacobian nor the inverse involves the Jacobians or inverses of s and t. As a result, s and t can be arbitrarily complex networks, and RealNVP uses deep convolutional networks (ResNet).
Choosing the split with a mask
The split of the input can be expressed with a binary mask b (Eq. 9).
y=b⊙x+(1−b)⊙(x⊙exp(s(b⊙x))+t(b⊙x))
To exploit the correlation between nearby pixels in an image, two kinds of masks are used (lower right of the figure at the top of the article; Figure 3 of the paper).
Checkerboard mask: a checkerboard pattern that is 1 at pixels whose row and column coordinates sum to an odd number and 0 where they sum to an even number.
Channel-wise mask: 1 for the first half of the channels and 0 for the second half.
Within a single coupling layer, the part where the mask is 1 does not change. The next layer therefore flips the mask and transforms the part that the previous layer left unchanged (Figure 4 (a)). The determinant of the Jacobian of a composition is the product of the individual determinants (Eqs. 10–11), so the overall log-Jacobian is the sum of the per-layer values.
Multi-scale architecture
The whole model repeats the following procedure as one scale (Section 3.6; left side of the figure at the top of the article).
Apply three affine coupling layers with alternating checkerboard masks.
Apply a squeeze, which rearranges each 2×2 patch of each channel into 1×1×4. An s×s×c tensor becomes 2s×2s×4c, trading spatial size for channels.
Apply three affine coupling layers with alternating channel-wise masks.
Factor out half of the dimensions as z(i) and pass only the other half on to the next scale.
This repeats until the input is 4×4×c, and the final scale applies four affine coupling layers with checkerboard masks. The concatenation of everything factored out along the way is z=(z(1),…,z(L)) (Eq. 16).
The networks for s and t use batch normalization and weight normalization, and batch normalization is also applied to the whole output of each coupling layer (Section 3.7). Because batch normalization is a linear per-dimension rescaling, its log-Jacobian −21∑ilog(σ~i2+ϵ) is easy to add as well.
Why the likelihood can be computed exactly
The strength of RealNVP lies in reconciling "highly expressive networks" with "an easy-to-compute Jacobian" through the form of the affine coupling layer.
Expressiveness comes from the networks s and t
A single affine coupling layer is a weak transformation that only scales and shifts half of the dimensions. But s and t, which determine the scale and shift, depend in complex ways on the other half, so the overall transformation is powerful. Moreover, s and t never have to be inverted, so deep ResNets can be used freely.
The Jacobian reduces to the diagonal of a triangular matrix
In general, computing a high-dimensional Jacobian and its determinant is very expensive. In an affine coupling layer, the diagonal entries are just exp(sj) and 1, so it is enough to sum the outputs of s. The forward and inverse computations also cost the same (Figure 2).
The "NVP" in the name (non-volume preserving) refers to the fact that this transformation changes volume. The scale exp(s) expands and contracts space differently at each location. In the form that fixes the scale to 1 and only adds the shift t (the additive coupling layer, which the Glow paper lists as a special case), the log-Jacobian is always 0 and volume is preserved.
The multi-scale design reduces computation and separates representations into levels
Transforming every dimension all the way to the end inflates computation, memory, and parameters. Factoring out half at each stage greatly reduces computation and memory, allowing larger models to be trained. In addition, variables factored out earlier come to represent fine, local features, while those factored out later represent larger structure, so the intermediate representations are separated into levels. The loss also acts directly on intermediate layers, which makes the training signal easier to propagate.
No fixed-form reconstruction error
A VAE measures reconstruction error with a fixed form such as squared error. The paper argues that squared error weights low-frequency components heavily, which tends to make images blurry. RealNVP maximizes the likelihood directly, so it has no such constraint and produced sharp samples that are globally coherent.
Experimental results
The paper trained on CIFAR-10, ImageNet (downsampled to 32×32 and 64×64), LSUN (bedroom, tower, church outdoor), and CelebA. Evaluation uses bits per dimension (bits/dim: the negative log-likelihood in base 2 divided by the number of dimensions; lower is better) (Table 1; CIFAR-10 values are on test data, the others on validation data, with training-data values in parentheses).
Dataset
PixelRNN
RealNVP
Conv DRAW
IAF-VAE
CIFAR-10
3.00
3.49
< 3.59
< 3.28
ImageNet (32×32)
3.86 (3.83)
4.28 (4.26)
< 4.40 (4.35)
—
ImageNet (64×64)
3.63 (3.57)
3.98 (3.75)
< 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)
—
—
"<" indicates a value derived from a lower bound on the log-likelihood (the actual bits/dim is at most this value). RealNVP did not reach the autoregressive PixelRNN, but it was competitive with the other generative models. The paper notes that results improved as parameters were added, so larger models could likely improve further. On CelebA and LSUN, it reports that the validation value kept decreasing throughout training, with almost no overfitting.
Samples and latent space
Unlike a VAE, the generated images are sharp while remaining globally coherent, and on ImageNet and LSUN they appeared to capture the relationship between background and foreground, and between the direction of light sources and reflections and shadows.
Unlike autoregressive models, generation computes all dimensions in parallel.
Mapping four validation images into the latent space and moving between them with z=cosϕ(cosϕ′z(1)+sinϕ′z(2))+sinϕ(cosϕ′z(3)+sinϕ′z(4)) produced meaningful changes in the images, beyond a simple blend in pixel space (Figure 6).
Training setup
Item
Value
Networks for s, t
Convolutional ResNet with ReLU and residual connections; s multiplies tanh by a learned scale, t is an affine output
32×32 images
4 residual blocks and 32 feature maps in the first checkerboard coupling layer
64×64 images
2 residual blocks
CIFAR-10
8 residual blocks and 64 feature maps, downscaling only once
Adam (default hyperparameters), L2 regularization with coefficient 5×10−5 on the weight-normalization scale parameters
Data augmentation
Horizontal flips on CIFAR-10, CelebA, and LSUN
Practical considerations
Keep the following points in mind when using RealNVP.
Make pixel values continuous before training: RealNVP models densities over continuous values. Following the recommended procedure, the paper adds uniform noise to pixel values (dequantization) to make them continuous values in the range [0,256].
Use a transformation that avoids boundary effects: for bounded data, the density is hard to handle near the edges. The paper models the density of logit(α+(1−α)⊙256x) (α=0.05) and includes the log-Jacobian of this transformation in the likelihood and bits/dim.
Alternate the masks: within a single coupling layer, the part where the mask is 1 does not change. Unless layers are stacked with flipped masks, some dimensions are never transformed.
The latent variable has the same dimension as the data: z cannot be compressed into a smaller size. Memory and computation grow in proportion to the image size.
High likelihood is not the same as visual quality: the paper also notes that maximizing the likelihood under limited capacity favors diversity over quality, so it sometimes produces quite implausible samples (especially on CelebA).
Training distributions with scale parameters by gradient methods is known to be prone to instability (Section 3.7 of the paper). The paper builds s as the product of tanh and a learned scale, and additionally applies batch normalization to the output of each coupling layer. This batch normalization is reported to make it possible to train deep stacks of coupling layers and to ease this instability. When using batch normalization, remember to add its log-Jacobian to the likelihood as well.
Comparison with other methods
The following compares likelihood-based generative models and GANs from the same perspectives (based on the discussion in Sections 2 and 5 of the paper).
It is also compared with its successor among flows. Glow lowered bits/dim on every dataset through improvements such as replacing RealNVP's "channel permutation" with a learned invertible 1×1 convolution (values from Table 2 of the Glow paper).
Dataset
RealNVP
Glow
CIFAR-10
3.49
3.35
ImageNet (32×32)
4.28
4.09
ImageNet (64×64)
3.98
3.81
LSUN (bedroom)
2.72
2.38
Guidelines for choosing:
To compute the likelihood exactly while generating quickly: normalizing flows such as RealNVP are a good fit. Because they map data to latent variables exactly, they can also be used for interpolation and attribute manipulation.
To get the best likelihood value alone: autoregressive models have the edge, but generation is slow.
To prioritize visual quality above all: the GAN family (StyleGAN and others) is a good fit.
To get higher quality and larger images with a flow: use Glow, which develops RealNVP further. For audio, there is WaveGlow, based on the same idea.
PyTorch example
▶Show code
python
import math
import torch
import torch.nn as nn
"""
A small implementation of RealNVP by Dinh et al. (2016) (32×32 color images, 2 scales)
- Affine coupling layer (Eqs. 4–9): y = b⊙x + (1−b)⊙(x⊙exp(s(b⊙x)) + t(b⊙x)); the log-Jacobian is Σ s
- Masks: checkerboard (1 where the coordinate sum is odd) and channel-wise after squeeze (first half is 1), flipped alternately
- Multi-scale: 3 coupling layers (checkerboard) → squeeze → 3 coupling layers (channel) → factor out half as z (Section 3.6)
- Preprocessing: logit(α + (1−α)·x/256), α = 0.05 (Section 4.1). Its log-Jacobian is included in the likelihood
PyTorch has no built-in RealNVP. Batch/weight normalization inside s, t and batch normalization on the coupling-layer outputs (Section 3.7) are omitted
"""
def checkerboard(h, w, parity):
ii, jj = torch.meshgrid(torch.arange(h), torch.arange(w), indexing="ij")
return (((ii + jj) % 2) == parity).float()[None, None] # [1, 1, h, w]
def channel_mask(c, parity):
m = torch.zeros(1, c, 1, 1)
m[:, : c // 2] = 1.0
return m if parity == 1 else 1.0 - m
class ResNetST(nn.Module):
"""Network that outputs s and t (convolutions with ReLU and residual connections)"""
def __init__(self, c, hidden=64, blocks=2):
super().__init__()
self.inp = nn.Conv2d(c, hidden, 3, padding=1)
self.blocks = nn.ModuleList([
nn.Sequential(nn.ReLU(), nn.Conv2d(hidden, hidden, 3, padding=1), nn.ReLU(), nn.Conv2d(hidden, hidden, 3, padding=1))
for _ in range(blocks)])
self.out = nn.Conv2d(hidden, 2 * c, 3, padding=1)
self.s_scale = nn.Parameter(torch.zeros(1, c, 1, 1)) # s = (learned scale) × tanh(·)
def forward(self, x):
h = self.inp(x)
for blk in self.blocks:
h = h + blk(h)
s, t = self.out(torch.relu(h)).chunk(2, dim=1)
return self.s_scale * torch.tanh(s), t
class AffineCoupling(nn.Module):
def __init__(self, c, mask):
super().__init__()
self.register_buffer("b", mask)
self.net = ResNetST(c)
def forward(self, x): # x → y and the log-Jacobian
s, t = self.net(self.b * x)
s, t = (1 - self.b) * s, (1 - self.b) * t # leave entries where the mask is 1 unchanged
y = self.b * x + (1 - self.b) * (x * torch.exp(s) + t)
return y, s.flatten(1).sum(1)
def inverse(self, y): # y → x (Eq. 8). No inverse of s, t is needed
s, t = self.net(self.b * y)
s, t = (1 - self.b) * s, (1 - self.b) * t
return self.b * y + (1 - self.b) * ((y - t) * torch.exp(-s))
def squeeze(x): # [B, C, H, W] → [B, 4C, H/2, W/2]
b, c, h, w = x.shape
x = x.view(b, c, h // 2, 2, w // 2, 2).permute(0, 1, 3, 5, 2, 4)
return x.reshape(b, c * 4, h // 2, w // 2)
def unsqueeze(x): # inverse of squeeze
b, c, h, w = x.shape
x = x.view(b, c // 4, 2, 2, h, w).permute(0, 1, 4, 2, 5, 3)
return x.reshape(b, c // 4, h * 2, w * 2)
class RealNVP(nn.Module):
def __init__(self, c=3, size=32):
super().__init__()
h = size
# scale 1 (32×32×3)
self.s1_a = nn.ModuleList([AffineCoupling(c, checkerboard(h, h, k % 2)) for k in range(3)])
self.s1_b = nn.ModuleList([AffineCoupling(4 * c, channel_mask(4 * c, k % 2)) for k in range(3)])
# final scale (16×16×6 after factoring out half): 4 checkerboard coupling layers
self.s2 = nn.ModuleList([AffineCoupling(2 * c, checkerboard(h // 2, h // 2, k % 2)) for k in range(4)])
def forward(self, x): # x → z, sum of log-Jacobians
logdet = torch.zeros(x.size(0), device=x.device)
for layer in self.s1_a:
x, ld = layer(x); logdet = logdet + ld
x = squeeze(x)
for layer in self.s1_b:
x, ld = layer(x); logdet = logdet + ld
z1, x = x.chunk(2, dim=1) # factor out half early as z(1)
for layer in self.s2:
x, ld = layer(x); logdet = logdet + ld
return torch.cat([z1.flatten(1), x.flatten(1)], dim=1), logdet
@torch.no_grad()
def sample(self, n, size=32):
z = torch.randn(n, 3 * size * size)
half = z.size(1) // 2
z1 = z[:, :half].view(n, 6, size // 2, size // 2)
x = z[:, half:].view(n, 6, size // 2, size // 2)
for layer in reversed(self.s2):
x = layer.inverse(x)
x = torch.cat([z1, x], dim=1)
for layer in reversed(self.s1_b):
x = layer.inverse(x)
x = unsqueeze(x)
for layer in reversed(self.s1_a):
x = layer.inverse(x)
return 256 * (torch.sigmoid(x) - 0.05) / 0.95 # inverse of the preprocessing (pixel values in 0–256)
ALPHA = 0.05
def preprocess(x_uint8):
"""x: integer pixels in 0–255. Dequantize with uniform noise and use logit to avoid boundary effects"""
x = x_uint8.float() + torch.rand_like(x_uint8.float()) # [0, 256)
p = ALPHA + (1 - ALPHA) * x / 256
y = torch.log(p) - torch.log1p(-p) # logit(p)
# sum the log of dy/dx = (1−α)/256 / (p(1−p)) over all pixels
logdet = (math.log(1 - ALPHA) - math.log(256) - torch.log(p) - torch.log1p(-p)).flatten(1).sum(1)
return y, logdet
def bits_per_dim(model, x_uint8):
y, ld_pre = preprocess(x_uint8)
z, ld = model(y)
log_pz = -0.5 * (z.pow(2) + math.log(2 * math.pi)).sum(1) # standard normal
log_px = log_pz + ld + ld_pre # change-of-variables formula (Eq. 3)
dims = x_uint8[0].numel()
return (-log_px / (dims * math.log(2))).mean()
model = RealNVP()
opt = torch.optim.Adam(model.parameters(), lr=1e-3) # the paper uses Adam's defaults
x = torch.randint(0, 256, (8, 3, 32, 32)) # in practice, images from a dataset
loss = bits_per_dim(model, x)
opt.zero_grad()
loss.backward()
opt.step()
images = model.sample(4) # [4, 3, 32, 32]
FAQ
Q. Why can RealNVP compute the likelihood without approximation?
A.
Because every transformation is invertible and its log-Jacobian is easy to compute. By the change-of-variables formula, logpX(x)=logpZ(f(x))+log∣det(∂f/∂x⊤)∣. The Jacobian of an affine coupling layer is triangular, so its determinant is the product of the diagonal entries and the log-Jacobian is the sum of the outputs of s. Training maximizes this value itself, not a lower bound as in a VAE.
Q. Why can $s$ and $t$ in an affine coupling layer be complex networks?
A.
The inverse of a coupling layer is xd+1:D=(yd+1:D−t(y1:d))⊙exp(−s(y1:d)), which only recomputes s and t from the passed-through y1:d. The Jacobians of s and t do not appear in the log-Jacobian either. Since s and t never need to be inverted, the paper uses deep convolutional ResNets.
Q. How do RealNVP and Glow differ?
A.
Glow is a flow built on RealNVP. It replaces the channel permutation with a learned invertible 1×1 convolution, replaces batch normalization with actnorm, and drops the checkerboard mask in favor of channel-wise splitting only. CIFAR-10 bits/dim dropped from RealNVP's 3.49 to 3.35, and it became possible to generate 256×256 face images.