Role: This lecture does not correspond to any session of the original course. The original prerequisites are a deep-learning course (MIT 6.S898 / 6.7960) plus either computer vision or NLP, and students are assumed to know probability and information theory. Kaiming He’s slides use the KL divergence, the ELBO, reparameterization, Jensen’s inequality and the JS divergence directly when deriving VAEs, GANs and diffusion models. This lecture fills in the probability and information-theory tools that the main lectures actually use, and marks where each one first appears. Basis: The content is standard probability and information theory (see Cover & Thomas, Elements of Information Theory, and Murphy’s Probabilistic Machine Learning, volumes 1 and 2). The examples and experiments were designed for this course. The VAE regularizer formula of §2.3 is problem 3 of the original Pset 1; the ELBO identity of §4.3 is the core of Lecture 3; the bits/dim conversion and dequantization of §7 follow Theis, van den Oord & Bethge (2016). Code:
code/prereq1/(7 scripts; numpy + PyTorch (CPU) + matplotlib; each under 6 seconds) When to read: Before or together with Lecture 1; at the latest before Lecture 3 (VAE). About 4 hours including running the code.
0. How to read this lecture
0.1 Why this lecture
Almost every objective in this course is written in the language of probability and information theory:
| Tool | Where it is first used |
|---|---|
| Joint / marginal / conditional, Bayes’ rule, chain rule | Lecture 1 (discriminative vs generative), Lecture 5 (autoregressive models) |
| Conditional independence (“given the latent, pixels are independent”) | Lecture 3 (the VAE decoder) |
| Gaussian reparameterization, the KL between two Gaussians | Lecture 3 (VAE), Lecture 12 (every step of a diffusion model) |
| Entropy, cross-entropy, KL, maximum likelihood | Lecture 1 §5; then almost every lecture |
| Mutual information | Lecture 1 §7, Lecture 3 (InfoVAE) |
| Monte Carlo, importance sampling | Lecture 3 (estimating the ELBO), Lecture 12 (normalizing constants of energy models) |
| Score-function vs reparameterization gradients, straight-through, Gumbel-softmax | Lecture 3 (VAE, VQ-VAE), Lecture 7 (DALL·E’s discrete VAE) |
| The change-of-variables formula | Lecture 4 (normalizing flows), Lecture 6 (IAF / MAF) |
| bits/dim, dequantization | Lectures 4 and 6 (the likelihoods of Glow and PixelCNN) |
If you already know a section, just run its script and glance at the “Observations” to make sure nothing surprises you.
0.2 Learning goals
- Compute marginals, conditionals and Bayesian posteriors fluently from a joint table; understand that the chain rule “holds in any order, with no approximation”; distinguish independence from conditional independence.
- Sample a multivariate Gaussian by reparameterization; write the conditional of a multivariate Gaussian; derive ; know where the samples of a high-dimensional Gaussian are.
- Understand entropy, cross-entropy and KL as “code lengths”; derive “maximum likelihood = minimizing KL” and understand how maximum likelihood overfits on finite data; compute mutual information.
- Estimate expectations by Monte Carlo with an error bar; use importance sampling, choose a proposal and know when it fails; verify with numbers.
- Derive and compare the two estimators of “the gradient of an expectation” (score function, reparameterization); know why discrete variables are hard and what the straight-through estimator and Gumbel-softmax each pay.
- Use the change-of-variables formula to get the density after an invertible map; understand why flows prefer triangular Jacobians; understand why “density” does not exist when the dimension is lowered.
- Convert the negative log-likelihood of a continuous model into bits/dim; understand why dequantization is necessary, and that “likelihood = compression”.
0.3 Map
§1 joint, marginal, conditional; chain rule; independence vs conditional independence; total expectation/variance ← code 01
§2 Gaussians: reparameterization, conditionals and marginals, the KL between two Gaussians, the soap bubble ← code 02
§3 information theory: entropy, cross-entropy, KL, maximum likelihood, mutual information, differential entropy ← code 03
§4 Monte Carlo and importance sampling; the likelihood of a latent-variable model, ELBO, IWAE ← code 04
§5 gradients of expectations: score function vs reparameterization; discrete variables ← code 05
§6 change of variables; triangular Jacobians; lowering the dimension ← code 06
§7 bits/dim, dequantization, likelihood = compression ← code 07
§8 summary §9 common pitfalls §10 exercises §11 further reading
0.4 Notation
| Symbol | Meaning |
|---|---|
| a probability mass function (a probability) for discrete , a probability density (can exceed 1) for continuous | |
| , | joint; conditional |
| expectation of under | |
| Gaussian density with mean and covariance | |
| , | entropy; cross-entropy |
| KL divergence | |
| mutual information | |
| bit / nat | log base 2 / base e; 1 nat = 1/ln 2 ≈ 1.443 bit |
1. Joint, marginal, conditional
1.1 A joint probability table
The slides of Lecture 5 (autoregressive models) use a three-variable example: vehicle type , color , age . Script 01 makes up probabilities for it, giving a joint distribution whose 8 entries sum to 1. With the joint, everything else can be computed:
- Marginal: sum over the variables you do not care about. . Here .
- Conditional: joint divided by marginal. . Here .
- Bayes’ rule: “reverse” a conditional, . The two computations in the code give exactly the same numbers. After seeing , goes from the prior 0.300 to the posterior 0.454 — buses are more often old, and the observation changes the belief.
The hard part is never these formulas but the joint distribution itself. A joint table over binary variables has free parameters; one 28×28 black-and-white image means numbers. All the effort of generative modeling goes into representing this table without writing it down (the “factorizations” of Lecture 1 §6).
1.2 The chain rule: any order, no approximation
Applying the definition of a conditional repeatedly gives the chain rule:
Part 2 of script 01 factorizes the same table in all 6 orders (A→B→C, A→C→B, …), multiplies the factors back, and gets the original table to within (floating-point rounding). Two things to remember:
- The chain rule holds for any order, with no approximation. So an autoregressive model may generate in any order (Lecture 5; MAR in Lecture 8 exploits “any order”). The approximation only enters through “what we use to represent each conditional”.
- The data were generated A → B → C, but that does not make other orders “untrue”. A factorization is a modeling choice, not a causal claim. (Different orders can still be easier or harder to learn — the unimodal-Gaussian example of Lecture 1, script 06.)
1.3 Independence and conditional independence
- Independence: , equivalently — knowing does not help you guess .
- Conditional independence: given , .
Neither implies the other. Part 3 of script 01 shows both directions:
(a) Independent causes become dependent through a common effect (“explaining away”). Rain (20%) and a sprinkler (30%) are independent; wet grass .
| Probability | Value |
|---|---|
| 0.201 | |
| 0.200 | |
| 0.455 | |
| 0.200 | |
| 1.000 |
Seeing wet grass makes rain more likely; learning that the sprinkler was on brings rain back to its prior — the sprinkler “explains away” the wet grass. Given the common effect , the originally independent and become dependent.
(b) Dependent observations become independent given a common latent. Let mean “this is a 0 or a 1”; given , two pixels , turn on independently with probability (, ):
| Quantity | Value |
|---|---|
| correlation of ( unknown) | +0.639 |
| correlation given / | −0.003 / −0.002 |
| → | 0.499 → 0.819 |
This is the central trick of latent-variable models:
Each is extremely simple (pixels independent), but after summing (or integrating) over , the components of have rich dependencies. The decoder of the Lecture 3 VAE outputs “an independent Gaussian per pixel”, yet the whole model represents complex correlations between pixels — for exactly this reason. GlyphWorld in Lecture 1 §4.2 works the same way: given all 7 latents the image is determined; without them the pixels have long-range correlations.
1.4 The laws of total expectation and total variance
Part 4 of script 01 checks this on a mixture of three Gaussians: sample mean −0.1037 (formula −0.1000), sample variance 4.3573 (formula 0.28 + 4.09 = 4.37), with Monte Carlo error as the only difference. The law of total variance has exactly the shape of the mean-squared-error decomposition of Lecture 1 §2.3: regression can only remove the “between” part; is a floor that no regression can go below — and a generative model’s job is precisely to represent that remaining uncertainty instead of averaging it away.
2. The Gaussian
2.1 Density and reparameterization
The density of a -dimensional Gaussian is
Reparameterization: every Gaussian can be written as “a standard normal + a deterministic transformation”:
Part 1 of script 02 checks this with 200,000 samples: the largest difference between the sample covariance and the target is 0.0022. The point of reparameterization: all randomness is in , and the parameters , appear only in the deterministic part, so we can differentiate through the sample (§5). The log density is computed with the Cholesky factor too: the quadratic form and , more stable than an explicit inverse.
2.2 Marginals, conditionals, the linear-Gaussian model
Split into two blocks , with the mean and covariance split accordingly:
- Marginal: (just take the block).
- Conditional: .
The conditional mean is a linear function of the observation ; the conditional covariance does not depend on the observed value and is always smaller than the marginal covariance (knowing reduces uncertainty). Part 2 of script 02 takes samples in a thin slice around : mean 0.395, variance 0.693, against the formula’s 0.400 and 0.680 (the small variance difference comes from the slice’s width). A conditional is “a slice of the joint along a line, renormalized”:

A linear-Gaussian latent-variable model: , . is jointly Gaussian, so the marginal and the posterior have closed forms (precisions add: , ). With , , , samples give a posterior mean 0.4711 and variance 0.0589, the formula 0.4706 and 0.0588. The multivariate version is “probabilistic PCA”. A VAE’s decoder is a nonlinear neural network, and its posterior has no closed form — which is why Lecture 3 approximates the posterior with an encoder . §4.3 keeps using this model for experiments, because everything about it can be computed exactly.
2.3 The KL between two Gaussians
The KL divergence (formally defined in §3) between two -dimensional Gaussians has a closed form:
The special case used most in VAEs is a diagonal Gaussian against the standard normal:
This is exactly what problem 3 of the original Pset 1 asks you to prove. The derivation is short. The dimensions are independent, so the KL is a sum over dimensions; in one dimension, .
Part 3 of script 02 compares the closed form with Monte Carlo estimates (true KL 0.5531):
| Monte Carlo samples | mean of 50 estimates | std of 50 estimates |
|---|---|---|
| 10 | 0.5961 | 0.1948 |
| 100 | 0.5493 | 0.0579 |
| 1,000 | 0.5522 | 0.0234 |
| 10,000 | 0.5531 | 0.0067 |
| 100,000 | 0.5535 | 0.0022 |
Monte Carlo is unbiased but noisy; at the noise is about as large as the KL itself. Use the closed form wherever it exists — the difference between the “SGVB estimator” and the “analytic KL” ways of training a VAE in the original Pset 1 is exactly this.
The per-dimension contributions have an intuitive meaning. In the example, and , and the four dimensions contribute 0.229, 0.794, 0.000 and 3.025:
- the dimension with , contributes exactly 0;
- the further the mean from 0 and the variance from 1, the larger the contribution.
This is what the VAE regularizer does: it “pulls each data point’s code distribution toward the standard normal”.
2.4 The high-dimensional “soap bubble”
Samples of a -dimensional standard normal have norms concentrated around : has mean and variance , so .
| dimension | mean | std | fraction with | ||
|---|---|---|---|---|---|
| 1 | 1.00 | 0.81 | 0.605 | 0.386 | 0.5 |
| 10 | 3.16 | 3.08 | 0.688 | 0.009 | 5.0 |
| 100 | 10.00 | 9.98 | 0.714 | 0.000 | 50.0 |
| 10000 | 100.00 | 100.00 | 0.690 | 0.000 | 5000.1 |
The density at the origin (the mode) is nats higher than at a typical sample, yet no sample is there. The point of highest probability density is not where the probability mass is: mass = density × volume, and the volume of a shell grows rapidly with its distance from the origin. This is the mathematical reason behind pitfall 2 of Lecture 1 (“the best generation is the most probable sample”), and the reason why “noisy images in a diffusion model almost all lie on a shell of radius ”.
3. Information theory
3.1 Entropy: the average length of the best code
The entropy of a discrete distribution is
The best way to understand it is through coding. Shannon’s source coding theorem says:
- for symbols from , no uniquely decodable binary code can have an average length below ;
- a code with average length below always exists;
- ideally, a symbol of probability should get bits (the more common, the shorter).
Script 03 checks this with Huffman codes:
| distribution | entropy | mean Huffman length |
|---|---|---|
| uniform (8 symbols) | 3.0000 | 3.0000 |
| skewed (0.5, 0.2, 0.1, 0.1, 0.05, 0.03, 0.01, 0.01) | 2.1295 | 2.1700 |
| almost certain | 0.2519 | 1.0650 |
| all probabilities powers of 2 | 1.9844 | 1.9844 |
Entropy measures “uncertainty”: the uniform distribution is the most uncertain (3 bits), the almost-certain one less than 0.3 bit. When all probabilities are powers of 2, the code lengths equal exactly. Huffman cannot go below 1 bit per symbol in the “almost certain” row. Encoding many symbols together, or arithmetic coding, approaches the entropy.
3.2 Cross-entropy and KL: the extra bits of the wrong code
Encoding data from with “the ideal code designed for ” (length ) takes, on average, the cross-entropy:
The KL divergence is “the extra bits spent because the model is wrong”. Part 2 of script 03 (data from the “skewed” distribution above, ):
| distribution used for the code | |||
|---|---|---|---|
| 2.1295 | 0.0000 | 0.0000 | |
| = uniform | 3.0000 | 0.8705 | 1.0793 |
| first two probabilities swapped | 2.5261 | 0.3966 | 0.3966 |
| misses the last symbol (prob. 0) | ∞ | ∞ | 0.0166 |
Three properties:
- Non-negative: , with equality iff (by Jensen’s inequality, exercise 2).
- Asymmetric: (the uniform row; the forward / reverse KL of Lecture 1 §5.3).
- Support: as soon as gives probability 0 to a symbol that really occurs, ; the other direction can still be small (last row).
3.3 Maximum likelihood = minimizing KL = sample frequencies; and its overfitting
Fit a -class categorical distribution to samples. The mean log-likelihood is ( = how often class occurs). Maximizing it subject to with a Lagrange multiplier gives , i.e.
The maximum-likelihood estimate is the sample frequency. It is also the solution of “minimize ” ( = the empirical distribution of the samples), the same derivation as Lecture 1 §5.2.
The trouble is finite data. Part 3 of script 03 uses a 50-class long-tailed distribution (entropy 4.234 bits):
| samples | unseen classes | their total true probability | cross-entropy of MLE | after smoothing |
|---|---|---|---|---|
| 20 | 82% | 0.346 | ∞ | 4.732 |
| 100 | 54% | 0.116 | ∞ | 4.505 |
| 1,000 | 26% | 0.004 | ∞ | 4.261 |
| 10,000 | 12% | 0.000 | ∞ | 4.236 |
Maximum likelihood gives unseen classes probability 0; as soon as real data contain one, the cross-entropy is infinite. This is overfitting for a probability model, the same thing as the kernel density estimate with bandwidth in Lecture 1 §4.5. The simplest remedy is add- smoothing, (equivalent to putting a prior on the model), with chosen on a validation set. This “zero-probability disaster” is everywhere in language and pixel models; it comes back with PixelCNN (Lecture 6).
3.4 Mutual information and the data processing inequality
Mutual information measures “how much the uncertainty about drops once is known”:
The second form says that mutual information is “how far the joint is from independence”. Part 4 of script 03 uses a binary symmetric channel: uniform on 0/1, = flipped with probability , = flipped again with probability :
| flip probability | (both formulas) | |
|---|---|---|
| 0.0 | 1.0000 | 1.0000 |
| 0.05 | 0.7136 | 0.5471 |
| 0.1 | 0.5310 | 0.3199 |
| 0.2 | 0.2781 | 0.0956 |
| 0.5 | 0.0000 | 0.0000 |
Data processing inequality: if is a Markov chain, then — no processing of data can create new information. The conditional-entropy table of Lecture 1 §7 asks “how much information about does the condition contain”; the forward process of a diffusion model (Lecture 12) is a Markov chain that loses information step by step.
3.5 Continuous variables: differential entropy and the invariance of KL
The “differential entropy” of a continuous variable is not a direct generalization of discrete entropy. A Gaussian’s differential entropy is . For it is +3.05, +2.05, +1.05 and −1.27 bits: it can be negative. Scaling the variable by adds . It depends on units and coordinates.
The KL divergence, however, is invariant under invertible transformations. Applying the same invertible map to both distributions multiplies both densities by the same Jacobian factor (§6), which cancels in the ratio . Part 5 of script 03: is 0.3499 nat in closed form, estimated as 0.3505 on , and still 0.3505 after the transformation . So comparisons between models use likelihood differences (or KL), and reporting a single negative log-likelihood of continuous data requires saying how the data were scaled and discretized (§7).
3.6 Preview: “distances” beyond KL
| divergence / distance | definition (intuition) | lecture |
|---|---|---|
| KL (forward, reverse) | extra bits of the wrong code | Lectures 1, 3, 12 |
| Jensen–Shannon (JS) | mean of the KLs to “the average of the two”; symmetric, bounded in | Lecture 9 (the original GAN) |
| Wasserstein-1 (earth mover’s distance) | minimal cost of moving one pile of earth into another | Lecture 9 (WGAN) |
| Fisher divergence | squared difference of the score functions of two distributions | Lecture 12 (score matching) |
4. Monte Carlo and importance sampling
4.1 Monte Carlo: if you can sample, you can estimate expectations
The estimate is unbiased, its standard deviation is , and it does not depend on the dimension of . Part 1 of script 04 estimates for . For the standard deviations are 0.142, 0.044, 0.014 and 0.0046, so “std × ” stays at about 0.45. The interval “mean ± 1.96 × standard error” contains the truth 94–95% of the time, but only 87% at , where the standard error itself is poorly estimated. Ten times the accuracy costs a hundred times the samples, but the dimension does not matter — which is why all training of generative models is built on “sample + average”.
4.2 Importance sampling
To estimate when is hard to sample (or to sample more “where it matters”), sample from another distribution and reweight:
Even better, when is known only up to a constant (), we can estimate the normalizing constant: . This is the core difficulty of the energy-based models of Lecture 12 (). Part 2 of script 04 uses the double-well energy (true ) and proposals , with 1000 samples each:
| mean of | relative std | median / truth | effective sample size | |
|---|---|---|---|---|
| 0.3 | 6.19 | 374% | 0.42 | 37 |
| 0.7 | 7.58 | 5.6% | 1.00 | 226 |
| 1.5 | 7.60 | 1.9% | 1.00 | 694 |
| 3.0 | 7.59 | 3.1% | 1.00 | 472 |
| 8.0 | 7.58 | 6.7% | 1.00 | 192 |

