Foundations to Frontier
Tests
H. Generative Models › H5 Normalizing Flows

RealNVP: affine coupling and multi-scale flows

RealNVP (real-valued non-volume preserving transformations; Dinh, Sohl-Dickstein and Bengio, 2016) extended NICE with the affine coupling layer: the transformed half is scaled by exp(s(x_A)) and shifted by t(x_A), where s and t are arbitrary networks of the kept half. The Jacobian stays triangular, so the log-determinant is just the sum of s, but now volume can change differently at every point. RealNVP also introduced checkerboard and channel masks, the squeeze operation, a multi-scale architecture that factors out half the dimensions at each level, and batch normalisation inside the flow; it produced the first sharp samples from an exact-likelihood model on CelebA and LSUN. This page covers all of these and the stability tricks (bounded log-scales, zero-initialised last layers). In the exercises you build the affine coupling and its inverse, then compare additive and affine coupling at equal depth and training budget. On a funnel density, where the spread of x2 depends on x1, affine coupling closed about 95% of the gap to the true density (2.892 against 2.878 nats) while additive stalled at 3.146. On two moons the difference was within seed-to-seed noise: affine won on two seeds and lost on one.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Stretch as well as shift

NICE could only slide points, never stretch them. RealNVP lets each coupling layer also stretch or squeeze the moving half, by an amount that depends on where the point is. That small change makes a big difference: a cloud can become thin in one place and wide in another, like a river that narrows through a gorge and spreads across a delta. The layer is still easy to undo and its volume change is easy to compute. In the demo, raise the scale slider to see local stretching appear.

Flow lab
The second coordinate is scaled by exp(s·sin 2u) and shifted by t·u², where u is the first coordinate after mixing. Log-det per point ranges from -0.60 to 0.60.
Why engineers care

RealNVP-style coupling flows remain the workhorse for neural posterior estimation, Boltzmann generators for molecular configurations, and fast samplers for simulation-based inference.

📝 Quick check (Level 0)
0/3 answered
  1. 1. Affine coupling adds to NICE…
  2. 2. Its inverse needs…
  3. 3. Its log-det is…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

The RealNVP toolbox

  • Affine coupling: y_A = x_A, y_B = x_B ⊙ exp(s(x_A)) + t(x_A); log-det = Σ s(x_A).
  • Inverse: x_B = (y_B − t(y_A)) ⊙ exp(−s(y_A)); s and t (deep ResNets in the paper) are never inverted.
  • Masks: checkerboard (alternating pixels) and channel-wise splits, alternated so every variable is updated.
  • Squeeze: reshape C×H×W into 4C×H/2×W/2 so channel masks can mix spatial neighbours.
  • Multi-scale: after a few couplings, factor out half the variables as latents and keep transforming the other half; this saves compute and gives a hierarchy of latents.
  • Stability: bound s (tanh times a learned scale, or soft clamping), zero-initialise the last layer so each coupling starts as the identity, use weight normalisation.
  • Batch normalisation as a flow layer: a per-dimension affine map using batch (training) or running (evaluation) statistics, with its own log-det.
  • Preprocessing: dequantise pixels, then logit(α + (1 − 2α) x) to map [0, 1] to the real line, counting that transform’s log-det.
📝 Quick check (Level 1)
0/3 answered
  1. 1. The squeeze operation turns C×H×W into…
  2. 2. Zero-initialising the last layer makes each coupling start as…
  3. 3. Multi-scale architectures factor out…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

Building affine couplings

Exercise 1.

  • Affine coupling forward with its log-det.
  • The inverse.
  • A soft clamp for the log-scale.

Practice.

  • Bound log-scales (tanh or soft clamp) and zero-initialise the output layer.
  • Check log-det against a finite-difference Jacobian on a few points.
  • For images, use the squeeze + checkerboard / channel masks and a multi-scale design; for tabular data, alternate or randomly permute features.
  • Use normflows, nflows, Zuko (PyTorch) or distrax / TensorFlow Probability (JAX) rather than hand-rolling for production.
  • Watch for NaNs from exp(s): clip gradients and use a modest learning rate.
import torch, normflows as nf
base = nf.distributions.DiagGaussian(2)
flows = []
for i in range(8):
    param_map = nf.nets.MLP([1, 64, 64, 2], init_zeros=True)      # outputs (shift, log-scale)
    flows += [nf.flows.AffineCouplingBlock(param_map), nf.flows.Permute(2, mode="swap")]
