Lecture 5 · Flow Models I: Change of Variables in One and Two Dimensions

Deep Unsupervised Learning · Lecture 05。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

个人整理的学习笔记,非官方讲义;课程来源与整理说明见课程介绍。配套示例未逐一运行验证。

本篇目录

Maps to: UC Berkeley CS294-158 Deep Unsupervised Learning (Spring 2024), Lecture 3 · Thu 2/1/2024 · Likelihood Models: Flow Models, first part (slides 1–41): what we want from a generative model, a density-model refresher, the mixture-of-Gaussians aside, flows as invertible maps from data to an embedding, the change-of-variables formula, training, 1-D flows to Gaussian / uniform / Beta bases, CDFs as flows, how general flows are, 2-D autoregressive flows (two moons, a face), autoregressive and inverse autoregressive flows, distilling one into the other. Basis: The slides state the formulas and show trained flows as pictures. These notes derive change of variables from “probability is conserved”, prove that a CDF flow is exactly a mixture density and that 1-D flows are universal, and run every claim on toy densities whose log-densities are known exactly — so each trained flow is measured against the truth, as ShapeWorld does for discrete images. The AF vs IAF trade-off is timed, and distillation is tested on data where it works and on data where it does not. Code: code/lecture05/ (4 scripts + flows.py; PyTorch (CPU); 3 s to ~100 s each) Reading time: 3–4 hours including running the code


0. How to read this lecture

0.1 Learning goals

After this lecture you should be able to:

  1. List what we want from a generative model (fit, density evaluation, sampling, a latent space) and say which boxes autoregressive models leave empty and why flows promise to fill them.
  2. Explain why a mixture of Gaussians works in one dimension and fails on images (samples = stored centers + noise).
  3. Derive the change-of-variables formula pX(x)=pZ(f(x)) ∣f′(x)∣p_X(x) = p_Z(f(x))\,|f'(x)| from conservation of probability, and explain why forgetting ∣f′∣|f'| breaks normalization.
  4. Train a 1-D flow by maximum likelihood towards any base distribution; show that a CDF flow with a uniform base is a mixture density model; argue that 1-D flows are universal.
  5. Sample from a flow by inverting it, including by bisection when no closed-form inverse exists.
  6. Build a 2-D autoregressive flow and explain why its conditioner can be any network while each conditional map must be monotone.
  7. Write the MAF and IAF equations, explain their triangular Jacobians, count their network passes, and explain probability density distillation — and when an IAF cannot imitate its teacher.

0.2 Prerequisites and scope

AssumedIntroduced hereDeveloped later
Lecture 2 (maximum likelihood = KL, CDFs and inverse-CDF sampling, mixtures of logistics)change of variables in 1-D and 2-D, base distributions, CDF flowschange of many variables, coupling layers, Glow (Lecture 6)
Lecture 3 (MADE masks, the chain rule, sequential sampling)autoregressive flows (MAF), inverse autoregressive flows (IAF)dequantization: flows on discrete data (Lecture 6)
derivatives, the chain rule of calculusprobability density distillationIAF posteriors in VAEs (Lecture 8); flows for compression (Lecture 21)

0.3 Map

§1  what we want from a generative model; continuous densities; why not a mixture of Gaussians   ← code 01
§2  flows and the change-of-variables formula                                                    ← code 02 (Part 1)
§3  one-dimensional flows: bases, CDF flows, universality, sampling by inversion                ← code 02
§4  two-dimensional autoregressive flows                                                         ← code 03
§5  N dimensions: autoregressive vs inverse autoregressive flows, distillation                  ← code 04
§6  summary   §7 pitfalls   §8 exercises   §9 further reading   §10 next lecture

0.4 Notation

SymbolMeaning
x∈RDx \in \mathbb{R}^Da data point (continuous in this lecture)
z=fθ(x)z = f_\theta(x)the flow: an invertible, differentiable map from data to latent; x=fθ−1(z)x = f_\theta^{-1}(z)
pZp_Zthe base distribution of zz (standard normal, uniform on (0,1)D(0,1)^D, Beta)
∂f/∂x\partial f / \partial xthe Jacobian matrix (D×DD \times D); in 1-D just f′(x)f'(x)
log⁡∣det⁡∣\log\lvert\det\rvert, “logdet”log⁡∣det⁡∂f/∂x∣\log \lvert \det \partial f/\partial x \rvert, one number per data point
h(X)h(X)differential entropy −E[log⁡p(X)]-E[\log p(X)] in nats
AF / MAF, IAF(masked) autoregressive flow, inverse autoregressive flow

0.5 How the experiments are run

Continuous data have densities, so all numbers in this lecture are negative log-densities in nats (natural logs) per data point — they can be negative, and they are compared with the exact differential entropy or, better, with the true density’s NLL on the same test points (Lecture 4’s lesson: a finite test set has its own “truth”). The toy distributions live in flows.py, each with an exact log_prob:

namewhat it isexact hh (nats)
WORLD_1Dmixture of 3 Gaussians: weights 0.45 / 0.20 / 0.35, means −2 / 0.3 / 2.5, stds 0.55 / 0.20 / 0.901.7993
two_moons()two half circles of radius 1, blurred with σ=0.1\sigma = 0.1 (density = an integral over the arc, by quadrature)1.008 ± 0.002
smiley()a face: round outline, two eyes, a smiling mouth, blurred with σ=0.1\sigma = 0.11.548 ± 0.004
MarkovChainND(16, c)x1∼N(0,1)x_1 \sim N(0,1), xi∣xi−1∼N(csin⁡2xi−1, (0.15+0.35∣tanh⁡xi−1∣)2)x_i \mid x_{i-1} \sim N(c\sin 2x_{i-1},\ (0.15 + 0.35\lvert\tanh x_{i-1}\rvert)^2)Monte Carlo

The image experiment of §1.4 uses Lecture 1’s 10,000 / 2,000 ShapeWorld images. Everything runs on a laptop CPU with fixed seeds; reruns print identical numbers except wall-clock columns.


1. What we want, and why not a mixture of Gaussians

1.1 The checklist

The slides open with what we want from a generative model:

  1. a good fit to the training data — really, to the underlying distribution;
  2. for a new xx, the ability to evaluate p(x)p(x);
  3. the ability to sample;
  4. a latent representation — an embedding space that is meaningful.

Autoregressive models (Lectures 2–4) check the first two boxes very well: our best Transformer got within one bit of ShapeWorld’s 17.80-bit floor. But sampling is serial (one network pass per token: 288 for raw pixels), there is no latent space (the model is a stack of conditionals; there is no vector that “is” the image), and their success has been mostly on discrete data. Flow models promise all four boxes at once — the slides’ caveat in parentheses: performance not as good as other models. Both halves of that promise are tested in this lecture and the next.

1.2 Continuous data: densities, not probabilities