The effective sample size measures how uneven the weights are. The rule: must “cover” the target; its tails must not be lighter than the target’s. When is too narrow, the target’s two valleys are almost never sampled, and the rare hit gets an enormous weight. The estimate is unbiased in theory, but in practice it is almost always too small and occasionally huge. This is the same reason why the forward KL of Lecture 1 “must cover all the data”.
Rare events are the classic use of importance sampling. For with (truth ):
- plain sampling with 100,000 samples has relative std 52.6%;
- sampling from and reweighting has relative std 0.71%.
4.3 The likelihood of a latent-variable model: ELBO and IWAE
How do we compute the likelihood of a latent-variable model ? Importance-sample with an approximate posterior :
Taking the log and using Jensen’s inequality ( is concave, so ):
And the gap is exactly a KL:
(Proof: substitute into the ELBO; does not depend on and comes out, and what remains is .) This is the central identity of the VAE in Lecture 3. Part 4 of script 04 checks it on the linear-Gaussian model of §2.2, whose is known exactly:
| approximate posterior | ELBO | IWAE | ||||
|---|---|---|---|---|---|---|
| prior | −10.198 | 8.438 | 8.466 | −1.951 | −1.777 | −1.760 |
| true posterior | −1.760 | 0.000 | 0.000 | −1.760 | −1.760 | −1.760 |
| mean shifted by 0.3 | −2.519 | 0.759 | 0.765 | −1.895 | −1.788 | −1.754 |
| 4× variance | −2.565 | 0.805 | 0.807 | −1.781 | −1.759 | −1.761 |
- Columns 3 and 4 agree (up to Monte Carlo error): the gap between the ELBO and the true log-likelihood is the KL from the approximate posterior to the true one.
- When is the true posterior, every sample’s weight equals exactly; the estimate has zero variance and the ELBO equals . So “maximize the ELBO” does two things at once: it raises the likelihood and pushes toward the true posterior.
- The IWAE bound (average the weights first, then take the log) approaches as grows; the worse , the larger the needed. = prior is the worst — which is why a VAE trains an encoder to approximate the posterior instead of sampling from the prior. (At a few numbers are slightly above : IWAE is a lower bound only in expectation, and the average over 200 repeats is still noisy.)
5. Gradients of expectations
5.1 The problem
Generative models often optimize : an expectation over a distribution that depends on the parameters. Examples are the ELBO as a function of the encoder’s parameters, a reverse KL, and reinforcement learning. We cannot simply move inside the expectation, because the sampling itself depends on .
The score-function estimator (also called REINFORCE or the likelihood-ratio estimator) uses the “log-derivative trick” :
It needs only the values of ; need not be differentiable, and discrete variables are fine. Since , any baseline that does not depend on can be subtracted from without changing the expectation. A good baseline can cut the variance dramatically.
The reparameterization estimator (also called pathwise). If with the distribution of independent of (§2.1), then
It needs differentiable in and differentiable in , but it uses the extra information in the derivative of .
5.2 Experiment: variance, baselines and dimension
has true gradient at , . With samples per estimate (part 1 of script 05):
| method | ||
|---|---|---|
| score function | −3.96 ± 2.93 | +1.94 ± 5.69 |
| score function + baseline | −4.00 ± 2.14 | +1.91 ± 4.51 |
| reparameterization | −3.99 ± 0.62 | +1.98 ± 1.55 |
All three are unbiased; reparameterization has a 3–5× smaller standard deviation. The dimension matters even more. Take and the gradient with respect to :
| 1 | 10 | 100 | 1000 | |
|---|---|---|---|---|
| score function (with baseline), std | 2.1 | 5.0 | 14.3 | 44.8 |
| reparameterization, std | ≈ 0.63 | ≈ 0.63 | ≈ 0.63 | ≈ 0.63 |
In the score-function estimator, the value of contains the random fluctuations of the other dimensions, and all of it becomes noise. A VAE has tens to hundreds of latent dimensions, so it cannot do without reparameterization (Lecture 3).
5.3 The precondition of reparameterization
Take the step function , so , with true gradient .
- The score-function estimator gives 0.2403 ± 0.0571.
- Reparameterization gives 0.0000 ± 0.0000.
A step function has derivative 0 almost everywhere, and reparameterization “honestly” returns 0 — completely wrong. Reparameterization requires to be differentiable.
5.4 Discrete variables: straight-through and Gumbel-softmax
A discrete variable cannot be written as “a continuous, differentiable transformation”, so reparameterization fails. The VQ-VAE of Lecture 3 (a discrete codebook) and DALL·E’s discrete VAE in Lecture 7 both face this problem. Part 4 of script 05 compares several approaches on ; the exact gradient can be computed by enumeration and has length 0.450.
| estimator | bias | noise |
|---|---|---|
| score function + baseline | 0.008 | 0.456 |
| straight-through | 0.609 | 0.547 |
| Gumbel-softmax | 0.390 | 0.079 |
| Gumbel-softmax | 0.337 | 0.214 |
| Gumbel-softmax | 0.236 | 0.419 |
| Gumbel-softmax | 0.080 | 1.195 |
- The score-function estimator is still unbiased for discrete variables, just noisy.
- The straight-through estimator uses the real discrete sample (a one-hot) in the forward pass and pretends it was the softmax output in the backward pass. In code it is the one line on the Lecture 3 slides,
stop_grad(hardmax(y) − softmax(y)) + softmax(y). It is a heuristic: unbiased exactly when is linear (because ), and more biased the more curved is. Here its bias (0.61) exceeds the true gradient itself (0.45), and its noise is no smaller than the score function’s. It is good enough in VQ-VAE because only a “roughly correct direction” is needed there and the quantization is a deterministic nearest-neighbour choice. - Gumbel-softmax. The Gumbel-max trick says that , with independent Gumbel noises , is distributed exactly as . Replacing the argmax with a softmax at temperature gives a differentiable “soft one-hot”. A large is smooth, with low noise and high bias; approaches true discrete sampling, with low bias and high noise. The temperature trades bias against variance.
6. Change of variables
6.1 One dimension
Let and with strictly monotone. The probability that falls in equals the probability that falls in the corresponding interval : , so
Wherever the map stretches an interval, the density thins out by the same factor. Part 1 of script 06 checks three maps:
- (log-normal, ): at the histogram gives 0.6450 and the formula 0.6442.
- (the normal CDF) turns a normal into a uniform distribution (all three histogram values ≈ 1). Conversely, turns a uniform into a normal.
- The non-monotone has two preimages , and the two branches must be added: .
Finding all preimages is almost impossible in high dimensions, so models that want exact likelihoods insist on invertible maps.
6.2 Several dimensions: the Jacobian determinant
For an invertible, differentiable with the Jacobian :
is “how much magnifies a small volume”. Part 2 of script 06: for linear maps , the densities of the group are all about 2.85 times smaller.
Triangular Jacobians. The banana map , is nonlinear, but depends only on and the “earlier” . So:
- its Jacobian is lower triangular, ;
- its determinant is always 1;
- its inverse is explicit ().
Histograms and the formula agree (e.g. 0.0851 vs 0.0852). The coupling layers of Lecture 4 and the autoregressive flows (IAF / MAF) of Lecture 6 all have this structure.

