Lecture 2 · Likelihood-Based Models in One Dimension, and the Curse of Dimensionality

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

课程源码 ZIP ↓

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

本篇目录

Maps to: UC Berkeley CS294-158 Deep Unsupervised Learning (Spring 2024), Lecture 2 · Thu 1/25/2024 · Likelihood Models: Autoregressive Models, first part (slides 1–20 of 192): motivation and desiderata, 1-D distributions (histograms; parameterized distributions and maximum likelihood; stochastic gradient descent; the logistic distribution and mixtures of logistics), the challenge of high-dimensional data, the chain rule. Homework 1, Question 1. Basis: The slides give each step in a few lines: the histogram recipe (count, look up, invert the CDF), “lack of generalization”, maximum likelihood “equivalent to minimizing KL divergence between the empirical data distribution and the model”, SGD, why discrete data call for a distribution with an easy CDF (and the warning about density-at-center shortcuts), 27842^{784} bins for binary MNIST, and the chain rule. These notes supply the derivations (the histogram as the maximum-likelihood solution, add-α smoothing as a Bayesian estimate, MLE = KL, consistency and misspecification, the softmax gradient, the stable log-difference of sigmoids) and five experiments on worlds with exactly known distributions, including both homework datasets. Code: code/lecture02/ (5 scripts + dists1d.py; numpy + PyTorch (CPU); 1–7 seconds each) Reading time: 3–4 hours including running the code


0. How to read this lecture

0.1 Learning goals

After this lecture you should be able to:

  1. Say what a likelihood-based model provides (evaluate p(x)p(x), sample xx) and what it is used for (generation, compression, anomaly detection), and list the desiderata of the slides.
  2. Fit a histogram, sample from it by inverting its CDF, explain why counting is the maximum-likelihood solution, and why it fails to generalize with little data; interpret add-α smoothing.
  3. Derive maximum likelihood = minimizing KL from the empirical distribution to the model, and explain consistency (the family contains the truth) vs misspecification (the MLE converges to the best member of a wrong family).
  4. Train a model by stochastic gradient descent on the log-likelihood; compute the gradient for softmax logits; explain why early stopping acts as smoothing.
  5. Model discrete values with a discretized (mixture of) logistic distribution: exact bin masses from CDF differences, the edge bins, the numerically stable formula, and why “density at the bin center” is a trap.
  6. Explain the curse of dimensionality for histograms, state the chain rule, and explain why the chain rule alone does not solve anything — the conditionals must be restricted and shared.

0.2 Prerequisites and scope

AssumedIntroduced hereDeveloped later
Lecture 1 (bits, entropy, test bits=H+KL\text{test bits} = H + \text{KL})maximum likelihood, KL to the empirical distributionneural conditionals: MADE, PixelCNN (Lecture 3), Transformers (Lecture 4)
derivatives, the chain rule of calculusSGD, softmax, the logistic distributioncontinuous data and change of variables (Lecture 5)
a little PyTorch (tensors, backward())the probabilistic chain ruledequantization of continuous models (Lecture 6)

0.3 Map

§1  likelihood-based models: what problems, what they provide, desiderata
§2  the histogram: count, look up, invert the CDF; why it does not generalize; smoothing        ← code 01
§3  parameterized distributions and maximum likelihood = KL; consistency and misspecification   ← code 02
§4  stochastic gradient descent; the softmax histogram of homework Q1a; early stopping          ← code 03
§5  smooth distributions for discrete data: discretized logistics, stability, a trap            ← code 04
§6  high dimensions: the curse of dimensionality                                               ← code 05
§7  the chain rule: exact, but not yet a solution; orderings                                     ← code 05
§8  summary   §9 pitfalls   §10 exercises   §11 further reading   §12 next lecture

0.4 Notation

SymbolMeaning
x∈{0,…,d−1}x \in \{0, \dots, d-1\}one discrete value (§2–§5); in §6–§7, x=(x1,…,xD)x = (x_1, \dots, x_D) is a vector
x(1),…,x(n)x^{(1)}, \dots, x^{(n)}the training data, drawn from pdatap_{\text{data}}
nkn_kthe number of training points equal to kk; p^data(k)=nk/n\hat p_{\text{data}}(k) = n_k / n is the empirical distribution
pθp_\thetaa model with parameters θ\theta
σ(t)=1/(1+e−t)\sigma(t) = 1/(1+e^{-t})the sigmoid (logistic CDF)
softmax(θ)k=eθk/∑jeθj\mathrm{softmax}(\theta)_k = e^{\theta_k} / \sum_j e^{\theta_j}turns dd real “logits” into a probability vector
NLLnegative log-likelihood, here always averaged per value and in bits (homework reports nats: divide bits by 1/ln⁡2≈1.44271/\ln 2 \approx 1.4427)

0.5 The worlds of this lecture

Three toy worlds, all with exact probabilities:

  • Homework world 1: d=20d = 20; a Gaussian with mean 0.2 and standard deviation 0.2 on the [0,1][0,1] scale, cut into 20 bins; everything below 0 piles up in bin 0 (probability 0.227). Entropy 3.454 bits.
  • Homework world 2: d=100d = 100; three equally likely Gaussians, (0.4,0.05)(0.4, 0.05), (0.5,0.10)(0.5, 0.10), (0.7,0.02)(0.7, 0.02). The last one is only two bins wide, so values 68–70 have probability ≈ 0.05–0.066 each. Entropy 5.293 bits (a uniform distribution on 100 values would have 6.644).
  • Sticky Markov bits (§6–§7): binary sequences of length dd in which each bit repeats the previous one with probability 0.9.

The homework generates its data with np.digitize; we use floor(u·d) clipped to {0,…,d−1}\{0, \dots, d-1\} so that all values are valid indices. The shapes are the same.


1. Likelihood-based models

1.1 The problems

The slides list three problems we would like to solve:

  1. Generate data: synthesize images, video, speech, text.
  2. Compress data: construct efficient codes (Lecture 1: a model with probability p(x)p(x) gives a code of −log⁡2p(x)-\log_2 p(x) bits).
  3. Detect anomalies: recognize data that are out of distribution (an observation the model finds extremely unlikely).

A likelihood-based model addresses all three with one object: an estimate pp of pdatap_{\text{data}}, learned from samples x(1),…,x(n)∼pdatax^{(1)}, \dots, x^{(n)} \sim p_{\text{data}}, that allows

  • computing p(x)p(x) for arbitrary xx (compression, anomaly detection, model comparison), and
  • sampling x∼p(x)x \sim p(x) (generation).

This lecture and the next two deal with discrete data (pixel intensities, characters, tokens); continuous data arrive with flows in Lecture 5.

1.2 Desiderata