For continuous xx there is no “probability of xx”; there is a density p(x)≥0p(x) \ge 0 with ∫p(x) dx=1\int p(x)\,dx = 1, and probabilities of regions, P(X∈A)=∫Ap(x) dxP(X \in A) = \int_A p(x)\,dx. Maximum likelihood looks the same as in Lecture 2,

max⁡θ1n∑i=1nlog⁡pθ(x(i))⟺min⁡θ Ex∼pdata[−log⁡pθ(x)]=h(pdata)+KL(pdata∥pθ),\max_\theta \frac{1}{n}\sum_{i=1}^n \log p_\theta(x^{(i)}) \quad\Longleftrightarrow\quad \min_\theta\ E_{x \sim p_{\text{data}}}[-\log p_\theta(x)] = h(p_{\text{data}}) + \mathrm{KL}(p_{\text{data}} \Vert p_\theta),

and the floor is the differential entropy hh. Two differences from the discrete case matter in practice:

  • A density can exceed 1 (a bump of width 0.01 has height ~40), so −log⁡p-\log p and hh can be negative. A narrow distribution has very negative entropy; nothing is wrong.
  • Nothing stops a model from putting an infinitely tall, infinitely thin spike on a training point: the training likelihood goes to infinity. With continuous data that is a sign of over-fitting (a component collapsing onto one point); with discrete data treated as continuous it is the rule, not the exception — Lecture 6’s dequantization.

1.3 A mixture of Gaussians in one dimension

The simplest flexible density is a mixture of Gaussians (MoG), p(x)=∑kπk N(x;μk,σk2)p(x) = \sum_k \pi_k\, N(x; \mu_k, \sigma_k^2), with parameters means, variances and mixture weights, fitted by EM or gradient descent. Script 01, Part 1, fits it by EM to 2,000 points of WORLD_1D (itself a 3-component mixture):

KKtrain NLLtest NLLtest − truth
12.16392.1669+0.3623
21.93531.9465+0.1419
31.80361.8044−0.0002
51.80281.8050+0.0004
101.80211.8063+0.0017

(truth = the true density’s NLL on the same 5,000 test points, 1.8046; h=1.7993h = 1.7993.) In one dimension a MoG is essentially perfect, and extra components cost almost nothing.

1.4 …and on images

The slides’ aside: does a MoG work for high-dimensional data? Its sampling process is pick a cluster center, add Gaussian noise. For natural images, a realistic sample can only come out if its center already is a realistic image — stored in the parameters. Script 01, Part 2, tests it on ShapeWorld images viewed as vectors in R288\mathbb{R}^{288}: a spherical MoG with centers from k-means (hard EM), a shared noise level σ\sigma chosen to maximize the likelihood of held-out images (a Parzen-window bandwidth, in GAN-lecture terms), and K=N=10,000K = N = 10{,}000 meaning “every training image is a center”:

KKbest σ\sigmatest log-lik (nats)gray share of center inkcenters validsamples valid (best σ\sigma)samples valid (σ=0.1\sigma = 0.1)of which copies
10.40−151.1100%0%0%0%–
160.30−104.988%0%0%0%–
2560.30−43.070%0.4%0%0%–
2,0480.25−7.445%23.9%0%5.8%100%
10,0000.25+4.40%100%0.3%100%100%

MoG centers and samples

Cluster centers (left) and center + noise samples (right) for K = 16, 256, 2,048 (01_mixtures_in_high_dimensions.py).

Three lessons:

  1. Small KK: centers are averages. A center summarizes hundreds of images of different shapes at different places — a gray blob. Thresholded, it is not a valid shape; adding noise adds speckle.
  2. Large KK: valid only by memorizing. Centers become crisp images only as KK approaches the number of training images, and then every valid sample is a copy of a training image. To cover ShapeWorld’s 921,600 images the mixture would need about one component per image — Lecture 2’s histogram again, with Gaussian bumps instead of bins.
  3. Likelihood and samples pull σ\sigma apart. The noise level that best explains new images is large (0.25–0.4: a test image is several pixels away from every center), and that noise destroys samples. Lecture 9 meets the same tension when GANs are evaluated with Parzen windows.

A flow keeps the useful part of the MoG recipe — sample simple noise, then transform it — but replaces “add noise to a stored center” by a learned invertible transformation that can generalize.


2. Flows and the change-of-variables formula

2.1 The picture

A flow is an invertible map between the data space, where the distribution is complicated, and an embedding space, where we enforce a simple distribution:

x  →  fθ    z∼pZ(inference),z∼pZ  →  fθ−1    x(sampling).x \;\xrightarrow{\;f_\theta\;}\; z \sim p_Z \quad(\text{inference}), \qquad z \sim p_Z \;\xrightarrow{\;f_\theta^{-1}\;}\; x \quad(\text{sampling}).

(The slides note that a VAE, Lecture 7, has a very similar diagram but learns both directions instead of imposing invertibility.) Because fθf_\theta is invertible, zz is a complete description of xx: the latent representation of the checklist comes for free, with the same dimension as xx.

2.2 Probability is conserved

