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:
- 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.
- Explain why a mixture of Gaussians works in one dimension and fails on images (samples = stored centers + noise).
- Derive the change-of-variables formula from conservation of probability, and explain why forgetting breaks normalization.
- 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.
- Sample from a flow by inverting it, including by bisection when no closed-form inverse exists.
- Build a 2-D autoregressive flow and explain why its conditioner can be any network while each conditional map must be monotone.
- 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
| Assumed | Introduced here | Developed 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 flows | change 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 calculus | probability density distillation | IAF 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
| Symbol | Meaning |
|---|---|
| a data point (continuous in this lecture) | |
| the flow: an invertible, differentiable map from data to latent; | |
| the base distribution of (standard normal, uniform on , Beta) | |
| the Jacobian matrix (); in 1-D just | |
| , “logdet” | , one number per data point |
| differential entropy 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:
| name | what it is | exact (nats) |
|---|---|---|
WORLD_1D | mixture of 3 Gaussians: weights 0.45 / 0.20 / 0.35, means −2 / 0.3 / 2.5, stds 0.55 / 0.20 / 0.90 | 1.7993 |
two_moons() | two half circles of radius 1, blurred with (density = an integral over the arc, by quadrature) | 1.008 ± 0.002 |
smiley() | a face: round outline, two eyes, a smiling mouth, blurred with | 1.548 ± 0.004 |
MarkovChainND(16, c) | , | 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:
- a good fit to the training data — really, to the underlying distribution;
- for a new , the ability to evaluate ;
- the ability to sample;
- 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 there is no “probability of ”; there is a density with , and probabilities of regions, . Maximum likelihood looks the same as in Lecture 2,
and the floor is the differential entropy . Two differences from the discrete case matter in practice:
- A density can exceed 1 (a bump of width 0.01 has height ~40), so and 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), , 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):
| train NLL | test NLL | test − truth | |
|---|---|---|---|
| 1 | 2.1639 | 2.1669 | +0.3623 |
| 2 | 1.9353 | 1.9465 | +0.1419 |
| 3 | 1.8036 | 1.8044 | −0.0002 |
| 5 | 1.8028 | 1.8050 | +0.0004 |
| 10 | 1.8021 | 1.8063 | +0.0017 |
(truth = the true density’s NLL on the same 5,000 test points, 1.8046; .) 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 : a spherical MoG with centers from k-means (hard EM), a shared noise level chosen to maximize the likelihood of held-out images (a Parzen-window bandwidth, in GAN-lecture terms), and meaning “every training image is a center”:
| best | test log-lik (nats) | gray share of center ink | centers valid | samples valid (best ) | samples valid () | of which copies | |
|---|---|---|---|---|---|---|---|
| 1 | 0.40 | −151.1 | 100% | 0% | 0% | 0% | – |
| 16 | 0.30 | −104.9 | 88% | 0% | 0% | 0% | – |
| 256 | 0.30 | −43.0 | 70% | 0.4% | 0% | 0% | – |
| 2,048 | 0.25 | −7.4 | 45% | 23.9% | 0% | 5.8% | 100% |
| 10,000 | 0.25 | +4.4 | 0% | 100% | 0.3% | 100% | 100% |

