Prerequisite P1 · Probability, Information & Maximum Likelihood

Deep Generative Models · 预备知识 1。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

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

本篇目录

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:

ToolWhere it is first used
Joint / marginal / conditional, Bayes’ rule, chain ruleLecture 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 GaussiansLecture 3 (VAE), Lecture 12 (every step of a diffusion model)
Entropy, cross-entropy, KL, maximum likelihoodLecture 1 §5; then almost every lecture
Mutual informationLecture 1 §7, Lecture 3 (InfoVAE)
Monte Carlo, importance samplingLecture 3 (estimating the ELBO), Lecture 12 (normalizing constants of energy models)
Score-function vs reparameterization gradients, straight-through, Gumbel-softmaxLecture 3 (VAE, VQ-VAE), Lecture 7 (DALL·E’s discrete VAE)
The change-of-variables formulaLecture 4 (normalizing flows), Lecture 6 (IAF / MAF)
bits/dim, dequantizationLectures 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

  1. 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.
  2. Sample a multivariate Gaussian by reparameterization; write the conditional of a multivariate Gaussian; derive DKL(N(μ,diag⁡σ2)∥N(0,I))D_{\text{KL}}(\mathcal{N}(\mu, \operatorname{diag}\sigma^2) \Vert \mathcal{N}(0, I)); know where the samples of a high-dimensional Gaussian are.
  3. 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.
  4. Estimate expectations by Monte Carlo with an error bar; use importance sampling, choose a proposal and know when it fails; verify log⁡p(x)=ELBO+DKL(q∥p(z∣x))\log p(x) = \text{ELBO} + D_{\text{KL}}(q \Vert p(z \mid x)) with numbers.
  5. 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.
  6. 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.
  7. 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

SymbolMeaning
p(x)p(x)a probability mass function (a probability) for discrete xx, a probability density (can exceed 1) for continuous xx
p(x,y)p(x, y), p(x∣y)p(x \mid y)joint; conditional
Ex∼p[f(x)]\mathbb{E}_{x \sim p}[f(x)]expectation of f(x)f(x) under x∼px \sim p
N(x;μ,Σ)\mathcal{N}(x; \mu, \Sigma)Gaussian density with mean μ\mu and covariance Σ\Sigma
H(p)H(p), H(p,q)H(p, q)entropy; cross-entropy
DKL(p∥q)D_{\text{KL}}(p \Vert q)KL divergence
I(X;Y)I(X; Y)mutual information
bit / natlog 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 A∈{car,bus}A \in \{\text{car}, \text{bus}\}, color B∈{dark,light}B \in \{\text{dark}, \text{light}\}, age C∈{new,old}C \in \{\text{new}, \text{old}\}. Script 01 makes up probabilities for it, giving a 2×2×22 \times 2 \times 2 joint distribution p(A,B,C)p(A, B, C) whose 8 entries sum to 1. With the joint, everything else can be computed:

  • Marginal: sum over the variables you do not care about. p(B)=∑a∑cp(a,B,c)p(B) = \sum_a \sum_c p(a, B, c). Here p(B=dark)=0.48p(B = \text{dark}) = 0.48.
  • Conditional: joint divided by marginal. p(A∣B)=p(A,B)/p(B)p(A \mid B) = p(A, B) / p(B). Here p(A∣B=dark)=(0.875,0.125)p(A \mid B = \text{dark}) = (0.875, 0.125).
  • Bayes’ rule: “reverse” a conditional, p(A∣B)=p(B∣A) p(A)/p(B)p(A \mid B) = p(B \mid A)\,p(A) / p(B). The two computations in the code give exactly the same numbers. After seeing C=oldC = \text{old}, p(A=bus)p(A = \text{bus}) 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 dd binary variables has 2d−12^d - 1 free parameters; one 28×28 black-and-white image means 27842^{784} 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 p(A,B)=p(A) p(B∣A)p(A, B) = p(A)\,p(B \mid A) repeatedly gives the chain rule:

p(x1,x2,…,xd)=p(x1) p(x2∣x1) p(x3∣x1,x2)⋯p(xd∣x1,…,xd−1).p(x_1, x_2, \dots, x_d) = p(x_1)\, p(x_2 \mid x_1)\, p(x_3 \mid x_1, x_2) \cdots p(x_d \mid x_1, \dots, x_{d-1}) .

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 10−1710^{-17} (floating-point rounding). Two things to remember:

  1. 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”.
  2. 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: p(x,y)=p(x) p(y)p(x, y) = p(x)\,p(y), equivalently p(x∣y)=p(x)p(x \mid y) = p(x) — knowing yy does not help you guess xx.
  • Conditional independence: given zz, p(x,y∣z)=p(x∣z) p(y∣z)p(x, y \mid z) = p(x \mid z)\, p(y \mid z).

Neither implies the other. Part 3 of script 01 shows both directions:

(a) Independent causes become dependent through a common effect (“explaining away”). Rain RR (20%) and a sprinkler SS (30%) are independent; wet grass W≈R∨SW \approx R \lor S.

ProbabilityValue
P(R)P(R)0.201
P(R∣S=1)P(R \mid S{=}1)0.200
P(R∣W=1)P(R \mid W{=}1)0.455
P(R∣W=1,S=1)P(R \mid W{=}1, S{=}1)0.200
P(R∣W=1,S=0)P(R \mid W{=}1, S{=}0)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 WW, the originally independent RR and SS become dependent.

(b) Dependent observations become independent given a common latent. Let zz mean “this is a 0 or a 1”; given zz, two pixels x1x_1, x2x_2 turn on independently with probability qzq_z (q0=0.1q_0 = 0.1, q1=0.9q_1 = 0.9):

QuantityValue
correlation of x1,x2x_1, x_2 (zz unknown)+0.639
correlation given z=0z = 0 / z=1z = 1−0.003 / −0.002
P(x2 on)P(x_2 \text{ on}) → P(x2 on∣x1 on)P(x_2 \text{ on} \mid x_1 \text{ on})0.499 → 0.819