We want to model complex, high-dimensional data — a 128×128128 \times 128 color image lives in a space of about 50,000 dimensions — and we want efficiency of two kinds:

  • computational: efficient training and a compact model representation; fast sampling; fast compression;
  • statistical: expressiveness (the family can represent the data) and generalization (it learns from finitely many samples); good samples; good compression rates.

These pull in different directions. This lecture shows the tension in its simplest form, one variable at a time: the most expressive model (one free probability per value) generalizes worst; the most data-efficient model (a smooth family with two parameters) may be unable to represent the data.


2. The simplest generative model: a histogram

2.1 Count, look up, invert

Suppose the data take values in {0,…,d−1}\{0, \dots, d-1\}. The slides’ model is a histogram, described (redundantly) by dd non-negative numbers p0,…,pd−1p_0, \dots, p_{d-1}:

  • Training: count frequencies, pk=nk/np_k = n_k / n.
  • Inference (querying pkp_k): a lookup in an array.
  • Sampling: compute the cumulative distribution Fk=p0+⋯+pkF_k = p_0 + \dots + p_k, draw u∼Uniform[0,1)u \sim \text{Uniform}[0,1), and return the smallest kk with u<Fku < F_k.

Why does sampling work? Value kk is returned exactly when Fk−1≤u<FkF_{k-1} \le u < F_k, an interval of length pkp_k; a uniform uu lands in it with probability pkp_k. This inverse-CDF method works for any distribution on an ordered set — we will meet it again in Lecture 5, where a continuous CDF becomes a “flow”.

Script 01 checks it: drawing from world 2’s pmf by inverse CDF, the total variation between sample frequencies and the pmf is 0.278 with 100 samples, 0.028 with 10,000 and 0.0025 with a million — shrinking like 1/n1/\sqrt{n}, pure sampling noise.

2.2 Why counting is maximum likelihood

Counting is not an arbitrary recipe: it is the distribution under which the training data are most probable. The log-likelihood of the data under probabilities pp is

log⁡p(x(1),…,x(n))=∑i=1nlog⁡px(i)=∑k=0d−1nklog⁡pk.\log p(x^{(1)}, \dots, x^{(n)}) = \sum_{i=1}^{n} \log p_{x^{(i)}} = \sum_{k=0}^{d-1} n_k \log p_k .

Maximize it subject to ∑kpk=1\sum_k p_k = 1 with a Lagrange multiplier λ\lambda: setting the derivative of ∑knklog⁡pk−λ(∑kpk−1)\sum_k n_k \log p_k - \lambda(\sum_k p_k - 1) to zero gives nk/pk=λn_k / p_k = \lambda, so pk∝nkp_k \propto n_k, i.e. pk=nk/np_k = n_k / n. The histogram is the maximum-likelihood estimate of the most flexible model there is — one free probability per value.

2.3 Are we done? Lack of generalization

The slides’ answer: no. The learned histogram is the training data distribution, and that generalizes poorly. Script 01 fits histograms to growing training sets from world 2 and evaluates on 2,000 test values:

nn traintrain bits (α=0\alpha=0)test bits (α=0\alpha=0)test values unseentest bits (α=1\alpha=1)KL (α=1\alpha=1)non-zero bins
103.122∞70.0%6.4641.1659
304.190∞41.3%6.1970.93120
1004.892∞13.3%5.9210.62736
3005.189∞3.0%5.5460.25846
1,0005.236∞0.5%5.3670.08055
10,0005.289∞0.1%5.2940.00866
100,0005.289∞0.1%5.2890.00176

(The entropy floor is 5.293 bits.)

Histograms vs truth

Unsmoothed histograms from 30, 1,000 and 100,000 samples against the true pmf (01_histograms.py).

Three failures, all visible in the table:

  1. Infinite test bits. A value never seen in training gets probability 0, and a single such value in the test set makes the average −log⁡2p-\log_2 p infinite. Even 100,000 training points leave a few far-tail test values unseen (0.1%).
  2. Over-fitting. With 10 training points the training data cost 3.12 bits per value — less than the entropy (5.29). The training set looks more predictable than the world is, because the model was fitted to exactly these points. Train and test bits meet only when n≫dn \gg d.
  3. Slow learning. Even with a pseudo-count that rules out infinities, the KL to the truth is 0.63 bits at n=100n = 100: one hundred free parameters need far more than one hundred data points.

2.4 Smoothing as a prior

Adding α\alpha pseudo-counts to every bin,

pk=nk+αn+αd,p_k = \frac{n_k + \alpha}{n + \alpha d},

is the classical fix. It has a clean Bayesian reading: with a Dirichlet prior Dir(α,…,α)\text{Dir}(\alpha, \dots, \alpha) on the probability vector, this is the posterior mean after observing the counts (Exercise 2). α=1\alpha = 1 is Laplace’s rule of succession; α=0.5\alpha = 0.5 is the Krichevsky–Trofimov estimator used in compression.

How much smoothing is best (test bits; best α per row starred)?

nn trainα=0.01α=0.1α=0.5α=1α=3α=10
107.9416.4896.354*6.4246.5376.606
1005.8965.691*5.7415.8636.1466.420
1,0005.3625.344*5.3525.3745.4725.731
10,0005.2935.291*5.2925.2945.3045.345

The best pseudo-count settles around 0.1–0.5, but what matters is its weight relative to the data: αd\alpha d imaginary points against nn real ones. With 10 points the prior dominates and helps; with 10,000 it hardly matters. And no amount of smoothing teaches a histogram that neighbouring values have similar probabilities — the knowledge a smooth parametric family builds in (§3, §5).

Run it. python3 01_histograms.py (about 1 second).


3. Parameterized distributions and maximum likelihood

The slides’ remedy for poor generalization is a parameterized distribution pθp_\theta whose form already encodes assumptions (smoothness, a few bumps, …). Learning becomes a search over θ\theta, and the loss + search procedure must:

  1. work with large datasets (nn in the millions);
  2. yield θ\theta such that pθp_\theta matches pdatap_{\text{data}} — think of the loss as a distance between distributions;
  3. note that training sees only the empirical distribution, never pdatap_{\text{data}} itself: we want the model to generalize.

3.2 Maximum likelihood is a KL divergence

Maximum likelihood chooses

θML=arg⁡max⁡θ1n∑i=1nlog⁡pθ(x(i))=arg⁡min⁡θ  Ex∼p^data ⁣[−log⁡pθ(x)].\theta_{\text{ML}} = \arg\max_\theta \frac{1}{n}\sum_{i=1}^{n} \log p_\theta(x^{(i)}) = \arg\min_\theta \; \mathbb{E}_{x \sim \hat p_{\text{data}}}\!\left[-\log p_\theta(x)\right].

The quantity on the right is a cross-entropy, and Lecture 1’s identity splits it:

Ep^data[−log⁡2pθ(x)]=H(p^data)⏟does not depend on θ+KL(p^data ∥ pθ).\mathbb{E}_{\hat p_{\text{data}}}[-\log_2 p_\theta(x)] = \underbrace{H(\hat p_{\text{data}})}_{\text{does not depend on } \theta} + \mathrm{KL}(\hat p_{\text{data}} \,\Vert\, p_\theta).

So maximum likelihood is minimization of the KL divergence from the empirical distribution to the model — the slides’ claim. Script 02 checks the identity for 44 discretized Gaussians on a grid (500 training points from world 2):

Model θ\thetaavg train NLLH(p^)H(\hat p)KL(p^∥pθ)\mathrm{KL}(\hat p \Vert p_\theta)H+KLH + \mathrm{KL}
μ=0.30,σ=0.10\mu = 0.30, \sigma = 0.109.78605.28244.50359.7860
μ=0.50,σ=0.10\mu = 0.50, \sigma = 0.106.18805.28240.90566.1880
μ=0.80,σ=0.10\mu = 0.80, \sigma = 0.1011.60225.28246.319811.6022

Over all 44 points the largest discrepancy is 3.6×10−153.6 \times 10^{-15} bits — rounding error.

Two remarks:

  • KL is asymmetric. Maximum likelihood minimizes KL(data∥model)\mathrm{KL}(\text{data} \Vert \text{model}), the “forward” direction: every value the data contain must get probability, or the cost explodes. (A model that misses data pays infinitely; a model that puts mass where there is no data pays only a little.) Lecture 9 contrasts this with GANs, which effectively optimize other divergences.
  • It is the KL to the empirical distribution. What we really care about is KL(pdata∥pθ)\mathrm{KL}(p_{\text{data}} \Vert p_\theta) = test bits minus entropy. How close the two minimizers are is the question of generalization.

3.3 Consistency and misspecification

The slides: statistics tells us that if the model family is expressive enough and enough data are given, maximum likelihood yields parameters that generate the data. Two cases make this precise:

  • Well-specified: pdata=pθ∗p_{\text{data}} = p_{\theta^*} for some θ∗\theta^* in the family. As n→∞n \to \infty, p^data→pdata\hat p_{\text{data}} \to p_{\text{data}}, the minimizer of KL(p^∥pθ)\mathrm{KL}(\hat p \Vert p_\theta) approaches θ∗\theta^*, and KL(pdata∥pθML)→0\mathrm{KL}(p_{\text{data}} \Vert p_{\theta_{\text{ML}}}) \to 0.
  • Misspecified: no member equals pdatap_{\text{data}}. Maximum likelihood still converges — to the best member of the family, θ†=arg⁡min⁡θKL(pdata∥pθ)\theta^\dagger = \arg\min_\theta \mathrm{KL}(p_{\text{data}} \Vert p_\theta) (the “projection” of pdatap_{\text{data}} onto the family) — and the KL stalls at a positive floor.

Script 02 fits a discretized Gaussian (2 parameters) by maximum likelihood and compares with a histogram (α=0.5\alpha = 0.5), measuring KL(pdata∥model)\mathrm{KL}(p_{\text{data}} \Vert \text{model}) exactly:

World 1 (one Gaussian, μ=0.2\mu = 0.2, σ=0.2\sigma = 0.2): the family contains the truth.

nnμ^\hat\muσ^\hat\sigmaKL Gaussian MLEKL histogram
100.26500.11700.54370.9204
300.25660.15620.13880.4501
1000.20270.18250.00880.0796
1,0000.20280.19680.00040.0169
10,0000.19990.19860.00010.0016
100,0000.19860.19980.00000.0001

World 2 (three Gaussians): the family is misspecified. Best possible discretized Gaussian: KL = 0.5710 bits.

nnμ^\hat\muσ^\hat\sigmaKL Gaussian MLEKL histogram
100.52700.15350.58221.0645
300.56830.14700.61440.8766
1000.52710.14290.57270.4216
1,0000.53610.14130.57130.0729
10,0000.53420.14030.57110.0061
100,0000.53290.14090.57100.0006

Consistency

KL to the truth as the training set grows (02_maximum_likelihood.py).

  • In world 1 the MLE recovers μ=σ=0.2\mu = \sigma = 0.2 ever more precisely and its KL falls to zero. With 2 parameters instead of 20 it beats the histogram at every nn: correct assumptions are worth a lot of data.
  • In world 2 the Gaussian MLE converges just as nicely — to the best Gaussian, not to the truth: its KL stalls at 0.571 bits. The histogram, which assumes nothing, overtakes it between n=30n = 30 and n=100n = 100.

How fast does the excess shrink? A classical result (the same one behind the Akaike information criterion) says that for a well-specified model with kk free parameters, the expected excess test loss of the MLE is about k2n\frac{k}{2n} nats, i.e. k2nln⁡2\frac{k}{2n \ln 2} bits. Check it against the table: the world-1 histogram has k=19k = 19, predicting 0.01370.0137 bits at n=1,000n = 1{,}000 (measured 0.0169) and 0.00140.0014 at n=10,000n = 10{,}000 (measured 0.0016); the world-2 histogram (k=99k = 99) is predicted at 0.07140.0714 and 0.00710.0071 (measured 0.0729 and 0.0061). Every free parameter costs about half a nat divided by nn — which is why a model with fewer, well-chosen parameters wins when data are scarce, and why a misspecified model’s fixed bias eventually loses to a flexible model’s shrinking variance. This bias–variance negotiation runs through the whole course.

Run it. python3 02_maximum_likelihood.py (about 3 seconds).


4. Stochastic gradient descent

4.1 Why SGD?

Maximum likelihood is an optimization problem; for neural networks it has no closed form. The slides’ answer is stochastic gradient descent (SGD), which minimizes expectations. Our objective is an expectation over the empirical distribution,

L(θ)=Ex∼p^data[−log⁡pθ(x)]=1n∑i=1n−log⁡pθ(x(i)),\mathcal{L}(\theta) = \mathbb{E}_{x \sim \hat p_{\text{data}}}[-\log p_\theta(x)] = \frac{1}{n}\sum_{i=1}^n -\log p_\theta(x^{(i)}),

and a minibatch of BB random training points gives an unbiased estimate of it and of its gradient. Each SGD step costs O(B)O(B) instead of O(n)O(n). Why maximum likelihood + SGD? Because it works with large datasets and with any differentiable model — in particular neural networks.

4.2 Homework Q1a: a histogram written with logits

Homework 1 asks for the histogram as a parameterized model, pθ(x)=softmax(θ)xp_\theta(x) = \mathrm{softmax}(\theta)_x with θ∈Rd\theta \in \mathbb{R}^d initialized to zero (the uniform distribution), trained by SGD. The softmax turns any real vector into a valid distribution, so SGD needs no constraints.