Cluster centers (left) and center + noise samples (right) for K = 16, 256, 2,048 (01_mixtures_in_high_dimensions.py).
Three lessons:
- Small : 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.
- Large : valid only by memorizing. Centers become crisp images only as 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.
- Likelihood and samples pull 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:
(The slides note that a VAE, Lecture 7, has a very similar diagram but learns both directions instead of imposing invertibility.) Because is invertible, is a complete description of : the latent representation of the checklist comes for free, with the same dimension as .
2.2 Probability is conserved
Take a 1-D increasing . The event ” lies in the small interval ” is the same event as ” lies in ”. Equal events have equal probabilities:
The absolute value covers decreasing maps. Equivalently, via CDFs: , then differentiate. In words: is likely if it is mapped to a likely , and if stretches a neighbourhood of into a large region of (a large ). The second factor is what makes flows differ from “just transform the samples”.
Two requirements are hidden in this derivation: must be invertible (otherwise two intervals of share one interval of and the event identity fails) and differentiable (for to exist).
Script 02, Part 1 checks it with and (four million samples):
| histogram | (formula) | (no Jacobian) | |
|---|---|---|---|
| 0.25 | 0.6059 | 0.6105 | 0.1526 |
| 0.50 | 0.6322 | 0.6275 | 0.3137 |
| 1.00 | 0.4002 | 0.3989 | 0.3989 |
| 2.00 | 0.1572 | 0.1569 | 0.3137 |
| 4.00 | 0.0381 | 0.0382 | 0.1526 |
Integrated over , the formula gives 1.0000; without the Jacobian, 1.6471 — not a density at all. Near , squeezes a wide range of into a narrow range of , so the density there must be higher than ; for large it stretches, and the density is lower.
2.3 Training and sampling
With the formula, maximum likelihood is ordinary stochastic optimization:
So a flow layer must deliver two things in its forward pass: and (logdet in the code). Inference = evaluate this objective. Sampling = draw and compute . Both are useful only if , its derivative and its inverse are cheap — the design constraint of every flow architecture.
2.4 Flows compose
If and are flows, so is , and by the chain rule of calculus : 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: with ; polynomials with positive coefficients and only odd powers; ; ; CDFs (of a Gaussian mixture or a sum of logistics); and compositions of these. If the base lives on , the flow must map into (a sigmoid or a CDF at the end).
flows.py provides a flexible increasing map of the whole real line,
(MonotoneMLP1D; positivity through softplus): a sum of increasing functions is increasing, and makes it unbounded in both directions, so it is a bijection of . Each is a “step” where rises steeply — where the model puts probability mass. For bases on a sigmoid follows, with (stable, no ).
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 before and after training. Script 02, Part 2 repeats it ( steps, Adam with learning rate 0.1, 4,000 steps of 256 points; truth on the test points 1.7917 nats):
| base | test NLL at init | at steps 800 / 1600 / 2400 / 3200 | final test NLL | − truth | KS(z, base) at init | final |
|---|---|---|---|---|---|---|
| 19.90 | 1.950 1.824 1.804 1.800 | 1.7958 | +0.0040 | 0.423 | 0.024 | |
| 4.61 | 1.803 1.803 1.798 1.800 | 1.7945 | +0.0028 | 0.376 | 0.023 | |
| Beta(5, 5) | 21.04 | 1.946 1.947 1.806 1.802 | 1.7966 | +0.0049 | 0.432 | 0.024 |
(KS = Kolmogorov–Smirnov distance between the empirical CDF of and the base CDF; about 0.01–0.02 is sampling noise for 5,000 points.)

Each row: data and model density, the learned map , and the distribution of 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 ), 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 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, , and the base uniform on . Then and , the corresponding density:
“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 flow | test NLL | − truth | max |flow log p − mixture log p| | KS(z, U(0,1)) |
|---|---|---|---|---|
| Gaussian mixture, | 1.7924 | +0.0007 | 8.8e-07 | 0.021 |
| Gaussian mixture, | 1.7924 | +0.0007 | 7.6e-07 | 0.021 |
| logistic mixture, | 1.7994 | +0.0076 | – | 0.022 |
| logistic mixture, | 1.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:
- The CDF turns any density into uniform. If has a continuous CDF , then is uniform on : (the probability integral transform).
- The inverse of a flow is a flow. So , the inverse CDF of any target, turns uniform into that target (this is Lecture 2’s inverse-CDF sampling).
Composed, turns any smooth into any smooth . Script 02, Part 4 runs it with the true CDF of the 1-D world:
| what is compared | KS distance |
|---|---|
| itself vs | 0.2950 |
| vs | 0.0170 |
| vs | 0.0170 |
| reference: 5,000 true samples | 0.0235 |
(mean / std of : +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 ‘s or a mixture CDF has no closed-form inverse, but it is monotone, so bisection finds with : keep a bracket with and halve it; after 60 halvings it is of its width. For MonotoneMLP1D the bracket is exact: since , . Script 02, Part 5:
| flow (base) | max | KS(samples, data CDF) | time for 5,000 samples |
|---|---|---|---|
| normal | 1.9e-06 | 0.017 | ~18 ms |
| uniform | 2.2e-05 | 0.018 | ~19 ms |
| Beta(5, 5) | 4.8e-06 | 0.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:
where is a 1-D flow whose parameters depend on . The slides’ architecture: base uniform on ; = the CDF of a mixture of 5 Gaussians; = the CDF of a mixture of 5 Gaussians whose weights, means and variances are produced from by an arbitrary neural network (ARFlow2D, ConditionalMixtureCDF).
Why can the dependence on be arbitrarily complex, with no invertibility requirement? Because when we invert, is already known: first , then with fixed. Invertibility is needed in for each fixed , not in .
4.2 The objective is the chain rule
The Jacobian of is triangular — does not depend on :
The off-diagonal entry — however complicated the network — does not enter the determinant. With a uniform base and CDF flows, and , so
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 or components, in both orders:
Two moons (truth on the test points 1.0245):
| model | test NLL | − truth | corr() | worst 4×4 cell (vs 6.25%) | samples in the true 99% region |
|---|---|---|---|---|---|
| Gaussian (affine flow) | 1.9082 | +0.884 | – | – | 59.6% |
| AR flow , first | 1.0644 | +0.040 | −0.035 | 1.23% | 97.6% |
| AR flow , first | 1.1082 | +0.084 | +0.001 | 1.63% | 96.2% |
| AR flow , first | 1.0469 | +0.022 | −0.036 | 1.21% | 98.1% |
| AR flow , first | 1.0427 | +0.018 | −0.002 | 0.63% | 98.4% |
Face (truth on the test points 1.5640):
| model | test NLL | − truth | corr() | worst cell | samples in the true 99% region |
|---|---|---|---|---|---|
| Gaussian (affine flow) | 2.9853 | +1.421 | – | – | 34.9% |
| AR flow , first | 1.7101 | +0.146 | −0.042 | 2.19% | 92.8% |
| AR flow , first | 1.6001 | +0.036 | −0.012 | 1.01% | 97.9% |
| AR flow , first | 1.5876 | +0.024 | −0.032 | 0.99% | 98.0% |
| AR flow , first | 1.5906 | +0.027 | −0.014 | 0.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%.)

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