This is the central trick of latent-variable models:

p(x)=∑zp(z)∏ip(xi∣z).p(x) = \sum_z p(z) \prod_i p(x_i \mid z) .

Each p(xi∣z)p(x_i \mid z) is extremely simple (pixels independent), but after summing (or integrating) over zz, the components of xx 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

E[X]=E[E[X∣Y]],Var⁡(X)=E[Var⁡(X∣Y)]⏟within groups+Var⁡(E[X∣Y])⏟between groups.\mathbb{E}[X] = \mathbb{E}\big[\mathbb{E}[X \mid Y]\big],\qquad \operatorname{Var}(X) = \underbrace{\mathbb{E}\big[\operatorname{Var}(X \mid Y)\big]}_{\text{within groups}} + \underbrace{\operatorname{Var}\big(\mathbb{E}[X \mid Y]\big)}_{\text{between groups}} .

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; E[Var⁡(X∣Y)]\mathbb{E}[\operatorname{Var}(X \mid Y)] 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 dd-dimensional Gaussian N(μ,Σ)\mathcal{N}(\mu, \Sigma) is

N(x;μ,Σ)=1(2π)d/2∣Σ∣1/2exp⁡(−12(x−μ)⊤Σ−1(x−μ)).\mathcal{N}(x; \mu, \Sigma) = \frac{1}{(2\pi)^{d/2} |\Sigma|^{1/2}} \exp\Big(-\tfrac12 (x - \mu)^\top \Sigma^{-1} (x - \mu)\Big) .

Reparameterization: every Gaussian can be written as “a standard normal + a deterministic transformation”:

x=μ+Lϵ,ϵ∼N(0,I),Σ=LL⊤ (Cholesky factorization).x = \mu + L\epsilon,\qquad \epsilon \sim \mathcal{N}(0, I),\qquad \Sigma = LL^\top \ (\text{Cholesky factorization}) .

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 ϵ\epsilon, and the parameters μ\mu, LL 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 =∥L−1(x−μ)∥2= \Vert L^{-1}(x-\mu) \Vert^2 and log⁡∣Σ∣=2∑ilog⁡Lii\log|\Sigma| = 2\sum_i \log L_{ii}, more stable than an explicit inverse.

2.2 Marginals, conditionals, the linear-Gaussian model

Split xx into two blocks (x1,x2)(x_1, x_2), with the mean and covariance split accordingly:

μ=(μ1μ2),Σ=(Σ11Σ12Σ21Σ22).\mu = \begin{pmatrix}\mu_1 \\ \mu_2\end{pmatrix},\qquad \Sigma = \begin{pmatrix}\Sigma_{11} & \Sigma_{12} \\ \Sigma_{21} & \Sigma_{22}\end{pmatrix} .
  • Marginal: x1∼N(μ1,Σ11)x_1 \sim \mathcal{N}(\mu_1, \Sigma_{11}) (just take the block).
  • Conditional: x1∣x2∼N(μ1+Σ12Σ22−1(x2−μ2), Σ11−Σ12Σ22−1Σ21)x_1 \mid x_2 \sim \mathcal{N}\big(\mu_1 + \Sigma_{12}\Sigma_{22}^{-1}(x_2 - \mu_2),\ \Sigma_{11} - \Sigma_{12}\Sigma_{22}^{-1}\Sigma_{21}\big).

The conditional mean is a linear function of the observation x2x_2; the conditional covariance does not depend on the observed value and is always smaller than the marginal covariance (knowing x2x_2 reduces uncertainty). Part 2 of script 02 takes samples in a thin slice around x2=2x_2 = 2: 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”:

Conditional Gaussian and the high-dimensional soap bubble

A linear-Gaussian latent-variable model: z∼N(0,1)z \sim \mathcal{N}(0, 1), x∣z∼N(az,s2)x \mid z \sim \mathcal{N}(az, s^2). (z,x)(z, x) is jointly Gaussian, so the marginal p(x)=N(0,a2+s2)p(x) = \mathcal{N}(0, a^2 + s^2) and the posterior p(z∣x)p(z \mid x) have closed forms (precisions add: 1/σpost2=1+a2/s21/\sigma_{\text{post}}^2 = 1 + a^2/s^2, μpost=σpost2 ax/s2\mu_{\text{post}} = \sigma_{\text{post}}^2\, a x / s^2). With a=2a = 2, s=0.5s = 0.5, x=1x = 1, 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 qϕ(z∣x)q_\phi(z \mid x). §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 dd-dimensional Gaussians has a closed form:

DKL(N(μ1,Σ1) ∥ N(μ2,Σ2))=12[tr⁡(Σ2−1Σ1)+(μ2−μ1)⊤Σ2−1(μ2−μ1)−d+log⁡∣Σ2∣∣Σ1∣].D_{\text{KL}}\big(\mathcal{N}(\mu_1, \Sigma_1) \,\Vert\, \mathcal{N}(\mu_2, \Sigma_2)\big) = \frac12\Big[\operatorname{tr}(\Sigma_2^{-1}\Sigma_1) + (\mu_2 - \mu_1)^\top \Sigma_2^{-1}(\mu_2 - \mu_1) - d + \log\frac{|\Sigma_2|}{|\Sigma_1|}\Big] .

The special case used most in VAEs is a diagonal Gaussian against the standard normal:

DKL(N(μ,diag⁡σ2) ∥ N(0,I))=−12∑j=1d(1+log⁡σj2−μj2−σj2).D_{\text{KL}}\big(\mathcal{N}(\mu, \operatorname{diag}\sigma^2) \,\Vert\, \mathcal{N}(0, I)\big) = -\frac12\sum_{j=1}^{d}\big(1 + \log\sigma_j^2 - \mu_j^2 - \sigma_j^2\big) .

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, DKL=Eq[log⁡q−log⁡p]=−12log⁡(2πeσ2)+12log⁡2π+12Eq[z2]=−12(1+log⁡σ2)+12(μ2+σ2)D_{\text{KL}} = \mathbb{E}_q[\log q - \log p] = -\tfrac12\log(2\pi e\sigma^2) + \tfrac12\log 2\pi + \tfrac12\mathbb{E}_q[z^2] = -\tfrac12(1 + \log\sigma^2) + \tfrac12(\mu^2 + \sigma^2).

Part 3 of script 02 compares the closed form with Monte Carlo estimates (true KL 0.5531):

Monte Carlo samplesmean of 50 estimatesstd of 50 estimates
100.59610.1948
1000.54930.0579
1,0000.55220.0234
10,0000.55310.0067
100,0000.55350.0022

Monte Carlo is unbiased but noisy; at N=10N = 10 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, μ=(0.3,−1.2,0,2)\mu = (0.3, -1.2, 0, 2) and log⁡σ2=(−1,0.5,0,−3)\log\sigma^2 = (-1, 0.5, 0, -3), and the four dimensions contribute 0.229, 0.794, 0.000 and 3.025:

  • the dimension with μ=0\mu = 0, σ2=1\sigma^2 = 1 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 dd-dimensional standard normal have norms concentrated around d\sqrt{d}: ∥x∥2=∑jxj2\Vert x\Vert^2 = \sum_j x_j^2 has mean dd and variance 2d2d, so ∥x∥≈d±0.7\Vert x \Vert \approx \sqrt{d} \pm 0.7.

dimension ddd\sqrt dmean ∥x∥\Vert x\Vertstdfraction with ∥x∥<d/2\Vert x\Vert < \sqrt d/2log⁡p(0)−log⁡p(x)‾\log p(\mathbf{0}) - \overline{\log p(x)}
11.000.810.6050.3860.5
103.163.080.6880.0095.0
10010.009.980.7140.00050.0
10000100.00100.000.6900.0005000.1

The density at the origin (the mode) is d/2d/2 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 d\sqrt d”.


3. Information theory

3.1 Entropy: the average length of the best code

The entropy of a discrete distribution pp is

H(p)=−∑xp(x)log⁡2p(x)(bits).H(p) = -\sum_x p(x) \log_2 p(x) \quad (\text{bits}) .

The best way to understand it is through coding. Shannon’s source coding theorem says:

  • for symbols from pp, no uniquely decodable binary code can have an average length below H(p)H(p);
  • a code with average length below H(p)+1H(p) + 1 always exists;
  • ideally, a symbol of probability p(x)p(x) should get −log⁡2p(x)-\log_2 p(x) bits (the more common, the shorter).

Script 03 checks this with Huffman codes:

distributionentropy HHmean Huffman length
uniform (8 symbols)3.00003.0000
skewed (0.5, 0.2, 0.1, 0.1, 0.05, 0.03, 0.01, 0.01)2.12952.1700
almost certain0.25191.0650
all probabilities powers of 21.98441.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 −log⁡2p-\log_2 p 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 pp with “the ideal code designed for qq” (length −log⁡2q(x)-\log_2 q(x)) takes, on average, the cross-entropy:

H(p,q)=−∑xp(x)log⁡2q(x)=H(p)+DKL(p∥q),DKL(p∥q)=∑xp(x)log⁡2p(x)q(x).H(p, q) = -\sum_x p(x) \log_2 q(x) = H(p) + D_{\text{KL}}(p \Vert q),\qquad D_{\text{KL}}(p \Vert q) = \sum_x p(x) \log_2\frac{p(x)}{q(x)} .

The KL divergence is “the extra bits spent because the model is wrong”. Part 2 of script 03 (data from the “skewed” distribution above, H=2.1295H = 2.1295):

distribution qq used for the codeH(p,q)H(p, q)DKL(p∥q)D_{\text{KL}}(p\Vert q)DKL(q∥p)D_{\text{KL}}(q\Vert p)
q=pq = p2.12950.00000.0000
qq = uniform3.00000.87051.0793
first two probabilities swapped2.52610.39660.3966
misses the last symbol (prob. 0)∞∞0.0166

Three properties:

  1. Non-negative: DKL(p∥q)≥0D_{\text{KL}}(p\Vert q) \ge 0, with equality iff p=qp = q (by Jensen’s inequality, exercise 2).
  2. Asymmetric: DKL(p∥q)≠DKL(q∥p)D_{\text{KL}}(p\Vert q) \ne D_{\text{KL}}(q \Vert p) (the uniform row; the forward / reverse KL of Lecture 1 §5.3).
  3. Support: as soon as qq gives probability 0 to a symbol that really occurs, DKL(p∥q)=∞D_{\text{KL}}(p\Vert q) = \infty; the other direction can still be small (last row).

3.3 Maximum likelihood = minimizing KL = sample frequencies; and its overfitting

Fit a KK-class categorical distribution q=(q1,…,qK)q = (q_1, \dots, q_K) to NN samples. The mean log-likelihood is 1N∑knklog⁡qk\frac1N\sum_k n_k \log q_k (nkn_k = how often class kk occurs). Maximizing it subject to ∑kqk=1\sum_k q_k = 1 with a Lagrange multiplier gives nkNqk=λ\frac{n_k}{N q_k} = \lambda, i.e.

qkMLE=nkN.q_k^{\text{MLE}} = \frac{n_k}{N} .

The maximum-likelihood estimate is the sample frequency. It is also the solution of “minimize DKL(p^data∥q)D_{\text{KL}}(\hat p_{\text{data}} \Vert q)” (p^data\hat p_{\text{data}} = 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):

