Course contents 32 / 34

32 / 34 · Autoregressive Models

Autoregressive models: PixelRNN and PixelCNN

Write the probability of an image as a product of one-pixel conditionals: the exact likelihood, bits per dimension, masked convolutions and their blind spot, Gated PixelCNN, PixelCNN++ and WaveNet.

On this page 11

Imagine a sensor that reports 0 or 1 at each of 12 time steps. There are only two values per step, yet there are 212=40962^{12} = 4096 possible records. A table of their probabilities needs 4095 free entries, with the last fixed by the sum. In this note’s synthetic exercise the sensor usually keeps its previous state. How can a model use that regularity and still assign an exact probability to every complete record?

Every family of this course has a way around this. A VAE bounds the likelihood, a GAN avoids it, a flow computes it through an invertible map. Autoregressive models keep the exact probability and change how it is written: as a product of one-dimensional conditionals, each predicting one pixel from the pixels before it. Each conditional is small and normalized by construction, so the likelihood of an image is exact and cheap to compute. The price is paid at sampling time, one pixel after another.

The chain rule as a model#

Take three binary pixels x=(x1,x2,x3)x = (x_1, x_2, x_3). Their joint distribution is a table of 8 probabilities. We can fill the same table in three steps: the probability of x1x_1, then of x2x_2 given x1x_1, then of x3x_3 given both. Why does the product of these three give the joint?

The definition of conditional probability, P(A∣B)=P(A∩B)/P(B)P(A \mid B) = P(A \cap B) / P(B) for P(B)>0P(B) > 0, rearranges to P(A∩B)=P(B) P(A∣B)P(A \cap B) = P(B)\, P(A \mid B). Apply it with A={Xn=xn}A = \{X_n = x_n\} and B={X1=x1,…,Xn−1=xn−1}B = \{X_1 = x_1, \dots, X_{n-1} = x_{n-1}\}, then again to the shorter prefix, and so on down to x1x_1:

p(x1,…,xn)=p(x1,…,xn−1) p(xn∣x<n)=p(x1,…,xn−2) p(xn−1∣x<n−1) p(xn∣x<n)    ⋮=∏i=1np(xi∣x<i),\begin{aligned} p(x_1, \dots, x_n) &= p(x_1, \dots, x_{n-1})\, p(x_n \mid x_{<n}) \\ &= p(x_1, \dots, x_{n-2})\, p(x_{n-1} \mid x_{<n-1})\, p(x_n \mid x_{<n}) \\ &\;\;\vdots \\ &= \prod_{i=1}^{n} p(x_i \mid x_{<i}) , \end{aligned}

where x<i=(x1,…,xi−1)x_{<i} = (x_1, \dots, x_{i-1}), and x<1x_{<1} is empty. This is the chain rule of probability. A conditional is defined by the usual ratio when its prefix has positive probability. At a zero-probability prefix it may be assigned arbitrarily: the joint probability stays zero. Taking logarithms turns the product into a sum,

log⁡p(x)=∑i=1nlog⁡p(xi∣x<i).\log p(x) = \sum_{i=1}^{n} \log p(x_i \mid x_{<i}) .

The chain rule is an identity: it holds for every distribution and every ordering of the coordinates, so writing a model this way assumes nothing. An image is ordered row by row from the top left, and in colour images red, green and blue within each pixel; values are integers in {0,…,255}\{0, \dots, 255\}.

Counting parameters#

The factorization alone saves nothing. For binary pixels, the conditional of pixel ii needs one probability for each of the 2i−12^{i-1} histories, and the geometric sum gives the size of the full table again:

∑i=1n2i−1=2n−1.\sum_{i=1}^{n} 2^{i-1} = 2^n - 1 .

The savings come from how the conditionals are represented. Independent binary values need nn parameters. A first-order Markov model with a separate transition rule at each position needs 1+2(n−1)1 + 2(n - 1): one initial probability and two probabilities per later position. If one transition rule is shared across time, only three free probabilities remain: the initial state and transitions after 0 and after 1. Sharing is an extra assumption, separate from the first-order restriction.

For image pixels, discarding distant dependencies can lose useful structure. The fully visible sigmoid belief network lets each conditional depend on all earlier values through a logistic regression,