Left: test data coloured by angle. Middle: the same points mapped to — they fill the unit square. Right: samples , uniform.
What the numbers say:
- 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.
- 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.
- The order matters when the conditionals are too simple. With , first is better on the moons (by 0.04) and 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 the orders are within 0.005 nats. The , -first face even shows a vertical streak (figure): as moves past the right eye, must jump from four modes to fewer, and a smooth network cannot switch abruptly — a typical autoregressive-flow artifact.
- The latent picture is the “embedding space” of the checklist: 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 variables. Sampling from an autoregressive model with Gaussian conditionals reads
an invertible map from noise to data , 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 , the two directions are
The direction has the structure of likelihood evaluation in an autoregressive model (all of is known, so one masked network pass gives all : fully parallelizable); has the structure of sampling ( needs first: sequential passes). And
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):
Now sampling is one pass and density evaluation of an arbitrary takes sequential passes. But for the model’s own samples, is known, so their density is cheap: from the same single pass.
5.3 Triangular Jacobians, cheap determinants
In both flows, output depends on input only if in the order, so the Jacobian is (lower) triangular, and its determinant is the product of the diagonal . Script 04, Part 1 prints the nonzero patterns of the Jacobians for (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:
| map | cheap (sum of log-scales) | slogdet of the full Jacobian |
|---|---|---|
| MAF | +1.167157 | +1.167157 |
| MAF reversed | −0.764333 | −0.764333 |
| IAF | +1.065799 | +1.065799 |
Round trips are exact to . 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 determinant costs , a triangular one .
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):
| MAF density | MAF sampling | IAF density of data | IAF sampling | IAF density of its own samples | |
|---|---|---|---|---|---|
| 16 | 1 pass · 1 ms | 16 passes · 4 ms | 17 passes · 4 ms | 1 pass · <1 ms | 1 pass · <1 ms |
| 64 | 1 pass · 1 ms | 64 passes · 28 ms | 65 passes · 30 ms | 1 pass · 1 ms | 1 pass · 1 ms |
| 256 | 1 pass · 2 ms | 256 passes · 295 ms | 257 passes · 302 ms | 1 pass · 3 ms | 1 pass · 3 ms |

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 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,
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 (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 () and weak () coupling between neighbouring coordinates:
Strongly coupled chain (truth on the test vectors: 5.477 nats):
| model | trained by | train time | ms / step | test NLL − truth (mean / median) | missed test points | KL(model ‖ truth) | sample 10,000 |
|---|---|---|---|---|---|---|---|
| MAF | max. likelihood | 4.0 s | 0.50 | +0.058 / +0.040 | 0.0% | 0.078 | ~33 ms |
| IAF | max. likelihood | 39.6 s | 4.95 | +1.860 / +1.609 | 0.1% | 3.704 | ~4 ms |
| IAF | distilled from the MAF | 5.1 s | 0.64 | +5.3e7 / +37,404 | 69.4% | 1.753 | ~3 ms |
Weakly coupled chain (truth: −0.058 nats):
| model | trained by | train time | ms / step | test NLL − truth (mean / median) | missed test points | KL(model ‖ truth) | sample 10,000 |
|---|---|---|---|---|---|---|---|
| MAF | max. likelihood | 3.4 s | 0.43 | +0.016 / +0.011 | 0.0% | 0.022 | ~33 ms |
| IAF | max. likelihood | 38.8 s | 4.85 | +0.067 / +0.044 | 0.0% | 0.065 | ~4 ms |
| IAF | distilled from the MAF | 5.1 s | 0.64 | +0.080 / +0.027 | 0.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 in one pass, the IAF’s network must compute from the noise — for , fifteen nested nonlinear steps , — 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 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 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: and must have the same dimension (the slides’ “high-dimensional data” slide), unlike the latent variable models of Lectures 7–8.
6. Summary
- A flow is an invertible, differentiable map to a simple base distribution; change of variables gives the exact density . Training is maximum likelihood; sampling is of base samples; is a latent representation of the same dimension.
- 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.
- 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.
- A 2-D autoregressive flow (CDF of , then a CDF of with parameters from any network of ) 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.
- MAF: density in 1 pass, sampling in . IAF: sampling in 1 pass, density of data in (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
- Forgetting the Jacobian. 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.
- The wrong sign of the log-determinant. . Script 04’s first version used the sign for the IAF’s map; the comparison with
slogdetcaught it. Always check one layer against autograd. - Non-monotone conditional maps. In an AR flow the conditioner may be any network of , but each map must be strictly monotone in , otherwise it is not invertible and the density formula is wrong.
- Bases with bounded support. A uniform or Beta base needs a flow into ; in float32 a sigmoid can return exactly 0 or 1 — clamp before taking logs.
- 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 .
- 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.
- 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 for a strictly decreasing differentiable using CDFs. Then derive the sampling form at .
Answer
For decreasing : . Differentiating: since . For the sampling form, with , and by the inverse function theorem , so : the density of is the density of divided by how much stretches.
Exercise 2 (the probability integral transform). Show that if has a continuous, strictly increasing CDF , then , and that the CDF flow with a uniform base has . What goes wrong for a discrete ?
Answer
for . For the flow : . For discrete , is a step function: takes only a few values (not uniform), is not invertible and has no derivative at the jumps — the reason Lecture 6 needs dequantization.
Exercise 3 (universality). Given smooth densities , on with CDFs , , show that is increasing and that .
Answer
and are increasing, so their composition is. . Multiplying by gives .
Exercise 4 (the base does not matter — sometimes). Let be a family of increasing maps into (e.g. mixture CDFs) and consider two models: (a) with a uniform base; (b) with a standard normal base. Show that they define the same densities. When does the base matter?
Answer
(b): . Since , the first two terms cancel: , 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 , with CDF flows and a uniform base, compute the Jacobian determinant and show , where and . Why may be anything?
Answer
, . Each factor is a density (the derivative of a CDF), so . 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 sequential network passes even though the network computes all at once. Why does the IAF need passes to evaluate the density of a data point, but only 1 for its own samples?
Answer
MAF sampling: depend on , which is not known until have been computed; one pass with the current partial gives correct only for the next coordinate. IAF density of data: depend on , which must be recovered from one coordinate at a time. For its own samples, the that produced is known, so one pass gives all and .
Exercise 7 (a Gaussian AR model is a one-layer MAF). Show that the log-likelihood of an autoregressive model with conditionals equals the MAF’s . What does stacking MAF layers add?
Answer
with . Summing over 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 with respect to the student’s parameters can be estimated from student samples , , using only and at those samples. Why is this objective mode-seeking?
Answer
; the expectation is over a fixed noise distribution, so moves inside: , estimated by averaging over sampled (pathwise / reparameterization gradient). The loss is an average over student samples: regions where has mass but has none are never visited, so they cost nothing — the student can drop modes. Forward KL (maximum likelihood) averages over data and pays wherever data lie, so it cannot.
Exercise 9 (why the strong chain defeats an IAF). For the chain with , write as a function of . For , how does the sensitivity behave for vs (consider )?
Answer
. By the chain rule, is a product of 15 factors . With , : the product shrinks geometrically, distant noise barely matters, and the map is close to “local” — easy for one network pass. With , reaches 1.8, the factors can exceed 1, and 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.