The gradient is beautifully simple. For one data point xx,

∂∂θk[−log⁡softmax(θ)x]=pθ(k)−1[x=k],\frac{\partial}{\partial \theta_k}\left[-\log \mathrm{softmax}(\theta)_x\right] = p_\theta(k) - \mathbb{1}[x = k],

and averaged over a batch, ∇θL=pθ−f\nabla_\theta \mathcal{L} = p_\theta - f, where ff is the vector of data frequencies in the batch. SGD pushes the model’s probabilities towards the data frequencies and stops (in expectation) when they are equal — the counting solution of §2.2.

Script 03, Part 1 (homework splits: 80% train, 20% test; Adam, batch 128):

Datatest bits after epoch 1finalcounting histogramentropyKL to truthTV(SGD, counting)
world 1 (d=20d = 20, n=800n = 800)4.1773.5893.5783.4540.02710.0209
world 2 (d=100d = 100, n=8,000n = 8{,}000)5.6215.308∞5.2930.00830.0128

Learning curves

Training (mean over minibatches) and test curves of the softmax histogram (03_sgd_on_a_histogram.py).

SGD gets close to the counting solution — and, on world 2, does better than it on the test set: the exact counting solution gives probability 0 to a test value never seen in training, while the softmax never quite reaches 0.

4.3 Early stopping is smoothing

Look again at the gradient for a value kk that never occurs in the training data: pθ(k)−0>0p_\theta(k) - 0 > 0, always. Its logit keeps falling and its probability creeps towards 0 — but slowly. The model travels from “uniform” (the start) towards “counting” (the optimum), and stopping early leaves it in between, i.e. smoothed.

Script 03, Part 2 trains on only 50 points from world 2 with full-batch gradient descent:

steptrain bitstest bits
16.6446.642
106.6176.628
1006.3596.496
1,0005.1526.072
1,598 (best test)4.9466.063
4,0004.6846.114

The test bits pass through a minimum and rise again while the training bits keep falling. The best stopping point (6.063 bits) comes close to the best Laplace smoothing on the same data (α = 0.3: 5.940 bits); pure counting gives infinity. Early stopping is an implicit prior towards the starting point — and the reason every model trained by SGD in this course needs a validation set.

4.4 Full batch vs minibatch vs Adam

Compared at equal compute — passes over the 8,000 training points (one full-batch step per epoch vs 63 minibatch steps):

optimizerlrsteps in 20 epochstest bits after 1 epoch5 epochs20 epochs
gradient descent, full batch (best of lr 1/5/20/50)20206.1055.5635.372
gradient descent, full batch, lr too large100206.5779.46312.423
SGD, batch 12821,2605.5395.3475.316
Adam, batch 1280.021,2605.6215.3315.308

Minibatch SGD after 5 epochs (5.347 bits) is already better than full-batch descent after 20 epochs with its best learning rate (5.372): many noisy steps beat a few exact ones. Too large a step diverges. Adam rescales each parameter’s step by a running estimate of its gradient’s magnitude, which makes it forgiving about the learning rate — the default for the neural models ahead.

Run it. python3 03_sgd_on_a_histogram.py (about 2 seconds).


5. Smooth distributions for discrete data

5.1 The problem

A smooth family — a few bumps — would generalize much better than dd free probabilities. But smooth families are usually continuous (densities on the real line), while our data are discrete. The slides’ design principle: choose a distribution with easy access to its cumulative distribution function, so that the probability mass of each value’s interval [x−0.5,x+0.5][x - 0.5, x + 0.5] can be computed exactly and differentiated. A good choice: the logistic distribution.

5.2 The logistic distribution

With location μ\mu and scale s>0s > 0:

f(x)=e−(x−μ)/ss (1+e−(x−μ)/s)2,F(x)=σ ⁣(x−μs)=11+e−(x−μ)/s.f(x) = \frac{e^{-(x-\mu)/s}}{s\,\big(1 + e^{-(x-\mu)/s}\big)^2}, \qquad F(x) = \sigma\!\left(\frac{x - \mu}{s}\right) = \frac{1}{1 + e^{-(x-\mu)/s}} .

It looks like a Gaussian with heavier tails (variance π2s2/3\pi^2 s^2 / 3), and its CDF is the sigmoid: one exponential and a division, available in every framework, with a simple derivative. The Gaussian CDF needs the error function — fine too (script 02 uses it), but less convenient.

5.3 Discretizing it

The mass of value xx is the integral of the density over its bin:

P(x)=σ ⁣(x+0.5−μs)−σ ⁣(x−0.5−μs),P(x) = \sigma\!\left(\frac{x + 0.5 - \mu}{s}\right) - \sigma\!\left(\frac{x - 0.5 - \mu}{s}\right),

with one adjustment at the edges (homework Q1b, PixelCNN++): for x=0x = 0 the lower edge x−0.5x - 0.5 is replaced by −∞-\infty, and for x=d−1x = d - 1 the upper edge by +∞+\infty, so that the end bins collect all the mass beyond the range. The masses of all dd values then telescope to σ(+∞)−σ(−∞)=1\sigma(+\infty) - \sigma(-\infty) = 1: a proper distribution with three parameters. A mixture of KK components handles several modes:

pθ(x)=∑j=1Kπj[σ ⁣(x+0.5−μjsj)−σ ⁣(x−0.5−μjsj)],π=softmax(logits).p_\theta(x) = \sum_{j=1}^{K} \pi_j \left[\sigma\!\left(\frac{x + 0.5 - \mu_j}{s_j}\right) - \sigma\!\left(\frac{x - 0.5 - \mu_j}{s_j}\right)\right], \qquad \pi = \mathrm{softmax}(\text{logits}).

The open end bins matter in homework world 1, where 22.7% of the mass piles up at 0: one component sitting near 0 explains the whole pile-up.

5.4 Homework Q1b

Script 04, Part 1 (a mixture of 4 discretized logistics, 12 parameters, vs the softmax histogram of §4.2):

DataDMoL test bitsparamssoftmax-histogram test bitsparamsentropy
world 1 (n=800n = 800)3.598123.589203.454
world 2 (n=8,000n = 8{,}000)5.358125.3081005.293

DMoL fits

Fitted mixture of 4 discretized logistics (red), the SGD-trained softmax histogram (grey) and the truth (black) (04_discretized_logistic_mixture.py).

With lots of data the mixture comes within 0.01–0.05 bits of the histogram; the gap on world 2 comes from shape — four logistics are not three Gaussians, and the narrow bump is the hardest part. The advantage of smoothness appears when data are scarce (script 04, Part 2; world 2, test bits, entropy 5.293):

