Lecture 3 · Autoregressive Models I: From Bayes Nets to Masked Convolutions

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

课程源码 ZIP ↓

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

本篇目录

Maps to: UC Berkeley CS294-158 Deep Unsupervised Learning (Spring 2024), Lecture 2 · Thu 1/25/2024 · Likelihood Models: Autoregressive Models, second part (slides 21–81 of 192) and the appendix (slides 162–186): Bayes nets, MADE and its orderings, causal masked neural models (parameter sharing + coordinate coding), masked 1-D convolutions and WaveNet, RNNs, PixelCNN (masks, softmax sampling, the blind spot), gated PixelCNN, PixelCNN++, class-conditional PixelCNN, speed-ups. Homework 1, Question 2. Basis: The slides present each model in one or two pictures and a sentence of verdict (“efficient, but too strong an assumption”, “expressive, but not enough parameter sharing”, “limited receptive field, linear in number of layers”, “blind spot in receptive field”). These notes explain the mechanisms (how MADE’s degrees guarantee causality, why left-padding makes a convolution causal, why stacked masks leave a blind spot and how two stacks remove it, how channels are masked for colour) and test every verdict on ShapeWorld with the exact yardsticks of Lecture 1. Several verdicts held; some did not (see “Plan vs reality”). Code: code/lecture03/ (8 scripts + ar_models.py; PyTorch (CPU); models are trained once and cached; first runs 1–5 minutes each) Reading time: 4–5 hours including running the code


0. How to read this lecture

0.1 Learning goals

After this lecture you should be able to:

  1. State the three things we want from a parameterization of the chain rule’s conditionals — expressiveness (look at the whole prefix), parameter sharing (statistical efficiency), parallel training (all conditionals in one pass) — and place Bayes nets, FVSBN, MADE, causal convolutions, WaveNet, RNNs and PixelCNN on that map.
  2. Build MADE’s masks from degrees and prove that they make output ii depend only on inputs before ii; explain why the order is a modeling choice and how ensembles over orders help.
  3. Implement a causal 1-D convolution by left-padding, compute receptive fields with and without dilation, and explain what WaveNet’s gated residual blocks and coordinate coding add.
  4. Explain an RNN as a causal model with a fixed-size state, and the difference between wall-clock time and the length of the critical path.
  5. Build PixelCNN’s masks A and B, explain the blind spot, and how the gated PixelCNN’s vertical and horizontal stacks remove it.
  6. Condition a PixelCNN on a class, and model colour with independent or autoregressive channels.
  7. Use dependency maps (gradients of one output with respect to the input) to verify causality and to find receptive-field bugs.

0.2 Prerequisites and scope

AssumedIntroduced hereDeveloped later
Lecture 1 (ShapeWorld, bits, valid/novel samples) and Lecture 2 (MLE, SGD, the chain rule, discretized logistics)masked layers, receptive fields, dilations, gatingattention and Transformers (Lecture 4)
what a convolution and an MLP are; PyTorch basicscausal convolutions in 1-D and 2-D, RNN autoregressiontokenizers, KV caching (Lecture 4)
class conditioning, colour channelslatent-variable and diffusion models that sample in parallel (Lectures 7–12)

0.3 Map

§1  the design space: what we want from the conditionals
§2  Bayes nets: sparse parents, shared or per-position tables                        ← code 01
§3  FVSBN and MADE: masks and degrees; orderings and ensembles                        ← code 01, 02
§4  causal masked models: parameter sharing + coordinates; masked 1-D conv; WaveNet   ← code 03
§5  RNNs: the past in a fixed-size state                                               ← code 04
§6  PixelCNN: masks A/B; the blind spot; gated PixelCNN; class conditioning; colour    ← code 05-08
§7  beyond: PixelCNN++, faster sampling, hierarchies
§8  summary   §9 pitfalls   §10 exercises   §11 further reading   §12 next lecture

0.4 How the experiments are run

  • Data: the same 10,000 training and 2,000 test ShapeWorld images as Lecture 1 (binary 12×24; the floor is the entropy, 17.80 bits per image). Lecture 1’s best count model reached 47.4 bits.
  • Yardsticks: test bits per image; and on 64–100 samples per model: valid (a pixel-perfect ShapeWorld image), panels ok (each panel a valid shape), flips (pixels to change to reach the nearest valid image), novel valid (valid and not a training image), and the copy rate: among samples with two valid panels, how often both shapes are of the same kind (the world’s value is 0.5+0.5/8=0.56250.5 + 0.5/8 = 0.5625; ignoring the left panel gives about 1/81/8).
  • Budget: CPU-sized. The 1-D models and PixelCNNs train 1,500 Adam steps on minibatches of 32 images (4.8 passes over the data, 1–2.5 minutes each); the colour PixelCNNs get 3,000 steps; MADE and FVSBN are cheap per step and get 15,000 / 8,000 steps of 64 images. All numbers are for these budgets — a GPU and 100× more steps would move every model closer to the floor. Models are cached in checkpoints/ so that later scripts (and Lecture 4) reuse them.

1. The design space

The chain rule p(x)=∏ip(xi∣x<i)p(x) = \prod_{i} p(x_i \mid x_{<i}) is exact (Lecture 2, §7). Everything in this lecture is a different answer to: how should each conditional be represented? The slides list three solutions; it helps to keep three properties in mind:

PropertyWhy we want it
Expressiveness: the conditional may depend on the whole prefix, nonlinearlythe true conditionals of images do (a shape’s lower half depends on its upper half)
Parameter sharing across conditionalsstatistical efficiency: what is learned at one position transfers to others (Lecture 1: one count table for all pixels)
Parallel training: all DD conditionals from one pass, given the true xxGPUs: compute every conditional at once (“teacher forcing”)