p(xi=1∣x<i)=σ(αi+∑j<iαijxj),p(x_i = 1 \mid x_{<i}) = \sigma\Big(\alpha_i + \sum_{j<i} \alpha_{ij} x_j\Big),

with ii parameters for pixel ii and n(n+1)/2n(n+1)/2 in total (CS236 notes):

Model of a 12-step binary recordFree parameters
full table212−1=40952^{12} - 1 = 4095
independent values1212
first-order Markov, position-specific transitions1+2(12−1)=231 + 2(12 - 1) = 23
first-order Markov, shared transitions33
logistic conditionals (FVSBN)12⋅13/2=7812 \cdot 13 / 2 = 78

The practice script below fits the three-parameter shared-transition model to freshly generated records and checks its normalized distribution over all 4096 possibilities. Its transition probabilities are fitted separately: the model does not assume that switching from 0 and switching from 1 have the same probability.

Later models share more. NADE (Larochelle and Murray, 2011) computes all conditionals with one hidden layer whose weights are reused across positions; MADE (Germain et al., 2015) gets them all from one pass of an autoencoder whose weights are masked so that output ii depends only on inputs before ii, the same masks that build the autoregressive flows. PixelRNN and PixelCNN reuse one recurrent or convolutional network at every position, so the number of parameters no longer depends on the size of the image.

Why the exact likelihood is tractable#

An energy-based model writes p(x)=p~(x)/Zp(x) = \tilde p(x)/Z, and its normalizer Z=∑xp~(x)Z = \sum_x \tilde p(x) runs over every image: 2563072256^{3072} terms for a 32×3232 \times 32 colour image. An autoregressive model never needs such a sum. Each conditional is a softmax over the values of one pixel, so it sums to one by construction, and that is enough for the whole product. Sum over the last pixel first; it appears only in the last factor, so distributivity pulls the other factors out:

∑x∏i=1np(xi∣x<i)=∑x<n∏i=1n−1p(xi∣x<i)∑xnp(xn∣x<n)=∑x<n∏i=1n−1p(xi∣x<i)⋅1=⋯=1.\begin{aligned} \sum_{x} \prod_{i=1}^{n} p(x_i \mid x_{<i}) &= \sum_{x_{<n}} \prod_{i=1}^{n-1} p(x_i \mid x_{<i}) \sum_{x_n} p(x_n \mid x_{<n}) \\ &= \sum_{x_{<n}} \prod_{i=1}^{n-1} p(x_i \mid x_{<i}) \cdot 1 \\ &= \dots = 1 . \end{aligned}

Repeating the step for xn−1,…,x1x_{n-1}, \dots, x_1 gives 1. So the product is a normalized distribution for any network that outputs normalized conditionals, and evaluating log⁡p(x)\log p(x) costs nn softmaxes of a few hundred values each, 3072⋅2563072 \cdot 256 numbers for the colour image, instead of a sum over 2563072256^{3072} images.

Worked example. Give the three binary pixels logistic conditionals (toy numbers):

p(x1=1)=σ(0)=0.5,p(x2=1∣x1)=σ(−1+2x1),p(x3=1∣x1,x2)=σ(−2+1.5x1+1.5x2).\begin{aligned} p(x_1 = 1) &= \sigma(0) = 0.5, \\ p(x_2 = 1 \mid x_1) &= \sigma(-1 + 2x_1), \\ p(x_3 = 1 \mid x_1, x_2) &= \sigma(-2 + 1.5x_1 + 1.5x_2) . \end{aligned}

For the image (1,1,0)(1, 1, 0) the factors are 0.50.5, σ(1)=0.731\sigma(1) = 0.731 and 1−σ(1)=0.2691 - \sigma(1) = 0.269, so p(1,1,0)=0.0983p(1, 1, 0) = 0.0983. The Code section evaluates all eight images the same way and finds that they sum to 1, with no normalizer computed anywhere.

Maximum likelihood, which the KL note derives from minimizing DKL(pdata ∥ pθ)D_{\mathrm{KL}}(p_{\text{data}} \,\|\, p_\theta), becomes a sum of nn classification losses: at every position, predict the next value from the previous ones, and pay the cross-entropy of the true value.

Sampling follows the product: draw x1x_1, then x2x_2 given x1x_1, and so on. Each draw is the inverse-CDF method for a discrete variable: take u∼U(0,1)u \sim \mathcal U(0, 1) and return the smallest value whose cumulative probability reaches uu.