nn trainDMoL, 4 components (12 params)one discretized Gaussian (2)histogram, best α (100)
305.3655.8786.230
1005.4325.8705.655
3005.3305.8755.467
1,0005.3285.8685.353
8,0005.3395.8705.290

With 30 points the mixture is 0.87 bits better than the histogram — even though the histogram’s smoothing was chosen using the test set. Smoothness says “neighbouring values have similar probability”, so 30 points inform the whole curve instead of 30 separate bins. The histogram wins only at 8,000 points, when all that is left is the mixture’s shape bias. This is exactly the idea PixelCNN++ uses for the 256 values of a pixel (Lecture 3): a softmax over 256 values must learn that 127 and 128 are similar from data; a discretized logistic mixture knows it.

5.5 Computing it without breaking

The formula log⁡(σ(a)−σ(b))\log(\sigma(a) - \sigma(b)) looks harmless. It is not. Far to the right of a sharp component, both sigmoids round to exactly 1.0 in floating point; their difference is 0 and the log is −∞-\infty. Script 04, Part 3 puts four sharp components (scale 0.05 bins) at 30, 40, 55, 69:

  • the naive formula returns −∞-\infty for 27 of the 100 values;
  • the stable formula’s smallest log-probability is −591.4 nats — tiny but finite; the masses still sum to 1.000000;
  • the trap: the loss on the values 10, 35 and 69 is finite with both formulas, yet the naive version’s gradient is NaN. The −∞-\infty entries of other values break the backward pass (0×∞0 \times \infty), and one NaN step destroys every parameter.

The stable form never subtracts probabilities. Since σ(a)−σ(b)=ea−eb(1+ea)(1+eb)\sigma(a) - \sigma(b) = \frac{e^a - e^b}{(1+e^a)(1+e^b)},

log⁡(σ(a)−σ(b))=a+log⁡ ⁣(1−e−(a−b))−softplus(a)−softplus(b),softplus(t)=log⁡(1+et),\log\big(\sigma(a) - \sigma(b)\big) = a + \log\!\big(1 - e^{-(a-b)}\big) - \mathrm{softplus}(a) - \mathrm{softplus}(b), \qquad \mathrm{softplus}(t) = \log(1 + e^t),

where every term is computed stably (log1mexp switches between two formulas at ln⁡2\ln 2). The end bins are log⁡σ(a)\log \sigma(a) and log⁡σ(−b)\log \sigma(-b) (logsigmoid). Every likelihood in this course is computed in log space for the same reason.

5.6 The trap the slides warn about: density at the bin center

A tempting shortcut is to skip the CDF and use the density at the bin center times the bin width: "P(x)≈f(x)⋅1P(x) \approx f(x) \cdot 1". The slides warn that this inexactness makes debugging harder and can lead to learning poorly performing densities with extreme peaks. Script 04, Part 4 trains such a mixture on world 1 and also computes the exact bin masses of the same parameters:

epochscore bits (train)∑xscore(x)\sum_x \text{score}(x)smallest scalecomponents with π>1%\pi > 1\%true test bits
14.0610.880.886843.975
53.6610.940.517043.700
103.2061.400.085133.654
202.26411.210.004333.654
503.6010.970.004523.672
1002.26412.330.003223.684
2003.8850.880.002813.607

(The entropy of world 1 is 3.454 bits; the proper CDF-based mixture with the same training reaches 3.601 test bits.)

What happens:

  1. The training score falls below the entropy (2.264 < 3.454 bits). For a real probability model this is impossible — Lecture 1: no code beats the entropy. It is possible here because a density can exceed 1: a component shrinks to a spike of scale 0.004 bins centered on value 0 (the pile-up bin), where its “probability” is about 10.5. The scores of the 20 values sum to 11.2: the objective is not a likelihood at all.
  2. Spikes are knife-edges. A tiny shift of μ\mu off the integer kills the density, the component starves (π→0\pi \to 0) and dies; later another component forms a new spike (epoch 100). The objective oscillates and 3 of the 4 components end up dead.
  3. On this one-bump world the final model is not much worse than the proper one (3.607 vs 3.601 test bits): one surviving broad component suffices. The damage is an untrustworthy training curve and wasted capacity — “extreme peaks” and “harder debugging”, exactly as warned.

Rule of thumb: a training NLL below anything the data’s entropy could plausibly be — and for discrete data, below 0 — means the objective is not normalized. Integrate the density over each bin.

Run it. python3 04_discretized_logistic_mixture.py (about 7 seconds).


6. High-dimensional data: the curse of dimensionality

6.1 Too many bins

Everything so far was one variable. For a vector x=(x1,…,xD)x = (x_1, \dots, x_D) we could flatten all possible vectors into one long list and fit a histogram over it. The slides’ verdict: this does not work, even for simple cases. Script 05 counts the bins:

Datadimensionsvalues eachpossible examples (= bins)
homework world 2 (one value)1100102.010^{2.0}
binary MNIST 28×2828 \times 28784210236.010^{236.0}
ShapeWorld 12×2412 \times 24 (Lecture 1)28821086.710^{86.7}
CIFAR-10 32×32×332 \times 32 \times 3, 8 bits3,072256107,398.110^{7{,}398.1}
a 128×128×3128 \times 128 \times 3 photo, 8 bits49,15225610118,369.810^{118{,}369.8}

There are about 108010^{80} atoms in the observable universe. Any training set covers a vanishing fraction of these bins, and — the slides’ key point — each training example influences only one parameter. Nothing learned about one image says anything about another: no generalization whatsoever. Lecture 1’s memorizer is exactly this histogram over whole ShapeWorld images, and it needed 191 bits for a new image.

6.2 The curse, measured

To watch the curse happen with exact probabilities we need a world whose dimension we can turn up: sticky Markov bits. A sequence x1,…,xdx_1, \dots, x_d starts with a fair coin, and each next bit repeats the previous one with probability 0.9. Its probability is a product of d−1d - 1 factors, and its entropy is 1+(d−1)Hb(0.9)1 + (d-1) H_b(0.9) bits, about 0.47 bits per dimension for large dd.

With 1,000 training sequences, test bits per dimension (script 05, Part 2):

ddbins 2d2^dtest sequences seen in trainingentropy H/dH/djoint histogramindependent bitschain rule, shared xt∣xt−1x_t \mid x_{t-1} (3 numbers)per-position tables (numbers)
416100.0%0.60170.59991.00040.59790.5987 (7)
825697.8%0.53540.55471.00020.53610.5387 (15)
124,09690.5%0.51320.62561.00040.50480.5059 (23)
1665,53676.1%0.50220.77770.99990.50510.5057 (31)
241.7×1071.7 \times 10^742.1%0.49110.93831.00030.49610.4974 (47)
324.3×1094.3 \times 10^921.2%0.48560.98211.00050.47990.4811 (63)
641.8×10191.8 \times 10^{19}0.2%0.47731.00001.00160.47340.4749 (127)