There is no free lunch in the fourth property, sampling: whatever the representation, sampling is sequential — pixel ii needs pixels <i< i — so DD network passes per image (Lecture 4 makes each pass cheaper; Lectures 7–12 give up exact autoregression to sample in parallel).


2. Bayes nets: sparse conditioning

2.1 The idea

The slides’ Solution 1: sparsify the conditioning. Each variable depends on a few “parents” instead of the whole prefix, p(xi∣x<i)≈p(xi∣xpa(i))p(x_i \mid x_{<i}) \approx p(x_i \mid x_{\text{pa}(i)}), and each conditional is a table indexed by the parents’ values. If the data really have such (causal?) structure, this is a great inductive bias. But in general sparsification is a strong assumption that limits expressivity, and in standard form there is limited parameter sharing between conditionals (each node has its own table).

Lecture 1’s context models are Bayes nets: the parents are 4, 10 or 23 causal neighbours — with one twist, a single table shared by all positions.

2.2 Shared vs per-position tables

Script 01 compares the two (test bits per image; 10 parents → 1,024 contexts):

parentstraining imagesconditional tablesparameterstrain bitstest bits
410,000one shared table16101.1101.9
410,000one table per position4,60880.781.5
1010,000one shared table1,02468.368.7
1010,000one table per position294,91252.553.6
101,000one shared table1,02469.168.9
101,000one table per position294,91256.266.0
10100one shared table1,02469.671.5
10100one table per position294,91266.5109.2

Plan vs reality. The plan was “sharing wins”. With 10,000 images the per-position tables win instead (53.6 vs 68.7 bits): positions really differ in ShapeWorld — the middle of a panel is inked far more often than its corners, and the panel border cuts every row in two — and 10,000 examples per position fill the tables. Sharing wins only when data per position are scarce: with 100 images the per-position net needs 109.2 bits against 71.5. What we want is both: share parameters across positions and tell the model where it is. That is the slides’ third solution (§4).


3. FVSBN and MADE: one network for all conditionals

3.1 FVSBN: full conditioning, no hidden layer

The most direct neural chain rule is a fully visible sigmoid belief net: one logistic regression per pixel on all earlier pixels,

p(xi=1∣x<i)=σ(bi+∑j<iwijxj).p(x_i = 1 \mid x_{<i}) = \sigma\Big(b_i + \sum_{j < i} w_{ij} x_j\Big).

It can be written as one D×DD \times D linear layer whose weight matrix is masked to its strictly lower triangle. With D=288D = 288 it uses 41,616 parameters. It conditions on everything — but linearly, and without any sharing between pixels.

3.2 MADE: masks from degrees

The slides’ Solution 2, MADE (Germain, Gregor, Murray & Larochelle, 2015), puts a hidden layer in between: an ordinary autoencoder x↦h↦logitsx \mapsto h \mapsto \text{logits} in which connections are deleted so that output ii cannot see inputs ≥i\geq i. The recipe assigns every unit a degree mm:

  • input xkx_k gets m(xk)=m(x_k) = its position in the order (1,…,D1, \dots, D);
  • each hidden unit gets a random degree in {1,…,D−1}\{1, \dots, D-1\} (more precisely, between the smallest degree of the layer below and D−1D - 1);
  • a hidden unit hh may read a unit uu of the layer below iff m(h)≥m(u)m(h) \ge m(u);
  • output ii may read hidden unit hh iff m(xi)>m(h)m(x_i) > m(h) (strictly).

Why this works. Follow any path from input xkx_k to output ii: degrees never decrease along hidden connections and must increase strictly at the output, so m(xk)≤m(h1)≤⋯≤m(hL)<m(xi)m(x_k) \le m(h_1) \le \dots \le m(h_L) < m(x_i), i.e. kk comes before ii in the order. No path from a later input exists. Script 01 prints a 5-pixel example with hidden degrees [4,3,3,2,2,1][4, 3, 3, 2, 2, 1]:

hidden mask (rows = hidden units, cols = x1..x5)     output mask (rows = outputs 1..5, cols = hidden units)
  1 1 1 1 0     (degree 4: reads x1..x4)               0 0 0 0 0 0   (output 1 reads nothing: p(x1) is a bias)
  1 1 1 0 0     (degree 3)                             0 0 0 0 0 1   (output 2 reads the degree-1 unit)
  1 1 1 0 0                                            0 0 0 1 1 1
  1 1 0 0 0                                            0 1 1 1 1 1
  1 1 0 0 0                                            1 1 1 1 1 1   (output 5 reads every unit)
  1 0 0 0 0     (degree 1: reads x1 only)

The product of the two masks tells which inputs each output can reach: output ii sees exactly a subset of x<ix_{<i}. One forward pass gives all DD conditionals — training is fully parallel. In PyTorch a masked layer is just F.linear(x, W * M, b) with a fixed 0/1 matrix MM (the slides show the same three lines in TensorFlow).

3.3 Results

Script 01, Part 4 (test bits per image; samples: 100 per model):

modelparameterstrain bitstest bitsvalidpanels okflipsnovel valid
Bayes net, shared table, 23 parents (Lecture 1)8,388,60846.747.40%1%61.90%
FVSBN (linear, no hidden layer)83,23247.749.90%0%30.20%
MADE (one hidden layer of 1,024)591,13626.231.62%17%12.50%