Pixels as discrete values#

PixelRNN (van den Oord, Kalchbrenner and Kavukcuoglu, 2016) treats each colour value as a category and predicts it with a 256-way softmax. A categorical distribution assumes no shape, so it can be multimodal or skewed, and it gives probabilities rather than densities: log⁡p(x)≤0\log p(x) \le 0, and no dequantization is needed, unlike the continuous densities of flows.

Likelihoods of image models are reported in bits per dimension, the negative log-likelihood in base 2 divided by the number of values:

bits/dim=−log⁡2p(x)n=−ln⁡p(x)nln⁡2,\text{bits/dim} = -\frac{\log_2 p(x)}{n} = -\frac{\ln p(x)}{n \ln 2},

where the second form is the change of base log⁡2y=ln⁡y/ln⁡2\log_2 y = \ln y / \ln 2. A model that spreads probability uniformly over 256 values gives each image 256−n256^{-n}, so −log⁡2256−n/n=8-\log_2 256^{-n} / n = 8 bits/dim. The number is an ideal compressed size with the model already shared; it excludes model-description and file-format overhead. Shannon–Fano–Elias coding gives an outcome of probability p(x)p(x) a codeword of ⌈−log⁡2p(x)⌉+1<−log⁡2p(x)+2\lceil -\log_2 p(x) \rceil + 1 < -\log_2 p(x) + 2 bits, while ideal arithmetic coding has a comparable bound for a whole sequence, constructing its interval from conditionals one value at a time. Ignoring finite-precision and termination overhead, its length is less than −log⁡2p(x)+2-\log_2 p(x) + 2 bits (Cover and Thomas, 2006, Sections 5.9 and 13.3).

On CIFAR-10, n=32⋅32⋅3=3072n = 32 \cdot 32 \cdot 3 = 3072, and the best PixelRNN reaches 3.00 bits/dim:

QuantityValue
raw image, 8⋅30728 \cdot 307224,576 bits
at 3.00 bits/dim, 3.00⋅30723.00 \cdot 30729,216 bits, about 1.1 KiB
ratio37.5%

A model that predicts fewer levels solves a coarser problem. With 10 levels of grey a uniform guess costs log⁡210≈3.32\log_2 10 \approx 3.32 bits per pixel, and such numbers cannot be compared with bits/dim over 256 values.

Parallel training, sequential sampling#

During training the whole image is known. If the network is built so that its output at position ii depends only on the inputs x<ix_{<i}, one forward pass on the real image yields all nn conditionals at once, and the loss is their sum. Feeding the true previous values rather than the model’s own samples is called teacher forcing, and it makes training as parallel as for any convolutional network.

Ordinary ancestral sampling proceeds sequentially: xi+1x_{i+1} is drawn conditional on xix_i, which must be sampled first. A model that predicts one value per pass needs nn passes for a sample, 3072 for a CIFAR-10 image. A plain implementation also recomputes the whole image at every pass, although only one output is used. The masked autoregressive flow has the same asymmetry: cheap density, expensive sampling.

PixelRNN and PixelCNN#

The networks of van den Oord, Kalchbrenner and Kavukcuoglu (2016) differ in how the output at position ii collects information from x<ix_{<i} while seeing nothing of xix_i and later values.

Recurrent layers#

Row LSTM processes the image row by row and computes the state of a whole row at once, with a one-dimensional convolution over the previous row of states. Each step looks a little to the left and right in the row above, so the context of a pixel is a triangle above it and misses part of the past. Diagonal BiLSTM captures the whole past. It shifts each row one position to the right of the previous one, so that diagonals of the image become columns, and scans them with two LSTMs in opposite directions. Both recurrences run sequentially over rows or diagonals even during training.

Masked convolutions#

PixelCNN replaces the recurrences with convolutions whose kernels are multiplied by a mask. For a k×kk \times k kernel with centre c=⌊k/2⌋c = \lfloor k/2 \rfloor,

