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), 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:
- Say what a likelihood-based model provides (evaluate , sample ) and what it is used for (generation, compression, anomaly detection), and list the desiderata of the slides.
- 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.
- 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).
- Train a model by stochastic gradient descent on the log-likelihood; compute the gradient for softmax logits; explain why early stopping acts as smoothing.
- 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.
- 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
| Assumed | Introduced here | Developed later |
|---|---|---|
| Lecture 1 (bits, entropy, ) | maximum likelihood, KL to the empirical distribution | neural conditionals: MADE, PixelCNN (Lecture 3), Transformers (Lecture 4) |
| derivatives, the chain rule of calculus | SGD, softmax, the logistic distribution | continuous data and change of variables (Lecture 5) |
a little PyTorch (tensors, backward()) | the probabilistic chain rule | dequantization 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
| Symbol | Meaning |
|---|---|
| one discrete value (§2–§5); in §6–§7, is a vector | |
| the training data, drawn from | |
| the number of training points equal to ; is the empirical distribution | |
| a model with parameters | |
| the sigmoid (logistic CDF) | |
| turns real “logits” into a probability vector | |
| NLL | negative log-likelihood, here always averaged per value and in bits (homework reports nats: divide bits by ) |
0.5 The worlds of this lecture
Three toy worlds, all with exact probabilities:
- Homework world 1: ; a Gaussian with mean 0.2 and standard deviation 0.2 on the scale, cut into 20 bins; everything below 0 piles up in bin 0 (probability 0.227). Entropy 3.454 bits.
- Homework world 2: ; three equally likely Gaussians, , , . 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 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 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:
- Generate data: synthesize images, video, speech, text.
- Compress data: construct efficient codes (Lecture 1: a model with probability gives a code of bits).
- 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 of , learned from samples , that allows
- computing for arbitrary (compression, anomaly detection, model comparison), and
- sampling (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 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 . The slides’ model is a histogram, described (redundantly) by non-negative numbers :
- Training: count frequencies, .
- Inference (querying ): a lookup in an array.
- Sampling: compute the cumulative distribution , draw , and return the smallest with .
Why does sampling work? Value is returned exactly when , an interval of length ; a uniform lands in it with probability . 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 , 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 is
Maximize it subject to with a Lagrange multiplier : setting the derivative of to zero gives , so , i.e. . 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:
| train | train bits () | test bits () | test values unseen | test bits () | KL () | non-zero bins |
|---|---|---|---|---|---|---|
| 10 | 3.122 | ∞ | 70.0% | 6.464 | 1.165 | 9 |
| 30 | 4.190 | ∞ | 41.3% | 6.197 | 0.931 | 20 |
| 100 | 4.892 | ∞ | 13.3% | 5.921 | 0.627 | 36 |
| 300 | 5.189 | ∞ | 3.0% | 5.546 | 0.258 | 46 |
| 1,000 | 5.236 | ∞ | 0.5% | 5.367 | 0.080 | 55 |
| 10,000 | 5.289 | ∞ | 0.1% | 5.294 | 0.008 | 66 |
| 100,000 | 5.289 | ∞ | 0.1% | 5.289 | 0.001 | 76 |
(The entropy floor is 5.293 bits.)

Unsmoothed histograms from 30, 1,000 and 100,000 samples against the true pmf (01_histograms.py).
Three failures, all visible in the table:
- Infinite test bits. A value never seen in training gets probability 0, and a single such value in the test set makes the average infinite. Even 100,000 training points leave a few far-tail test values unseen (0.1%).
- 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 .
- Slow learning. Even with a pseudo-count that rules out infinities, the KL to the truth is 0.63 bits at : one hundred free parameters need far more than one hundred data points.
2.4 Smoothing as a prior
Adding pseudo-counts to every bin,
is the classical fix. It has a clean Bayesian reading: with a Dirichlet prior on the probability vector, this is the posterior mean after observing the counts (Exercise 2). is Laplace’s rule of succession; is the Krichevsky–Trofimov estimator used in compression.
How much smoothing is best (test bits; best α per row starred)?
| train | α=0.01 | α=0.1 | α=0.5 | α=1 | α=3 | α=10 |
|---|---|---|---|---|---|---|
| 10 | 7.941 | 6.489 | 6.354* | 6.424 | 6.537 | 6.606 |
| 100 | 5.896 | 5.691* | 5.741 | 5.863 | 6.146 | 6.420 |
| 1,000 | 5.362 | 5.344* | 5.352 | 5.374 | 5.472 | 5.731 |
| 10,000 | 5.293 | 5.291* | 5.292 | 5.294 | 5.304 | 5.345 |
The best pseudo-count settles around 0.1–0.5, but what matters is its weight relative to the data: imaginary points against 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
3.1 Learning as search
The slides’ remedy for poor generalization is a parameterized distribution whose form already encodes assumptions (smoothness, a few bumps, …). Learning becomes a search over , and the loss + search procedure must:
- work with large datasets ( in the millions);
- yield such that matches — think of the loss as a distance between distributions;
- note that training sees only the empirical distribution, never itself: we want the model to generalize.
3.2 Maximum likelihood is a KL divergence
Maximum likelihood chooses
The quantity on the right is a cross-entropy, and Lecture 1’s identity splits it:
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 | avg train NLL | |||
|---|---|---|---|---|
| 9.7860 | 5.2824 | 4.5035 | 9.7860 | |
| 6.1880 | 5.2824 | 0.9056 | 6.1880 | |
| 11.6022 | 5.2824 | 6.3198 | 11.6022 |
Over all 44 points the largest discrepancy is bits — rounding error.
Two remarks:
- KL is asymmetric. Maximum likelihood minimizes , 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 = 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: for some in the family. As , , the minimizer of approaches , and .
- Misspecified: no member equals . Maximum likelihood still converges — to the best member of the family, (the “projection” of 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 (), measuring exactly:
World 1 (one Gaussian, , ): the family contains the truth.
| KL Gaussian MLE | KL histogram | |||
|---|---|---|---|---|
| 10 | 0.2650 | 0.1170 | 0.5437 | 0.9204 |
| 30 | 0.2566 | 0.1562 | 0.1388 | 0.4501 |
| 100 | 0.2027 | 0.1825 | 0.0088 | 0.0796 |
| 1,000 | 0.2028 | 0.1968 | 0.0004 | 0.0169 |
| 10,000 | 0.1999 | 0.1986 | 0.0001 | 0.0016 |
| 100,000 | 0.1986 | 0.1998 | 0.0000 | 0.0001 |
World 2 (three Gaussians): the family is misspecified. Best possible discretized Gaussian: KL = 0.5710 bits.
| KL Gaussian MLE | KL histogram | |||
|---|---|---|---|---|
| 10 | 0.5270 | 0.1535 | 0.5822 | 1.0645 |
| 30 | 0.5683 | 0.1470 | 0.6144 | 0.8766 |
| 100 | 0.5271 | 0.1429 | 0.5727 | 0.4216 |
| 1,000 | 0.5361 | 0.1413 | 0.5713 | 0.0729 |
| 10,000 | 0.5342 | 0.1403 | 0.5711 | 0.0061 |
| 100,000 | 0.5329 | 0.1409 | 0.5710 | 0.0006 |

KL to the truth as the training set grows (02_maximum_likelihood.py).
- In world 1 the MLE recovers ever more precisely and its KL falls to zero. With 2 parameters instead of 20 it beats the histogram at every : 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 and .
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 free parameters, the expected excess test loss of the MLE is about nats, i.e. bits. Check it against the table: the world-1 histogram has , predicting bits at (measured 0.0169) and at (measured 0.0016); the world-2 histogram () is predicted at and (measured 0.0729 and 0.0061). Every free parameter costs about half a nat divided by — 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,
and a minibatch of random training points gives an unbiased estimate of it and of its gradient. Each SGD step costs instead of . 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, with 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 ,
and averaged over a batch, , where 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):
| Data | test bits after epoch 1 | final | counting histogram | entropy | KL to truth | TV(SGD, counting) |
|---|---|---|---|---|---|---|
| world 1 (, ) | 4.177 | 3.589 | 3.578 | 3.454 | 0.0271 | 0.0209 |
| world 2 (, ) | 5.621 | 5.308 | ∞ | 5.293 | 0.0083 | 0.0128 |

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 that never occurs in the training data: , 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:
| step | train bits | test bits |
|---|---|---|
| 1 | 6.644 | 6.642 |
| 10 | 6.617 | 6.628 |
| 100 | 6.359 | 6.496 |
| 1,000 | 5.152 | 6.072 |
| 1,598 (best test) | 4.946 | 6.063 |
| 4,000 | 4.684 | 6.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):
| optimizer | lr | steps in 20 epochs | test bits after 1 epoch | 5 epochs | 20 epochs |
|---|---|---|---|---|---|
| gradient descent, full batch (best of lr 1/5/20/50) | 20 | 20 | 6.105 | 5.563 | 5.372 |
| gradient descent, full batch, lr too large | 100 | 20 | 6.577 | 9.463 | 12.423 |
| SGD, batch 128 | 2 | 1,260 | 5.539 | 5.347 | 5.316 |
| Adam, batch 128 | 0.02 | 1,260 | 5.621 | 5.331 | 5.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 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 can be computed exactly and differentiated. A good choice: the logistic distribution.
5.2 The logistic distribution
With location and scale :
It looks like a Gaussian with heavier tails (variance ), 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 is the integral of the density over its bin:
with one adjustment at the edges (homework Q1b, PixelCNN++): for the lower edge is replaced by , and for the upper edge by , so that the end bins collect all the mass beyond the range. The masses of all values then telescope to : a proper distribution with three parameters. A mixture of components handles several modes:
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):
| Data | DMoL test bits | params | softmax-histogram test bits | params | entropy |
|---|---|---|---|---|---|
| world 1 () | 3.598 | 12 | 3.589 | 20 | 3.454 |
| world 2 () | 5.358 | 12 | 5.308 | 100 | 5.293 |

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):
| train | DMoL, 4 components (12 params) | one discretized Gaussian (2) | histogram, best α (100) |
|---|---|---|---|
| 30 | 5.365 | 5.878 | 6.230 |
| 100 | 5.432 | 5.870 | 5.655 |
| 300 | 5.330 | 5.875 | 5.467 |
| 1,000 | 5.328 | 5.868 | 5.353 |
| 8,000 | 5.339 | 5.870 | 5.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 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 . Script 04, Part 3 puts four sharp components (scale 0.05 bins) at 30, 40, 55, 69:
- the naive formula returns 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 entries of other values break the backward pass (), and one NaN step destroys every parameter.
The stable form never subtracts probabilities. Since ,
where every term is computed stably (log1mexp switches between two formulas at ). The end bins are and (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: "". 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:
| epoch | score bits (train) | smallest scale | components with | true test bits | |
|---|---|---|---|---|---|
| 1 | 4.061 | 0.88 | 0.8868 | 4 | 3.975 |
| 5 | 3.661 | 0.94 | 0.5170 | 4 | 3.700 |
| 10 | 3.206 | 1.40 | 0.0851 | 3 | 3.654 |
| 20 | 2.264 | 11.21 | 0.0043 | 3 | 3.654 |
| 50 | 3.601 | 0.97 | 0.0045 | 2 | 3.672 |
| 100 | 2.264 | 12.33 | 0.0032 | 2 | 3.684 |
| 200 | 3.885 | 0.88 | 0.0028 | 1 | 3.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:
- 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.
- Spikes are knife-edges. A tiny shift of off the integer kills the density, the component starves () and dies; later another component forms a new spike (epoch 100). The objective oscillates and 3 of the 4 components end up dead.
- 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 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:
| Data | dimensions | values each | possible examples (= bins) |
|---|---|---|---|
| homework world 2 (one value) | 1 | 100 | |
| binary MNIST | 784 | 2 | |
| ShapeWorld (Lecture 1) | 288 | 2 | |
| CIFAR-10 , 8 bits | 3,072 | 256 | |
| a photo, 8 bits | 49,152 | 256 |
There are about 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 starts with a fair coin, and each next bit repeats the previous one with probability 0.9. Its probability is a product of factors, and its entropy is bits, about 0.47 bits per dimension for large .
With 1,000 training sequences, test bits per dimension (script 05, Part 2):
| bins | test sequences seen in training | entropy | joint histogram | independent bits | chain rule, shared (3 numbers) | per-position tables (numbers) | |
|---|---|---|---|---|---|---|---|
| 4 | 16 | 100.0% | 0.6017 | 0.5999 | 1.0004 | 0.5979 | 0.5987 (7) |
| 8 | 256 | 97.8% | 0.5354 | 0.5547 | 1.0002 | 0.5361 | 0.5387 (15) |
| 12 | 4,096 | 90.5% | 0.5132 | 0.6256 | 1.0004 | 0.5048 | 0.5059 (23) |
| 16 | 65,536 | 76.1% | 0.5022 | 0.7777 | 0.9999 | 0.5051 | 0.5057 (31) |
| 24 | 42.1% | 0.4911 | 0.9383 | 1.0003 | 0.4961 | 0.4974 (47) | |
| 32 | 21.2% | 0.4856 | 0.9821 | 1.0005 | 0.4799 | 0.4811 (63) | |
| 64 | 0.2% | 0.4773 | 1.0000 | 1.0016 | 0.4734 | 0.4749 (127) |

Test bits per dimension of the three model types as the dimension grows (05_curse_of_dimensionality.py).
- The joint histogram (with in every one of the bins) is excellent while and then collapses. An unseen sequence costs about bits, which for is about 64 bits — one bit per dimension, as if every bit were a coin flip.
- Independent bits generalize at every 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 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 variables can be written as a product of conditionals:
It follows from applying the definition 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 is a product of conditionals, all computable in parallel when is given.
- Sampling follows the order: draw , then given , 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 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 to for every training sequence. The ratios telescope:
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:
- 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.
- Share the conditional across positions (one table for all ). 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:
| order | positions | ||
|---|---|---|---|
| natural | 1 2 3 4 5 6 7 8 9 10 | 5.2210 | 5.2210 |
| reversed | 10 9 8 7 6 5 4 3 2 1 | 5.2210 | 5.2210 |
| even then odd | 1 3 5 7 9 2 4 6 8 10 | 5.2210 | 7.4087 |
| random | 3 7 4 10 1 6 5 9 8 2 | 5.2210 | 8.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
- A likelihood-based model lets us evaluate and sample from it; it serves generation, compression and anomaly detection. We want it expressive, data-efficient, and fast to train, sample and evaluate.
- 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.
- Maximum likelihood minimizes . 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 nats of expected excess test loss: few well-chosen parameters win with little data, flexible families win with lots.
- 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.
- Discretized logistic mixtures give exact, smooth, few-parameter distributions over discrete values via CDF differences with open end bins. Compute stably. Density-at-center scores are not probabilities: training “NLL” can fall below the entropy while components collapse into spikes.
- In high dimensions histograms die (curse of dimensionality: 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
- 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.
- 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).
- Mixing up nats and bits. Homework plots are in nats per dimension; these notes use bits. 1 nat = 1.4427 bits.
- Subtracting probabilities in floating point. and similar expressions must be computed in log space; a finite loss with NaN gradients is a symptom.
- 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.
- Comparing optimizers by steps instead of compute. A full-batch step is times more expensive than a minibatch step.
- 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 subject to , . What happens to for a value with ?
Answer
Lagrangian ; stationarity gives , so , and normalization gives : . (The objective is concave, so this is the global maximum.) For the term is 0 whatever is, and any mass placed there is taken away from values that do occur, so the optimum is : maximum likelihood actively removes probability from unseen values.
Exercise 2 (derivation: smoothing as a posterior mean). With a Dirichlet prior on and counts , show that the posterior is and that its mean is . What prior belief does express?
Answer
Prior density , likelihood ; the product is a Dirichlet with parameters . The mean of is . is the uniform prior over all probability vectors (“every distribution equally plausible”); approaches pure counting; large pulls hard towards uniform.
Exercise 3 (inverse CDF). Prove that inverse-CDF sampling returns value with probability . 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 ?
Answer
is returned iff (with ), an interval of length , so for . side="right" returns the first with , which implements "" and never returns a zero-probability value (its interval is empty). Setting protects against rounding making for near 1 (which would return the out-of-range index ). With side="left" (first with ), would return even if — a zero-probability value with tiny but nonzero frequency.
Exercise 4 (derivation: the softmax gradient). Show that . Conclude that the gradient of the average NLL vanishes exactly at , and explain why a value absent from the training data can never be reached exactly (its logit would have to be ).
Answer
; differentiating, . Averaging over the data, , zero iff they are equal. For a value with frequency 0 the gradient is for every finite , so its logit decreases forever and only in the limit . 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 ( for , for ) the masses of one component sum to 1 for any , . What would be lost without the edge rule in homework world 1?
Answer
telescopes to once the outer edges are infinite. Without the rule the sum is : 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 .
Exercise 6 (the density-at-center objective). A component with weight and scale is centered exactly on a value that has frequency in the training data. Show that its contribution to the training “log-likelihood” grows like as . Why does the real (CDF-based) likelihood not have this problem?
Answer
The logistic density at its center is , so the score of that value is at least and the average log-score gains about as (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 (all of its mass in one bin), so the log-likelihood contribution is bounded by : a spike can at best put a point mass on a value, never “more than probability 1”.
Exercise 7 (the k/(2n) rule). Use bits to predict the KL of the world-2 histogram at and , and compare with script 02 (0.4216 and 0.0729). Why does the rule fail at ?
Answer
: predicted 0.714 bits at and 0.0714 at . The second matches (0.0729); the first is off (0.4216) because the rule is an asymptotic, large- approximation — at most bins have 0 or 1 counts, and smoothing () 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 , and , 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
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 , so roughly ≈ training sequences — for a world that three numbers describe exactly.
Exercise 9 (orders). (a) Show that for the sticky chain , 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 .
Answer
(a) The chain starts at its stationary distribution (a fair coin) and its transition matrix is symmetric, so the joint distribution of is symmetric and the two conditional entropies are equal (the chain is reversible).
(b) Let be independent fair coins and ; then bits. Natural order with one-step conditionals: , because needs , two steps back. Order : , exact. The best order puts each variable right after the variable it depends on.
Exercise 10 (anomaly detection, a thought question). Use under the world-2 model as an anomaly score. Which values of 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 . 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 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 . 2012 — the
log1mexpswitch at . - 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 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.