Bayes net, FVSBN and MADE samples

  • FVSBN lands near the 23-parent Bayes net: conditioning on everything does not help if the conditional is linear.
  • MADE’s hidden layer is shared by all 288 conditionals, and it gets much closer to the floor (31.6 bits). But its train bits are 5 bits below its test bits, and its few valid samples are copies of training images: 590,000 parameters, with every output pixel owning its own output weights, over-fit 10,000 images. This is exactly the slides’ verdict: expressive, but not enough parameter sharing for efficient learning. (A detail worth knowing: a MADE with two hidden layers of 512 trained worse — 47.0 bits — in a calibration run; random degrees thin out the connectivity of deep MADEs.)

3.4 Orderings and ensembles

Changing the input degrees changes the order. The slides report that on MNIST all orderings reach roughly the same negative log-likelihood, but the samples differ. Script 02 trains one MADE per order:

ordertrain bitstest bitsvalidpanels okflipsnovel valid
raster (row by row)26.231.62%17%12.50%
columns23.630.05%26%11.63%
even-then-odd pixels26.031.05%24%12.62%
random permutation28.333.01%12%16.31%

MADE orderings

The four orders land within 3 bits of each other, as on MNIST; the samples differ in character. The order is a modeling choice: in column order a pixel sees the whole columns to its left and the pixels above it in its own column — different conditionals to learn.

The four models also make different mistakes on individual images (4.4 bits on average between the raster and random orders). Averaging their probabilities gives a valid model, the mixture p(x)=14∑kpk(x)p(x) = \frac14 \sum_k p_k(x):

quantitytest bits
average of the four models31.38
mixture 14∑kpk(x)\frac14\sum_k p_k(x)28.90
oracle: best order chosen per image (not a valid model)27.47

On every image the mixture is at most log⁡24=2\log_2 4 = 2 bits worse than the best of the four (here 1.4 bits from the oracle on average) and 2.5 bits better than the average model. This is the idea of the slides’ “MADE: multiple orderings”: train with many orders (order-agnostic training) and ensemble them.


4. Causal masked neural models: sharing plus coordinates

4.1 The slides’ Solution 3

MADE gives every conditional its own output weights. Modern causal masked neural models keep MADE’s masking but add two ingredients:

  1. Parameter sharing: the same parameters are used when shifting from position ii to i+1i+1 — every position runs the same computation on its own window of the past. Padding with blanks makes all positions uniform.
  2. Coordinate coding: to retain the ability to individualize the conditionals, each input is tagged with its position, [xi,"i"][x_i, \text{"}i\text{"}].

Convolutions over a sequence are the simplest such model.

4.2 Masked (causal) 1-D convolutions

Flatten the image into a sequence of 288 pixels (raster order) and predict p(xt∣x<t)p(x_{t} \mid x_{<t}) with a 1-D convolution that only looks backwards. The slides’ implementation tip: rather than masking half of a kernel, pad (k−1)⋅d(k-1)\cdot d zeros on the left (kernel size kk, dilation dd); then the window of output tt ends at tt. Shifting the input right by one (so that position tt receives xt−1x_{t-1}) makes the model strictly causal. Pros: easy, a constant number of parameters for any sequence length, fast. Con: a limited receptive field, linear in the number of layers — LL layers of kernel 2 see the previous L+1L + 1 positions.

4.3 WaveNet

WaveNet (van den Oord et al., 2016) fixes the receptive field with dilated convolutions: layer ℓ\ell looks 2ℓ2^\ell positions back, so 7 layers with dilations 1,2,…,641, 2, \dots, 64 see 1+127=1281 + 127 = 128 positions. It improves expressiveness with gated residual blocks,

g=tanh⁡(Wa∗h)⊙σ(Wb∗h),h←h+Wrg,skip+=Wsg,g = \tanh(W_a * h) \odot \sigma(W_b * h), \qquad h \leftarrow h + W_r g, \qquad \text{skip} \mathrel{+}= W_s g,

where the tanh branch proposes a feature and the sigmoid gate decides how much of it passes; residual and skip connections keep a deep stack trainable. The slides also show WaveNet with pixel location appended: the (x,y)(x, y) coordinates of the pixel being predicted are fed as extra inputs. (Coordinates are not data — they are known before generation — so this does not break causality.)

Script 03 checks what each model can see, with a dependency map: the gradient of the output for pixel (8, 12) with respect to every input pixel, nonzero exactly where the output depends on the input.

masked 1-D conv, 7 layers, no dilation: 8 of 204 earlier pixels     WaveNet, dilations 1..64: 128 of 204
  ........................                                           ........................
  ....########X...........  (row 8)                                  ....####################  (row 3)
                                                                     ########################  (rows 4-7)
                                                                     ############X...........  (row 8)
modelparamstrain bitstest bitsvalidpanels okflipscopy rate
masked 1-D conv, 7 layers, no dilation100,609143.6143.60%0%63.9—
WaveNet, dilations 1..64100,60925.325.88%22%23.10.20 (n=5)
WaveNet + (x,y)(x, y) of the pixel100,70522.623.322%43%10.90.21 (n=14)

WaveNet samples

  • Without dilation the model never sees the row above (24 positions back) and is worse even than Lecture 1’s 4-neighbour count table (101.9 bits), which does.
  • Dilations cut the bits by a factor of 5.6 with the same depth.
  • Coordinates help a lot (25.8 → 23.3 bits; valid samples 8% → 22%): a 1-D convolution cannot otherwise know where a row ends or which panel it is in. With only 100,000 parameters, shared across all positions, this model generalizes almost perfectly (train 22.6, test 23.3) — compare MADE’s 26.2 / 31.6 with 6× more parameters.

5. Recurrent models

5.1 The past in a fixed-size state