Curse of dimensionality

Test bits per dimension of the three model types as the dimension grows (05_curse_of_dimensionality.py).

  • The joint histogram (with α=0.5\alpha = 0.5 in every one of the 2d2^d bins) is excellent while 2d≪n2^d \ll n and then collapses. An unseen sequence costs about log⁡2n+α2dα\log_2\frac{n + \alpha 2^d}{\alpha} bits, which for d=64d = 64 is about 64 bits — one bit per dimension, as if every bit were a coin flip.
  • Independent bits generalize at every dd but ignore the stickiness: one bit per dimension throughout.
  • The chain rule with the right conditional — each bit given only the previous one — stays at the entropy for every dd with just three numbers, because all positions share one table and pool their evidence. Per-position tables do almost as well here; with richer conditionals they would need more data per position. Restriction and sharing beat the curse.

7. The chain rule

7.1 Exact for every distribution

Any distribution over DD variables can be written as a product of conditionals:

p(x1,…,xD)=p(x1) p(x2∣x1) p(x3∣x1,x2)⋯p(xD∣x1,…,xD−1)=∏i=1Dp(xi∣x<i).p(x_1, \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}) = \prod_{i=1}^{D} p(x_i \mid x_{<i}).

It follows from applying the definition p(a,b)=p(a) p(b∣a)p(a, b) = p(a)\,p(b \mid a) repeatedly. A model written this way is called autoregressive: each variable is “regressed” on the ones before it. Two properties make it the backbone of Lectures 3–4 (and of every large language model):

  • Evaluating p(x)p(x) is a product of DD conditionals, all computable in parallel when xx is given.
  • Sampling follows the order: draw x1x_1, then x2x_2 given x1x_1, and so on — each step a one-dimensional problem, which §2–§5 just solved.

7.2 Are we done? No.

The chain rule is exact, but it does not say how to represent and learn each conditional. Take the most literal approach — estimate every conditional p(xt∣x<t)p(x_t \mid x_{<t}) by counting how often each prefix continues each way. Script 05, Part 3 does this for 12-bit sequences: the product of the counted conditionals equals count(x)/n\text{count}(x)/n to 5.6×10−175.6 \times 10^{-17} for every training sequence. The ratios telescope:

c(x1)n⋅c(x1x2)c(x1)⋅c(x1x2x3)c(x1x2)⋯=c(x1…xD)n.\frac{c(x_1)}{n} \cdot \frac{c(x_1 x_2)}{c(x_1)} \cdot \frac{c(x_1 x_2 x_3)}{c(x_1 x_2)} \cdots = \frac{c(x_1 \dots x_D)}{n}.

The chain rule with unrestricted, counted conditionals is the joint histogram, with all its problems. The gain in §6.2 came from two decisions about the conditionals:

  1. Restrict what each conditional depends on (here: only the previous bit). This is a Bayes net, the slides’ first practical incarnation — efficient, but a strong assumption that limits expressivity when the true dependencies are richer.
  2. Share the conditional across positions (one table for all tt). Lecture 1’s context models did both: 4, 10 or 23 causal neighbours, one table for all 288 pixels — and still stalled at 47 bits because local neighbours cannot capture global shape.

Lecture 3 replaces counted tables by neural networks that can condition on the whole prefix and still share parameters: MADE, causal masked networks, WaveNet, PixelCNN, RNNs.

7.3 Orders

The chain rule holds in every order of the variables, but the conditionals are not equally simple in every order. Script 05, Part 4 computes, for 10 sticky bits, the exact chain-rule entropy in four orders and the cross-entropy of a model whose conditionals may look only at the variable just before it in that order:

orderpositions∑tH(xt∣all earlier)\sum_t H(x_t \mid \text{all earlier})∑tH(xt∣previous in this order)\sum_t H(x_t \mid \text{previous in this order})
natural1 2 3 4 5 6 7 8 9 105.22105.2210
reversed10 9 8 7 6 5 4 3 2 15.22105.2210
even then odd1 3 5 7 9 2 4 6 8 105.22107.4087
random3 7 4 10 1 6 5 9 8 25.22108.2981

The first column is the entropy, 5.2210 bits, in every order: exactness. The second shows that a cheap model is only good in an order where the data’s dependencies are short: in the “even then odd” order, bit 2 comes right after bit 9 and needs bits 1 and 3, which a one-step model cannot use. Order is free mathematically and decisive for modeling — MADE’s orderings (Lecture 3) and masked attention’s arbitrary orders (Lecture 4) come back to this.

Run it. python3 05_curse_of_dimensionality.py (about 3 seconds).


8. Summary

  1. A likelihood-based model lets us evaluate p(x)p(x) and sample from it; it serves generation, compression and anomaly detection. We want it expressive, data-efficient, and fast to train, sample and evaluate.
  2. The histogram (counting) is the maximum-likelihood estimate of the most flexible discrete model. It fails to generalize: unseen values get probability 0, small training sets look more predictable than the world. Add-α smoothing is a Dirichlet prior; its weight must shrink relative to the data.
  3. Maximum likelihood minimizes KL(p^data∥pθ)\mathrm{KL}(\hat p_{\text{data}} \Vert p_\theta). It is consistent when the family contains the truth and converges to the best member of a misspecified family otherwise. Each free parameter costs about 12n\frac{1}{2n} nats of expected excess test loss: few well-chosen parameters win with little data, flexible families win with lots.
  4. SGD minimizes the expected NLL from minibatches; for softmax logits the gradient is “model probabilities minus data frequencies”. Starting from uniform and stopping early acts as smoothing.
  5. Discretized logistic mixtures give exact, smooth, few-parameter distributions over discrete values via CDF differences with open end bins. Compute log⁡(σ(a)−σ(b))\log(\sigma(a) - \sigma(b)) stably. Density-at-center scores are not probabilities: training “NLL” can fall below the entropy while components collapse into spikes.
  6. In high dimensions histograms die (curse of dimensionality: 1023610^{236} bins for binary MNIST, one parameter per example). The chain rule is exact in any order but solves nothing by itself; restricting and sharing the conditionals is what generalizes — the program of Lectures 3–4.