6.3 Composition: log-determinants add up
For with every step invertible:
This is the whole secret of normalizing flows. Part 3 of script 06 composes “scale-and-shift → banana → rotation”, inverts step by step and adds the log-determinants; the result agrees with the histogram (e.g. 0.1081 vs 0.1073).
The cost is in the determinant:
- a general determinant needs (LU factorization);
- a triangular one needs (the product of the diagonal).
At the timings on this machine are about 8 ms vs 0.01 ms. A 256×256 color image has , and the determinant of a general Jacobian is out of reach. The two constraints “invertible + cheap determinant” are the root of the structural limits of normalizing flows (Lecture 4).
6.4 When the dimension drops, the density does not exist
If maps a low-dimensional into a higher-dimensional space (, ), all samples lie on a straight line. A line has “zero area” in the plane, so the 2-D density is infinite on the line and zero off it — it does not exist. Part 4 of script 06 has to add a small noise to the covariance of a 2-D Gaussian to invert it. As falls from 0.1 to , the mean log-likelihood of test samples climbs from −2.00 to +6.06, without limit.
Real images may also concentrate near a low-dimensional manifold (Lecture 1: GlyphWorld has only 7 knobs). Hence:
- a VAE’s decoder outputs a noisy distribution (Lecture 3);
- a normalizing flow keeps the dimension (Lecture 4);
- discrete pixel values must be “dequantized” before a continuous density is computed (§7).
7. Bits per dimension, dequantization and “likelihood = compression”
7.1 Discrete and continuous likelihoods
Pixels are integers 0–255, but models are often continuous densities (flows, VAEs, diffusion). With the data scaled to , the integer corresponds to the interval of width :
Part 1 of script 07: the discrete negative log-likelihood is 6.9815 bits, the continuous density at the bin centers gives −1.0185 bits, and adding 8 gives exactly 6.9815. A continuous “negative log-likelihood” can be negative; only after adding 8 bits does it mean “how many bits to encode one 8-bit pixel”. The bits/dim in papers is
(With data scaled to , and the constant becomes 7 — check the scaling before comparing numbers across papers.) For reference, PixelCNN++ reports about 2.92 bits/dim on CIFAR-10; 8 bits would mean “the model learned nothing”.
7.2 Continuous models cheat on discrete data; dequantization
Fit a continuous density directly to integer data and the model can pile its probability onto the integers, exactly where the test data fall too — the likelihood can be infinite. Part 2 of script 07 (16 gray levels, true entropy 3.337 bits) shows this with a kernel density estimate:
| bandwidth | continuous density directly | bound after dequantization | induced discrete NLL |
|---|---|---|---|
| 1.0 | 3.340 | 3.350 | 3.349 |
| 0.1 | 1.341 | 3.361 | 3.341 |
| 0.01 | −1.981 | 4.497 | 3.342 |
| 0.001 | −5.303 | 149.177 | 3.359 |
Without dequantization, the smaller the bandwidth, the lower the “negative log-likelihood” — far below the entropy and even negative: cheating. Uniform dequantization (Theis et al. 2016): add uniform noise to every integer and train and evaluate the continuous model on . By Jensen’s inequality,
so the continuous dequantized NLL is an upper bound on the induced discrete NLL, and cheating is impossible (column 3 ≥ column 4 ≥ entropy). With a too-small bandwidth the bound gets worse again — gaps between training points, overfitting once more. Flow++ (Ho et al. 2019) replaces the uniform noise with a learned “variational dequantization” distribution to tighten the bound.
7.3 Likelihood = compression
§3.1 said that the ideal code gives data of probability a length of bits (arithmetic coding achieves this almost exactly). So every probability model is a compression method, and bits/dim is the number of bits per pixel it needs. Part 3 of script 07 compares models on glyph images quantized to 0–255:
| model / compressor | bits/dim |
|---|---|
| (a) uniform: 8 bits per pixel | 8.000 |
| (b) one histogram for all pixels | 2.868 |
| (c) one histogram per position (independent pixels) | 2.572 |
| (d) autoregressive: , 64 contexts | 2.134 |
| zlib (DEFLATE) | 2.270 |
| lzma (xz) | 1.871 |
Each extra dependency the model captures saves bits:
- (b) treats all pixels alike;
- (c) lets each position have its own distribution;
- (d) makes each pixel depend on its neighbours, and with only two neighbours it already beats zlib.
lzma is better still, because it finds long repeated fragments (the same strokes recur across the 2000 images). Probability models with larger contexts — the PixelCNN of Lectures 5–6 — are needed to go lower. The “negative log-likelihood = cross-entropy” that problem 1 of the original Pset 2 proves is exactly what trains this column.
8. Summary
- With the joint distribution everything can be computed; the hard part is the joint itself. The chain rule holds exactly in any order; independence and conditional independence do not imply each other; “components independent given a latent” can represent rich correlations — the trick of latent-variable models.
- Gaussians:
- reparameterization ;
- the conditional mean is linear and the conditional variance does not depend on the observation;
- the KL between two Gaussians has a closed form (the VAE regularizer );
- high-dimensional samples live on a thin shell of radius , and the mode is not typical.
- Information theory:
- entropy = optimal code length; cross-entropy = entropy + KL;
- maximum likelihood = minimizing KL = sample frequencies, which on finite data gives unseen events probability 0;
- mutual information = how far the joint is from independence, and it only decreases along a chain;
- KL is invariant under invertible maps, differential entropy is not.
- Monte Carlo is unbiased, its error is , and it does not depend on the dimension. An importance-sampling proposal must cover the target. , and the IWAE bound approaches as the number of samples grows.
- Gradients of expectations:
- the score-function estimator is general but noisy, and gets worse with dimension;
- reparameterization has low variance but requires differentiability;
- for discrete variables, use the score function (unbiased, noisy), straight-through (a biased heuristic) or Gumbel-softmax (the temperature trades bias for variance).
- Change of variables: , and log-determinants add under composition. Triangular Jacobians turn into . When the dimension drops, the density does not exist.
- bits/dim = negative log-likelihood per dimension (in bits) + a discretization constant. Continuous models need dequantization on discrete data. Likelihood is compression.
9. Common pitfalls
- “A probability density cannot exceed 1.” A probability mass function cannot; a density can ( is about 4 at 0). So the “negative log-likelihood” of a continuous model can be negative (§7.1).
- “The chain rule is an approximation / autoregressive models assume independence.” The chain rule is an identity; the approximation comes from how each conditional is represented (§1.2).
- “The KL divergence is a distance.” It is asymmetric and violates the triangle inequality (§3.2).
- “Maximum likelihood is always a good estimator.” On finite data it overfits and gives unseen events probability 0 (§3.3); in the continuous case it can even push the likelihood to infinity (§6.4, §7.2).
- “Importance sampling is unbiased, so any proposal will do.” Unbiased only in expectation; with a too-narrow proposal the variance can be infinite and the estimate you actually get is almost always too small (§4.2).
- “A larger ELBO means a better approximate posterior.” ELBO = depends both on the model’s likelihood and on the quality of the posterior approximation; the ELBOs of two different models say nothing direct about whose posterior approximation is better (§4.3).
- “Reparameterization is always better than the score function.” It requires a differentiable and continuous variables; with a non-differentiable it gives a wrong gradient (§5.3).
- “Straight-through gives an approximation of the true gradient.” It is a biased heuristic, and its bias can exceed the gradient itself (§5.4).
- “Bits/dim can be compared directly across papers.” Check how the data were scaled, discretized and dequantized (§7.1, §7.2).
10. Exercises
Exercise 1 (the parameter count of the chain rule) How many free parameters does the full joint table of discrete variables with values each have? What if you use the chain rule with every conditional also stored as a full table? Explain why “the chain rule itself saves no parameters; the savings come from how the conditionals are represented”.
Answer
Full joint table: . Chain rule with full conditional tables: the -th conditional needs numbers for each of the values of , for a total of — exactly the same. The chain rule only rewrites; it saves no parameters. Replacing the conditionals with a neural network with shared parameters (Lectures 5, 6) makes the parameter count polynomial in , at the price of assumptions about the form of the conditionals (an inductive bias).
Exercise 2 (non-negativity of KL and maximum likelihood) (a) Prove with Jensen’s inequality. (b) Derive the maximum-likelihood solution for a categorical distribution with a Lagrange multiplier. (c) Explain why the solution of (b) equals , where is the empirical distribution.
Answer
(a) (summing over the with ). (b) Maximize : the derivative in gives , i.e. ; gives . (c) . The first term does not depend on , and minimizing the negative of the second is maximizing the mean log-likelihood. By (a), the minimum 0 is attained at , i.e. .
Exercise 3 (the VAE regularizer) Derive and its gradients with respect to and . When are the gradients zero?
Answer
(the negative entropy of a Gaussian), and . Subtract. With : , . The gradients vanish at , : the regularizer pulls the code distribution toward the standard normal. Its tug-of-war with the reconstruction term decides what a VAE’s latent space looks like (Lecture 3).
Exercise 4 (the ELBO identity) Prove that holds for any distribution . What does this mean for Lecture 3?
Answer
The second term on the right is . Adding the first term, and cancel, leaving . Meaning:
- Since the KL is ≥ 0, the ELBO is a lower bound of for every , and can be maximized.
- With the model fixed, maximizing the ELBO is equivalent to minimizing the KL from to the true posterior.
- The identity holds for “any ”. The Lecture 3 slides stress repeatedly that “this equation holds for any distribution q(z)” — the starting point for parameterizing with a network in the VAE.
Exercise 5 (the variance of importance sampling) Let and the proposal . Show that () is infinite when . How does this relate to the result of part 2 of script 04?
Answer
. The coefficient of in the exponent is , which is non-negative for , so the integral diverges. The weights have infinite variance; the estimate is correct in expectation, but the fluctuations of the sample mean are unbounded — in practice “mostly too small, occasionally huge”. The double-well target of script 04 is even wider than a standard normal, and is far below the threshold, hence the relative std of 374% and a median of only 0.42 of the truth.
Exercise 6 (the Gumbel-max trick) Let be independent standard Gumbel variables (CDF ). Prove .
Answer
is “a Gumbel with location ”, with CDF and density . Then . With the integral becomes , where . That is the softmax.
Exercise 7 (change of variables) Let and . Find the density of . What sampling method does this give?
Answer
is increasing, , and , so for : the exponential distribution. This is inverse-CDF sampling: the exponential CDF is , and turns a uniform into the target. In one dimension every distribution can be sampled this way; in high dimensions there is no such simple “inverse CDF”, so generative models have to learn a map from a simple distribution to a complex one (Lecture 1 §6).
Exercise 8 (converting to bits/dim) A continuous model reports a mean negative log-likelihood of nats per image on 32×32×3 images scaled to (with uniform dequantization and nothing else). Convert to bits/dim.
Answer
. Per dimension: nats, i.e. bits. With data in , and . So bpd .
11. Further reading
- T. M. Cover & J. A. Thomas, Elements of Information Theory (2nd ed.): Chapter 2 (entropy, KL, mutual information, Jensen, data processing) and Chapter 5 (source coding, Huffman).
- K. P. Murphy, Probabilistic Machine Learning: An Introduction (2022), Chapters 2–6; Advanced Topics (2023), Chapter 6 (Monte Carlo and gradient estimation) and Chapter 11 (importance sampling).
- D. P. Kingma & M. Welling, Auto-Encoding Variational Bayes, ICLR 2014: the reparameterization trick and the SGVB estimator (required for Lecture 3).
- Y. Burda, R. Grosse, R. Salakhutdinov, Importance Weighted Autoencoders, ICLR 2016: the IWAE bound.
- S. Mohamed, M. Rosca, M. Figurnov, A. Mnih, Monte Carlo Gradient Estimation in Machine Learning, JMLR 2020: a systematic survey of score-function, pathwise and measure-valued derivatives.
- E. Jang, S. Gu, B. Poole, Categorical Reparameterization with Gumbel-Softmax, ICLR 2017; C. Maddison, A. Mnih, Y. W. Teh, The Concrete Distribution, ICLR 2017.
- Y. Bengio, N. Léonard, A. Courville, Estimating or Propagating Gradients Through Stochastic Neurons for Conditional Computation, 2013: the straight-through estimator.
- L. Theis, A. van den Oord, M. Bethge, A note on the evaluation of generative models, ICLR 2016: dequantization, bits/dim, and “likelihood and sample quality can disagree badly”.
- MIT6.S184 prerequisite P1: conditional expectation, vector calculus (divergence, Laplacian) and the instantaneous change of variables of flows — used in Lectures 12 and 16 (diffusion, flow matching). (That course’s notes are in Chinese.)