The slides’ RNN incarnation (char-rnn, Karpathy 2015; earlier Bengio et al. 2003 and Sutskever, Vinyals & Le 2014): a hidden state is updated once per position, ht=f(ht−1,xt−1)h_t = f(h_{t-1}, x_{t-1}), and the conditional is read from it, p(xt∣x<t)=g(ht)p(x_t \mid x_{<t}) = g(h_t). The same ff and gg at every position — full parameter sharing — and an unlimited receptive field: script 04’s dependency map shows the GRU’s output for pixel (8, 12) depending on all 204 earlier pixels. The slides offer a nice re-reading: an RNN is a special, highly restrictive causal masked model — very deep, with very sparse connectivity (each “layer” connects only position t−1t-1 to tt).

5.2 Results

modelparamstrain bitstest bitsvalidpanels okflips
GRU, hidden 12850,43339.739.80%3%22.6
GRU + (x,y)(x, y)51,20132.432.80%3%22.3
(for comparison) WaveNet + (x,y)(x, y)100,70522.623.3

Everything must squeeze through 128 numbers, updated one pixel at a time: to finish a shape’s row the state must remember what happened 24 pixels earlier. At this budget the GRU stays well behind WaveNet and produces no valid image (it also learned more slowly and needed a larger learning rate). Coordinates help it as well.

5.3 Wall clock vs critical path

Plan vs reality. The plan was to show that the GRU is slow. On one CPU thread its forward pass over 64 images is actually faster than WaveNet’s (21 ms vs 37 ms): with a single core there is no parallelism to lose, and PyTorch’s fused GRU kernel is efficient. The real difference is the critical path: the GRU needs 288 sequential steps, WaveNet 7 layers whose 288 positions can all be computed at once. On a GPU with thousands of cores, that is the difference between idle and busy hardware — one reason Transformers (Lecture 4), which are parallel like convolutions and see everything like RNNs, replaced both.


6. PixelCNN: masked 2-D convolutions

6.1 Masks A and B

Images can be flattened, but they are fundamentally 2-D: in a sequence the pixel above is 24 steps away, in an image it is one step away. PixelCNN (van den Oord, Kalchbrenner & Kavukcuoglu, 2016) imposes raster order on the image and masks every 2-D convolution kernel so that the output at (i,j)(i, j) only sees pixels before (i,j)(i, j):

type A (first layer)        type B (later layers)
1 1 1 1 1                   1 1 1 1 1
1 1 1 1 1                   1 1 1 1 1
1 1 0 0 0                   1 1 1 0 0
0 0 0 0 0                   0 0 0 0 0
0 0 0 0 0                   0 0 0 0 0

Rows above: allowed; same row to the left: allowed; to the right and below: masked. The only difference is the centre. In the first layer the centre is the pixel being predicted and must be hidden (type A). In later layers the centre is a feature that already only summarizes pixels before (i,j)(i, j), so it may be used (type B). Homework 1 Q2a recommends a 7×77 \times 7 type-A convolution, then several 7×77 \times 7 type-B convolutions and two 1×11 \times 1 type-B layers, with ReLUs; we use a 7×77 \times 7 A layer, four 5×55 \times 5 B layers and 32 channels to fit a CPU.

The output layer is a softmax over the values of a pixel (2 for binary images; 256 for 8-bit images — the slides’ “softmax sampling” animation shows the 256-way distribution changing as the image is generated). Sampling draws one value, writes it into the image, and runs the whole network again for the next pixel.

6.2 The blind spot