samplesunseen classestheir total true probabilitycross-entropy of MLEafter smoothing
2082%0.346∞4.732
10054%0.116∞4.505
1,00026%0.004∞4.261
10,00012%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 h→0h \to 0 in Lecture 1 §4.5. The simplest remedy is add-α\alpha smoothing, qk=(nk+α)/(N+Kα)q_k = (n_k + \alpha)/(N + K\alpha) (equivalent to putting a prior on the model), with α\alpha 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 XX drops once YY is known”:

I(X;Y)=H(X)−H(X∣Y)=DKL(p(x,y) ∥ p(x)p(y)) ≥0.I(X; Y) = H(X) - H(X \mid Y) = D_{\text{KL}}\big(p(x, y) \,\Vert\, p(x)p(y)\big) \ \ge 0 .

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: XX uniform on 0/1, YY = XX flipped with probability ε\varepsilon, ZZ = YY flipped again with probability ε\varepsilon:

flip probability ε\varepsilonI(X;Y)I(X;Y) (both formulas)I(X;Z)I(X;Z)
0.01.00001.0000
0.050.71360.5471
0.10.53100.3199
0.20.27810.0956
0.50.00000.0000

Data processing inequality: if X→Y→ZX \to Y \to Z is a Markov chain, then I(X;Z)≤I(X;Y)I(X; Z) \le I(X; Y) — no processing of data can create new information. The conditional-entropy table of Lecture 1 §7 asks “how much information about xx does the condition yy 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” h(p)=−∫plog⁡ph(p) = -\int p \log p of a continuous variable is not a direct generalization of discrete entropy. A Gaussian’s differential entropy is 12log⁡2(2πeσ2)\tfrac12\log_2(2\pi e\sigma^2). For σ=2,1,0.5,0.1\sigma = 2, 1, 0.5, 0.1 it is +3.05, +2.05, +1.05 and −1.27 bits: it can be negative. Scaling the variable by aa adds log⁡2∣a∣\log_2|a|. It depends on units and coordinates.

The KL divergence, however, is invariant under invertible transformations. Applying the same invertible map y=g(x)y = g(x) to both distributions multiplies both densities by the same Jacobian factor (§6), which cancels in the ratio p/qp/q. Part 5 of script 03: DKL(N(0,1)∥N(1,1.52))D_{\text{KL}}(\mathcal{N}(0,1) \Vert \mathcal{N}(1, 1.5^2)) is 0.3499 nat in closed form, estimated as 0.3505 on xx, and still 0.3505 after the transformation y=exy = e^x. 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 / distancedefinition (intuition)lecture
KL (forward, reverse)extra bits of the wrong codeLectures 1, 3, 12
Jensen–Shannon (JS)mean of the KLs to “the average of the two”; symmetric, bounded in [0,log⁡2][0, \log 2]Lecture 9 (the original GAN)
Wasserstein-1 (earth mover’s distance)minimal cost of moving one pile of earth into anotherLecture 9 (WGAN)
Fisher divergencesquared difference of the score functions ∇xlog⁡p\nabla_x \log p of two distributionsLecture 12 (score matching)

4. Monte Carlo and importance sampling

4.1 Monte Carlo: if you can sample, you can estimate expectations

Ex∼p[f(x)]≈1n∑i=1nf(xi),xi∼p.\mathbb{E}_{x\sim p}[f(x)] \approx \frac1n\sum_{i=1}^n f(x_i),\quad x_i \sim p .

The estimate is unbiased, its standard deviation is σf/n\sigma_f / \sqrt{n}, and it does not depend on the dimension of xx. Part 1 of script 04 estimates E[cos⁡X]\mathbb{E}[\cos X] for X∼N(0,1)X \sim \mathcal{N}(0,1). For n=10,100,1000,10000n = 10, 100, 1000, 10000 the standard deviations are 0.142, 0.044, 0.014 and 0.0046, so “std × n\sqrt n” stays at about 0.45. The interval “mean ± 1.96 × standard error” contains the truth 94–95% of the time, but only 87% at n=10n = 10, 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 Ep[f]\mathbb{E}_p[f] when pp is hard to sample (or to sample more “where it matters”), sample from another distribution qq and reweight:

Ep[f(x)]=∫q(x)p(x)q(x)f(x) dx=Eq[w(x)f(x)],w(x)=p(x)q(x).\mathbb{E}_{p}[f(x)] = \int q(x)\frac{p(x)}{q(x)}f(x)\,dx = \mathbb{E}_{q}\big[w(x)f(x)\big],\qquad w(x) = \frac{p(x)}{q(x)} .

Even better, when pp is known only up to a constant (p(x)=p~(x)/Zp(x) = \tilde p(x)/Z), we can estimate the normalizing constant: Z=∫p~=Eq[p~(x)/q(x)]Z = \int \tilde p = \mathbb{E}_q[\tilde p(x)/q(x)]. This is the core difficulty of the energy-based models of Lecture 12 (p(x)∝e−E(x)p(x) \propto e^{-E(x)}). Part 2 of script 04 uses the double-well energy E(x)=x4/4−x2E(x) = x^4/4 - x^2 (true Z=7.5875Z = 7.5875) and proposals q=N(0,s2)q = \mathcal{N}(0, s^2), with 1000 samples each:

ssmean of Z^\hat Zrelative stdmedian / trutheffective sample size
0.36.19374%0.4237
0.77.585.6%1.00226
1.57.601.9%1.00694
3.07.593.1%1.00472
8.07.586.7%1.00192

Importance sampling and the IWAE bound

The effective sample size ESS=(∑wi)2/∑wi2\text{ESS} = (\sum w_i)^2 / \sum w_i^2 measures how uneven the weights are. The rule: qq must “cover” the target; its tails must not be lighter than the target’s. When qq 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 P(X>4)P(X > 4) with X∼N(0,1)X \sim \mathcal N(0,1) (truth 3.17×10−53.17\times10^{-5}):

  • plain sampling with 100,000 samples has relative std 52.6%;
  • sampling from N(4,1)\mathcal{N}(4, 1) 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 p(x)=∫p(z) p(x∣z) dzp(x) = \int p(z)\,p(x \mid z)\,dz? Importance-sample with an approximate posterior q(z∣x)q(z \mid x):