9. Common pitfalls

  1. Reporting training NLL as model quality. With 10 points the histogram’s training bits (3.12) were 2.2 bits below the entropy. Always report held-out NLL.
  2. Zero probabilities. One unseen value makes the test NLL infinite. Every model needs to give every possible value some probability (smoothing, softmax, continuous families with full support).
  3. Mixing up nats and bits. Homework plots are in nats per dimension; these notes use bits. 1 nat = 1.4427 bits.
  4. Subtracting probabilities in floating point. log⁡(σ(a)−σ(b))\log(\sigma(a) - \sigma(b)) and similar expressions must be computed in log space; a finite loss with NaN gradients is a symptom.
  5. Scoring discrete values with densities. Densities can exceed 1; the objective then stops being a likelihood. A training NLL below the entropy, or below 0 for discrete data, is the alarm.
  6. Comparing optimizers by steps instead of compute. A full-batch step is n/Bn/B times more expensive than a minibatch step.
  7. Believing the chain rule is a model. It is an identity; the modeling is in how the conditionals are restricted and shared.

10. Exercises

Exercise 1 (derivation: the histogram is the MLE). Maximize ∑knklog⁡pk\sum_k n_k \log p_k subject to ∑kpk=1\sum_k p_k = 1, pk≥0p_k \ge 0. What happens to pkp_k for a value with nk=0n_k = 0?

Answer

Lagrangian ∑knklog⁡pk−λ(∑kpk−1)\sum_k n_k \log p_k - \lambda(\sum_k p_k - 1); stationarity gives nk/pk=λn_k / p_k = \lambda, so pk=nk/λp_k = n_k / \lambda, and normalization gives λ=n\lambda = n: pk=nk/np_k = n_k/n. (The objective is concave, so this is the global maximum.) For nk=0n_k = 0 the term nklog⁡pkn_k \log p_k is 0 whatever pkp_k is, and any mass placed there is taken away from values that do occur, so the optimum is pk=0p_k = 0: maximum likelihood actively removes probability from unseen values.

Exercise 2 (derivation: smoothing as a posterior mean). With a Dirichlet prior Dir(α,…,α)\text{Dir}(\alpha, \dots, \alpha) on (p0,…,pd−1)(p_0, \dots, p_{d-1}) and counts nkn_k, show that the posterior is Dir(α+n0,…,α+nd−1)\text{Dir}(\alpha + n_0, \dots, \alpha + n_{d-1}) and that its mean is nk+αn+dα\frac{n_k + \alpha}{n + d\alpha}. What prior belief does α=1\alpha = 1 express?

Answer

Prior density ∝∏kpkα−1\propto \prod_k p_k^{\alpha - 1}, likelihood ∏kpknk\prod_k p_k^{n_k}; the product ∏kpkα+nk−1\prod_k p_k^{\alpha + n_k - 1} is a Dirichlet with parameters α+nk\alpha + n_k. The mean of Dir(a0,… )\text{Dir}(a_0, \dots) is ak/∑jaj=(nk+α)/(n+dα)a_k / \sum_j a_j = (n_k + \alpha)/(n + d\alpha). α=1\alpha = 1 is the uniform prior over all probability vectors (“every distribution equally plausible”); α→0\alpha \to 0 approaches pure counting; large α\alpha pulls hard towards uniform.

Exercise 3 (inverse CDF). Prove that inverse-CDF sampling returns value kk with probability pkp_k. Why does the code use searchsorted(..., side="right") and set the last CDF entry to exactly 1? What would go wrong with side="left" when p0=0p_0 = 0?

Answer

kk is returned iff Fk−1≤u<FkF_{k-1} \le u < F_k (with F−1=0F_{-1} = 0), an interval of length pkp_k, so P(k)=pkP(k) = p_k for u∼U[0,1)u \sim U[0,1). side="right" returns the first ii with Fi>uF_i > u, which implements "u<Fku < F_k" and never returns a zero-probability value (its interval is empty). Setting Fd−1=1F_{d-1} = 1 protects against rounding making Fd−1<uF_{d-1} < u for uu near 1 (which would return the out-of-range index dd). With side="left" (first ii with Fi≥uF_i \ge u), u=0u = 0 would return k=0k = 0 even if p0=0p_0 = 0 — a zero-probability value with tiny but nonzero frequency.

Exercise 4 (derivation: the softmax gradient). Show that ∂θk[−log⁡softmax(θ)x]=pθ(k)−1[x=k]\partial_{\theta_k} [-\log \mathrm{softmax}(\theta)_x] = p_\theta(k) - \mathbb{1}[x=k]. Conclude that the gradient of the average NLL vanishes exactly at pθ=p^datap_\theta = \hat p_{\text{data}}, and explain why a value absent from the training data can never be reached exactly (its logit would have to be −∞-\infty).

Answer

−log⁡softmax(θ)x=−θx+log⁡∑jeθj-\log \mathrm{softmax}(\theta)_x = -\theta_x + \log \sum_j e^{\theta_j}; differentiating, −1[x=k]+eθk/∑jeθj-\mathbb{1}[x=k] + e^{\theta_k}/\sum_j e^{\theta_j}. Averaging over the data, ∇=pθ−p^data\nabla = p_\theta - \hat p_{\text{data}}, zero iff they are equal. For a value with frequency 0 the gradient is pθ(k)>0p_\theta(k) > 0 for every finite θ\theta, so its logit decreases forever and pθ(k)→0p_\theta(k) \to 0 only in the limit θk→−∞\theta_k \to -\infty. This slow approach is why finite training (early stopping) acts as smoothing (§4.3).

Exercise 5 (the discretized logistic sums to 1). Show that with the edge rule (−∞-\infty for x=0x=0, +∞+\infty for x=d−1x = d-1) the masses of one component sum to 1 for any μ\mu, ss. What would be lost without the edge rule in homework world 1?

Answer

∑x=0d−1[F(x+12)−F(x−12)]\sum_{x=0}^{d-1} [F(x+\tfrac12) - F(x-\tfrac12)] telescopes to F(+∞)−F(−∞)=1−0F(+\infty) - F(-\infty) = 1 - 0 once the outer edges are infinite. Without the rule the sum is F(d−12)−F(−12)<1F(d - \tfrac12) - F(-\tfrac12) < 1: the mass beyond the range is lost and the model is not normalized. World 1 puts 22.7% of its mass at 0 — all of the Gaussian’s left tail; without the open first bin the model could only represent it with a component centered near 0 that wastes half its mass below −0.5-0.5.

Exercise 6 (the density-at-center objective). A component with weight π\pi and scale ss is centered exactly on a value that has frequency ff in the training data. Show that its contribution to the training “log-likelihood” grows like flog⁡π4sf \log \frac{\pi}{4s} as s→0s \to 0. Why does the real (CDF-based) likelihood not have this problem?

Answer