Stacking masked layers grows the receptive field, but not evenly. Script 05 prints the dependency map of a 5-layer stack of 3×33 \times 3 masked convolutions (# = seen, o = an earlier pixel inside the window that is not seen):

.......###########......
.......##########o......
.......#########oo......
.......########ooo......
.......#######oooo......
.......#####X...........

Each layer extends the view one pixel up-left, up and up-right of every pixel it reads — but the pixels to the right on the current row are masked, so the up-right growth is lost one row per layer. The result is a triangular blind spot above and to the right: 10 earlier pixels inside the window that the model can never use, however deep it is. The full PixelCNN of script 05 sees 175 of the 204 earlier pixels for pixel (8, 12), and 20 of the unseen ones lie in the blind spot.

6.3 Results, and a leaderboard

PixelCNN after 1,500 steps: 25.0 test bits; 14% valid samples (all of them new images), 30% valid panels, 19.0 flips; copy rate 0.29 over 14 samples with two valid panels.

PixelCNN samples

The leaderboard of Lectures 1 and 3 (test bits per image, same data):

modelparameterstest bits
memorizer (Lecture 1)—191.1
independent pixels (Lecture 1)—212.1
count table, 23 neighbours (Lecture 1)—47.4
FVSBN83,23249.9
MADE, raster order591,13631.6
masked 1-D conv, no dilation100,609143.6
WaveNet100,60925.8
WaveNet + (x,y)(x, y)100,70523.3
GRU50,43339.8
GRU + (x,y)(x, y)51,20132.8
PixelCNN105,25025.0
gated PixelCNN (§6.4)176,38622.3
true distribution—17.8

Plan vs reality. The plan was “PixelCNN beats every 1-D model”. It does not beat WaveNet with coordinates (23.3 bits and more valid samples); it is on par with WaveNet without coordinates (25.8). Two handicaps explain it: convolutions are translation-equivariant, so without coordinates the PixelCNN cannot tell where the panel border is — decisive in ShapeWorld, where no shape crosses it — and the blind spot hides pixels up-right. Coordinate channels would address the first (Exercise 7); the gated PixelCNN addresses the second.

A second observation: every model so far copies the left shape into the right panel far less often than the world does (0.2–0.3 vs 0.56). The dependency spans 12 or more columns; none of these models learns it at this budget. Attention (Lecture 4) can reach any earlier pixel in one step.

6.4 The gated PixelCNN: no blind spot

The gated PixelCNN (van den Oord et al., 2016, “Conditional image generation with PixelCNN decoders”; slides’ appendix) combines two streams of convolutions:

  • a vertical stack whose activations at row ii depend only on rows <i< i: a (⌊k/2⌋+1)×k(\lfloor k/2 \rfloor + 1) \times k convolution padded so that its output at row ii covers rows up to ii, then shifted down by one row before it is used;
  • a horizontal stack that looks only along the current row to the left — “easy, we know how to do 1-D masked convolutions” — and adds the shifted vertical features.

Together they cover everything above and everything to the left: no blind spot. Both stacks use the gated activation tanh⁡(a)⊙σ(b)\tanh(a) \odot \sigma(b), and the horizontal stack is residual (“gated ResNet block”). Script 06:

PixelCNN: sees 175 of 204, 20 unseen inside       gated PixelCNN: sees 178 of 204, 0 unseen inside
.#######################                           ..#####################.
.#####################oo                           ..#####################.
.###################oooo                           ..#####################.
.#################oooooo                           ..#####################.
.###############oooooooo                           ..##########X...........
.###########X...........
modelparamstrain bitstest bitsvalidpanels okflipsnovel validcopy rate
PixelCNN105,25024.725.014%30%19.014%0.29 (n=14)
gated PixelCNN176,38622.122.338%44%14.738%0.05 (n=38)

Gated vs plain PixelCNN

The gated model is the best of the lecture: 22.3 bits and 38% valid samples, all of them new images. (Its gain mixes the full receptive field and the gated blocks; this experiment does not separate them.) It costs more parameters and about 1.6× the computation per step. The copy rule is still not learned — the copy rates, computed over few samples and therefore noisy, are closer to “no copying” (1/81/8) than to the world’s 0.56.

A debugging story. The first version of this model shifted its first horizontal layer twice and silently lost the pixel immediately to the left. Nothing crashed, and the causality check passed — seeing less than allowed is still causal. Only the dependency map revealed the missing pixel; fixing it moved the model from 31.6 to 22.5 bits in a calibration run. Always look at the receptive field.

6.5 Class-conditional PixelCNN

To model p(x∣y)p(x \mid y) for a class yy, the slides (appendix) multiply the one-hot label by a different learned matrix in each convolutional layer and add the result as a channel-wise bias, broadcast over all positions. Script 07 conditions on the left shape’s kind (8 classes):

modeltest bits per image
unconditional PixelCNN24.99
conditional, given the true label20.70
conditional, given a wrong label35.72

Lecture 1 computed that the label carries exactly I(label;X)=3.00I(\text{label}; X) = 3.00 bits about the image, so two perfect models would differ by exactly 3 bits. Plan vs reality: the label saves 4.29 bits — more than it carries. No contradiction: both models are imperfect, and the conditional one is also the better model of its own task (its excess over H(X∣label)=14.80H(X \mid \text{label}) = 14.80 is 5.9 bits; the unconditional model’s excess over H(X)=17.80H(X) = 17.80 is 7.2 bits). Knowing the shape from the first pixel on makes every conditional easier to learn. A wrong label costs 11 bits: the model really uses it.

Samples on request (12 per class, pooled): the left panel is valid in 40% of samples, and then it is the requested shape 97% of the time (37 of 38). The right panel is valid in 26% of samples, and then it repeats the requested shape 76% of the time (19 of 25) — more than the world’s 56%. The label bias is added at every position, and without coordinates the network cannot tell that the label describes only the left panel. Conditioning information must be routed to where it applies — a theme of text-to-image models later.

Class-conditional samples

6.6 Colour: independent vs autoregressive channels

Homework 1 Q2b moves to colour images with 2 bits per channel (values 0–3) and first assumes the channels are independent given the previous pixels,

p(x)=∏i∏c∈{R,G,B}p(xic∣x<i),p(x) = \prod_{i} \prod_{c \in \{R, G, B\}} p(x_i^c \mid x_{<i}),

a 4-way softmax for each channel. The original PixelCNN instead orders the channels too — R, then G given R, then B given R and G:

p(x)=∏ip(xiR∣x<i) p(xiG∣x<i,xiR) p(xiB∣x<i,xiR,xiG).p(x) = \prod_i p(x_i^R \mid x_{<i})\, p(x_i^G \mid x_{<i}, x_i^R)\, p(x_i^B \mid x_{<i}, x_i^R, x_i^G).

This is implemented with channel groups: hidden channels are split into an R, a G and a B group, and at the centre position of every kernel a group may only read groups before it (mask A) or up to itself (mask B). Everywhere else in the kernel the usual spatial mask applies.

Colored ShapeWorld paints each shape in one of 8 palette colours (red, green, blue, yellow, magenta, cyan, white, orange) on black; its exact entropy is 17.80+2×3=23.8017.80 + 2 \times 3 = 23.80 bits. Script 08 trains both models (residual blocks, 30 channels, 3,000 steps — with the plain stack and 1,500 steps both stalled at 85–91 bits, so the colour models got a longer budget):

modeltest bitsvalidpanels: valid shapeink blobs in one palette colourP(palette colour given ink) at a shape’s first ink pixel
independent channels52.473%8%81% of 1440.924
autoregressive channels38.160%5%71% of 1400.948

Where the bits go (1,000 test images):

modelR bitsG bitsB bitstotalon background pixelson ink pixels
independent channels18.320.114.753.116.936.2
autoregressive channels19.711.66.838.110.827.3

Colour samples

Plan vs reality. The plan: independent channels fail at the first ink pixel of each shape, where the colour is still undecided and a product of three per-channel distributions cannot say “red or cyan”. That failure barely shows (0.924 vs 0.948 of the probability on palette colours). The reason is in the palette: seven of the eight colours are exactly the product set {0,3}3\{0, 3\}^3 minus black — a distribution independent channels can represent. Only orange (3,1,0)(3, 1, 0) breaks the product structure. (With a palette of colours that are not a product set, the effect would be large; Exercise 11.)

The 14-bit gap comes from somewhere else, and the per-channel table shows where: the three channels share one big uncertainty — is there ink at this pixel at all? At the edge of a shape, an independent model pays for that coin flip three times, once per channel (18–20 bits each). The ordered model pays it once, in R; G and B, which see R at the same pixel, then cost only 11.6 and 6.8 bits. Correlations within a pixel are what the channel ordering buys.

The samples of both models are mostly broken shapes at this budget, and blob colour consistency does not favour the better-likelihood model: at 38–52 bits, far from the 23.8-bit floor, sample quality reflects under-training more than channel structure. (Lecture 4 models colour differently, the iGPT way: one token per pixel with 64 possible colours.)


7. Beyond: PixelCNN++, faster sampling, hierarchies

The slides’ appendix lists improvements that this lecture’s code does not implement, but that complete the picture:

  • PixelCNN++ (Salimans et al., 2017) replaces the 256-way softmax by a discretized mixture of logistics (Lecture 2, §5): nearby pixel values are likely to co-occur, and a smooth distribution knows it. It also captures long-range dependencies efficiently by downsampling (a U-Net-like structure inside the causal network), with dropout for regularization.
  • Speed-ups by caching activations (Fast PixelCNN++, Ramachandran et al., 2017): during sampling, only the activations that depend on the new pixel need recomputing; the rest can be cached — the convolutional analogue of Lecture 4’s KV cache.
  • Breaking the autoregressive pattern: generate groups of pixels in parallel (e.g. sample a whole sub-grid at once given coarser ones). Sampling drops from O(d)O(d) to O(log⁡d)O(\log d) steps (Multiscale PixelCNN, Reed et al., 2017), at the price of assuming the pixels within a group are conditionally independent — usually false, so expressivity is traded for speed.
  • Hierarchies and super-resolution: a PixelCNN conditioned on a 7×77 \times 7 subsampled image generates the 28×2828 \times 28 image (Dahl et al., 2017); a grayscale PixelCNN first, then a colour one conditioned on it (Kolesnikov & Lampert, 2017); Subscale Pixel Networks (Menick & Kalchbrenner, 2018); autoregressive video models (Weissenborn et al., 2019).
  • Sample quality: AR models can produce excellent samples, especially when they condition selectively on the most informative bits (grayscale PixelCNN, subscale networks).
  • Latent representations from AR models (Yan, Ho & Abbeel, 2019): an AR model has no latent vector; Fisher scores (gradients of the log-likelihood with respect to the parameters) can serve as one, for image manipulation.

8. Summary

  1. The chain rule’s conditionals can be represented with sparse tables (Bayes nets), one masked network (FVSBN, MADE), shared causal convolutions (WaveNet; PixelCNN in 2-D), or a recurrent state (RNNs). We want expressive conditionals, parameter sharing, and parallel training; sampling is sequential in all of them.
  2. Bayes nets are efficient but rigid. Per-position tables won over a shared table with plenty of data, because ShapeWorld’s positions differ — the motivation for sharing plus coordinates.
  3. MADE builds masks from degrees so that every path from input kk to output ii has kk before ii. It is expressive but over-fits (train 26.2 vs test 31.6 bits). Orders are modeling choices; ensembling orders by averaging probabilities helped by 2.5 bits.
  4. Causal 1-D convolutions are causal by left-padding; dilations give exponential receptive fields (WaveNet), coordinates tell the model where it is. WaveNet + (x,y)(x, y) reached 23.3 bits with 100,000 shared parameters.
  5. RNNs see the whole past through a fixed-size state; at our budget a GRU trailed WaveNet. Their real cost is a critical path of DD sequential steps, invisible on one CPU thread.
  6. PixelCNN uses masks A and B in 2-D; its stacked masks leave a blind spot, which the gated PixelCNN’s vertical and horizontal stacks remove (22.3 bits, 38% valid samples — the best of the lecture). Class conditioning works as a learned bias; colour channels can be modeled independently or autoregressively.
  7. Every model was far from the floor (17.80 bits) and none learned the long-range copy rule: the reach of a receptive field is the bottleneck that attention removes.

9. Common pitfalls

  1. Off-by-one masks. Type A vs B, the shift of the vertical stack, the shift of the input in 1-D models: one wrong offset either leaks the answer (training NLL implausibly low, samples garbage) or hides context (silently worse). Check both directions with dependency maps.
  2. Trusting a causality check alone. It catches leaks, not missing context. Look at what the model can see, too.
  3. Comparing models at different budgets without saying so. MADE got 15,000 steps, the convolutional models 1,500; numbers are budget-dependent.
  4. Forgetting coordinates in translation-equivariant models. Convolutions cannot know absolute position unless told (or unless padding leaks it weakly).
  5. Sampling with the training graph. Sampling must write each sampled value back into the input before predicting the next pixel; running the network once on zeros and sampling all pixels from those logits ignores every dependency.
  6. Reading copy rates or validity from a handful of samples. With 14 valid samples, a rate has a standard error of about 0.13.
  7. Treating the order as free. All orders are exact, but they need different conditionals; an order that puts dependent pixels far apart is harder to learn.

10. Exercises

Exercise 1 (derivation: MADE’s guarantee). Prove that with MADE’s degree rules there is no path from input xkx_k to output ii unless m(xk)<m(xi)m(x_k) < m(x_i). What goes wrong if hidden units are allowed degree DD?

Answer

Along a path xk→h(1)→⋯→h(L)→outix_k \to h^{(1)} \to \dots \to h^{(L)} \to \text{out}_i, the hidden rule gives m(xk)≤m(h(1))≤⋯≤m(h(L))m(x_k) \le m(h^{(1)}) \le \dots \le m(h^{(L)}) and the output rule m(h(L))<m(xi)m(h^{(L)}) < m(x_i); chaining, m(xk)<m(xi)m(x_k) < m(x_i). A hidden unit of degree DD could read every input but could feed no output (it would need m(xi)>Dm(x_i) > D), so it is wasted; degrees are drawn up to D−1D - 1 for that reason.

Exercise 2 (receptive fields). (a) How many past positions does a causal 1-D convolution stack with kernel 2 and dilations 1,2,4,…,2L−11, 2, 4, \dots, 2^{L-1} see? (b) How many layers are needed to see two full rows of a 24-pixel-wide image? (c) With kernel 3 and the same dilations?

Answer

(a) 1+∑ℓ=0L−12ℓ=2L1 + \sum_{\ell=0}^{L-1} 2^\ell = 2^L positions including the current input position (i.e. 2L2^L inputs: with the right-shift, pixels t−1t-1 back to t−2Lt - 2^L). (b) Two rows plus the current one need reach ≥ 48: 2L≥482^L \ge 48 gives L=6L = 6. (c) Each layer adds (k−1)d=2⋅2ℓ(k-1) d = 2 \cdot 2^\ell, total 1+2(2L−1)1 + 2(2^L - 1); L=5L = 5 gives 63.

Exercise 3 (the blind spot). For a stack of LL masked 3×33 \times 3 convolutions (one A, then B’s), count the earlier pixels inside the (2L+1)(2L+1)-wide window that are not seen, and check against script 05 (1 for L=2L = 2, 10 for L=5L = 5).

Answer

Moving one column to the right of jj costs one row up: the only way information flows “right” is through the above-right neighbour of a type-B kernel, and each layer can take that step once. So in row i−ri - r the view reaches rr columns to the right of jj, while the window reaches LL columns: L−rL - r pixels are missing (in the printed map, 4, 3, 2, 1, 0 for r=1..5r = 1..5). Summing over r=1..Lr = 1..L gives L(L−1)/2L(L-1)/2: 1 for L=2L = 2 and 10 for L=5L = 5 — the printed counts. Deeper stacks make the blind spot bigger, not smaller.

Exercise 4 (two stacks). Explain why the vertical stack must be shifted down by one row before being added to the horizontal stack, and why the vertical stack itself may see its own row in earlier layers.

Answer

The horizontal stack at row ii predicts pixel (i,j)(i, j); it may use rows <i< i fully, but from row ii only columns <j< j. The vertical convolution’s output at row ii covers rows up to ii including columns to the right of jj — illegal for (i,j)(i, j). Shifting down makes the feature used at row ii cover rows ≤i−1\le i - 1 only. Inside the vertical stack, features at row ii may summarize row ii because they are only ever consumed (after the shift) by row i+1i + 1 and below.

Exercise 5 (sharing vs coordinates). In §2.2 per-position tables won with 10,000 images. Propose a model that shares one table across positions but still captures position effects, and predict how it compares.

Answer

Add coarse position information to the context, e.g. which third of the panel the pixel is in (3×3 = 9 regions) or the distance to the panel border: the table grows by a factor of 9 instead of 288, so it fills with far fewer images while capturing the main position effects. It should approach the per-position table with 10,000 images and beat it with 100–1,000 — the same logic as WaveNet + (x,y)(x, y).

Exercise 6 (the label’s bits). In §6.5 the label saved 4.29 bits, more than the 3.00 bits it carries. Show that for perfect models the saving is exactly I(label;X)I(\text{label}; X), and express the measured saving as 3.00+(excess of the unconditional model)−(excess of the conditional model)3.00 + (\text{excess of the unconditional model}) - (\text{excess of the conditional model}).

Answer

Perfect models have expected test bits H(X)H(X) and H(X∣Y)H(X \mid Y); the difference is I(X;Y)=3.00I(X; Y) = 3.00 (the label is a function of XX, so I=H(Y)=3I = H(Y) = 3). With excesses Δu=24.99−17.80=7.19\Delta_u = 24.99 - 17.80 = 7.19 and Δc=20.70−14.80=5.90\Delta_c = 20.70 - 14.80 = 5.90: saving =(17.80+7.19)−(14.80+5.90)=3.00+7.19−5.90=4.29= (17.80 + 7.19) - (14.80 + 5.90) = 3.00 + 7.19 - 5.90 = 4.29.

Exercise 7 (coordinates for PixelCNN). Add two input channels with the normalized row and column to the PixelCNN (they must bypass the type-A mask’s centre restriction — why is that allowed?). Predict the effect on test bits and on samples crossing the panel border.

Answer

Coordinates of the pixel being predicted are known in advance and are not data, so the network may see the coordinates of every position, including the centre, without breaking causality (only the pixel values must be hidden). Expect fewer shapes crossing the red line in samples (as in the class-conditional figure, where some do), and lower test bits — WaveNet gained 2.5 bits from coordinates. (Try it: add the channels in PixelCNN.forward before the first convolution, with an unmasked 1×11 \times 1 path.)

Exercise 8 (ensembles). Prove that log⁡21K∑kpk(x)≥max⁡klog⁡2pk(x)−log⁡2K\log_2 \frac{1}{K}\sum_k p_k(x) \ge \max_k \log_2 p_k(x) - \log_2 K and ≥1K∑klog⁡2pk(x)\ge \frac{1}{K}\sum_k \log_2 p_k(x). Which inequality explains each comparison in §3.4?

Answer

The first: the sum is at least its largest term. The second: Jensen’s inequality for the concave log⁡\log. The mixture is within 2 bits of the per-image best order (oracle 27.47 vs mixture 28.90) and better than the average of the models’ log-probabilities (31.38).

Exercise 9 (critical paths). A GRU over 288 positions and a 7-layer WaveNet each run on a GPU that can process all positions of one layer in a single time unit. How many time units does each need for one forward pass? For sampling one image?

Answer

Forward (teacher forcing): GRU 288 units (one per step), WaveNet 7 (one per layer). Sampling: both need 288 sequential samples; the GRU spends 1 unit per step (it just advances its state), WaveNet 7 per step if it recomputes everything — or about 7 with caching of earlier activations. Teacher-forced training is where convolutions (and attention) win; sampling is sequential for all autoregressive models.

Exercise 10 (homework). Homework 1 Q2a reports test NLL in nats per dimension. Convert the gated PixelCNN’s 22.3 bits per image to nats per dimension, and the entropy floor too.

Answer

22.3/288=0.077422.3 / 288 = 0.0774 bits/dim =0.0774×ln⁡2=0.0537= 0.0774 \times \ln 2 = 0.0537 nats/dim. The floor: 17.80/288×ln⁡2=0.042817.80 / 288 \times \ln 2 = 0.0428 nats/dim.

Exercise 11 (when independence hurts). Suppose the palette were {red (3, 0, 0), cyan (0, 3, 3)} only. What is the best an independent-channel model can do at a shape’s first ink pixel (if the two colours are equally likely), and how many bits does it lose per shape compared with ordered channels?

Answer

The best product distribution matches the marginals: P(R=3)=P(G=3)=P(B=3)=1/2P(R=3) = P(G=3) = P(B=3) = 1/2 (each channel 0 or 3). It gives each of the 8 combinations {0,3}3\{0,3\}^3 probability 1/81/8, so red and cyan get 1/81/8 each: 1/41/4 of the mass is on real colours, 3 of 4 on impossible ones. The code length of the true colour is log⁡28=3\log_2 8 = 3 bits instead of log⁡22=1\log_2 2 = 1 bit with ordered channels (R decides; G and B follow): 2 bits lost per shape — and samples come out in impossible colours 3 times out of 4.


11. Further reading

From the slides

  • M. Germain, K. Gregor, I. Murray, H. Larochelle. MADE: Masked Autoencoder for Distribution Estimation. ICML 2015.
  • A. van den Oord et al. WaveNet: A Generative Model for Raw Audio. 2016.
  • A. van den Oord, N. Kalchbrenner, K. Kavukcuoglu. Pixel Recurrent Neural Networks. ICML 2016 (PixelRNN and PixelCNN).
  • A. van den Oord et al. Conditional Image Generation with PixelCNN Decoders. NeurIPS 2016 (gated PixelCNN, class conditioning).
  • T. Salimans, A. Karpathy, X. Chen, D. P. Kingma. PixelCNN++. ICLR 2017.
  • X. Chen et al. PixelSNAIL: An Improved Autoregressive Generative Model. 2017.
  • P. Ramachandran et al. Fast Generation for Convolutional Autoregressive Models. 2017.
  • S. Reed et al. Parallel Multiscale Autoregressive Density Estimation. ICML 2017.
  • A. Kolesnikov, C. H. Lampert. PixelCNN Models with Auxiliary Variables for Natural Image Modeling. ICML 2017.
  • J. Menick, N. Kalchbrenner. Generating High Fidelity Images with Subscale Pixel Networks and Multidimensional Upscaling. 2018.
  • R. Dahl, M. Norouzi, J. Shlens. Pixel Recursive Super Resolution. ICCV 2017.
  • D. Weissenborn, O. Täckström, J. Uszkoreit. Scaling Autoregressive Video Models. 2019.
  • W. Yan, J. Ho, P. Abbeel. Natural Image Manipulation for Autoregressive Models using Fisher Scores. 2019.
  • A. Karpathy. The Unreasonable Effectiveness of Recurrent Neural Networks (char-rnn), 2015; Y. Bengio et al. A Neural Probabilistic Language Model, 2003; I. Sutskever, O. Vinyals, Q. V. Le. Sequence to Sequence Learning with Neural Networks, 2014.

Added by these notes

  • B. Uria, M.-A. Côté, K. Gregor, I. Murray, H. Larochelle. Neural Autoregressive Distribution Estimation. JMLR 2016 — NADE, FVSBN and order-agnostic training.
  • R. Liu et al. An Intriguing Failing of Convolutional Neural Networks and the CoordConv Solution. NeurIPS 2018 — coordinates as input channels (Exercise 7).
  • D. Koller, N. Friedman. Probabilistic Graphical Models, chapter 3 — Bayes nets.

12. Next lecture

Lecture 4 completes the autoregressive story with the third part of the slides:

  • masked attention and the Transformer: an unlimited receptive field, O(1)O(1) parameters with respect to the data dimension, and parallel computation — and its quadratic cost (8D2L+4DL28D^2L + 4DL^2 FLOPs per attention layer);
  • tokens: characters, words and byte-pair encoding for text; raw pixels, iGPT’s colour palette and discrete autoencoders for images; the trade-off between sequence length, vocabulary and fidelity;
  • KV caching for fast sampling; decoder-only vs encoder-decoder models; modern recurrent models (state-space models, linear attention) that train in parallel and sample like RNNs;
  • homework 1 Q3–Q6 in CPU form: an iGPT on ShapeWorld (can attention finally learn the copy rule?), text, and a multimodal model that generates captions from images and images from captions.
← 返回课程目录