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.
Conditional probability · Entropy, cross-entropy and KL divergence · Normalizing flows: change of variables
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 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 . Their joint distribution is a table of 8 probabilities. We can fill the same table in three steps: the probability of , then of given , then of given both. Why does the product of these three give the joint?
The definition of conditional probability, for , rearranges to . Apply it with and , then again to the shorter prefix, and so on down to :
where , and 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,
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 .
Counting parameters#
The factorization alone saves nothing. For binary pixels, the conditional of pixel needs one probability for each of the histories, and the geometric sum gives the size of the full table again:
The savings come from how the conditionals are represented. Independent binary values need parameters. A first-order Markov model with a separate transition rule at each position needs : 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,
with parameters for pixel and in total (CS236 notes):
| Model of a 12-step binary record | Free parameters |
|---|---|
| full table | |
| independent values | |
| first-order Markov, position-specific transitions | |
| first-order Markov, shared transitions | |
| logistic conditionals (FVSBN) |
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 depends only on inputs before , 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 , and its normalizer runs over every image: terms for a 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:
Repeating the step for gives 1. So the product is a normalized distribution for any network that outputs normalized conditionals, and evaluating costs softmaxes of a few hundred values each, numbers for the colour image, instead of a sum over images.
Worked example. Give the three binary pixels logistic conditionals (toy numbers):
For the image the factors are , and , so . 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 , becomes a sum of 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 , then given , and so on. Each draw is the inverse-CDF method for a discrete variable: take and return the smallest value whose cumulative probability reaches .
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: , 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:
where the second form is the change of base . A model that spreads probability uniformly over 256 values gives each image , so 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 a codeword of 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 bits (Cover and Thomas, 2006, Sections 5.9 and 13.3).
On CIFAR-10, , and the best PixelRNN reaches 3.00 bits/dim:
| Quantity | Value |
|---|---|
| raw image, | 24,576 bits |
| at 3.00 bits/dim, | 9,216 bits, about 1.1 KiB |
| ratio | 37.5% |
A model that predicts fewer levels solves a coarser problem. With 10 levels of grey a uniform guess costs 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 depends only on the inputs , one forward pass on the real image yields all 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: is drawn conditional on , which must be sampled first. A model that predicts one value per pass needs 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 collects information from while seeing nothing of 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 kernel with centre ,
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 has been computed from only, and passing it on is safe. The paper’s PixelCNN has fifteen layers, a first layer with mask A followed by layers with mask B.
The 5×5 convolution masks of PixelCNN
Colour channels#
With colour, each pixel holds three values, and the chain rule goes over all of them:
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: rows up and columns to the right, with to the left. A mask lets one layer read the row above at column shifts , or , written , and , or the current row at shift , written , plus the centre under mask B. A dependency through layers is a sequence of such moves. Counting the moves of each kind, and so on:
No move in the current row goes right, so only the moves raise , and each of them also raises . The row steps above the target is therefore covered up to only columns to the right, whatever is. Every other pixel of the window is reached: upward moves, to gain columns and to lose them, and or centre moves for the remaining layers reach any from to . Within the window of rows above and columns, the earlier pixels number in the rows above plus in the current row, in all, and the unreachable triangle at the upper right holds
of them: 6 of 40 for . As grows the share tends to , 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.
The blind spot of PixelCNN
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:
where is a convolution, the layer and the element-wise product. A condition , such as a one-hot class label, enters as an extra term inside both nonlinearities,
and the model becomes . For a spatial condition , the products become convolutions . 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 with a mixture of logistic distributions and models the observed value as 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:
where is the logistic sigmoid, the CDF of the logistic distribution. For the term is replaced by , and for the term by . The intervals then tile the real line, so the probabilities sum to one over , and the edges collect the mass beyond them.
With one component, and , the values 126, 127, 128 and 129 get probabilities 0.112, 0.124, 0.121 and 0.105: neighbours are close automatically. With and , 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, and . That is outputs per pixel: weights, a mean and a scale for each channel and component, and three coefficients per component. With , 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, . 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 see only earlier audio samples. The current target is not an input to its own prediction. Raw audio has 16-bit samples; WaveNet first compresses them with the μ-law 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 and kernel size 2 reads hidden positions and , so a layer adds samples to the receptive field. With dilations in ten layers,
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):
| Model | Bits/dim |
|---|---|
| Uniform distribution | 8.00 |
| Multivariate Gaussian | 4.70 |
| NICE (flow) | 4.48 |
| Real NVP (flow) | 3.49 |
| PixelCNN | 3.14 |
| Row LSTM | 3.07 |
| Gated PixelCNN | 3.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 colour image is values; a sub-pixel model needs that many network passes, and one that predicts whole pixels, as PixelCNN++ does, still needs . 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: , an identity for any order.
- Normalized conditionals make the product normalized: the likelihood is exact, 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 , 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 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 , 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 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 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#
- A. van den Oord, N. Kalchbrenner, K. Kavukcuoglu. Pixel Recurrent Neural Networks. ICML, 2016. (2016a) Section 2 (the factorization and the softmax), Section 3 (Row LSTM, Diagonal BiLSTM, PixelCNN, masks), Table 5.
- A. van den Oord, N. Kalchbrenner, O. Vinyals, L. Espeholt, A. Graves, K. Kavukcuoglu. Conditional Image Generation with PixelCNN Decoders. NeurIPS, 2016. (2016b) Section 2 (gated units, the blind spot, conditioning).
- A. van den Oord, S. Dieleman, H. Zen, K. Simonyan, O. Vinyals, A. Graves, N. Kalchbrenner, A. Senior, K. Kavukcuoglu. WaveNet: A Generative Model for Raw Audio. arXiv, 2016. (2016c) Sections 2.1–2.2 (dilated causal convolutions, μ-law).
- T. Salimans, A. Karpathy, X. Chen, D. P. Kingma. PixelCNN++: Improving the PixelCNN with Discretized Logistic Mixture Likelihood and Other Modifications. ICLR, 2017. Section 2, Table 1 and Section 3.4.4 (training without dropout).
- H. Larochelle, I. Murray. The Neural Autoregressive Distribution Estimator. AISTATS, 2011.
- M. Germain, K. Gregor, I. Murray, H. Larochelle. MADE: Masked Autoencoder for Distribution Estimation. ICML, 2015.
- I. Gulrajani, K. Kumar, F. Ahmed, A. A. Taiga, F. Visin, D. Vazquez, A. Courville. PixelVAE: A Latent Variable Model for Natural Images. ICLR, 2017.
- S. Ermon, A. Grover et al. Autoregressive models, CS236 course notes, Stanford University (the FVSBN, NADE and their parameter counts).
- R. Isachenko. Deep Generative Models, MIPT and Yandex School of Data Analysis, 2025, lecture 1 (histogram, Markov and autoregressive parameter counts).
- T. M. Cover, J. A. Thomas. Elements of Information Theory, 2nd ed. Wiley, 2006. Section 5.9 (Shannon–Fano–Elias coding) and Section 13.3 (arithmetic coding).