The logistic density at its center is 14s\frac{1}{4s}, so the score of that value is at least π/(4s)\pi/(4s) and the average log-score gains about flog⁡π4s→+∞f \log \frac{\pi}{4s} \to +\infty as s→0s \to 0 (the other values lose only a bounded amount as long as other components cover them). With the CDF, the component’s mass on its value is at most π⋅1\pi \cdot 1 (all of its mass in one bin), so the log-likelihood contribution is bounded by flog⁡π≤0f \log \pi \le 0: a spike can at best put a point mass on a value, never “more than probability 1”.

Exercise 7 (the k/(2n) rule). Use k2nln⁡2\frac{k}{2n\ln 2} bits to predict the KL of the world-2 histogram at n=100n = 100 and n=1,000n = 1{,}000, and compare with script 02 (0.4216 and 0.0729). Why does the rule fail at n=100n = 100?

Answer

k=99k = 99: predicted 0.714 bits at n=100n = 100 and 0.0714 at n=1,000n = 1{,}000. The second matches (0.0729); the first is off (0.4216) because the rule is an asymptotic, large-nn approximation — at n=100n = 100 most bins have 0 or 1 counts, and smoothing (α=0.5\alpha = 0.5) changes the estimator substantially. The rule is good once every bin with non-negligible probability has many counts.

Exercise 8 (the curse in numbers). For the sticky chain with d=64d = 64, n=1,000n = 1{,}000 and α=0.5\alpha = 0.5, compute the joint histogram’s code length for a sequence it has never seen, and compare with the entropy. How many training sequences would be needed for half of the test sequences to have been seen?

Answer

−log⁡20+0.51000+0.5⋅264≈log⁡2(2⋅9.2×1018)≈64.0-\log_2 \frac{0 + 0.5}{1000 + 0.5 \cdot 2^{64}} \approx \log_2(2 \cdot 9.2 \times 10^{18}) \approx 64.0 bits, i.e. 1.0 bit per dimension vs an entropy of 0.477 — the measured 1.0000. For half of the test sequences to be seen, the training set must cover sequences carrying half of the probability mass; with entropy ≈ 30.5 bits, a typical sequence has probability around 2−30.52^{-30.5}, so roughly 2302^{30} ≈ 10910^9 training sequences — for a world that three numbers describe exactly.

Exercise 9 (orders). (a) Show that for the sticky chain H(xt∣xt+1)=H(xt+1∣xt)H(x_t \mid x_{t+1}) = H(x_{t+1} \mid x_t), which explains why the reversed order loses nothing in §7.3. (b) Construct a distribution on 3 bits for which one-step conditionals (“each variable given only the one just before it”) are exact in some order but not in the natural order x1,x2,x3x_1, x_2, x_3.

Answer

(a) The chain starts at its stationary distribution (a fair coin) and its transition matrix is symmetric, so the joint distribution of (xt,xt+1)(x_t, x_{t+1}) is symmetric and the two conditional entropies are equal (the chain is reversible).

(b) Let x1,x2x_1, x_2 be independent fair coins and x3=x1x_3 = x_1; then H=2H = 2 bits. Natural order with one-step conditionals: H(x1)+H(x2∣x1)+H(x3∣x2)=1+1+1=3>2H(x_1) + H(x_2 \mid x_1) + H(x_3 \mid x_2) = 1 + 1 + 1 = 3 > 2, because x3x_3 needs x1x_1, two steps back. Order (x1,x3,x2)(x_1, x_3, x_2): 1+H(x3∣x1)+H(x2∣x3)=1+0+1=21 + H(x_3 \mid x_1) + H(x_2 \mid x_3) = 1 + 0 + 1 = 2, exact. The best order puts each variable right after the variable it depends on.

Exercise 10 (anomaly detection, a thought question). Use −log⁡2p(x)-\log_2 p(x) under the world-2 model as an anomaly score. Which values of xx would be flagged? Now suppose the “anomalies” are values drawn uniformly from 0–99. What fraction of them would a threshold at 12 bits catch, and why might likelihood-based anomaly detection fail in high dimensions (think of Lecture 1’s 288-pixel images)?

Answer

Values far from all three bumps (below ~20 or above ~80) have tiny probability and huge −log⁡2p-\log_2 p. Uniform anomalies land in those regions roughly half the time; values inside the bumps cost only 4–8 bits and pass as normal. In high dimensions the issue becomes severe: an atypically simple input (an almost empty canvas) can get a higher likelihood than any real example, so “low likelihood” and “out of distribution” diverge — a phenomenon reported for deep generative models (e.g. models trained on CIFAR assigning higher likelihood to SVHN) and revisited when we discuss evaluation.


11. Further reading

From the slides

  • T. Salimans, A. Karpathy, X. Chen, D. P. Kingma. PixelCNN++: Improving the PixelCNN with Discretized Logistic Mixture Likelihood and Other Modifications. ICLR 2017 — the discretized logistic mixture of §5.
  • The homework: https://github.com/rll/deepul (homeworks/hw1, Question 1).

Added by these notes

  • K. P. Murphy. Probabilistic Machine Learning: An Introduction (2022), chapters 4 (statistics: MLE, the Dirichlet–multinomial model) and 8 (optimization, SGD).
  • T. M. Cover, J. A. Thomas. Elements of Information Theory, chapter 2 — entropy, relative entropy, the chain rule for entropy.
  • H. Akaike. A New Look at the Statistical Model Identification. IEEE TAC 1974 — the k/2nk/2n penalty behind §3.3.
  • H. White. Maximum Likelihood Estimation of Misspecified Models. Econometrica 1982 — MLE converges to the KL projection onto the family.
  • M. Mächler. Accurately Computing log⁡(1−exp⁡(−∣a∣))\log(1 - \exp(-|a|)). 2012 — the log1mexp switch at ln⁡2\ln 2.
  • D. P. Kingma, J. Ba. Adam: A Method for Stochastic Optimization. ICLR 2015.
  • E. Nalisnick et al. Do Deep Generative Models Know What They Don’t Know? ICLR 2019 — likelihood-based anomaly detection failing in high dimensions (Exercise 10).

12. Next lecture

Lecture 3 takes the chain rule into high dimensions with neural conditionals, following the second part of the original slides:

  • Bayes nets (restricted conditionals; Lecture 1’s context models are one), MADE (a masked autoencoder that outputs all DD conditionals in one pass; orderings), and causal masked neural models that share parameters across positions and add coordinate information;
  • masked 1-D convolutions and WaveNet (dilations, gated residual blocks), RNNs (char-rnn; an RNN as a very deep, sparse causal model), and PixelCNN for images (masks A and B, the blind spot, the gated two-stack fix), with softmax vs discretized logistic outputs;
  • all trained by the maximum likelihood + SGD recipe of this lecture on ShapeWorld, measured against Lecture 1’s count models (47.4 bits per image) and the exact floor of 17.80 bits — for the first time with a real chance of producing valid shapes.
← 返回课程目录