p(x)=Ez∼q[p(x,z)q(z∣x)].p(x) = \mathbb{E}_{z \sim q}\left[\frac{p(x, z)}{q(z \mid x)}\right] .

Taking the log and using Jensen’s inequality (log⁡\log is concave, so log⁡E≥Elog⁡\log \mathbb{E} \ge \mathbb{E} \log):

log⁡p(x) ≥ Ez∼q[log⁡p(x,z)q(z∣x)]≡ELBO(q).\log p(x) \ \ge\ \mathbb{E}_{z\sim q}\left[\log\frac{p(x, z)}{q(z \mid x)}\right] \equiv \text{ELBO}(q) .

And the gap is exactly a KL:

log⁡p(x)=ELBO(q)+DKL(q(z∣x) ∥ p(z∣x)).\log p(x) = \text{ELBO}(q) + D_{\text{KL}}\big(q(z \mid x) \,\Vert\, p(z \mid x)\big) .

(Proof: substitute p(x,z)=p(z∣x)p(x)p(x, z) = p(z \mid x)p(x) into the ELBO; log⁡p(x)\log p(x) does not depend on zz and comes out, and what remains is −DKL-D_{\text{KL}}.) 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 log⁡p(x)=−1.7600\log p(x) = -1.7600 is known exactly:

approximate posterior qqELBOlog⁡p(x)−ELBO\log p(x) - \text{ELBO}DKL(q∥p(z∣x))D_{\text{KL}}(q\Vert p(z\mid x))IWAE K=10K = 10K=100K = 100K=1000K = 1000
prior N(0,1)\mathcal{N}(0, 1)−10.1988.4388.466−1.951−1.777−1.760
true posterior−1.7600.0000.000−1.760−1.760−1.760
mean shifted by 0.3−2.5190.7590.765−1.895−1.788−1.754
4× variance−2.5650.8050.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 qq is the true posterior, every sample’s weight equals p(x)p(x) exactly; the estimate has zero variance and the ELBO equals log⁡p(x)\log p(x). So “maximize the ELBO” does two things at once: it raises the likelihood and pushes qq toward the true posterior.
  • The IWAE bound E[log⁡1K∑kwk]\mathbb{E}\big[\log \frac1K\sum_k w_k\big] (average the weights first, then take the log) approaches log⁡p(x)\log p(x) as KK grows; the worse qq, the larger the KK needed. qq = prior is the worst — which is why a VAE trains an encoder to approximate the posterior instead of sampling zz from the prior. (At K=1000K = 1000 a few numbers are slightly above log⁡p(x)\log p(x): 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 L(θ)=Ez∼qθ[f(z)]L(\theta) = \mathbb{E}_{z \sim q_\theta}[f(z)]: 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 ∇θ\nabla_\theta inside the expectation, because the sampling itself depends on θ\theta.

The score-function estimator (also called REINFORCE or the likelihood-ratio estimator) uses the “log-derivative trick” ∇θqθ=qθ∇θlog⁡qθ\nabla_\theta q_\theta = q_\theta \nabla_\theta \log q_\theta:

∇θL=∫f(z)∇θqθ(z) dz=Ez∼qθ[f(z) ∇θlog⁡qθ(z)].\nabla_\theta L = \int f(z)\nabla_\theta q_\theta(z)\,dz = \mathbb{E}_{z\sim q_\theta}\big[f(z)\,\nabla_\theta \log q_\theta(z)\big] .

It needs only the values of ff; ff need not be differentiable, and discrete variables are fine. Since Eq[∇θlog⁡qθ]=∇θ∫qθ=0\mathbb{E}_q[\nabla_\theta \log q_\theta] = \nabla_\theta \int q_\theta = 0, any baseline bb that does not depend on zz can be subtracted from ff without changing the expectation. A good baseline can cut the variance dramatically.

The reparameterization estimator (also called pathwise). If z=gθ(ϵ)z = g_\theta(\epsilon) with the distribution of ϵ\epsilon independent of θ\theta (§2.1), then

∇θL=Eϵ[∇θf(gθ(ϵ))]=Eϵ[∇zf(z)⋅∇θgθ(ϵ)].\nabla_\theta L = \mathbb{E}_{\epsilon}\big[\nabla_\theta f(g_\theta(\epsilon))\big] = \mathbb{E}_{\epsilon}\big[\nabla_z f(z) \cdot \nabla_\theta g_\theta(\epsilon)\big] .

It needs ff differentiable in zz and zz differentiable in θ\theta, but it uses the extra information in the derivative of ff.

5.2 Experiment: variance, baselines and dimension

L(μ,σ)=Ez∼N(μ,σ2)[(z−2)2]=(μ−2)2+σ2L(\mu, \sigma) = \mathbb{E}_{z\sim\mathcal{N}(\mu,\sigma^2)}[(z-2)^2] = (\mu-2)^2 + \sigma^2 has true gradient (−4,2)(-4, 2) at μ=0\mu = 0, σ=1\sigma = 1. With B=10B = 10 samples per estimate (part 1 of script 05):

method∂L/∂μ\partial L/\partial\mu∂L/∂σ\partial L/\partial\sigma
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 f(z)=∥z−2∥2f(z) = \Vert z - 2\Vert^2 and the gradient with respect to μ1\mu_1:

dd1101001000
score function (with baseline), std2.15.014.344.8
reparameterization, std≈ 0.63≈ 0.63≈ 0.63≈ 0.63

In the score-function estimator, the value of ff contains the random fluctuations of the other d−1d-1 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 f(z)=1[z>1]f(z) = \mathbb{1}[z > 1], so L=P(z>1)L = P(z > 1), with true gradient ϕ(1)=0.242\phi(1) = 0.242.

  • 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 ff to be differentiable.

5.4 Discrete variables: straight-through and Gumbel-softmax

A discrete variable k∼Categorical(softmax⁡(θ))k \sim \text{Categorical}(\operatorname{softmax}(\theta)) 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 L=E[(vk−c)2]L = \mathbb{E}[(v_k - c)^2]; the exact gradient can be computed by enumeration and has length 0.450.

estimatorbias ∥Eg^−∇L∥\Vert\mathbb{E}\hat g - \nabla L\Vertnoise ∑Var⁡\sqrt{\sum \operatorname{Var}}
score function + baseline0.0080.456
straight-through0.6090.547
Gumbel-softmax τ=2\tau = 20.3900.079
Gumbel-softmax τ=1\tau = 10.3370.214
Gumbel-softmax τ=0.5\tau = 0.50.2360.419
Gumbel-softmax τ=0.1\tau = 0.10.0801.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 ff is linear (because E[one-hot]=softmax\mathbb{E}[\text{one-hot}] = \text{softmax}), and more biased the more curved ff 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 arg⁡max⁡k(θk+gk)\arg\max_k(\theta_k + g_k), with independent Gumbel noises gkg_k, is distributed exactly as softmax⁡(θ)\operatorname{softmax}(\theta). Replacing the argmax with a softmax at temperature τ\tau gives a differentiable “soft one-hot”. A large τ\tau is smooth, with low noise and high bias; τ→0\tau \to 0 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 z∼pzz \sim p_z and x=g(z)x = g(z) with gg strictly monotone. The probability that xx falls in [x,x+dx][x, x + dx] equals the probability that zz falls in the corresponding interval [z,z+dz][z, z + dz]: px(x)∣dx∣=pz(z)∣dz∣p_x(x)|dx| = p_z(z)|dz|, so

px(x)=pz(z)∣dzdx∣=pz(g−1(x))∣g′(g−1(x))∣.p_x(x) = p_z(z)\left|\frac{dz}{dx}\right| = \frac{p_z(g^{-1}(x))}{|g'(g^{-1}(x))|} .

Wherever the map stretches an interval, the density thins out by the same factor. Part 1 of script 06 checks three maps:

  • x=ezx = e^z (log-normal, px(x)=ϕ(log⁡x)/xp_x(x) = \phi(\log x)/x): at x=0.3x = 0.3 the histogram gives 0.6450 and the formula 0.6442.
  • x=Φ(z)x = \Phi(z) (the normal CDF) turns a normal into a uniform distribution (all three histogram values ≈ 1). Conversely, Φ−1\Phi^{-1} turns a uniform into a normal.
  • The non-monotone x=z2x = z^2 has two preimages ±x\pm\sqrt{x}, and the two branches must be added: px(x)=[ϕ(x)+ϕ(−x)]/(2x)p_x(x) = [\phi(\sqrt x) + \phi(-\sqrt x)]/(2\sqrt x).

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 x=g(z)x = g(z) with the d×dd \times d Jacobian J=∂g/∂zJ = \partial g / \partial z:

px(x)=pz(z)∣det⁡J(z)∣,z=g−1(x);log⁡px(x)=log⁡pz(z)−log⁡∣det⁡J(z)∣.p_x(x) = \frac{p_z(z)}{|\det J(z)|},\qquad z = g^{-1}(x);\qquad \log p_x(x) = \log p_z(z) - \log|\det J(z)| .

∣det⁡J∣|\det J| is “how much gg magnifies a small volume”. Part 2 of script 06: for linear maps x=Azx = Az, the densities of the det⁡A=2.85\det A = 2.85 group are all about 2.85 times smaller.

Triangular Jacobians. The banana map x1=z1x_1 = z_1, x2=z2+b(z12−1)x_2 = z_2 + b(z_1^2 - 1) is nonlinear, but x2x_2 depends only on z2z_2 and the “earlier” z1z_1. So:

  • its Jacobian is lower triangular, (102bz11)\begin{pmatrix}1 & 0\\ 2bz_1 & 1\end{pmatrix};
  • its determinant is always 1;
  • its inverse is explicit (z2=x2−b(x12−1)z_2 = x_2 - b(x_1^2-1)).

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.

The banana map

6.3 Composition: log-determinants add up

For x=gK∘⋯∘g1(z)x = g_K \circ \cdots \circ g_1(z) with every step invertible:

log⁡px(x)=log⁡pz(z)−∑k=1Klog⁡∣det⁡Jk∣.\log p_x(x) = \log p_z(z) - \sum_{k=1}^K \log\big|\det J_k\big| .

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 d×dd \times d determinant needs O(d3)O(d^3) (LU factorization);
  • a triangular one needs O(d)O(d) (the product of the diagonal).

At d=1600d = 1600 the timings on this machine are about 8 ms vs 0.01 ms. A 256×256 color image has d≈200,000d \approx 200{,}000, 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 gg maps a low-dimensional zz into a higher-dimensional space (x=(z,2z)x = (z, 2z), z∈Rz \in \mathbb{R}), 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 ε\varepsilon to the covariance of a 2-D Gaussian to invert it. As ε\varepsilon falls from 0.1 to 10−810^{-8}, 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 [0,1][0, 1], the integer kk corresponds to the interval [k/256,(k+1)/256)[k/256, (k+1)/256) of width Δ=1/256\Delta = 1/256:

P(k)=∫k/256(k+1)/256p(x) dx≈p(x) Δ⟹−log⁡2P(k)≈−log⁡2p(x)+log⁡2256=−log⁡2p(x)+8.P(k) = \int_{k/256}^{(k+1)/256} p(x)\,dx \approx p(x)\,\Delta \quad\Longrightarrow\quad -\log_2 P(k) \approx -\log_2 p(x) + \log_2 256 = -\log_2 p(x) + 8 .

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

bpd=−1dlog⁡p(x) (nats, data in [0,1])ln⁡2+8.\text{bpd} = \frac{-\frac1d\log p(x)\ (\text{nats, data in }[0,1])}{\ln 2} + 8 .

(With data scaled to [−1,1][-1, 1], Δ=2/256\Delta = 2/256 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 hhcontinuous density directlybound after dequantizationinduced discrete NLL
1.03.3403.3503.349
0.11.3413.3613.341
0.01−1.9814.4973.342
0.001−5.303149.1773.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 u∈[0,1)u \in [0,1) to every integer and train and evaluate the continuous model on k+uk + u. By Jensen’s inequality,

Eu[−log⁡p(k+u)] ≥ −log⁡∫01p(k+u) du=−log⁡P(k),\mathbb{E}_u\big[-\log p(k + u)\big] \ \ge\ -\log\int_0^1 p(k+u)\,du = -\log P(k),

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 pp a length of −log⁡2p-\log_2 p 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 / compressorbits/dim
(a) uniform: 8 bits per pixel8.000
(b) one histogram for all pixels2.868
(c) one histogram per position (independent pixels)2.572
(d) autoregressive: p(pixel∣left, upper neighbours)p(\text{pixel} \mid \text{left, upper neighbours}), 64 contexts2.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

  1. 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.
  2. Gaussians:
    • reparameterization x=μ+Lϵx = \mu + L\epsilon;
    • 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 −12∑(1+log⁡σ2−μ2−σ2)-\tfrac12\sum(1 + \log\sigma^2 - \mu^2 - \sigma^2));
    • high-dimensional samples live on a thin shell of radius d\sqrt d, and the mode is not typical.
  3. 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.
  4. Monte Carlo is unbiased, its error is ∝1/n\propto 1/\sqrt n, and it does not depend on the dimension. An importance-sampling proposal must cover the target. log⁡p(x)=ELBO+DKL(q∥p(z∣x))\log p(x) = \text{ELBO} + D_{\text{KL}}(q \Vert p(z\mid x)), and the IWAE bound approaches log⁡p(x)\log p(x) as the number of samples grows.
  5. 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).
  6. Change of variables: log⁡px=log⁡pz−log⁡∣det⁡J∣\log p_x = \log p_z - \log|\det J|, and log-determinants add under composition. Triangular Jacobians turn O(d3)O(d^3) into O(d)O(d). When the dimension drops, the density does not exist.
  7. 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

  1. “A probability density cannot exceed 1.” A probability mass function cannot; a density can (N(0,0.12)\mathcal N(0, 0.1^2) is about 4 at 0). So the “negative log-likelihood” of a continuous model can be negative (§7.1).
  2. “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).
  3. “The KL divergence is a distance.” It is asymmetric and violates the triangle inequality (§3.2).
  4. “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).
  5. “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).
  6. “A larger ELBO means a better approximate posterior.” ELBO = log⁡p(x)−DKL\log p(x) - D_{\text{KL}} 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).
  7. “Reparameterization is always better than the score function.” It requires a differentiable ff and continuous variables; with a non-differentiable ff it gives a wrong gradient (§5.3).
  8. “Straight-through gives an approximation of the true gradient.” It is a biased heuristic, and its bias can exceed the gradient itself (§5.4).
  9. “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 dd discrete variables with KK 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: Kd−1K^d - 1. Chain rule with full conditional tables: the ii-th conditional needs K−1K - 1 numbers for each of the Ki−1K^{i-1} values of x<ix_{<i}, for a total of ∑i=1dKi−1(K−1)=Kd−1\sum_{i=1}^d K^{i-1}(K-1) = K^d - 1 — 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 dd, 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 DKL(p∥q)≥0D_{\text{KL}}(p\Vert q) \ge 0 with Jensen’s inequality. (b) Derive the maximum-likelihood solution qk=nk/Nq_k = n_k/N for a categorical distribution with a Lagrange multiplier. (c) Explain why the solution of (b) equals arg⁡min⁡qDKL(p^∥q)\arg\min_q D_{\text{KL}}(\hat p \Vert q), where p^\hat p is the empirical distribution.

