Glow is a generative model (normalizing flow) that treats actnorm, an invertible 1×1 convolution, and an affine coupling layer as one "flow step" and stacks many of them to map images invertibly to Gaussian noise. It simplifies the architecture of RealNVP and replaces its channel permutation with a "learned invertible 1×1 convolution." It can be trained by computing the log-likelihood exactly, without approximation, and it can realistically generate and edit large images such as 256×256 faces.
Kingma and Dhariwal of OpenAI proposed it in 2018 in the paper "Glow: Generative Flow with Invertible 1×1 Convolutions" (NeurIPS 2018).
There are three families of likelihood-based generative models.
Autoregressive models (PixelCNN and others): Simple, but generation cost grows with the data dimension, making them hard to parallelize for large images.
VAEs: Both training and generation can be parallelized, but they maximize a lower bound on the log-likelihood, which can make optimization difficult.
Flow-based generative models (NICE, RealNVP): Models that stack invertible transformations.
The paper lists the following advantages of flows.
Exact latent variables and log-likelihood: VAEs can only infer latent variables approximately, and GANs have no encoder at all. Flows compute both without approximation and can maximize the log-likelihood itself rather than a lower bound.
Parallel inference and generation: Unlike autoregressive models, both can be computed at once.
A latent space useful for downstream tasks: It supports interpolation between images and editing attributes (smiles, hair color, and so on).
Room for memory savings: Because the model is invertible, layer outputs can be recomputed backward instead of stored, allowing gradients to be computed with memory that does not depend on depth.
At a time when flows drew less attention than GANs or VAEs, Glow showed that a model trained purely on likelihood can efficiently generate large, realistic images.
Theory
Glow maps data x to a latent variable z through a sequence of invertible transformations f=f1∘f2∘⋯∘fK and assumes a standard normal distribution N(0,I) for z. Writing the intermediate values as h0=x,h1,…,hK=z, the log-likelihood is computed as follows (Equations 6–7).
logpθ(x)=logpθ(z)+i=1∑Klogdet(dhi−1dhi)
The key is to design every layer so that each term log∣det(dhi/dhi−1)∣ (the log-determinant) is easy to compute.
One flow step
One step applies the following three layers in this order (right side of the figure at the top of the article; Table 1 of the paper). Inputs and outputs are h×w×c tensors, and (i,j) is a spatial position.
Layer
Forward
Reverse
Log-determinant
actnorm
yi,j=s⊙xi,j+b
xi,j=(yi,j−b)/s
h⋅w⋅sum(log∣s∣)
Invertible 1×1 convolution
yi,j=Wxi,j
xi,j=W−1yi,j
h⋅w⋅log∣detW∣
Affine coupling layer
See below
See below
sum(log∣s∣)
actnorm: A layer that normalizes values like batch normalization, using a per-channel scale s and bias b. On the first mini-batch, s and b are initialized so that the output has zero mean and unit variance per channel (data-dependent initialization); after that they are trained as ordinary parameters.
Invertible 1×1 convolution: A c×c matrix W mixes the channels at each position. It generalizes RealNVP's fixed permutation, which reversed the channel order, into a learned transformation. W is initialized as a random rotation matrix (log-determinant 0).
Affine coupling layer: Splits the channels in half and transforms one half with a scale and shift computed from the other half (the same idea as in RealNVP).
The forward computation of the affine coupling layer is:
Finally, y=concat(ya,yb). The reverse recomputes logs,t with the same NN from the passed-through yb and recovers xa=(ya−t)/s. The NN is three convolution layers (3×3, 1×1, 3×3) with 512 hidden channels and ReLU. The split is along the channel dimension only, without RealNVP's checkerboard. Fixing s=1 gives what is called an additive coupling layer, whose log-determinant is 0.
Multi-scale architecture
The overall model uses the same multi-scale architecture as RealNVP (left side of the figure at the top of the article; Figure 2 (b)).
Squeeze halves the height and width and quadruples the channels.
Apply K flow steps.
Split the channels in half, emit one half early as zl, and pass the rest to the next level.
Repeat steps 1–3 L−1 times; at the last level, apply only squeeze and K flow steps to produce zL.
Training on continuous values
Because pixel values are discrete, the model minimizes the negative log-likelihood of x~=x+u, with uniform noise u∼U(0,a) added (Equation 2). a is determined by the discretization level of the data, and adding the constant c=−Mloga (M is the dimension of x) gives the expected compression cost measured in bits.
Why It Improves on RealNVP
Each of Glow's three layers addresses a weakness of RealNVP.
Invertible 1×1 convolution: letting every dimension affect every other dimension
A coupling layer passes half of the dimensions through unchanged, so unless dimensions are shuffled between layers, some dimensions are never transformed. RealNVP used a fixed permutation that reversed the channel order. A 1×1 convolution is a more general linear transformation that includes permutations as a special case, and how to mix can be learned from data.
Computing detW costs O(c3), comparable to the cost of the convolution itself, O(h⋅w⋅c2). Furthermore, parameterizing W directly in LU-decomposed form reduces this to O(c) (Equations 10–11).
W=PL(U+diag(s)),log∣detW∣=sum(log∣s∣)
P is a permutation matrix (fixed), L is a lower triangular matrix with ones on the diagonal, U is an upper triangular matrix with zeros on the diagonal, and s is a vector. Starting from the decomposition of a random rotation matrix, L, U, and s are learned. The paper notes that at the scale of its experiments, the difference in actual wall-clock time was not large.
actnorm: normalization that works even with small mini-batches
RealNVP used batch normalization, but the noise batch normalization adds grows as the mini-batch per device shrinks, which hurts performance. For large images, memory constraints required a mini-batch of 1 per device. actnorm uses data statistics only at initialization and afterward acts as a scale and bias independent of the mini-batch, so it does not have this problem.
Zero initialization: starting a deep network from the identity
Initializing the last convolution of each coupling layer's NN to zero gives logs=0 and t=0 at the start of training, so each coupling layer returns its input unchanged. The paper reports that this helped train very deep networks.
For all three layers, the log-determinant comes down to "the sum of log scales" or "the determinant of a small matrix," and the reverse computation is about as cheap as the forward one. Most of the expressive power comes from the coupling layer's NN. Since the NN never needs to be inverted, any ordinary convolutional network can be used.
Experimental Results
Effect of the invertible 1×1 convolution
On CIFAR-10, three kinds of channel permutation were compared: reversal as in RealNVP, a fixed random permutation, and the invertible 1×1 convolution (Figure 3). With K=32 and L=3, conditions were matched and results averaged over three random seeds.
With both additive and affine coupling layers, the 1×1 convolution reached the lowest negative log-likelihood and also converged fastest.
Affine coupling layers converged faster than additive ones.
The 1×1 convolution increased the number of parameters by 0.2% and computation time by about 7%.
Comparison with RealNVP
Using the same preprocessing as RealNVP, bits per dimension (bits/dim, lower is better) were compared (Table 2).
Glow improved on every dataset. Training used Adam (learning rate 0.001); for example, CIFAR-10 used a mini-batch of 512 with L=3 and K=32, and ImageNet (64×64) and LSUN used a mini-batch of 128 with L=4 and K=48 (Appendix C).
Generating and editing large images
The model was trained on CelebA-HQ (30,000 images) at 256×256 with K=32 and L=6. To improve visual quality at a slight cost to color fidelity, it was trained on 5-bit images, with a mini-batch of 1 per device and gradient checkpointing.
Sampling at a lower temperature: At temperature T, samples are drawn from pθ,T(x)∝(pθ(x))T2 (with additive coupling layers, this simply multiplies the standard deviation of pθ(z) by T). High temperatures produced noisy images, so T=0.7 was chosen as a good balance of quality and diversity (Figure 8).
Speed: Generating one 256×256 image took about 130 ms on a single 1080 Ti and about 550 ms on a K80.
Interpolation: Encoding two real images and linearly interpolating their latent variables produced natural-looking faces for nearly all intermediate images (Figure 5).
Attribute editing: After training, for each CelebA label (smiling, blond hair, young, and so on), the mean latent zpos of images with the attribute and the mean zneg of images without it were computed; moving along the difference zpos−zneg changed that attribute (Figure 6). No labels were used during training.
Effect of depth: A deeper model with L=6 levels captured relationships between distant parts of the image better than a shallower model with L=4 (Figure 9).
Practical Considerations
Keep the following points in mind when using Glow.
Initialize actnorm with data: Pass the first mini-batch through and set the scale and bias so that the output has zero mean and unit variance per channel before training begins.
Initialize the last layer of the coupling NN to zero: Each coupling layer then starts as the identity, allowing deep networks to train stably.
Adjust sampling with the temperature: At temperature 1, images tend to be noisy; the paper chose 0.7. Lowering the temperature raises quality and reduces diversity.
The latent variable has the same dimension as the data: z cannot be compressed to a smaller size.
For large images, memory is the tightest constraint. For 256×256 images, the paper used a mini-batch of 1 per device and gradient checkpointing. It also trained on 5-bit images to improve visual quality, which slightly reduces color fidelity. Exploiting invertibility to train with memory independent of depth is left as future work.
Comparison with Other Methods
Among flow-based generative models, RealNVP and Glow compare as follows.
You want exact likelihoods plus image interpolation and editing: Normalizing flows such as Glow are a good fit. Attribute directions are easy to compute after training.
You want the best visual quality: The GAN family (such as StyleGAN) is a strong choice. The Glow paper also acknowledges that GANs are known for generating large, realistic images. At the same time, it lists GAN weaknesses: no encoder, a tendency not to cover the full data distribution, difficult optimization, and difficulty assessing overfitting.
You want to try flows or understand their structure: Glow is simpler than RealNVP. Reading it alongside RealNVP, on which it is based, makes the differences easy to see.
You want to generate audio: WaveGlow applies Glow to speech.
PyTorch example
▶Show code
python
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
"""
A small implementation of Glow from Kingma & Dhariwal (2018) (Table 1, Section 3, Equations 2 and 9–11)
- One flow step: actnorm → invertible 1×1 convolution (LU-decomposed form) → affine coupling layer
- Affine coupling layer: x_a, x_b = split(x), (log s, t) = NN(x_b), y_a = s ⊙ x_a + t, y_b = x_b
- Multi-scale: squeeze → step × K → split, L − 1 times; the last level is squeeze → step × K
PyTorch has no built-in Glow (the official implementation is openai/glow on GitHub, in TensorFlow)
"""
class ActNorm(nn.Module):
def __init__(self, c):
super().__init__()
self.logs = nn.Parameter(torch.zeros(1, c, 1, 1))
self.b = nn.Parameter(torch.zeros(1, c, 1, 1))
self.register_buffer("initialized", torch.tensor(False))
def forward(self, x):
if not self.initialized: # data-dependent init: zero mean, unit variance on the first mini-batch
with torch.no_grad():
mean = x.mean(dim=(0, 2, 3), keepdim=True)
std = x.std(dim=(0, 2, 3), keepdim=True) + 1e-6
self.b.data.copy_(-mean / std)
self.logs.data.copy_(-torch.log(std))
self.initialized.fill_(True)
y = x * torch.exp(self.logs) + self.b
logdet = x.size(2) * x.size(3) * self.logs.sum() # h·w·sum(log|s|)
return y, logdet
def inverse(self, y):
return (y - self.b) * torch.exp(-self.logs)
class InvConv1x1LU(nn.Module):
"""W = P L (U + diag(s)). log|det W| = sum(log|s|) (Equations 10–11)"""
def __init__(self, c):
super().__init__()
w = torch.linalg.qr(torch.randn(c, c))[0] # initialize with a random rotation matrix
P, L, U = torch.linalg.lu(w)
s = torch.diagonal(U)
self.register_buffer("P", P) # the permutation matrix is fixed
self.register_buffer("sign_s", torch.sign(s))
self.register_buffer("l_mask", torch.tril(torch.ones(c, c), -1))
self.L = nn.Parameter(L)
self.U = nn.Parameter(torch.triu(U, 1))
self.log_s = nn.Parameter(torch.log(torch.abs(s)))
def weight(self):
c = self.L.size(0)
L = self.L * self.l_mask + torch.eye(c, device=self.L.device) # lower triangular with ones on the diagonal
U = self.U * self.l_mask.T + torch.diag(self.sign_s * torch.exp(self.log_s))
return self.P @ L @ U
def forward(self, x):
W = self.weight()
y = F.conv2d(x, W[:, :, None, None])
return y, x.size(2) * x.size(3) * self.log_s.sum() # h·w·log|det W|
def inverse(self, y):
W_inv = torch.inverse(self.weight())
return F.conv2d(y, W_inv[:, :, None, None])
class AffineCoupling(nn.Module):
def __init__(self, c, hidden=512):
super().__init__()
self.nn = nn.Sequential(
nn.Conv2d(c // 2, hidden, 3, padding=1), nn.ReLU(),
nn.Conv2d(hidden, hidden, 1), nn.ReLU(),
nn.Conv2d(hidden, c, 3, padding=1), # log s and t (c/2 each)
)
nn.init.zeros_(self.nn[-1].weight) # zero-init the last convolution → start from the identity
nn.init.zeros_(self.nn[-1].bias)
def forward(self, x):
x_a, x_b = x.chunk(2, dim=1)
log_s, t = self.nn(x_b).chunk(2, dim=1)
y_a = torch.exp(log_s) * x_a + t
return torch.cat([y_a, x_b], dim=1), log_s.flatten(1).sum(1)
def inverse(self, y):
y_a, y_b = y.chunk(2, dim=1)
log_s, t = self.nn(y_b).chunk(2, dim=1) # recompute from the passed-through y_b
return torch.cat([(y_a - t) * torch.exp(-log_s), y_b], dim=1)
class FlowStep(nn.Module):
def __init__(self, c):
super().__init__()
self.layers = nn.ModuleList([ActNorm(c), InvConv1x1LU(c), AffineCoupling(c)])
def forward(self, x):
logdet = 0
for layer in self.layers:
x, ld = layer(x)
logdet = logdet + ld
return x, logdet
def inverse(self, y):
for layer in reversed(self.layers):
y = layer.inverse(y)
return y
def squeeze(x):
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):
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 Glow(nn.Module):
def __init__(self, c=3, K=8, L=3): # the paper's CIFAR-10 setup is K = 32, L = 3
super().__init__()
self.levels = nn.ModuleList()
for l in range(L):
c = c * 4 # squeeze quadruples the channels
self.levels.append(nn.ModuleList([FlowStep(c) for _ in range(K)]))
if l < L - 1:
c = c // 2 # split emits half early
def forward(self, x):
logdet, zs = 0, []
for l, steps in enumerate(self.levels):
x = squeeze(x)
for step in steps:
x, ld = step(x)
logdet = logdet + ld
if l < len(self.levels) - 1:
z, x = x.chunk(2, dim=1) # emit early as z_l
zs.append(z)
zs.append(x) # z_L
return zs, logdet
@torch.no_grad()
def sample(self, zs):
x = zs[-1]
for l in reversed(range(len(self.levels))):
if l < len(self.levels) - 1:
x = torch.cat([zs[l], x], dim=1)
for step in reversed(self.levels[l]):
x = step.inverse(x)
x = unsqueeze(x)
return x
def bits_per_dim(model, x, n_bins=256):
"""x: image scaled to 0–1. Make it continuous with uniform noise and compute the negative log-likelihood (Equation 2)"""
M = x[0].numel()
x = x + torch.rand_like(x) / n_bins # u ~ U(0, a), a = 1/n_bins
zs, logdet = model(x - 0.5)
log_pz = sum((-0.5 * (z ** 2 + math.log(2 * math.pi))).flatten(1).sum(1) for z in zs)
log_px = log_pz + logdet - M * math.log(n_bins) # c = −M·log a
return (-log_px / (M * math.log(2))).mean()
model = Glow()
opt = torch.optim.Adam(model.parameters(), lr=1e-3) # paper: Adam, α = 0.001
x = torch.rand(16, 3, 32, 32) # images from the dataset in practice
loss = bits_per_dim(model, x) # actnorm is initialized on the first call
opt.zero_grad()
loss.backward()
opt.step()
# Sample at temperature T (0.7 in the paper; it is exactly p^(T^2) only with additive coupling layers)
T = 0.7
with torch.no_grad():
zs, _ = model(torch.rand(4, 3, 32, 32) - 0.5) # to get the shapes of z
images = model.sample([T * torch.randn_like(z) for z in zs]) + 0.5
FAQ
Q. What is the invertible 1×1 convolution for?
A.
An affine coupling layer passes half of the dimensions through unchanged, so unless dimensions are mixed between layers, some dimensions are never transformed. RealNVP used a fixed permutation that reversed the channel order, while Glow replaced it with a 1×1 convolution using a learned c×c matrix W. Since a permutation is a special case of a 1×1 convolution, this is more general, and how to mix can be learned from data. In the CIFAR-10 experiments, it lowered the negative log-likelihood and sped up convergence.
Q. How does actnorm differ from batch normalization?
A.
Both normalize values with a per-channel scale and bias, but batch normalization uses the statistics of each mini-batch every time, while actnorm uses the first mini-batch's statistics only to initialize the scale and bias and then trains them as ordinary parameters. Batch normalization degrades with small mini-batches, but actnorm does not depend on mini-batch size. Glow needed this property because it used a mini-batch of 1 per device for large images.
Q. What is the "temperature" in Glow?
A.
It is a value T that controls how tightly the distribution is concentrated around its mean during sampling. At temperature T, samples are drawn from pθ,T(x)∝(pθ(x))T2, which, with additive coupling layers, amounts to simply multiplying the standard deviation of the latent variable by T. Lowering the temperature raises image quality and reduces diversity. The paper chose T=0.7 as a good balance between quality and diversity.