Autoregressive Density Models
MADE, PixelCNN, WaveNet and masked autoregressive flows.
Every autoregressive model computes the same product of conditionals. What sets them apart is how one network outputs all the conditionals at once without ever peeking at the future: masked weights for MLPs, masked convolutions for images, dilated causal convolutions for audio, causal attention for transformers. This lesson proves the masks correct, finds the blind spot of the first PixelCNN, and follows two escapes from one-value-at-a-time sampling: distill the model into a flow that samples in parallel, or change what counts as one step.
What you’ll learn
- Prove that MADE's degree masks make output depend only on the inputs before , and explain what order-agnostic training buys.
- Derive the receptive fields of masked and dilated causal convolutions: PixelCNN's blind spot, which tends to a quarter of the causal window, and WaveNet's field of samples after doubling layers.
- Derive MAF and IAF from , prove that maximum likelihood for a MAF is variational inference for an implicit IAF, and explain probability density distillation.
- Assess what next-scale prediction changes about the sequential cost of autoregressive image generation, and what it assumes in exchange.
One network, every conditional: MADE
MADE (Germain, Gregor, Murray & Larochelle, 2015) turns an ordinary autoencoder into an autoregressive network by multiplying each weight matrix elementwise by a binary mask. Every unit gets a degree. Input has degree , and hidden unit of layer gets , the largest input index it may see. Degree is excluded because such a unit could feed no output, and degree because it would see nothing. A hidden unit connects only to units of no larger degree in the layer below, and an output only to units of strictly smaller degree:
Input can influence output only along a path of nonzero weights through hidden units , one per layer, and every mask on the path must be . Read the degrees along the path:
So every such path has , and inputs have no path at all. In matrix form, the product of the masks counts paths and is strictly lower-triangular:
Elementwise activations act unit by unit and create no new paths, so for .
In a MADE with one hidden layer and , a hidden unit has degree . Which connections do its masks allow?
- From inputs 1 and 2; to outputs 2, 3 and 4
- From inputs 1, 2 and 3; to outputs 3 and 4
- From inputs 1 and 2; to outputs 3 and 4
- From input 2 only; to output 3 only
Show the answer
C. From inputs 1 and 2; to outputs 3 and 4
The input mask admits inputs and , and the output mask admits outputs and . Those outputs may use whatever tell this unit; output 2 may not, since it would then see itself.
Order-agnostic training. Nothing ties the masks to the natural order of the coordinates. Permute the input degrees and the same architecture models a different factorization of the same distribution. MADE resampled the ordering (and the hidden degrees) during training, so one set of weights learned many factorizations. Conditionals from different orderings never agree exactly, so averaging the probabilities given by several orderings acts as a free ensemble, and an ordering that puts the observed coordinates first lets the model fill in the missing ones. Its predecessor NADE (Larochelle & Murray, 2011) shared weights so that all conditionals of a one-hidden-layer model cost operations for hidden units, but deeper versions needed passes; masks give any depth in one ordinary forward pass, which suits GPUs.
Pixels: masked convolutions and a blind spot
PixelRNN and PixelCNN (van den Oord, Kalchbrenner & Kavukcuoglu, 2016) order an image in raster scan, row by row, and within each pixel red before green before blue. Each channel value gets a 256-way softmax, which can take any shape. In a PixelCNN every convolution is masked: the kernel weights to the right of the center in its middle row, and in all rows below, are zeroed. Two variants are needed. Mask A, used only in the first layer, also cuts the connection from a channel value to itself, because the raw input at position is . Mask B, used in every later layer, keeps it, because those layers read features that at position were already computed from the past alone.
Each layer adds one of the allowed kernel offsets to the dependence: up-left, up, up-right or left, plus the center after the first layer. Only up-right moves right, and it also climbs a row, so a dependence that has climbed rows has moved right by at most columns. Each layer moves at most one step, so layers reach at most rows up and columns left:
Every offset within these bounds is reached: climb with up-right or up as needed, move left with up-left or left, and spend leftover layers on the center tap of mask B. Count the excluded offsets row by row:
A PixelCNN stacks one mask-A and seven mask-B layers, so . How many of the causal pixels within its reach does the blind spot hide?
Show the answer
28 pixels
of the causal pixels within 8 rows and columns, about 19%. All of them lie up and to the right: exactly the pixels a raster-scan model should consult to continue an edge or an object it is halfway through.
The gated PixelCNN (van den Oord et al., 2016, "Conditional image generation with PixelCNN decoders") removed the blind spot with two stacks. A vertical stack sees every pixel of the rows above, so its field grows as a full rectangle; a horizontal stack sees the current row to the left. The vertical stack feeds the horizontal one after every layer, never the reverse, which would leak pixels from below or to the right. ReLUs gave way to the gated unit , modeled on LSTM gates, and a conditioning vector such as a class embedding enters both factors. On CIFAR-10 test data this took PixelCNN from 3.14 to 3.03 bits per dimension, close to PixelRNN's 3.00, and on ImageNet the gated model matched PixelRNN in less than half its training time.
PixelCNN++ (Salimans, Karpathy, Chen & Kingma, 2017) replaced the 256-way softmax, which learns every intensity separately and spreads its gradient thinly, with a discretized logistic mixture that builds in the similarity of neighboring values:
the mass that a mixture of logistic densities puts on the unit-width bin around the integer , with the end bins at and stretched to and so the probabilities sum to one. With downsampling, shortcut connections and dropout it reached 2.92 bits per dimension on CIFAR-10.
Audio: dilated causal convolutions
WaveNet (van den Oord et al., 2016) models raw audio, 16,000 samples per second, one sample at a time. Its layers are causal convolutions, whose output at time sees only inputs at times up to , so the whole stack is autoregressive. With kernel size and dilation in layer , the receptive field grows by per layer (the recursion of Convolution, Pooling & Receptive Fields, with stride 1):
With kernel size 2 and every , the field creeps forward by one sample per layer, . WaveNet doubles the dilation from layer to layer, , so the field doubles with every layer, , and then repeats the ten-layer block. Each sample is quantized to 256 levels with the -law (formula in Loss Functions & Maximum Likelihood), which spends its levels where speech lives: 59% of them cover amplitudes below a tenth of full scale. The layers use the gated unit of the gated PixelCNN with residual and skip connections, and a conditional WaveNet adds a speaker identity (global conditioning) or linguistic features upsampled to the audio rate (local conditioning) inside the gates.
A WaveNet stacks three blocks, each of ten causal layers with kernel size 2 and dilations . How many samples wide is the receptive field of one output?
Show the answer
3070 samples
With kernel size 2, a layer widens the field by exactly its dilation, and the ten dilations of a block sum to . Start from the one sample the output sits on and add three blocks' worth: , just under a fifth of a second (192 ms) of 16 kHz audio. A single block already spans samples, while plain causal layers of kernel size 2 would need of them to match the three.
A large field is necessary, not sufficient. The authors noted that their multi-speaker model, with a field of about 300 ms, could only remember the last two or three phonemes it had produced, so its babble lacked long-range structure. And dilation leaves the cost of sampling untouched: one second of 16 kHz audio still takes 16,000 sequential network passes.
Two directions: MAF, IAF and Parallel WaveNet
Write a Gaussian autoregressive model as a map from noise to data, with a shift and a log-scale computed by a MADE. In a masked autoregressive flow (MAF; Papamakarios, Pavlakou & Murray, 2017) they are computed from the data:
Density evaluation inverts the map in one pass, since all of is given, and the Jacobian of is triangular with diagonal . Sampling must run the recursion: passes.
An inverse autoregressive flow (IAF; Kingma et al., 2016) computes the same parameters from the noise. Sampling takes one pass, and so does the density of the model's own samples, whose is known. The density of an arbitrary needs the recursion for : passes. Stacked layers alternate the ordering, and a coupling layer is the special case of either in which the second half conditions only on the first.
Both densities transform with the Jacobian of the same map. For :
The Jacobian cancels in the ratio, and an expectation over is an expectation over :
The right side is the objective of variational inference: a reverse KL to the target , minimized through the reparameterized samples . Fitting a density by maximum likelihood with one direction of a flow is fitting the inverse direction to the base density. The whole content of the theorem is that KL divergence is invariant under invertible maps.
Parallel WaveNet (van den Oord et al., 2018) used the duality to make audio fast. A trained WaveNet, the teacher , scores a given waveform in one parallel pass but samples slowly. An IAF student samples in one pass and can score its own samples. Probability density distillation trains the student to minimize
The entropy is cheap: with logistic noise and an output scale , each step contributes , the entropy of a logistic distribution, so without generating any audio. The cross-entropy is estimated by sampling from the student and letting the teacher score every time step in parallel. Both terms are needed: the cross-entropy alone is minimized by collapsing onto the teacher's most probable waveform, which, the authors note, is not a good sample. Distillation alone still left the student under-constrained, so it was trained with extra losses: a power loss matching the average spectrum of real speech, which kept it from drifting into high-entropy modes such as whispering, plus perceptual and contrastive terms. The student generated speech more than 20 times faster than real time and over 1000 times faster than the original WaveNet, with no significant difference in quality in the authors' listening tests.
Transformers, tokens and the order of generation
A transformer with a causal mask is an autoregressive network too, with attention in place of masked convolutions, so every position can draw on the entire prefix. The Sparse Transformer (Child, Gray, Radford & Sutskever, 2019) factorized attention to reach long pixel sequences and 2.80 bits per dimension on CIFAR-10, below PixelCNN++'s 2.92. Image GPT (Chen et al., 2020) trained GPT-2-style transformers on images flattened in raster order, with colors reduced to a 9-bit palette of 512 k-means clusters and no 2-D structure built in; linear probes on its features rivaled supervised networks on CIFAR-10. Neither changed the sampling bill: one pass per pixel.
Most autoregressive image generators since then model tokens from a learned tokenizer (Learned Tokenizers for Images & Audio): a image becomes, say, a grid, generated in 256 sequential steps. Visual autoregressive modeling (VAR; Tian, Jiang, Yuan, Peng & Wang, 2024) changes the unit of autoregression from a token to a whole token map. A multi-scale tokenizer encodes the image as maps of increasing resolution, from up to , and a transformer predicts each scale from the coarser ones,
sampling every token of in parallel: 10 steps instead of 256. The authors reported class-conditional ImageNet samples that surpassed a diffusion-transformer baseline, and a loss that fell as a power law in model size.
The cost accounting deserves care too. The VAR paper counts attention work for raster-order generation of an token map against for next-scale prediction, but the assumes that attention over the whole prefix is recomputed at every step. With a KV cache, step attends over cached keys, and raster order also costs . The robust gain is in sequential steps: for raster order against scales, which grows only logarithmically in when resolutions grow geometrically.
Key takeaways
- An autoregressive network makes output depend only on ; any such network defines a normalized distribution evaluated in one pass. MADE enforces this with degree masks, proved correct by following degrees along every path.
- Stacked masked convolutions miss a triangle of pixels up and to the right, tending to a quarter of the causal window; the gated PixelCNN's vertical and horizontal stacks remove it, and PixelCNN++'s discretized logistic mixture reached 2.92 bits per dimension on CIFAR-10.
- Dilated causal convolutions with doubling dilations give WaveNet a field of samples from layers of kernel size 2, but sampling still costs one pass per sample.
- A MAF evaluates densities in one pass and samples in ; an IAF does the reverse. Because KL divergence is invariant under invertible maps, maximum likelihood for a MAF is variational inference for an implicit IAF, and Parallel WaveNet distilled a WaveNet teacher into an IAF student with .
- Next-scale prediction cuts the sequential steps of image generation from to a number of scales that grows like , by assuming that the tokens of a scale are conditionally independent given the coarser scales.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Why does a PixelCNN use mask A in its first layer and mask B in all later layers?
- Mask B is wider, which grows the receptive field faster in deep layers
- The raw input at position contains itself, so the first layer must exclude it; later layers read features that at position depend only on the past, so they may keep the center connection
- Mask A removes the blind spot, and mask B restores it to keep training stable
- The two masks differ only in how the weights are initialized
Show the answer
B. The raw input at position contains itself, so the first layer must exclude it; later layers read features that at position depend only on the past, so they may keep the center connection
Mask A zeroes the connection from the current value to its own prediction. After that layer the feature at position summarizes only, so mask B can use it without leaking . Using mask B in the first layer would let each prediction read its own target.
Why does MADE never give a hidden unit degree , the number of inputs?
- It would make the network too large
- It would let some output depend on its own input
- It would break order-agnostic training
- Such a unit may see all inputs, so the output mask would allow it to feed no output at all
Show the answer
D. Such a unit may see all inputs, so the output mask would allow it to feed no output at all
An output connects only to units of degree below . A unit of degree could therefore influence nothing, wasting capacity; degrees run from to .
In probability density distillation the student minimizes . What would happen if it minimized the cross-entropy alone?
- Nothing different: the entropy term is constant
- The student would collapse onto the teacher's most probable outputs, which are not good samples
- The student would become a copy of the teacher, with sequential sampling
- Training would need samples from the teacher, which are slow to draw
Show the answer
B. The student would collapse onto the teacher's most probable outputs, which are not good samples
is smallest when the student puts all its mass where the teacher's density is highest. The term rewards spread, and together they form a divergence minimized only at .
VAR samples every token of scale in parallel, given the coarser scales. What does this assume that raster-order generation does not?
- That the tokens of one scale are conditionally independent given the coarser scales
- That attention can be computed without a KV cache
- That the image has no fine detail
- That the tokenizer is invertible
Show the answer
A. That the tokens of one scale are conditionally independent given the coarser scales
Raster order applies the chain rule token by token, so it can represent any joint distribution over a scale. Parallel sampling draws each token from its own conditional, so within a scale the model can only express a product of independent factors.
Further reading
- M. Germain, K. Gregor, I. Murray & H. Larochelle, "MADE: Masked autoencoder for distribution estimation," ICML (2015).
- A. van den Oord, N. Kalchbrenner & K. Kavukcuoglu, "Pixel recurrent neural networks," ICML (2016).
- 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:1609.03499 (2016).
- G. Papamakarios, T. Pavlakou & I. Murray, "Masked autoregressive flow for density estimation," NeurIPS (2017).
- A. van den Oord et al., "Parallel WaveNet: Fast high-fidelity speech synthesis," ICML (2018).