Answer

(a) −DKL=Ep[log⁡(q/p)]≤log⁡Ep[q/p]=log⁡∑xq(x)≤log⁡1=0-D_{\text{KL}} = \mathbb{E}_p[\log(q/p)] \le \log\mathbb{E}_p[q/p] = \log\sum_x q(x) \le \log 1 = 0 (summing over the xx with p>0p > 0). (b) Maximize ∑knklog⁡qk−λ(∑kqk−1)\sum_k n_k\log q_k - \lambda(\sum_k q_k - 1): the derivative in qkq_k gives nk/qk=λn_k/q_k = \lambda, i.e. qk=nk/λq_k = n_k/\lambda; ∑qk=1\sum q_k = 1 gives λ=N\lambda = N. (c) DKL(p^∥q)=∑kp^klog⁡p^k−∑knkNlog⁡qkD_{\text{KL}}(\hat p\Vert q) = \sum_k \hat p_k\log\hat p_k - \sum_k \frac{n_k}{N}\log q_k. The first term does not depend on qq, and minimizing the negative of the second is maximizing the mean log-likelihood. By (a), the minimum 0 is attained at q=p^q = \hat p, i.e. qk=nk/Nq_k = n_k/N.

Exercise 3 (the VAE regularizer) Derive DKL(N(μ,σ2)∥N(0,1))=−12(1+log⁡σ2−μ2−σ2)D_{\text{KL}}(\mathcal{N}(\mu, \sigma^2) \Vert \mathcal{N}(0, 1)) = -\tfrac12(1 + \log\sigma^2 - \mu^2 - \sigma^2) and its gradients with respect to μ\mu and log⁡σ2\log\sigma^2. When are the gradients zero?

Answer