Muv={1,u<c or (u=c and v<c),0,otherwise,M_{uv} = \begin{cases} 1, & u < c \text{ or } (u = c \text{ and } v < c), \\ 0, & \text{otherwise}, \end{cases}

so a position sees the rows above it and the pixels to its left. The first layer uses mask A, which excludes the centre, because its input at the centre is the value to be predicted. The later layers use mask B, which includes it: after the first layer, the feature at position ii has been computed from x<ix_{<i} only, and passing it on is safe. The paper’s PixelCNN has fifteen layers, a 7×77 \times 7 first layer with mask A followed by 3×33 \times 3 layers with mask B.

Figure

The 5×5 convolution masks of PixelCNN

Type-A and type-B masksTwo 5×5 grids of zeros and ones. Ones fill the two top rows and the two left cells of the middle row; mask B also has a one at the centre.mask A: first layer1111111111110000000000000mask B: later layers1111111111111000000000000centre: the pixel being predicted
The mask multiplies the kernel element-wise. Its ones cover the rows above the centre and the positions left of the centre in its row: the pixels before the current one in raster order. Mask A also zeroes the centre (12 ones of 25); mask B keeps it (13 ones).

Colour channels#

With colour, each pixel xix_i holds three values, and the chain rule goes over all of them:

p(xi∣x<i)=p(xi,R∣x<i)⋅p(xi,G∣x<i,xi,R)⋅p(xi,B∣x<i,xi,R,xi,G).\begin{aligned} p(x_i \mid x_{<i}) = {}& p(x_{i,R} \mid x_{<i}) \\ &\cdot p(x_{i,G} \mid x_{<i}, x_{i,R}) \\ &\cdot p(x_{i,B} \mid x_{<i}, x_{i,R}, x_{i,G}) . \end{aligned}

The feature maps of every layer are split into three groups, one per colour. Mask A lets the red group see no value of the current pixel, the green group see red, and the blue group see red and green; mask B in addition connects each group to itself. Dropping the dependence among the three values of the current pixel would be an assumption, and in samples the three channels of a pixel, and the edges they draw, would not have to agree.

The blind spot#

Stacking masked convolutions does not give the whole past. Describe an input pixel by its offset from the target: aa rows up and bb columns to the right, with b<0b < 0 to the left. A 3×33 \times 3 mask lets one layer read the row above at column shifts −1-1, 00 or +1+1, written ↖\nwarrow, ↑\uparrow and ↗\nearrow, or the current row at shift −1-1, written ←\leftarrow, plus the centre under mask B. A dependency through LL layers is a sequence of LL such moves. Counting the moves of each kind, n↗n_\nearrow and so on:

a=n↖+n↑+n↗≤L,b=n↗−n↖−n←≤n↗≤a.\begin{aligned} a &= n_\nwarrow + n_\uparrow + n_\nearrow \le L, \\ b &= n_\nearrow - n_\nwarrow - n_\leftarrow \\ &\le n_\nearrow \le a . \end{aligned}

No move in the current row goes right, so only the ↗\nearrow moves raise bb, and each of them also raises aa. The row aa steps above the target is therefore covered up to only aa columns to the right, whatever LL is. Every other pixel of the window is reached: aa upward moves, ↗\nearrow to gain columns and ↖\nwarrow to lose them, and ←\leftarrow or centre moves for the remaining layers reach any bb from −L-L to aa. Within the window of LL rows above and ±L\pm L columns, the earlier pixels number L(2L+1)L(2L + 1) in the rows above plus LL in the current row, 2L(L+1)2L(L+1) in all, and the unreachable triangle at the upper right holds

∑a=1L−1(L−a)=L(L−1)2\sum_{a=1}^{L-1} (L - a) = \frac{L(L-1)}{2}

of them: 6 of 40 for L=4L = 4. As LL grows the share tends to L2/22L2=14\tfrac{L^2/2}{2L^2} = \tfrac14, the share of the receptive field that van den Oord et al. (2016b), Section 2.2, say this blind spot can cover. The Code section finds the same 6 pixels by perturbing the input of a random network.

Figure

The blind spot of PixelCNN

Receptive field and blind spotTwo 6×11 grids with the pixel being predicted in the bottom row. In the PixelCNN grid, part of the past at the upper right (6 pixels) is outside the receptive field. In the Gated PixelCNN grid the receptive field covers the whole past within 4 rows.PixelCNN: 4 masked 3×3 convolutionsGated PixelCNN: two stacks, 4 layersvisible part of the pastblind spotpixel being predictedReceptive field and blind spotTwo 6×11 grids with the pixel being predicted in the bottom row. In the PixelCNN grid, part of the past at the upper right (6 pixels) is outside the receptive field. In the Gated PixelCNN grid the receptive field covers the whole past within 4 rows.PixelCNN: 4 masked 3×3 convolutionsGated PixelCNN: two stacks, 4 layersvisible part of the pastblind spotpixel being predicted
Earlier pixels that can influence the prediction at the marked pixel after 4 layers. Left: PixelCNN with 3×3 masks; the triangle at the upper right stays out of reach at any depth (6 pixels in this window). Right: Gated PixelCNN, whose vertical and horizontal stacks leave no blind spot.

Gated PixelCNN#

van den Oord et al. (2016b) close the gap between PixelCNN and PixelRNN with two changes. The first removes the blind spot with two stacks of convolutions. A vertical stack is unmasked within its window and sees all rows above the current one, so its receptive field grows as a rectangle. A horizontal stack sees the current row up to the current pixel. After each layer the vertical stack feeds the horizontal one, never the other way round. The vertical stack is the context for every pixel of a row and spreads over columns on both sides; if it took in the horizontal stack’s features of that row, a pixel would see pixels to its right in its own row, which come later in raster order.

The second change replaces the ReLUs between layers with multiplicative units, a stand-in for the gates of an LSTM:

y=tanh⁡(Wk,f∗x)⊙σ(Wk,g∗x),y = \tanh(W_{k,f} * x) \odot \sigma(W_{k,g} * x),

where ∗* is a convolution, kk the layer and ⊙\odot the element-wise product. A condition hh, such as a one-hot class label, enters as an extra term inside both nonlinearities,

y=tanh⁡(Wk,f∗x+Vk,f⊤h)⊙σ(Wk,g∗x+Vk,g⊤h),y = \tanh(W_{k,f} * x + V_{k,f}^\top h) \odot \sigma(W_{k,g} * x + V_{k,g}^\top h),

and the model becomes p(x∣h)=∏ip(xi∣x<i,h)p(x \mid h) = \prod_i p(x_i \mid x_{<i}, h). For a spatial condition ss, the products V⊤hV^\top h become 1×11 \times 1 convolutions V∗sV * s. On CIFAR-10 the Gated PixelCNN reaches 3.03 bits/dim, against 3.14 for PixelCNN and 3.00 for PixelRNN. On ImageNet, the paper reports performance similar to Row LSTM in less than half the training time.

PixelCNN++#

A 256-way softmax knows nothing about the order of its classes: 127 and 128 are as unrelated as 0 and 255 until the network learns otherwise, and a value never seen in training gets almost no probability. PixelCNN++ (Salimans et al., 2017) assumes a continuous intensity ν\nu with a mixture of KK logistic distributions and models the observed value as ν\nu rounded to an integer. The probability of a value is then the mass of the interval that rounds to it, a difference of two logistic CDFs:

P(x∣π,μ,s)=∑k=1Kπk[σ(x+0.5−μksk)−σ(x−0.5−μksk)],P(x \mid \pi, \mu, s) = \sum_{k=1}^{K} \pi_k \Big[\sigma\Big(\frac{x + 0.5 - \mu_k}{s_k}\Big) - \sigma\Big(\frac{x - 0.5 - \mu_k}{s_k}\Big)\Big],

where σ\sigma is the logistic sigmoid, the CDF of the logistic distribution. For x=0x = 0 the term x−0.5x - 0.5 is replaced by −∞-\infty, and for x=255x = 255 the term x+0.5x + 0.5 by +∞+\infty. The intervals then tile the real line, so the probabilities sum to one over {0,…,255}\{0, \dots, 255\}, and the edges collect the mass beyond them.

With one component, μ=127.3\mu = 127.3 and s=2s = 2, the values 126, 127, 128 and 129 get probabilities 0.112, 0.124, 0.121 and 0.105: neighbours are close automatically. With μ=254\mu = 254 and s=2s = 2, the edge value 255 gets 0.438 and 254 gets 0.124, which suits the excess of saturated pixels in real photographs.

The network conditions on whole pixels above and to the left and predicts the three channels of a pixel together. The mixture indicator is shared by the channels, and inside a component the means depend linearly on the channels already drawn, μG+αR\mu_G + \alpha R and μB+βR+γG\mu_B + \beta R + \gamma G. That is 10K10K outputs per pixel: KK weights, a mean and a scale for each channel and component, and three coefficients per component. With K=5K = 5, downsampling with short-cut connections in place of dilated convolutions, and dropout, PixelCNN++ reaches 2.92 bits/dim on CIFAR-10. Without dropout its training loss falls below 2.0 bits and the test loss rises above 6.0.

WaveNet: the same idea in one dimension#

Audio is a one-dimensional sequence of samples, and WaveNet (van den Oord et al., 2016c) models it with the same chain rule, p(x)=∏tp(xt∣x<t)p(x) = \prod_t p(x_t \mid x_{<t}). With the input shifted one position to the right before the first layer, a causal convolution, the one-dimensional mask, lets the prediction at time tt see only earlier audio samples. The current target xtx_t is not an input to its own prediction. Raw audio has 16-bit samples; WaveNet first compresses them with the μ-law f(x)=sign⁡(x)ln⁡(1+255∣x∣)/ln⁡256f(x) = \operatorname{sign}(x) \ln(1 + 255|x|)/\ln 256 and quantizes to 256 values, so each conditional is again a 256-way softmax.

Speech needs a long context, and plain causal convolutions grow it slowly. A dilated convolution with dilation δ\delta and kernel size 2 reads hidden positions tt and t−δt - \delta, so a layer adds δ\delta samples to the receptive field. With dilations 1,2,4,…,5121, 2, 4, \dots, 512 in ten layers,

1+∑l=092l=1+(210−1)=10241 + \sum_{l=0}^{9} 2^l = 1 + (2^{10} - 1) = 1024

samples, about 64 ms at 16 kHz, where ten undilated layers would see 11. The cost of sampling is the PixelCNN’s: one network pass per sample, 16,000 per second of audio. The audio note places WaveNet among today’s speech generators.

How the likelihoods compare#

Test negative log-likelihood on CIFAR-10, in bits per dimension (van den Oord et al., 2016a, 2016b; Salimans et al., 2017):

ModelBits/dim
Uniform distribution8.00
Multivariate Gaussian4.70
NICE (flow)4.48
Real NVP (flow)3.49
PixelCNN3.14
Row LSTM3.07
Gated PixelCNN3.03
Diagonal BiLSTM (PixelRNN)3.00
PixelCNN++2.92

In this table every autoregressive model has a lower test negative log-likelihood than every flow. A likelihood measures how well the model compresses the test set, which is a different question from how good its samples look; the evaluation notes measure the second, and a model can win on one and lose on the other.

Where it breaks#

Ordinary ancestral sampling is the bottleneck. A 256×256256 \times 256 colour image is 196,608196{,}608 values; a sub-pixel model needs that many network passes, and one that predicts whole pixels, as PixelCNN++ does, still needs 65,53665{,}536. Each draw depends on previous draws. Parallel hardware and caching can accelerate a pass; they do not remove those dependencies in this sampling procedure. Diffusion also needs many passes, but their number is set by the noise schedule, independent of the number of pixels.

The ordering is arbitrary and there is no latent code. Nothing summarizes an image in a few numbers, and the model must learn global structure from top-left-to-bottom-right prediction. Two remedies point to the next note. PixelVAE (Gulrajani et al., 2017) uses a PixelCNN as the decoder of a VAE, so that the latent carries global structure and the autoregressive part fills in detail. And over a small grid of discrete codes an autoregressive model is an excellent prior: VQ-VAE fits a PixelCNN over its code indices.

What you should remember#

  • Chain rule: p(x)=∏ip(xi∣x<i)p(x) = \prod_i p(x_i \mid x_{<i}), an identity for any order.
  • Normalized conditionals make the product normalized: the likelihood is exact, nn softmaxes.
  • Training is parallel with teacher forcing; ordinary ancestral sampling draws successive values using the generated prefix.
  • Mask A hides the current value, mask B passes features on; stacked masks leave a blind spot, fixed by vertical and horizontal stacks.
  • Bits/dim =−log⁡2p(x)/n= -\log_2 p(x)/n, 8 for a uniform model over 256 values.
  • PixelCNN++: a discretized logistic mixture; WaveNet: dilated causal convolutions on audio.

Notebook#

Run python3 scripts/notes/generative-practice.py autoregressive-models. The standard-library script generates binary sequences of length 12. The first symbol is equally likely to be 0 or 1; each next symbol flips its predecessor with probability 0.17. Seed 9305 fixes 2,048 training sequences and a separate 256-sequence evaluation split. No text, poster or image corpus is loaded.

  • Fit initial and transition probabilities from training counts, adding one to each count. Evaluate the product of conditionals on the held-out split. The saved result is 0.668339 bits per symbol, compared with 1 bit for a uniform prediction. The evaluation split does not contribute to the fitted counts.
  • Enumerate all 2122^{12} binary sequences. Their model probabilities sum to 1.000000, checking the chain-rule normalization.
  • Keep the prefix 1, 0, 0 and sample the remaining symbols sequentially from the fitted transition table. Three saved completions preserve that prefix. Each new symbol can use only earlier symbols. This is a trained first-order Markov baseline; it does not implement PixelCNN’s spatial masks or demonstrate image-generation quality.

The example, script and observations were newly authored for this course with Codex assistance; the numerical results are from the linked run.

Code#

The worked example of three pixels with a check that the product sums to 1, and a PixelCNN in NumPy whose receptive field is found by perturbing one input pixel at a time. It runs in a second.

import itertools
import numpy as np

sig = lambda z: 1 / (1 + np.exp(-z))

def p3(x):                                    # chain rule with logistic conditionals
    x1, x2, x3 = x
    q = [sig(0.0), sig(-1 + 2 * x1), sig(-2 + 1.5 * x1 + 1.5 * x2)]
    return np.prod([qi if xi else 1 - qi for qi, xi in zip(q, x)])

print(round(p3((1, 1, 0)), 4), round(sum(p3(x) for x in itertools.product([0, 1], repeat=3)), 10))
# 0.0983 1.0

def mask(k, include_center):
    m = np.zeros((k, k))
    m[: k // 2] = 1                           # rows above the centre
    m[k // 2, : k // 2] = 1                   # left of the centre in its row
    m[k // 2, k // 2] = include_center
    return m

def masked_conv(x, w, m):                     # x: [C, H, W], w: [C_out, C, k, k]
    k = w.shape[-1]
    H, W = x.shape[1:]
    xp = np.pad(x, ((0, 0), (k // 2, k // 2), (k // 2, k // 2)))
    out = np.zeros((w.shape[0], H, W))
    for u in range(k):
        for v in range(k):
            if m[u, v]:
                out += np.einsum('oc,chw->ohw', w[:, :, u, v], xp[:, u:u + H, v:v + W])
    return out

rng = np.random.default_rng(0)
layers, hidden = 4, 16
ws = [rng.normal(size=(hidden, 1 if l == 0 else hidden, 3, 3)) for l in range(layers)]
ms = [mask(3, l > 0) for l in range(layers)]  # mask A first, then mask B

def pixelcnn(x):
    h = x[None]
    for w, m in zip(ws, ms):
        h = np.tanh(masked_conv(h, w, m))
    return h

x = rng.normal(size=(11, 11))
base = pixelcnn(x)[:, 5, 5]
field = np.zeros((11, 11), dtype=int)
for i in range(11):
    for j in range(11):
        y = x.copy(); y[i, j] += 1.0          # does pixel (i, j) change the output at (5, 5)?
        field[i, j] = np.abs(pixelcnn(y)[:, 5, 5] - base).max() > 1e-12
print(field[1:6, 1:10])
print('blind spot:', int((field[1:5, 1:10] == 0).sum()))

The printed window covers the four rows above position (5,5)(5, 5), its own row and four columns to each side:

[[1 1 1 1 1 1 1 1 1]
 [1 1 1 1 1 1 1 1 0]
 [1 1 1 1 1 1 1 0 0]
 [1 1 1 1 1 1 0 0 0]
 [1 1 1 1 0 0 0 0 0]]
blind spot: 6

No input at or after (5,5)(5, 5) in raster order changes the output, and the zeros in the rows above are the 6 pixels of the blind spot.

Next#

PixelCNN predicts each pixel from a fixed neighbourhood, and a 256×256256 \times 256 image is a chain of hundreds of thousands of steps. Autoregressive transformers replace the convolutions with causal self-attention, which sees the whole past at every layer, and shorten the chain by modelling the discrete codes of a learned autoencoder instead of pixels.

References#