model = nf.NormalizingFlow(base, flows)
loss = model.forward_kld(x_batch)          # = mean NLL; backpropagate and step an optimizer
🐍 Exercise 1: affine coupling
Write the affine coupling layer, its inverse and a soft clamp for the log-scale.
📝 Quick check (Level 2)
0/3 answered
  1. 1. NaNs in RealNVP training usually come from…
  2. 2. For tabular data, between couplings…
  3. 3. A PyTorch library for flows is…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

Log-det. The Jacobian of an affine coupling is [[I, 0], [∂y_B/∂x_A, diag(exp(s(x_A)))]], block lower-triangular, so log |det| = Σ_j s_j(x_A). Computing it is free: s is already evaluated in the forward pass.

Expressiveness. Each coupling is a conditionally affine (Gaussian-like) update, so a single layer can only model x_B given x_A as a location-scale family. Depth composes these into non-Gaussian conditionals. Affine coupling flows are universal approximators in distribution given enough layers (Teshima et al., 2020), but the required depth can be large for multimodal conditionals, which motivated spline couplings.

When scaling matters. If the conditional spread of x_B varies with x_A (heteroscedastic structure such as a funnel), additive coupling must emulate scaling with many shears, while one affine layer can represent it directly: for the funnel, s(x1) = −x1 maps x2 | x1 to a standard normal.

Exercise check. On the funnel, with 4 layers and 350 Adam steps, affine coupling reached 2.892 nats against 2.878 for the true density; additive coupling 3.146. The per-point log-det had a standard deviation of 0.96 nats: the layer really did scale differently in different places.

📝 Quick check (Level 3)
0/3 answered
  1. 1. The affine coupling log-det is computed…
  2. 2. One affine coupling models x_B given x_A as…
  3. 3. For the funnel, the ideal log-scale is…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

When does affine coupling beat additive coupling at the same depth and budget?

History.

  • L. Dinh, J. Sohl-Dickstein and S. Bengio, “Density estimation using Real NVP” (ICLR 2017; arXiv 2016).
  • R. M. Neal, “Slice sampling” (2003): the funnel as a hard test density.
  • T. Teshima et al., “Coupling-based invertible neural networks are universal diffeomorphism approximators” (NeurIPS 2020).

Exercise 2. Two 2-D densities, 2000 training and 2000 test points each.

  • Funnel: x1 ~ N(0, 1), x2 given x1 ~ N(0, exp(x1)²), exact density known.
  • Moons: two moons, noise 0.08, standardised; reference NLL by quadrature.
  • Models: 4 coupling layers alternating halves, conditioner 1 → 16 tanh → 2, final diagonal scaling; additive (s = 0) versus affine (s = 2 tanh(raw/2)). Adam, learning rate 0.02, batch 256, 350 steps.
data model seed 0 seed 1 seed 2
funnel Gaussian 3.890 3.783 3.728
funnel additive 3.146 3.074 3.130
funnel affine 2.892 2.830 2.906
funnel true 2.878 2.818 2.881
moons Gaussian 2.740 2.735 2.733
moons additive 2.119 1.967 1.987
moons affine 2.064 2.094 1.796
moons true 1.643 1.610 1.618
  • Funnel: affine coupling closed 90–95% of the additive model’s gap to the true density, landing within 0.03 nats of it on every seed.
  • Moons (a mixed result): the winner changed with the seed (gap closed 0.12, −0.36 and 0.52); at this budget, optimisation noise mattered as much as the layer type.
  • Lesson: affine scaling pays off when the data have position-dependent spread; for thin curved manifolds, depth and training time limit both models.
  • Caveat: small models and 350 steps; longer training generally favours affine coupling.
🐍 Exercise 2 (research): when does affine coupling beat additive coupling at the same depth and budget?
Compare additive and affine coupling flows at equal depth and budget on a funnel and on two moons.

RealNVP in AI, robotics and aerospace

  • Simulation-based inference: conditional affine-coupling flows estimate posteriors over physical parameters (e.g. gravitational-wave source parameters in DINGO, atmospheric retrievals for exoplanets).
  • Boltzmann generators: RealNVP flows sample molecular configurations with exact importance weights (Noé et al., Science 2019).
  • Robotics: flows model multimodal action or grasp distributions and serve as exact-likelihood priors in planners.

References

  1. L. Dinh, J. Sohl-Dickstein and S. Bengio (2017). “Density estimation using Real NVP.” ICLR.
  2. F. Noé, S. Olsson, J. Köhler and H. Wu (2019). “Boltzmann generators: sampling equilibrium states of many-body systems with deep learning.” Science.
  3. T. Teshima et al. (2020). “Coupling-based invertible neural networks are universal diffeomorphism approximators.” NeurIPS.
  4. M. Dax et al. (2021). “Real-time gravitational wave science with neural posterior estimation.” Physical Review Letters.