Eq[log⁡q]=−12log⁡(2πσ2)−12\mathbb{E}_q[\log q] = -\tfrac12\log(2\pi\sigma^2) - \tfrac12 (the negative entropy of a Gaussian), and Eq[log⁡p]=−12log⁡2π−12Eq[z2]=−12log⁡2π−12(μ2+σ2)\mathbb{E}_q[\log p] = -\tfrac12\log 2\pi - \tfrac12\mathbb{E}_q[z^2] = -\tfrac12\log 2\pi - \tfrac12(\mu^2 + \sigma^2). Subtract. With v=log⁡σ2v = \log\sigma^2: ∂/∂μ=μ\partial/\partial\mu = \mu, ∂/∂v=−12(1−ev)=12(σ2−1)\partial/\partial v = -\tfrac12(1 - e^v) = \tfrac12(\sigma^2 - 1). The gradients vanish at μ=0\mu = 0, σ2=1\sigma^2 = 1: 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 log⁡p(x)=Eq(z)[log⁡p(x,z)q(z)]+DKL(q(z)∥p(z∣x))\log p(x) = \mathbb{E}_{q(z)}\big[\log \frac{p(x,z)}{q(z)}\big] + D_{\text{KL}}(q(z)\Vert p(z \mid x)) holds for any distribution q(z)q(z). What does this mean for Lecture 3?

Answer

The second term on the right is Eq[log⁡q(z)−log⁡p(z∣x)]=Eq[log⁡q(z)−log⁡p(x,z)+log⁡p(x)]\mathbb{E}_q[\log q(z) - \log p(z\mid x)] = \mathbb{E}_q[\log q(z) - \log p(x, z) + \log p(x)]. Adding the first term, log⁡q\log q and log⁡p(x,z)\log p(x,z) cancel, leaving Eq[log⁡p(x)]=log⁡p(x)\mathbb{E}_q[\log p(x)] = \log p(x). Meaning:

  1. Since the KL is ≥ 0, the ELBO is a lower bound of log⁡p(x)\log p(x) for every qq, and can be maximized.
  2. With the model fixed, maximizing the ELBO is equivalent to minimizing the KL from qq to the true posterior.
  3. The identity holds for “any qq”. The Lecture 3 slides stress repeatedly that “this equation holds for any distribution q(z)” — the starting point for parameterizing qq with a network qϕ(z∣x)q_\phi(z\mid x) in the VAE.

Exercise 5 (the variance of importance sampling) Let p=N(0,1)p = \mathcal{N}(0, 1) and the proposal q=N(0,s2)q = \mathcal{N}(0, s^2). Show that Eq[w2]\mathbb{E}_q[w^2] (w=p/qw = p/q) is infinite when s2≤1/2s^2 \le 1/2. How does this relate to the s=0.3s = 0.3 result of part 2 of script 04?

Answer

Eq[w2]=∫p2/q=∫s2πexp⁡(−x2+x22s2)dx\mathbb{E}_q[w^2] = \int p^2/q = \int \frac{s}{\sqrt{2\pi}}\exp\big(-x^2 + \frac{x^2}{2s^2}\big)dx. The coefficient of x2x^2 in the exponent is −1+12s2-1 + \frac{1}{2s^2}, which is non-negative for s2≤1/2s^2 \le 1/2, 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 s=0.3s = 0.3 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 g1,…,gKg_1, \dots, g_K be independent standard Gumbel variables (CDF e−e−ge^{-e^{-g}}). Prove P(arg⁡max⁡k(θk+gk)=j)=softmax⁡(θ)jP\big(\arg\max_k(\theta_k + g_k) = j\big) = \operatorname{softmax}(\theta)_j.

Answer

θj+gj\theta_j + g_j is “a Gumbel with location θj\theta_j”, with CDF exp⁡(−e−(t−θj))\exp(-e^{-(t - \theta_j)}) and density e−(t−θj)exp⁡(−e−(t−θj))e^{-(t-\theta_j)}\exp(-e^{-(t-\theta_j)}). Then P(the j-th is the largest)=∫fj(t)∏k≠jFk(t) dt=∫e−(t−θj)exp⁡(−e−t∑keθk)dtP(\text{the } j\text{-th is the largest}) = \int f_j(t)\prod_{k\ne j}F_k(t)\,dt = \int e^{-(t-\theta_j)}\exp\big(-e^{-t}\sum_k e^{\theta_k}\big)dt. With u=e−tu = e^{-t} the integral becomes eθj∫0∞exp⁡(−uS) du=eθj/Se^{\theta_j}\int_0^\infty \exp(-u S)\,du = e^{\theta_j}/S, where S=∑keθkS = \sum_k e^{\theta_k}. That is the softmax.

Exercise 7 (change of variables) Let z∼U[0,1]z \sim \mathcal{U}[0, 1] and x=−log⁡(1−z)/λx = -\log(1 - z)/\lambda. Find the density of xx. What sampling method does this give?

Answer

gg is increasing, z=1−e−λxz = 1 - e^{-\lambda x}, dz/dx=λe−λxdz/dx = \lambda e^{-\lambda x} and pz=1p_z = 1, so px(x)=λe−λxp_x(x) = \lambda e^{-\lambda x} for x≥0x \ge 0: the exponential distribution. This is inverse-CDF sampling: the exponential CDF is F(x)=1−e−λxF(x) = 1 - e^{-\lambda x}, and x=F−1(z)x = F^{-1}(z) 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 −7000-7000 nats per image on 32×32×3 images scaled to [−1,1][-1, 1] (with uniform dequantization and nothing else). Convert to bits/dim.

Answer

d=3072d = 3072. Per dimension: −7000/3072≈−2.279-7000/3072 \approx -2.279 nats, i.e. −2.279/ln⁡2≈−3.288-2.279/\ln 2 \approx -3.288 bits. With data in [−1,1][-1,1], Δ=2/256\Delta = 2/256 and −log⁡2Δ=7-\log_2\Delta = 7. So bpd ≈−3.288+7=3.71\approx -3.288 + 7 = 3.71.


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.)
← 返回课程目录