Take a 1-D increasing ff. The event ”XX lies in the small interval [x,x+dx][x, x + dx]” is the same event as ”ZZ lies in [f(x),f(x)+f′(x) dx][f(x), f(x) + f'(x)\,dx]”. Equal events have equal probabilities:

pX(x) dx=pZ(f(x)) f′(x) dx⟹pX(x)=pZ(f(x)) ∣f′(x)∣.p_X(x)\,dx = p_Z(f(x))\,f'(x)\,dx \quad\Longrightarrow\quad p_X(x) = p_Z(f(x))\,\lvert f'(x) \rvert.

The absolute value covers decreasing maps. Equivalently, via CDFs: FX(x)=P(X≤x)=P(Z≤f(x))=FZ(f(x))F_X(x) = P(X \le x) = P(Z \le f(x)) = F_Z(f(x)), then differentiate. In words: xx is likely if it is mapped to a likely zz, and if ff stretches a neighbourhood of xx into a large region of zz (a large ∣f′∣|f'|). The second factor is what makes flows differ from “just transform the samples”.

Two requirements are hidden in this derivation: ff must be invertible (otherwise two intervals of xx share one interval of zz and the event identity fails) and differentiable (for f′f' to exist).

Script 02, Part 1 checks it with x∼N(0,1)x \sim N(0,1) and z=exz = e^x (four million samples):

zzhistogrampX(log⁡z)/zp_X(\log z)/z (formula)pX(log⁡z)p_X(\log z) (no Jacobian)
0.250.60590.61050.1526
0.500.63220.62750.3137
1.000.40020.39890.3989
2.000.15720.15690.3137
4.000.03810.03820.1526

Integrated over zz, the formula gives 1.0000; without the Jacobian, 1.6471 — not a density at all. Near z=0z = 0, exp⁡\exp squeezes a wide range of xx into a narrow range of zz, so the density there must be higher than pXp_X; for large zz it stretches, and the density is lower.

2.3 Training and sampling

With the formula, maximum likelihood is ordinary stochastic optimization:

max⁡θ∑ilog⁡pθ(x(i))=max⁡θ∑i[log⁡pZ(fθ(x(i)))+log⁡∣fθ′(x(i))∣].\max_\theta \sum_i \log p_\theta(x^{(i)}) = \max_\theta \sum_i \Big[\log p_Z\big(f_\theta(x^{(i)})\big) + \log\big\lvert f_\theta'(x^{(i)})\big\rvert\Big].

So a flow layer must deliver two things in its forward pass: zz and log⁡∣f′∣\log|f'| (logdet in the code). Inference = evaluate this objective. Sampling = draw z∼pZz \sim p_Z and compute x=fθ−1(z)x = f_\theta^{-1}(z). Both are useful only if fθf_\theta, its derivative and its inverse are cheap — the design constraint of every flow architecture.

2.4 Flows compose

If f1f_1 and f2f_2 are flows, so is f2∘f1f_2 \circ f_1, and by the chain rule of calculus log⁡∣(f2∘f1)′(x)∣=log⁡∣f1′(x)∣+log⁡∣f2′(f1(x))∣\log|(f_2 \circ f_1)'(x)| = \log|f_1'(x)| + \log|f_2'(f_1(x))|: log-derivatives add. Composition is the easy way to build expressive flows from simple pieces (“normalizing flow” = a composition of many flows); Flow1D in the code is exactly a list of layers whose logdets are summed.


3. One-dimensional flows

3.1 Two choices

A 1-D flow needs (1) an invertible function class — in 1-D, any strictly monotone function — and (2) a base distribution, ideally easy to sample. The slides’ examples of function classes: ax+bax + b with a>0a > 0; polynomials with positive coefficients and only odd powers; exp⁡(θx)\exp(\theta x); σ(ax+b)\sigma(ax + b); CDFs (of a Gaussian mixture or a sum of logistics); and compositions of these. If the base lives on [0,1][0,1], the flow must map into [0,1][0,1] (a sigmoid or a CDF at the end).

flows.py provides a flexible increasing map of the whole real line,

f(x)=ax+b+∑k=1Kwktanh⁡(skx+ck),a,wk,sk>0,f(x) = a x + b + \sum_{k=1}^{K} w_k \tanh(s_k x + c_k), \qquad a, w_k, s_k > 0,

(MonotoneMLP1D; positivity through softplus): a sum of increasing functions is increasing, and a>0a > 0 makes it unbounded in both directions, so it is a bijection of R\mathbb{R}. Each tanh⁡\tanh is a “step” where ff rises steeply — where the model puts probability mass. For bases on (0,1)(0,1) a sigmoid follows, with log⁡σ′(y)=−softplus(−y)−softplus(y)\log \sigma'(y) = -\text{softplus}(-y) - \text{softplus}(y) (stable, no log⁡0\log 0).

3.2 The same flow towards three bases

The slides show a flow trained to a Gaussian, a uniform and a Beta(5, 5) base, each with the empirical distribution of zz before and after training. Script 02, Part 2 repeats it (K=16K = 16 steps, Adam with learning rate 0.1, 4,000 steps of 256 points; truth on the test points 1.7917 nats):

basetest NLL at initat steps 800 / 1600 / 2400 / 3200final test NLL− truthKS(z, base) at initfinal
N(0,1)N(0,1)19.901.950 1.824 1.804 1.8001.7958+0.00400.4230.024
U(0,1)U(0,1)4.611.803 1.803 1.798 1.8001.7945+0.00280.3760.023
Beta(5, 5)21.041.946 1.947 1.806 1.8021.7966+0.00490.4320.024

(KS = Kolmogorov–Smirnov distance between the empirical CDF of z=f(xtest)z = f(x_{\text{test}}) and the base CDF; about 0.01–0.02 is sampling noise for 5,000 points.)

Flows to three bases

Each row: data and model density, the learned map z=f(x)z = f(x), and the distribution of f(xtest)f(x_{\text{test}}) against the base (02_one_dimensional_flows.py).

All three reach the truth within 0.005 nats and turn the data into their base. In 1-D the base hardly matters, because the flow adapts to it (Exercise 4 makes this exact). The flow curves show how: steep where the data are dense (it stretches dense regions over a large range of zz), flat in gaps between bumps.

The learning curves show something the slides do not: two of the three runs sit on a plateau near 1.95 nats for a while. The narrow middle bump (std 0.2) is smeared out until one tanh⁡\tanh step becomes steep enough to capture it. (Plan vs reality: a first version used learning rate 0.01 and 2,000 steps; all runs were still on the plateau, 0.15 nats above the truth.) Flows are fitted by gradient descent and inherit its plateaus.

3.3 CDF flows: a mixture density in disguise

Take the flow to be a parameterized CDF, z=Fθ(x)z = F_\theta(x), and the base uniform on (0,1)(0,1). Then log⁡pZ(z)=0\log p_Z(z) = 0 and f′(x)=Fθ′(x)=pθ(x)f'(x) = F_\theta'(x) = p_\theta(x), the corresponding density:

log⁡pX(x)=log⁡pZ(Fθ(x))⏟=0+log⁡Fθ′(x)=log⁡pθ(x).\log p_X(x) = \underbrace{\log p_Z(F_\theta(x))}_{=0} + \log F_\theta'(x) = \log p_\theta(x).

“If we use a flow defined as a parameterized CDF, we recover the original objective for fitting the corresponding parameterized PDF” (the slides). Script 02, Part 3 trains mixture-CDF flows (MixtureCDF) and compares the flow’s log-density with an independent float64 implementation of the mixture density:

CDF flowtest NLL− truthmax |flow log p − mixture log p|KS(z, U(0,1))
Gaussian mixture, K=3K=31.7924+0.00078.8e-070.021
Gaussian mixture, K=5K=51.7924+0.00077.6e-070.021
logistic mixture, K=3K=31.7994+0.0076–0.022
logistic mixture, K=5K=51.7947+0.0029–0.022

The difference is float32 rounding: fitting a CDF flow and fitting a mixture model are the same optimization. The logistic mixture is slightly misspecified for Gaussian bumps (tails too heavy), so it needs more components — Lecture 2’s discretized logistic mixture, seen from the other side. This is also why the mixture-of-logistics CDF reappears as a coupling transform in Flow++ (Lecture 6).

3.4 How general are flows?

Can every smooth distribution be represented by a flow? In 1-D, yes, by a two-step argument:

  1. The CDF turns any density into uniform. If XX has a continuous CDF FF, then U=F(X)U = F(X) is uniform on (0,1)(0,1): P(U≤u)=P(X≤F−1(u))=F(F−1(u))=uP(U \le u) = P(X \le F^{-1}(u)) = F(F^{-1}(u)) = u (the probability integral transform).
  2. The inverse of a flow is a flow. So G−1G^{-1}, the inverse CDF of any target, turns uniform into that target (this is Lecture 2’s inverse-CDF sampling).

Composed, f=G−1∘Ff = G^{-1} \circ F turns any smooth p(x)p(x) into any smooth p(z)p(z). Script 02, Part 4 runs it with the true CDF of the 1-D world:

what is comparedKS distance
xx itself vs N(0,1)N(0,1)0.2950
u=Fdata(x)u = F_{\text{data}}(x) vs U(0,1)U(0,1)0.0170
Φ−1(Fdata(x))\Phi^{-1}(F_{\text{data}}(x)) vs N(0,1)N(0,1)0.0170
reference: 5,000 true N(0,1)N(0,1) samples0.0235

(mean / std of Φ−1(Fdata(x))\Phi^{-1}(F_{\text{data}}(x)): +0.018 / 0.977.) The trimodal data become Gaussian noise as faithfully as genuine Gaussian samples. Universality in 1-D is therefore not the question; the question is whether a parameterized family can learn the map from data — and in many dimensions, whether it can be computed and inverted cheaply.

3.5 Sampling by inversion

Sampling runs the flow backwards. A sum of tanh⁡\tanh‘s or a mixture CDF has no closed-form inverse, but it is monotone, so bisection finds xx with f(x)=zf(x) = z: keep a bracket [ℓ,h][\ell, h] with f(ℓ)≤z≤f(h)f(\ell) \le z \le f(h) and halve it; after 60 halvings it is 2−602^{-60} of its width. For MonotoneMLP1D the bracket is exact: since −1<tanh⁡<1-1 < \tanh < 1, ax+b−∑wk≤f(x)≤ax+b+∑wkax + b - \sum w_k \le f(x) \le ax + b + \sum w_k. Script 02, Part 5:

flow (base)max ∣f−1(f(x))−x∣\lvert f^{-1}(f(x)) - x\rvertKS(samples, data CDF)time for 5,000 samples
normal1.9e-060.017~18 ms
uniform2.2e-050.018~19 ms
Beta(5, 5)4.8e-060.012~20 ms
reference: true samples–0.009–

Bisection costs ~60 forward evaluations per layer — cheap in 1-D and fully parallel across samples, but a reminder that “sampling is the inverse” is only fast when the inverse is.


4. Two-dimensional autoregressive flows

4.1 Construction

To go beyond 1-D, the slides chain two 1-D flows with the chain rule of probability:

z1=fθ(x1),z2=fθ(x2; x1),z_1 = f_{\theta}(x_1), \qquad z_2 = f_{\theta}(x_2;\ x_1),

where fθ(⋅ ;x1)f_\theta(\cdot\,; x_1) is a 1-D flow whose parameters depend on x1x_1. The slides’ architecture: base uniform on [0,1]2[0,1]^2; z1z_1 = the CDF of a mixture of 5 Gaussians; z2z_2 = the CDF of a mixture of 5 Gaussians whose weights, means and variances are produced from x1x_1 by an arbitrary neural network (ARFlow2D, ConditionalMixtureCDF).

Why can the dependence on x1x_1 be arbitrarily complex, with no invertibility requirement? Because when we invert, x1x_1 is already known: first x1=f−1(z1)x_1 = f^{-1}(z_1), then x2=f−1(z2;x1)x_2 = f^{-1}(z_2; x_1) with x1x_1 fixed. Invertibility is needed in x2x_2 for each fixed x1x_1, not in x1x_1.

4.2 The objective is the chain rule

The Jacobian of (x1,x2)↦(z1,z2)(x_1, x_2) \mapsto (z_1, z_2) is triangular — z1z_1 does not depend on x2x_2:

∂z∂x=(∂z1/∂x10∂z2/∂x1∂z2/∂x2),det⁡=∂z1∂x1⋅∂z2∂x2.\frac{\partial z}{\partial x} = \begin{pmatrix} \partial z_1/\partial x_1 & 0 \\ \partial z_2/\partial x_1 & \partial z_2/\partial x_2 \end{pmatrix}, \qquad \det = \frac{\partial z_1}{\partial x_1}\cdot\frac{\partial z_2}{\partial x_2}.

The off-diagonal entry — however complicated the network — does not enter the determinant. With a uniform base and CDF flows, ∂z1/∂x1=pθ(x1)\partial z_1/\partial x_1 = p_\theta(x_1) and ∂z2/∂x2=pθ(x2∣x1)\partial z_2/\partial x_2 = p_\theta(x_2 \mid x_1), so

log⁡pθ(x)=log⁡pθ(x1)+log⁡pθ(x2∣x1).\log p_\theta(x) = \log p_\theta(x_1) + \log p_\theta(x_2 \mid x_1).

A 2-D autoregressive flow is exactly an autoregressive model with continuous mixture conditionals (Lecture 3), seen as an invertible map.

4.3 Experiments

Script 03 trains, on 5,000 points of two moons and of the face (6,000 steps, Adam, learning rate 0.005), a full-covariance Gaussian (an affine flow) and AR flows with K=5K = 5 or 2020 components, in both orders:

Two moons (truth on the test points 1.0245):

modeltest NLL− truthcorr(z1,z2z_1, z_2)worst 4×4 cell (vs 6.25%)samples in the true 99% region
Gaussian (affine flow)1.9082+0.884––59.6%
AR flow K=5K=5, x1x_1 first1.0644+0.040−0.0351.23%97.6%
AR flow K=5K=5, x2x_2 first1.1082+0.084+0.0011.63%96.2%
AR flow K=20K=20, x1x_1 first1.0469+0.022−0.0361.21%98.1%
AR flow K=20K=20, x2x_2 first1.0427+0.018−0.0020.63%98.4%

Face (truth on the test points 1.5640):

modeltest NLL− truthcorr(z1,z2z_1, z_2)worst cellsamples in the true 99% region
Gaussian (affine flow)2.9853+1.421––34.9%
AR flow K=5K=5, x1x_1 first1.7101+0.146−0.0422.19%92.8%
AR flow K=5K=5, x2x_2 first1.6001+0.036−0.0121.01%97.9%
AR flow K=20K=20, x1x_1 first1.5876+0.024−0.0320.99%98.0%
AR flow K=20K=20, x2x_2 first1.5906+0.027−0.0140.73%98.3%

(“samples in the true 99% region” = fraction of model samples above the density threshold that 99% of true samples exceed; a perfect model scores 99%.)

2-D densities

Exact density and five trained models (03_two_dimensional_autoregressive_flows.py).

Latents and samples

Left: test data coloured by angle. Middle: the same points mapped to zz — they fill the unit square. Right: samples f−1(z)f^{-1}(z), zz uniform.

What the numbers say:

  1. An affine flow cannot bend. A full-covariance Gaussian is 0.9 / 1.4 nats from the truth; stretching and rotating never turns two moons into one blob.
  2. With enough components the AR flow is near-exact: within 0.02–0.03 nats, an almost uniform latent square, ~98% of samples inside the true 99% region.
  3. The order matters when the conditionals are too simple. With K=5K = 5, x1x_1 first is better on the moons (by 0.04) and x2x_2 first on the face (by 0.11): no order is right for every dataset. Both orders represent the same joint in principle, but they need differently shaped conditionals. With K=20K = 20 the orders are within 0.005 nats. The K=5K = 5, x1x_1-first face even shows a vertical streak (figure): as x1x_1 moves past the right eye, p(x2∣x1)p(x_2 \mid x_1) must jump from four modes to fewer, and a smooth network cannot switch abruptly — a typical autoregressive-flow artifact.
  4. The latent picture is the “embedding space” of the checklist: zz is uniform, and neighbourhoods of data map to regions of the square. (In 2-D with a uniform base, it is a rather literal map; Lecture 6 asks whether flow latents are meaningful on images.)

5. N dimensions: autoregressive and inverse autoregressive flows

5.1 Sampling from a Bayes net is a flow

Generalize §4 to DD variables. Sampling from an autoregressive model with Gaussian conditionals reads

xi=μi(x<i)+σi(x<i) zi,zi∼N(0,1),x_i = \mu_i(x_{<i}) + \sigma_i(x_{<i})\, z_i, \qquad z_i \sim N(0,1),

an invertible map from noise zz to data xx, one coordinate at a time: “the sampling process of a Bayes net is a flow”. If it is autoregressive, the flow is an autoregressive flow (AF; with MADE masks, the masked autoregressive flow, MAF, of Papamakarios et al., 2017). With σi=exp⁡(αi)\sigma_i = \exp(\alpha_i), the two directions are

MAF{x→z:zi=(xi−μi(x<i)) e−αi(x<i)all i at oncez→x:xi=zi eαi(x<i)+μi(x<i)one i at a time\text{MAF}\quad\begin{cases} x \to z: & z_i = (x_i - \mu_i(x_{<i}))\, e^{-\alpha_i(x_{<i})} & \text{all } i \text{ at once} \\ z \to x: & x_i = z_i\, e^{\alpha_i(x_{<i})} + \mu_i(x_{<i}) & \text{one } i \text{ at a time} \end{cases}

The x→zx \to z direction has the structure of likelihood evaluation in an autoregressive model (all of xx is known, so one masked network pass gives all μi,αi\mu_i, \alpha_i: fully parallelizable); z→xz \to x has the structure of sampling (xix_i needs x<ix_{<i} first: DD sequential passes). And

log⁡p(x)=∑ilog⁡N(zi;0,1)−∑iαi(x<i).\log p(x) = \sum_i \log N(z_i; 0, 1) - \sum_i \alpha_i(x_{<i}).

5.2 The inverse autoregressive flow

The inverse of an AF is also a flow; condition the shift and scale on the noise instead of the data and you get the inverse autoregressive flow (IAF; Kingma et al., 2016):

IAF{z→x:xi=zi eαi(z<i)+μi(z<i)all i at oncex→z:zi=(xi−μi(z<i)) e−αi(z<i)one i at a time\text{IAF}\quad\begin{cases} z \to x: & x_i = z_i\, e^{\alpha_i(z_{<i})} + \mu_i(z_{<i}) & \text{all } i \text{ at once} \\ x \to z: & z_i = (x_i - \mu_i(z_{<i}))\, e^{-\alpha_i(z_{<i})} & \text{one } i \text{ at a time} \end{cases}

Now sampling is one pass and density evaluation of an arbitrary xx takes DD sequential passes. But for the model’s own samples, zz is known, so their density is cheap: log⁡q(x)=∑ilog⁡N(zi)−∑iαi(z<i)\log q(x) = \sum_i \log N(z_i) - \sum_i \alpha_i(z_{<i}) from the same single pass.

5.3 Triangular Jacobians, cheap determinants

In both flows, output ii depends on input jj only if j≤ij \le i in the order, so the Jacobian is (lower) triangular, and its determinant is the product of the diagonal e∓αie^{\mp\alpha_i}. Script 04, Part 1 prints the nonzero patterns of the Jacobians for D=6D = 6 (MAF in raster order: lower triangle; MAF in reversed order: upper triangle; IAF sampling direction: lower triangle) and compares the cheap log-determinant with the full one:

mapcheap log⁡∣det⁡∣\log\lvert\det\rvert (sum of log-scales)slogdet of the full Jacobian
MAF x→zx \to z+1.167157+1.167157
MAF reversed x→zx \to z−0.764333−0.764333
IAF z→xz \to x+1.065799+1.065799

Round trips are exact to 10−710^{-7}. This is the “new key requirement” the slides state for N-D flows: the Jacobian determinant must be easy to compute and differentiate; a general D×DD \times D determinant costs O(D3)O(D^3), a triangular one O(D)O(D).

5.4 The cost table

Script 04, Part 2 counts network passes and times them for 1,000 points (untrained networks, hidden layers 256–256):

DDMAF densityMAF samplingIAF density of dataIAF samplingIAF density of its own samples
161 pass · 1 ms16 passes · 4 ms17 passes · 4 ms1 pass · <1 ms1 pass · <1 ms
641 pass · 1 ms64 passes · 28 ms65 passes · 30 ms1 pass · 1 ms1 pass · 1 ms
2561 pass · 2 ms256 passes · 295 ms257 passes · 302 ms1 pass · 3 ms1 pass · 3 ms

AF vs IAF cost

This is the slides’ table in numbers: AF — training (density) parallel and fast, sampling a long serial chain; IAF — training by maximum likelihood a long serial chain, sampling parallel and fast. At D=256D = 256 the slow direction is ~100× slower; for a one-megapixel image, “naively, both end up being as deep as the number of variables”. Parameter sharing (masks as in MADE, or an RNN) keeps the parameters manageable; it does not remove the sequential steps.

5.5 Best of both: distillation

Models such as Parallel WaveNet and IAF-VAE exploit the IAF’s fast sampling. The slides’ recipe: (1) train an AF — fast; (2) distill it: train an IAF on its own samples to match the AF. Concretely (probability density distillation, van den Oord et al., 2018), minimize the reverse KL from student to teacher,

KL(qIAF∥pAF)=Ex∼qIAF[log⁡qIAF(x)−log⁡pAF(x)],\mathrm{KL}(q_{\text{IAF}} \Vert p_{\text{AF}}) = E_{x \sim q_{\text{IAF}}}\big[\log q_{\text{IAF}}(x) - \log p_{\text{AF}}(x)\big],

which needs exactly the cheap operations: IAF samples with their log-density (one IAF pass) and the teacher’s density at those samples (one AF pass). No data are needed, and gradients reach the student through x=x(z)x = x(z) (the reparameterization trick of Lecture 7).

Script 04, Part 3 trains on 16-dimensional chains (MarkovChainND, 200,000 training vectors, 8,000 steps, hidden 256–256, one flow layer each), with strong (c=0.9c = 0.9) and weak (c=0.3c = 0.3) coupling between neighbouring coordinates:

Strongly coupled chain (truth on the test vectors: 5.477 nats):

modeltrained bytrain timems / steptest NLL − truth (mean / median)missed test pointsKL(model ‖ truth)sample 10,000
MAFmax. likelihood4.0 s0.50+0.058 / +0.0400.0%0.078~33 ms
IAFmax. likelihood39.6 s4.95+1.860 / +1.6090.1%3.704~4 ms
IAFdistilled from the MAF5.1 s0.64+5.3e7 / +37,40469.4%1.753~3 ms

Weakly coupled chain (truth: −0.058 nats):

modeltrained bytrain timems / steptest NLL − truth (mean / median)missed test pointsKL(model ‖ truth)sample 10,000
MAFmax. likelihood3.4 s0.43+0.016 / +0.0110.0%0.022~33 ms
IAFmax. likelihood38.8 s4.85+0.067 / +0.0440.0%0.065~4 ms
IAFdistilled from the MAF5.1 s0.64+0.080 / +0.0270.0%0.067~3 ms

(“missed test points” = test vectors whose model NLL is more than 10 nats above the truth’s; “KL(model ‖ truth)” estimated from 20,000 model samples with the exact density.)

The weak chain shows the slides’ story working: the distilled IAF trains as fast as the MAF (two passes per step, no data), samples ~10× faster, and is almost as good (KL 0.067 vs the teacher’s 0.022 nats per 16-D vector). Maximum-likelihood training of the IAF reaches the same quality but costs ~10× more per step.

The strong chain is the plan-vs-reality result of this lecture. The plan was to show the same success; instead every IAF fails — trained by maximum likelihood (+1.9 nats) or by distillation (70% of test points essentially given zero density). The reason is structural. To imitate xi=m(xi−1)+s(xi−1) εix_i = m(x_{i-1}) + s(x_{i-1})\,\varepsilon_i in one pass, the IAF’s network must compute xi−1x_{i-1} from the noise z<iz_{<i} — for x16x_{16}, fifteen nested nonlinear steps x2=m(x1)+s(x1)z2x_2 = m(x_1) + s(x_1)z_2, x3=m(x2)+…x_3 = m(x_2) + \dots — inside one 2-layer MLP. When coupling is weak, the nesting is nearly linear and easy; when it is strong, it is not. (A calibration run stacking 2 or 4 distilled IAF layers still left 1.2–1.5 nats of reverse KL.) The MAF has no such problem: its network sees xi−1x_{i-1} directly. Two more lessons hide in the strong-chain row:

  • Reverse KL is mode-seeking. The distilled student is penalized for putting mass where the teacher has little, but not for missing teacher mass, so when it cannot represent everything it drops whole regions: a moderate reverse KL (1.75 nats) and an astronomically bad test NLL. Maximum likelihood (forward KL) does the opposite — it covers everything and pays with blurry samples (reverse KL 3.7). Lecture 9 meets the same asymmetry between KL, reverse KL and GANs.
  • Fast sampling is not free. An IAF trades sequential computation for depth: the noise → data map must be computable in a few parallel steps. Real systems (Parallel WaveNet) stack several IAF flows and add auxiliary losses; whether data admit such a parallel map is a property of the data.

5.6 Where this leaves us

AF and IAF give exact likelihoods in any dimension, but one direction is always DD sequential steps. Lecture 6 removes that asymmetry with coupling layers (RealNVP): transform half of the variables conditioned on the other half, so both directions take one pass — at the price of needing many layers. One more constraint stays with every flow: xx and zz must have the same dimension (the slides’ “high-dimensional data” slide), unlike the latent variable models of Lectures 7–8.


6. Summary

  1. A flow is an invertible, differentiable map z=fθ(x)z = f_\theta(x) to a simple base distribution; change of variables gives the exact density pX(x)=pZ(f(x)) ∣det⁡∂f/∂x∣p_X(x) = p_Z(f(x))\,|\det \partial f/\partial x|. Training is maximum likelihood; sampling is f−1f^{-1} of base samples; zz is a latent representation of the same dimension.
  2. A mixture of Gaussians is excellent in 1-D (0.002 nats from the truth) but, on images, produces valid samples only from stored centers — copies.
  3. In 1-D: a flexible monotone map reaches every base (Gaussian, uniform, Beta) within 0.005 nats of the truth; a CDF flow with a uniform base is a mixture density (identical log-densities); CDF then inverse CDF makes 1-D flows universal; bisection inverts any monotone flow.
  4. A 2-D autoregressive flow (CDF of x1x_1, then a CDF of x2x_2 with parameters from any network of x1x_1) has a triangular Jacobian, equals the chain rule, and gets within 0.02–0.03 nats of the exact densities of two moons and a face; the order matters when conditionals are too simple.
  5. MAF: density in 1 pass, sampling in DD. IAF: sampling in 1 pass, density of data in DD (of its own samples in 1). Distillation (minimize KL(IAF ‖ AF) on IAF samples) gives a fast sampler cheaply when the data’s noise → data map is easy to compute in parallel — and fails, dropping whole regions of the data, when it is not.

7. Common pitfalls

  1. Forgetting the Jacobian. pZ(f(x))p_Z(f(x)) alone is not a density (it integrated to 1.65 in §2.2). Every flow layer must return its log-determinant, and they must be summed.
  2. The wrong sign of the log-determinant. log⁡∣det⁡∂z/∂x∣=−log⁡∣det⁡∂x/∂z∣\log|\det \partial z/\partial x| = -\log|\det \partial x/\partial z|. Script 04’s first version used the x→zx \to z sign for the IAF’s z→xz \to x map; the comparison with slogdet caught it. Always check one layer against autograd.
  3. Non-monotone conditional maps. In an AR flow the conditioner may be any network of x<ix_{<i}, but each map must be strictly monotone in xix_i, otherwise it is not invertible and the density formula is wrong.
  4. Bases with bounded support. A uniform or Beta base needs a flow into (0,1)(0,1); in float32 a sigmoid can return exactly 0 or 1 — clamp before taking logs.
  5. Comparing with the population entropy on a finite test set. Compare with the true density’s NLL on the same points when you have it. A first version of script 02 showed a CDF flow “beating” the exact entropy by 0.007 nats (§3.3); the test set was simply easier than average — the true density scores 1.7917 on it, 0.008 below hh.
  6. Reading a mean NLL of a reverse-KL-trained model. One missed region can make the mean astronomically large; look at the median and the fraction of missed points too.
  7. Expecting an IAF to sample “the same distribution, just faster”. Its single pass must compute what the AF computes sequentially; with strong sequential dependence it cannot.

8. Exercises

Exercise 1 (change of variables, both directions). Derive pX(x)=pZ(f(x)) ∣f′(x)∣p_X(x) = p_Z(f(x))\,|f'(x)| for a strictly decreasing differentiable ff using CDFs. Then derive the sampling form pX(x)=pZ(z)/∣(f−1)′(z)∣p_X(x) = p_Z(z)/|(f^{-1})'(z)| at z=f(x)z = f(x).

Answer

For decreasing ff: FX(x)=P(X≤x)=P(f(X)≥f(x))=1−FZ(f(x))F_X(x) = P(X \le x) = P(f(X) \ge f(x)) = 1 - F_Z(f(x)). Differentiating: pX(x)=−pZ(f(x))f′(x)=pZ(f(x)) ∣f′(x)∣p_X(x) = -p_Z(f(x)) f'(x) = p_Z(f(x))\,|f'(x)| since f′<0f' < 0. For the sampling form, x=g(z)x = g(z) with g=f−1g = f^{-1}, and by the inverse function theorem f′(x)=1/g′(z)f'(x) = 1/g'(z), so pX(x)=pZ(z)/∣g′(z)∣p_X(x) = p_Z(z)/|g'(z)|: the density of xx is the density of zz divided by how much gg stretches.

Exercise 2 (the probability integral transform). Show that if XX has a continuous, strictly increasing CDF FF, then F(X)∼U(0,1)F(X) \sim U(0,1), and that the CDF flow with a uniform base has log⁡pX(x)=log⁡F′(x)\log p_X(x) = \log F'(x). What goes wrong for a discrete XX?

Answer

P(F(X)≤u)=P(X≤F−1(u))=F(F−1(u))=uP(F(X) \le u) = P(X \le F^{-1}(u)) = F(F^{-1}(u)) = u for u∈(0,1)u \in (0,1). For the flow z=F(x)z = F(x): log⁡pX=log⁡pU(F(x))+log⁡F′(x)=0+log⁡F′(x)\log p_X = \log p_U(F(x)) + \log F'(x) = 0 + \log F'(x). For discrete XX, FF is a step function: F(X)F(X) takes only a few values (not uniform), FF is not invertible and has no derivative at the jumps — the reason Lecture 6 needs dequantization.

Exercise 3 (universality). Given smooth densities pXp_X, pZp_Z on R\mathbb{R} with CDFs FF, GG, show that f=G−1∘Ff = G^{-1} \circ F is increasing and that pZ(f(x)) f′(x)=pX(x)p_Z(f(x))\,f'(x) = p_X(x).

Answer

FF and G−1G^{-1} are increasing, so their composition is. f′(x)=(G−1)′(F(x)) F′(x)=pX(x)G′(G−1(F(x)))=pX(x)pZ(f(x))f'(x) = (G^{-1})'(F(x))\,F'(x) = \frac{p_X(x)}{G'(G^{-1}(F(x)))} = \frac{p_X(x)}{p_Z(f(x))}. Multiplying by pZ(f(x))p_Z(f(x)) gives pX(x)p_X(x).

Exercise 4 (the base does not matter — sometimes). Let F\mathcal{F} be a family of increasing maps into (0,1)(0,1) (e.g. mixture CDFs) and consider two models: (a) z=Fθ(x)z = F_\theta(x) with a uniform base; (b) z=Φ−1(Fθ(x))z = \Phi^{-1}(F_\theta(x)) with a standard normal base. Show that they define the same densities. When does the base matter?

Answer

(b): log⁡p(x)=log⁡φ(Φ−1(Fθ(x)))+log⁡(Φ−1)′(Fθ(x))+log⁡Fθ′(x)\log p(x) = \log \varphi(\Phi^{-1}(F_\theta(x))) + \log (\Phi^{-1})'(F_\theta(x)) + \log F_\theta'(x). Since (Φ−1)′(u)=1/φ(Φ−1(u))(\Phi^{-1})'(u) = 1/\varphi(\Phi^{-1}(u)), the first two terms cancel: log⁡p(x)=log⁡Fθ′(x)\log p(x) = \log F_\theta'(x), the same as (a). The base matters when the flow family is fixed and cannot absorb the base’s inverse CDF: e.g. a flow made of a few affine and elementwise layers maps to a Gaussian base more easily than to a uniform one (tails), and in many dimensions the base’s independence structure matters a lot.

Exercise 5 (the 2-D AR flow is the chain rule). For z1=F1(x1)z_1 = F_1(x_1), z2=F2(x2;x1)z_2 = F_2(x_2; x_1) with CDF flows and a uniform base, compute the Jacobian determinant and show log⁡p(x)=log⁡p(x1)+log⁡p(x2∣x1)\log p(x) = \log p(x_1) + \log p(x_2 \mid x_1), where p(x1)=F1′(x1)p(x_1) = F_1'(x_1) and p(x2∣x1)=∂F2/∂x2p(x_2 \mid x_1) = \partial F_2/\partial x_2. Why may ∂F2/∂x1\partial F_2/\partial x_1 be anything?

Answer

J=(F1′0∂x1F2∂x2F2)J = \begin{pmatrix} F_1' & 0 \\ \partial_{x_1}F_2 & \partial_{x_2}F_2 \end{pmatrix}, det⁡J=F1′(x1) ∂x2F2(x2;x1)\det J = F_1'(x_1)\,\partial_{x_2}F_2(x_2; x_1). Each factor is a density (the derivative of a CDF), so log⁡p=log⁡p(x1)+log⁡p(x2∣x1)\log p = \log p(x_1) + \log p(x_2 \mid x_1). The off-diagonal term multiplies the zero in the upper right and never enters the determinant; invertibility only requires each map to be monotone in its own variable.

Exercise 6 (counting passes). Show that sampling from a MAF needs DD sequential network passes even though the network computes all μi,αi\mu_i, \alpha_i at once. Why does the IAF need DD passes to evaluate the density of a data point, but only 1 for its own samples?

Answer

MAF sampling: μi,αi\mu_i, \alpha_i depend on x<ix_{<i}, which is not known until x1,…,xi−1x_1, \dots, x_{i-1} have been computed; one pass with the current partial xx gives correct μi,αi\mu_i, \alpha_i only for the next coordinate. IAF density of data: μi,αi\mu_i, \alpha_i depend on z<iz_{<i}, which must be recovered from xx one coordinate at a time. For its own samples, the zz that produced xx is known, so one pass gives all αi\alpha_i and log⁡q(x)=∑log⁡N(zi)−∑αi\log q(x) = \sum \log N(z_i) - \sum\alpha_i.

Exercise 7 (a Gaussian AR model is a one-layer MAF). Show that the log-likelihood of an autoregressive model with conditionals N(xi;μi(x<i),e2αi(x<i))N(x_i; \mu_i(x_{<i}), e^{2\alpha_i(x_{<i})}) equals the MAF’s ∑ilog⁡N(zi;0,1)−∑iαi\sum_i \log N(z_i; 0, 1) - \sum_i \alpha_i. What does stacking MAF layers add?

Answer

log⁡N(xi;μi,e2αi)=−12(xi−μi)2e−2αi−αi−12log⁡2π=log⁡N(zi;0,1)−αi\log N(x_i; \mu_i, e^{2\alpha_i}) = -\tfrac12 (x_i - \mu_i)^2 e^{-2\alpha_i} - \alpha_i - \tfrac12\log 2\pi = \log N(z_i; 0, 1) - \alpha_i with zi=(xi−μi)e−αiz_i = (x_i - \mu_i)e^{-\alpha_i}. Summing over ii gives the MAF formula. A single layer can only express Gaussian conditionals; stacking layers (typically with different orders) makes the conditionals non-Gaussian and the model more flexible, at no change in the per-layer cost structure.

Exercise 8 (distillation needs no data). Show that the gradient of KL(qϕ∥p)\mathrm{KL}(q_\phi \Vert p) with respect to the student’s parameters ϕ\phi can be estimated from student samples x=gϕ(z)x = g_\phi(z), z∼N(0,I)z \sim N(0, I), using only log⁡qϕ(x)\log q_\phi(x) and log⁡p(x)\log p(x) at those samples. Why is this objective mode-seeking?

Answer

KL=Ez[log⁡qϕ(gϕ(z))−log⁡p(gϕ(z))]\mathrm{KL} = E_{z}[\log q_\phi(g_\phi(z)) - \log p(g_\phi(z))]; the expectation is over a fixed noise distribution, so ∇ϕ\nabla_\phi moves inside: Ez[∇ϕ(log⁡qϕ(gϕ(z))−log⁡p(gϕ(z)))]E_z[\nabla_\phi(\log q_\phi(g_\phi(z)) - \log p(g_\phi(z)))], estimated by averaging over sampled zz (pathwise / reparameterization gradient). The loss is an average over student samples: regions where pp has mass but qq has none are never visited, so they cost nothing — the student can drop modes. Forward KL (maximum likelihood) averages over data and pays −log⁡q-\log q wherever data lie, so it cannot.

Exercise 9 (why the strong chain defeats an IAF). For the chain xi=m(xi−1)+s(xi−1)zix_i = m(x_{i-1}) + s(x_{i-1})z_i with x1=z1x_1 = z_1, write x3x_3 as a function of z1,z2,z3z_1, z_2, z_3. For m(u)=csin⁡2um(u) = c\sin 2u, how does the sensitivity ∂x16/∂z1\partial x_{16}/\partial z_1 behave for c=0.3c = 0.3 vs c=0.9c = 0.9 (consider ∣m′∣≤2c|m'| \le 2c)?

Answer

x3=m(m(z1)+s(z1)z2)+s(m(z1)+s(z1)z2) z3x_3 = m(m(z_1) + s(z_1)z_2) + s(m(z_1) + s(z_1)z_2)\,z_3. By the chain rule, ∂x16/∂z1\partial x_{16}/\partial z_1 is a product of 15 factors ∂xi/∂xi−1=m′(xi−1)+s′(xi−1)zi\partial x_{i}/\partial x_{i-1} = m'(x_{i-1}) + s'(x_{i-1})z_i. With c=0.3c = 0.3, ∣m′∣≤0.6|m'| \le 0.6: the product shrinks geometrically, distant noise barely matters, and the map is close to “local” — easy for one network pass. With c=0.9c = 0.9, ∣m′∣|m'| reaches 1.8, the factors can exceed 1, and x16x_{16} is an intricate, highly nonlinear function of all earlier noise — a deep composition that a 2-layer network cannot reproduce in one pass.

Exercise 10 (bisection cost). A 1-D flow is a composition of 4 monotone layers without closed-form inverses. With bisection to float32 precision, roughly how many layer evaluations does one sample cost? How would you reduce it?

Answer

Each layer needs ~25–30 halvings for float32 relative precision (60 in our code, to be safe), so ~4 × 30 = 120–240 layer evaluations, versus 4 for the forward direction. Reductions: Newton’s method (quadratic convergence, using the known derivative), a good initial bracket (exact bounds as in MonotoneMLP1D.bracket), or choosing layers with analytic inverses — the motivation for affine coupling layers (Lecture 6).


9. Further reading

From the slides

  • L. Dinh, D. Krueger, Y. Bengio. NICE: Non-linear Independent Components Estimation, 2014; L. Dinh, J. Sohl-Dickstein, S. Bengio. Density Estimation using Real NVP, ICLR 2017.
  • G. Papamakarios, T. Pavlakou, I. Murray. Masked Autoregressive Flow for Density Estimation, NeurIPS 2017; X. Chen et al. Variational Lossy Autoencoder, ICLR 2017 (AF).
  • D. P. Kingma et al. Improving Variational Inference with Inverse Autoregressive Flow, NeurIPS 2016.
  • A. van den Oord et al. Parallel WaveNet: Fast High-Fidelity Speech Synthesis, ICML 2018 (probability density distillation).
  • C.-W. Huang et al. Neural Autoregressive Flows, ICML 2018.
  • G. Papamakarios, E. Nalisnick, D. J. Rezende, S. Mohamed, B. Lakshminarayanan. Normalizing Flows for Probabilistic Modeling and Inference, JMLR 2021; I. Kobyzev, S. Prince, M. Brubaker. Normalizing Flows: An Introduction and Review of Current Methods, IEEE PAMI 2021 (surveys).

Added by these notes

  • D. J. Rezende, S. Mohamed. Variational Inference with Normalizing Flows, ICML 2015 — the paper that named “normalizing flows”.
  • E. G. Tabak, C. V. Turner. A Family of Nonparametric Density Estimation Algorithms, 2013 — flows before deep learning.
  • C. Durkan et al. Neural Spline Flows, NeurIPS 2019 — monotone rational-quadratic splines with analytic inverses (an alternative to bisection).

10. Next lecture

The 2-D autoregressive flow and the MAF / IAF pair show that triangular Jacobians make exact likelihoods possible in any dimension — but one direction is always sequential. Lecture 6 (flow models II) builds flows that are fast both ways: the change of many variables in general, affine and elementwise flows, coupling layers (NICE / RealNVP) whose Jacobian is triangular by construction, partitions (checkerboard, channels) and why a bad one hurts, Glow’s ActNorm and invertible 1×1 convolutions, Flow++‘s mixture-CDF couplings, continuous-time flows — and then confronts flows with discrete images, where an unregularized continuous density can reach infinite likelihood, and dequantization turns the flow’s likelihood into an honest bound on ShapeWorld’s 17.80 bits.

← 返回课程目录