Building Autoregressive Models
Prerequisite Knowledge
This lecture builds on the following concepts from earlier lectures. If any feel unfamiliar, review the linked notes before proceeding.
Previously Covered in This Subject
- Autoregressive Generative Models — covered in Lecture 1
- Autoencoders: Learned Feature Extraction — covered in Lecture 1
- The Autoencoder Architecture — covered in Lecture 3
- Convolutional Autoencoders — covered in Lecture 3
- Diffusion Models — covered in Lecture 1
Autoregressive models learn the probability distribution of a data set, then sample from it to create new data. This document builds the idea from histograms up to MADE, WaveNet, and PixelCNN, with every formula, worked computation, question from class, and practical warning included.
5.1 From Histograms to Learned Density Models
5.1.1 Where Histograms Break Down
Hook: How do you teach a machine the shape of your data — so well that it can invent new data that looks the same? Last session's tool was the histogram. It works for one measurement. It collapses completely for an image with hundreds of pixels. This lecture builds the fix.
The previous session covered likelihood-based approaches to estimating a probability distribution function. You start with an a priori assumption about the form of the distribution, then find the parameters of that distribution which maximize the likelihood of the training data. The first model type was the histogram-based model.
A histogram models a one-dimensional distribution reasonably well, though it is not perfect, because it does not generalize well. Split the value range into bins (equal-width intervals along the axis), count how many training points fall into each bin, and divide by the total count. Each bar height is then an estimate of probability. If a new point lands in a tall bar, it is likely; in an empty region, unlikely. And once built, you can sample from it to generate new data: pick a bar at random with probability equal to its height, then pick a value inside that bar. That sampling ability is a nice gift.
The gift does not survive high dimension. Here is why, with numbers. One feature split into bins needs 20 counts. Ten features, each split into 20 bins, need cells — over ten trillion counts, and you have maybe a few thousand rows. Divide each axis into bins and most of the multi-dimensional space ends up empty: regions where no training point ever falls get mapped to nothing usable. Push this further and the counting explodes outright: a small binary image of pixels has possible configurations — about , a number with more digits than there are atoms in the observable universe. No training set ever fills that space.
Think of a library that stores one shelf for every possible book of exactly 100 letters. With a 2-letter alphabet there are shelves. Your library owns a few thousand books, so almost every shelf sits empty, and a visitor asking for "the most typical book" learns nothing. A histogram in high dimension is that library: mostly empty shelves.
Scope: A histogram estimate is only trustworthy inside regions the training data actually covers. It assumes the data is i.i.d. (independent draws from one fixed distribution) and that the distribution does not change between training and use. Real unsupervised deep learning inputs — an image, a text snippet, a table row — have large feature dimension. At that scale the assumptions still hold but the counting fails anyway: the empty-space problem is about geometry, not about data quality.
Picture the failure on a chart. Axes are two features, say pixel brightness at two spots. The surface is a spiky city skyline: a few tall towers where training points cluster, surrounded by flat plains of zero everywhere else. Now imagine that skyline needing one extra axis per feature. After ten axes, the "towers" are lonely points floating in an enormous dark void. The takeaway: counting cells cannot beat the void, so the model must instead learn to interpolate — to guess sensibly between observed points. That is what neural networks will do.
5.1.2 What a Practical Density Model Needs
Three requirements drive the design of every model in this topic:
- Accuracy with a rich architecture. Many processing nodes, organized into many layers, can learn the probability distribution of the data reasonably accurately. Depth and width give the network room to represent complicated structure — remember from the autoencoder material how stacked encoders reconstructed images better than shallow ones.
- Fast training. It should not take five days, or fifty days, to learn the model. The learning procedure must run at reasonable speed, because you will retrain often while tuning.
- Efficient sampling. Once the model is learned, the final goal is generating data by sampling from the distribution, and that sampling process must be feasible and efficient. A perfect density you cannot draw from is a museum piece, not a generator.
No method available today does all of these things very well at once. Every family gives something up. That is why even older methods deserve study, and why one drawback matters: autoregressive models generate data sequentially, so sampling is slow — one variable after another, like a row of dominoes falling. They bring many other efficiencies in exchange: accurate densities, stable training, and compact models. Keep score of the trade-offs as each model appears in this lecture.
The job list for this whole topic: fit the distribution accurately, train fast, sample fast. Autoregressive models pass the first two and pay on the third — and they power GPT-1, GPT-2, GPT-3, and ChatGPT, so the price was worth paying. Next we build the mathematical core that all of them share.
Real-world: when ChatGPT writes an answer or such a tool creates an image, the picture does not appear in one shot — it appears slowly, piece by piece, because sequential generation is built into the method. The same slow-reveal behavior shows up in AI image generators that paint top to bottom. Sequential sampling is not a bug you can patch away; it is the shape of the method itself.
5.2 The Autoregressive Idea
5.2.1 Factorizing a Joint Distribution with the Chain Rule
Let be a training vector made up of features, so , where is a scalar count of features. An autoregressive model assumes the features occur one after another in time: occurs, then , then , and onward.
Analogy: Think of a relay race run in a fixed lane order. Runner 3's time depends on runners 1 and 2 before them, but never on runner 4 who has not raced yet. Each feature is a runner; its probability may consult every earlier teammate, never a later one. The analogy breaks only in one spot: real relays have small teams, while autoregressive models handle hundreds or thousands of features — the rule stays the same, just longer.
Under that assumption the joint probability of all features splits into a product of conditionals. This split is not an approximation — it follows from the definition of conditional probability, which says . Apply it twice and watch the pattern grow:
Repeating this for all features gives the chain-rule factorization:
Each factor reads: "probability of feature given every earlier feature." Each conditional is a probability value in . The key restriction is temporal dependence: may depend on , but not on or anything in the future. That one-sided dependence is the core of autoregression — the name literally means "self-regressing," each part regressed on its own past. Two facts deserve emphasis. First, the factorization itself is exact: it is the general law of probability, with no approximation anywhere. Second, the ordering of who comes first is a choice the modeler makes — any fixed order gives a valid decomposition, a freedom MADE will exploit later.
5.2.2 Training as Likelihood Maximization
The factorization turns one impossible job (model a whole vector at once) into many small jobs (model each feature given its predecessors). Training then maximizes the probability the model assigns to the training data. Working with products directly is awkward — numbers multiply toward zero fast — so take the natural log first. Logs turn products into sums and never change where the maximum sits, because is a monotonically increasing function (it preserves order):
Training maximizes this log likelihood, or equivalently minimizes the negative log likelihood (NLL) — the same expression multiplied by minus one, so "highest score" becomes "lowest loss," which matches how optimizers work:
After training you want a small NLL. A quick sanity check of the scale: if the model thinks the observed data was very likely, each term sits near zero (since probabilities are at most one) and the sum stays small; if the model assigns tiny probabilities like , each term is about and the loss grows. Model selection uses the same yardstick: train two architectures on the same data, and the one reaching the smaller NLL wins, purely on prediction accuracy grounds. Every recurrent architecture reviewed below trains exactly this way: compute the loss over the entire sequence and the entire training set, adjust the internal parameters so the loss reduces, and repeat.
Pitfalls: Beginners trip on three things here. One: NLL has no absolute meaning — only differences between models on the same data mean anything. Two: minimizing NLL is not a different objective from maximizing likelihood; they are the same number with opposite signs. Three: the sum runs over features within one data point; total loss averages (or sums) this over all training points as well — keep the two levels apart when reading code.
Exam note: know the equivalence "minimize negative log likelihood = maximize log likelihood" — it recurs across every model in this course.
5.2.3 A Toy Two-Variable Model
Picture a training set with two features, , holding about 10,000 data points. The goal is to estimate via maximum likelihood. The chain rule splits the job exactly in two:
Assign each factor to the tool that handles it best:
- is realized by a histogram. Its quality depends on bin choices, but in one dimension that is manageable — no empty-space explosion with a single axis.
- is realized by a multilayer perceptron (MLP). Here is the input, and the output node encapsulates the probability of .
Suppose can take 256 values. Use a softmax output layer with 256 nodes. Softmax takes the network's raw scores (called logits, ) and converts them into a proper probability table over all 256 outcomes. The output of softmax node , with pre-activation scores , is:
Here makes every score positive and emphasizes bigger scores, and dividing by the sum of all exponentials makes the outputs add to one. That is the beauty of softmax: because each output divides its exponential by the total, the outputs always sum to one, which gives a naturally probabilistic interpretation.
Worked example — checking softmax by hand. Shrink the alphabet to two values so the arithmetic fits on screen; the 256-node version works identically. Suppose the network produces scores and for the two possible values of . Exponentiate: and . Normalize:
The two outputs sum to , as promised. If the network had produced equal scores , both outputs would be — maximum uncertainty. Final answer: value 0 gets probability 0.881, value 1 gets 0.119, and sampling picks 0 about 88 times out of 100. Sense check: higher score, higher probability, total exactly one.
This little two-variable construction is a genuine autoregressive model: a histogram plus one network, chained by the law of probability. Every architecture ahead — RNN, MADE, WaveNet, PixelCNN — is this same skeleton wearing richer clothes.
5.2.4 Why Generation Stays Sequential
Generation runs the arrows forward one variable at a time: draw from its learned distribution, feed it in, draw given , and continue. Nothing about the training objective changes that — sampling is inherently a step-by-step process for autoregressive models, because step needs the value produced at step . Sequential sampling feels slow, yet autoregressive models come with many other efficiencies in exchange: training can be highly optimized, the model stays compact, and the exact density lets you score any data point you like.
Recap: the chain rule turns joint modeling into ordered conditionals; NLL trains them; softmax turns network scores into probabilities. Next we hand these conditionals to recurrent networks, the natural engine for sequences.
Real-world: the same machinery scales to the systems behind modern text and image tools. GPT-style assistants predict the next token given all previous tokens — literally with words instead of pixels.
5.3 Recurrent Networks as Autoregressive Engines
Two building blocks from earlier coursework power everything ahead: the CNN, built for two-dimensional data such as images, and the RNN, built for one-dimensional sequential data. Recall from the autoencoder material how CNN encoders and decoders reconstructed data very accurately — more accurately than MLP-based autoencoders and definitely better than PCA. A third block, the plain MLP, returns when MADE arrives. Everything in this section is review; its purpose is to line up the tools so the new masking models make sense.
5.3.1 RNN, LSTM, and GRU Compared
An in-class pop quiz opened the comparison of the recurrent family members. The exchange went:
Q: What is the advantage of LSTM with respect to a vanilla RNN? A: A vanilla RNN suffers from vanishing gradients, so for long sequences it cannot remember the data or history from far back. LSTM adds gating functions and separate memory highways, so it remembers both long-term and short-term context across the time sequence. GRU also avoids the vanishing gradient problem, but it merges gates into one unit and keeps fewer parameters, so its strength sits closer to short-to-medium memory. Unless you must remember really long sequences, GRU is enough and its training is easier and faster.
Here is why the vanilla RNN struggles, in one breath: during training, gradients are multiplied by the same recurrent weight matrix at every time step, so over many steps they shrink toward zero or blow up — the signal from step 1 barely reaches step 50. Gated cells fight this with an additive memory channel that lets information ride across steps without being repeatedly multiplied. That single mechanism difference explains most of the comparison table below.
| Property | Vanilla RNN | GRU | LSTM |
|---|---|---|---|
| Gates | none | update + reset (merged) | forget + input + output |
| Memory horizon | shortest | short-to-medium | longest |
| Parameter count | fewest | medium | most |
| Training | fastest, least stable | easy and fast | slower, more complex |
| Pick it when | sequences are tiny | you want cheap gating | you truly need long context |
When to pick which: default to GRU for speed, upgrade to LSTM only when sequences get really long.
5.3.2 Attention and Transformers: Parallelism Is the Big Deal
The quiz continued to attention and transformers.
Q: What is the key value that attention contributes? A: Attention assigns weight to the parts of a sentence, or the words inside it, that matter more for the current prediction. Instead of treating every position equally, the model learns which pieces deserve focus.
Q: What is the main advantage of transformer-based models over RNN-type architectures? A: Several answers surfaced — transformers attend over a very large context, effectively unlimited memory, and they predict the next token using attention with multi-head similarity matrices. Those are all correct, but the answer being hunted was this: training a recurrent network is sequential in nature. You send the first element, the second is predicted from it, the third from the second, and only after stepping through the whole pattern — five steps, or five hundred — can you compute the loss for that one training point. Transformers remove that wait: training happens in parallel across the sequence. That is the big deal.
Then the flip side:
Q: So what is the disadvantage of transformers? A: Multi-head attention compares every position with every other and stacks multiple transformer blocks, so they need a huge amount of data, more memory, and enormous computational power. As the quip in class put it: they are for rich people — a luxury.
A calibration on vanishing gradients followed. Saying "vanishing gradients are everywhere" is mathematically loose but practically fair. The problem exists in all these networks, yet its extent is worst in the vanilla RNN, milder with gating, and eliminated in the transformer design. Vanishing gradients also bridge to the next question — what basic mechanism trains any of these recurrent models? Compute the loss over the entire sequence and training set, adjust parameters to reduce it, and recognize this as likelihood maximization: maximize against the expected targets, which is minimizing NLL. Section 5.2's objective never changed; only the engine computing the conditionals did.
5.3.3 Causal, Bidirectional, and Deep Variants
The standard RNN diagram shows an input at time feeding a hidden state, with three learned matrices usually labeled , , and . In words: maps the current input into the hidden state, carries the hidden state from the previous step forward, and maps the hidden state to the output. These recurrent weights are learned as part of training by maximizing the log likelihood of predicted data — equivalently minimizing cross entropy over the entire sequence.
Variants differ in one key property:
- Unidirectional RNN. Every output depends only on whatever happened in the past. By definition this is autoregressive — the causal case.
- Bidirectional RNN. A forward pass and a backward (anti-causal) pass both feed the output, so information from the future propagates alongside the past. This is NOT an autoregressive model. It suits fill-in-the-gaps applications, where a missing datum is predicted from everything before and everything after it — think of a cloze test where the blank is surrounded by known words on both sides.
- Deep bidirectional RNN. Many stacked hidden layers improve the ability to predict missing data beyond a shallow bidirectional net — a general property of deep layers. Training such stacks is time consuming, and the gain only holds when enough training data exists; otherwise overfitting and other bad things arrive.
Keep the causal/anti-causal contrast handy: autoregressive means causal, always. If any pathway lets future information reach the prediction, the model is not autoregressive — however good its samples look. Exams love this distinction between unidirectional (causal, autoregressive) and bidirectional (anti-causal, fill-in-the-gap).
5.3.4 Inside the Cells: Gates in LSTM and GRU
Beyond the matrices of a vanilla RNN, LSTM trains extra gating machinery. A gate is a small network ending in a sigmoid , whose output lives between zero ("block completely") and one ("pass fully") — a dimmer switch rather than a plain wire. Tanh units generate the candidate signal that the gates modulate. The classic LSTM cell update shows both roles working together:
where is the cell memory at step , is the forget gate deciding how much old memory survives, is the input gate deciding how much new candidate enters, and means elementwise multiplication. Because the memory updates by addition of gated pieces instead of full reinvention each step, gradients can flow across many steps without vanishing — that is the "memory highway" from the quiz answer made concrete. All these trainable matrices are learned during the LSTM training process, which is more complex than RNN training; the reward is a much higher ability to carry context across long spans. GRU combines some gates into one, cutting parameter count so training gets easier.
5.3.5 Generating Handwritten Digits with an RNN
Worked example — synthesizing binary MNIST digits with an RNN. The run proceeds end to end:
- Take binary MNIST: handwritten digits as 28 by 28 images where any pen-stroke pixel is 1 (bright white) and everything else is 0. Flattened row by row, each image becomes a sequence the RNN can consume.
- Train the RNN on 60,000 training patterns; hold out 10,000 for testing and validation.
- Initialize the input stream with random values — generation starts from noise, exactly like the sampling loop in Section 5.2.4.
- Watch outputs evolve epoch by epoch (an epoch is one full pass through the training set). Early epochs emit nonsense. After roughly 19 iterations, recognizable handwritten characters emerge from the network's memory.
One refinement matters: besides pixel information, append the pixel location to each input. Comparing the 19th-iteration generations with and without location information, most observers agree the location-aware version reconstructs and generates noticeably better digits — location is extra conditioning information the model can exploit, because the same pixel value should mean something different in a corner than mid-stroke. Final result: readable synthetic digits sampled from a learned distribution. Sense check: the samples resemble training digits without being copies, which is what a decent density estimate should produce.
Real-world: this experiment is the classic demonstration that an autoregressive model trained on sequences of pixels learns a distribution good enough to synthesize new, plausible handwriting. Signature-verification systems and handwriting-based document pipelines build on exactly this ability to model stroke sequences.
Recap: recurrent engines differ in how far back they remember and whether they train sequentially; causality separates autoregressive models from fill-in-the-gap ones. Next, MADE keeps the autoregressive contract but replaces the slow sequential learner with a masked autoencoder that learns every conditional at once.
5.4 MADE: Masked Autoencoder for Density Estimation
5.4.1 Motivation: Learn Every Conditional in One Shot
Hook: An RNN learns one conditional at a time, in order, like reading a book page by page. What if a single network could learn every page simultaneously — and still hand you the pages strictly in order when it is time to generate? That is MADE.
Everything so far was review; masking-based autoregressive models are the new content. First, the meaning of the mask: during training, a mask ensures you use only information that has happened in the past and none of the information that comes later.
MADE stands for Masked Autoencoder for Density Estimation. Recall what autoencoders did so far: learn features by driving reconstruction error down, learn to strip noise, learn sparse representations of dense data — with a variational autoencoder promised later for generation. MADE is an interesting variation: an autoencoder architecture bent toward estimating the density of the training data itself. Same skeleton — encoder, bottleneck, decoder — new job.
Why bother with a classical building block? Because understanding how ideas evolve matters. Great things do not appear overnight — as if an apple falls on the ground and Newton is born the same day. Ideas arrive step by step, and appreciating prior work is why basics come first. When you later meet fancier relatives of MADE, you will recognize the family traits instead of memorizing strangers.
The motivation in one contrast:
| Aspect | RNN autoregression | MADE |
|---|---|---|
| Learning the conditionals | sequential, one after another | parallel, all at once |
| Training style | recurrent passes over time steps | ordinary autoencoder-style forward/backward passes |
| Generation | sequential | still sequential (the model is autoregressive) |
An RNN learns , then , then sequentially, one batch after another. MADE learns all those conditional probabilities in parallel, in one shot, after a few iterations of standard autoencoder training. Once training completes, you can generate samples — and generation is still sequential, because the model is autoregressive — but the expensive part, learning every conditional, happened in parallel. Remember this asymmetry; it returns at the end of the section. Texts on normalizing flows describe the same trade: masked models evaluate or train everything at once, while sampling must walk the ordering step by step.
5.4.2 Architecture and Output Activations
The backbone is a plain MLP autoencoder. The running example uses three-dimensional input , two hidden layers of four units each, and three output units. A standard autoencoder reconstructs data; by default it has no ability to calculate probabilities. MADE forces that ability through the output layer.
A review exchange pinned down the output activation choice:
Q: Which output activations have we used for autoencoders so far? A: For continuous data the output must be continuous too, so a linear activation served. Denoising autoencoders also produce real-valued outputs, so linear again. For binary inputs — strings of zeros and ones — a sigmoid fits, since it squashes into the interval between zero and one. We never used softmax, because a general binary pattern is not one-hot: it is not the case that exactly one feature is 1 and the rest are 0.
The distinction deserves one more sentence. Softmax makes its outputs compete — they must sum to one across nodes, which suits "pick exactly one class." A binary vector has no such contest: is perfectly legal, so each output needs its own independent probability, which sigmoid provides node by node.
MADE adds one requirement: outputs must live between zero and one, because each output represents a probability — , or , and so on. A probability cannot be negative. Sigmoid outputs satisfy this, and the training objective treats each output as a probability estimate. Concretely: with binary data, output unit emits a number , read as "the model's current estimate of that factor's probability," and cross-entropy-style NLL scoring compares against the observed bit.
5.4.3 Masks: Cutting Connections with 0/1 Matrices
A mask is a matrix of zeros and ones multiplied elementwise against a weight matrix of the same shape. Where the mask holds 1, the connection survives; where it holds 0, the connection is eliminated — the weight might as well not exist, because multiplying any weight by zero gives zero. Mechanically, imposing masks on a fully connected autoencoder produces a partially connected network whose wiring enforces the autoregressive property.
Shapes in the running example:
- Input to first hidden layer: three input units, four hidden units — a 4-row by 3-column mask.
- Hidden to hidden: four units to four units — a 4 by 4 mask.
- Last hidden to output: four units down to three outputs — a 3 by 4 mask.
Rows correspond to destination units and columns to source units, so reading a row tells you exactly which incoming connections that unit keeps. In the example mask, one input fed only the first two hidden units; another fed all four; a third fed none at all — its column was zeros from top to bottom. That dead column looks alarming until the numbering scheme explains it.
5.4.4 The Feature Ordering Assumption
The numbering creates the autoregressive structure. Assume an ordering — in the running example, occurs first, at ; occurs next, at ; and occurs last, at . Input nodes and output nodes carry labels 1, 2, 3 matching this assumed occurrence order: the input slot holding carries label 1, the slot holding carries label 2, and the slot holding carries label 3. The chain rule then reads, in occurrence order:
Same law of probability as Section 5.2.1 — just a different walking order through the same house. With a training set of three-dimensional instances, is easy: build a histogram of the middle coordinate. The hard parts are the conditionals, especially when the feature count grows large. MADE exists so that standard autoencoder training learns all of them in parallel, with the network wiring enforcing the ordering.
Three questions in class shaped this section:
Q: In the second layer, how were the numbers one-two-two-two assigned, when the first layer got one-two-three? A: Fair catch — node numbering had not been explained yet at that point. Only the mask mechanics had been shown. The numbering scheme comes next, and it answers both this and the disconnected-column puzzle.
Q: The third input node connects to nothing in the first mask. How can that be? A: That was flagged as the actual confusion, and the resolution is the numbering rule: the third input carries label 3, and no hidden unit ever holds a number that high, so the rule permits no connection. Nothing is broken — the ordering makes that isolation necessary.
Q: Is the ordering shared with us beforehand, or are we expected to assume it ourselves? A: Whichever ordering is assumed must be stated, and the numbering follows from it. Pick a different order and both the numbering and the masks change. The ordering is a modeling decision, communicated explicitly.
5.4.5 Random Hidden Numbers and Connection Rules
Here is the numbering algorithm:
- Number the input units 1 through , where is the total number of features, according to the assumed occurrence order.
- Assign every hidden unit in every hidden layer a random integer between 1 and . With , hidden units draw from — which is why a four-unit layer showed a pattern like 1, 2, 2, 2. Only the range is fixed; the exact draws differ run to run because they are random, and no specific draw sequence carries meaning. One pattern like 1, 2, 2, 2 is simply what the random draw produced on screen that day.
- Number the output units 1 through , matching the occurrence-order labels: the output labeled 1 computes , the output labeled 2 computes , and the output labeled 3 computes .
Why does the range stop at ? Two reasons. First, no output can ever use a hidden unit numbered : an output labeled accepts sources numbered below , so a source numbered would sit permanently unemployed — capping at wastes nothing. Second, keeping every hidden number below guarantees no single hidden unit can collect information from all inputs, which would let future features leak into early predictions.
The connection rule turns these numbers into wiring:
A source unit numbered connects to a destination unit numbered whenever . Equivalently, in mask form:
where rows index destination units and columns index source units . A unit may always see sources carrying its own number or lower — itself and its past.
Check the consequences for the first mask:
- Input 1 (holding ) connects to hidden units 1 and 2 — both satisfy .
- Input 2 (holding ) connects to hidden unit 2 only, since no hidden unit exceeds 2.
- Input 3 (holding ) connects nowhere, since every hidden number is below 3.
That last bullet is the dead column from the mask picture, fully explained. Following paths through the network confirms each output's dependence set. Trace the connections backward from each output: the output labeled 1 reaches no input, so its value conditions on nothing — it estimates outright. The output labeled 2 reaches only the input carrying label 1, namely . The output labeled 3 reaches the inputs labeled 1 and 2 — and — but never . The colored connection traces shown in lecture — blue and green links highlighting exactly these paths — made each dependency visible. Do this trace yourself once on paper; it converts the whole scheme from mysterious to obvious-in-retrospect.
5.4.6 Type A and Type B Masks
Two mask flavors appeared:
- Type B. A node may connect to the node carrying its own number and all numbers before it. Every node sees itself and its past — the relaxed rule used between hidden layers above.
- Type A. A node connects only to strictly earlier numbers, excluding itself — the strict rule .
The hidden layers use the relaxed, type-B-style rule. At the output layer, though, the walkthrough demands the strict flavor, and the dependency check shows why:
- Output 1 computes , an unconditional marginal. If it could touch even the input holding label 1, it would see the very value it is trying to predict — leakage. So output 1 touches no input at all.
- Output 2 computes . Under a self-inclusive rule it could reach the input holding label 2 — the value of itself — collapsing the conditional into a copy. It must stop at strictly earlier labels.
- Output 3 computes , so it should combine exactly the inputs labeled 1 and 2, never label 3.
Strictly-less-than masking at the output delivers precisely those three dependence sets; the relaxed rule would corrupt the first two. As a notation note: research papers package the same idea as two model variants called MADE-A and MADE-B, where A uses the strict comparison and B the inclusive one — identical meaning to the type A / type B language here.
5.4.7 The MADE Training Objective
Training maximizes the probability of the training data under the assumed ordering. The verbal statement: "I want to maximize ln of this plus ln of this plus ln of this — or put a minus in front and minimize the whole thing." Formally, start from the ordered factorization:
Take logs to turn the product into a sum, then negate to get a loss to minimize:
Each log term is scored against one output unit: the first against output 1's estimate, the second against output 2's, the third against output 3's. Because the masks guarantee each output sees exactly the right conditioning variables, one forward pass scores all three factors at once — that is the parallel-learning promise made real. Gradient updates adjust the weights subject to the mask constraints until this quantity bottoms out.
What you own afterward: estimates of , of , and of over the entire training data — and so, multiplied together, of the whole joint distribution. An autoencoder obeyed the feature ordering throughout, and density estimation fell out of ordinary reconstruction-style training.
Exam note: expect questions on how the mask rule plus the strict output mask jointly prevent leakage. Being able to trace which inputs each output can reach is the skill being tested.
5.4.8 Sampling New Data Step by Step
Learning the conditionals unlocks generation. The procedure walks the assumed ordering, filling one slot per pass:
Worked example — generating one sample with Bernoulli draws.
- Start with a randomly generated vector and set the counter . Call a random source that returns either zero or one, and drop that value into the slot, since comes first in the ordering. Ignore every other output on this pass; their slots hold nothing meaningful yet.
- Run the forward pass. The output node for returns a number — suppose it reads 0.37.
- Sample from a Bernoulli distribution with parameter 0.37. A Bernoulli distribution is the zero-or-one member of the binomial family, so the draw returns 1 with probability 0.37 and 0 otherwise. Place the result in the slot.
- Run the forward pass again, now conditioned on generated and , and sample the value for .
Final result: three filled slots — a complete synthetic data point drawn from the learned joint distribution. Sense check: every draw depended only on earlier-filled slots, exactly as the masks trained it to.
Training learned the conditionals in parallel, but generation walks the ordering: first , then given , then given and . The asymmetry — parallel learning, serial sampling — is the signature trade of masked autoregressive models.
5.4.9 Results on Binary MNIST
Trained on binary MNIST (zeros and ones, as before), MADE generates digit images through the sampling procedure above. The results look reasonable. Compare each generated digit with its nearest neighbors in the training set: the family resemblance holds.
Worked example — the NLL scoreboard against mixture models. Lower NLL wins; the numbers come from the MADE paper's binary MNIST benchmarks.
- One hidden layer, a single mask, one node: a certain minus-log-likelihood baseline.
- Two hidden layers: better.
- Many masks with hidden units organized in two layers: NLL reaches 86.64.
- A mixture of Bernoullis — tens to hundreds of Bernoulli components, even with 100 parameters or 500 weights — stalls near an NLL of about 140.
Final verdict: the MADE figure lands near 60% of the mixture figure — a significant improvement in the ability to learn probabilities. Sense check: lower is better on this scale, and the gap is dozens of points, not decimal dust.
Since MNIST pixels here are strictly zero or one, the competitor is a mixture of Bernoullis — weighted blends of "typical binary images." When intensity values varied between 0 and 255 in earlier machine learning coursework, the mixture components were Gaussians instead, because intensities are continuous. Match the component family to the data type: discrete bits take Bernoulli components, continuous intensities take Gaussians.
Real-world: mixture models remain strong baselines for tabular density estimation; knowing that a structured autoregressive network beats them by tens of NLL points calibrates when to reach for each.
Exam note: here is the take-home question posed in class — how does the MADE architecture change if features are 8-bit values between 0 and 255 instead of one-bit zeros and ones? Work it out before next session; using an AI tool is permitted, but the reasoning must be yours.
5.4.10 Orderings, Ensembles, and the Capacity Limit
The factorization written as is one choice among many. Any permutation of the features yields a valid chain-rule decomposition, and you can mix and match further. For tabular data with no natural ordering, random permutations work fine. Changing the ordering across training runs lets you learn an ensemble of MADE models — several networks, each with its own ordering — and averaging their density estimates sharpens the result, the way asking several experts and combining opinions beats asking one.
Capacity has a ceiling, though.
Plot NLL against the number of masks and the curve first goes down, then starts going up — operate in the range around the dip. For a fixed training set of a given size, arbitrarily increasing masks, nodes, or layers will not arbitrarily improve generation quality. More capacity eventually memorizes noise instead of distribution. Watch for this on any benchmark: if validation NLL turns upward while training NLL keeps falling, you have crossed the dip.
Recap: MADE bends a plain autoencoder into a parallel learner of every conditional, using random hidden numbering, an inclusive hidden-layer mask rule, and a strict output mask. Sampling then replays the ordering one Bernoulli draw at a time. Next, WaveNet scales the same contract to raw audio, where one-dimensional convolutions replace the MLP.
5.5 WaveNet: Dilated Causal Convolutions for Audio
5.5.1 Task and Motivation
Hook: Your voice is just a long list of numbers — air pressure sampled thousands of times per second. Learn the probability distribution of that list, and you can speak in any voice you like, forever. WaveNet is the model that did it first at production quality.
WaveNet is a one-dimensional, temporal autoregressive model for generating audio. The input is a digitized speech signal — a sequence of numbers , where this sample appears first, then that one, and so on, exactly like the waveform your voice produces. The goal is to learn the probability density of that input so new audio signals can be created. Make the setup arbitrarily complex and interesting, and the model can even synthesize someone singing.
Real-world: WaveNet is a very high-performing architecture, probably still used for speech-to-text at Google, where the speech signal is the input.
5.5.2 Tree Structure and the Linear Receptive Field
How can masking-style causality learn this distribution with convolutional machinery? WaveNet stacks layers in a tree-like structure. Each hidden node connects only to the input at its own time point and previous points. One unit sees and , the next sees and , and so on upward, until the top output predicts given everything in its past. Everything is causal — no future information leaks, exactly the autoregressive contract from Section 5.2.
Count the reach. Draw the connections upward and the picture is a binary tree lying on its side: each level doubles how far back parents sit, but because neighbors overlap heavily, the union grows slowly. With four levels the tree touches five time points (its own plus four past); in general a stack of layers reaches only time points. The receptive field size is limited, linear in the number of layers. A probability estimate built from such a narrow window of history will not be accurate — deciding how to pronounce a syllable may require context hundreds of samples back — so the achievable density estimation quality is capped.
Without widening tricks, causal stacking buys little ground per layer:
Doubling depth doubles cost yet adds only a handful of samples of context.
5.5.3 Dilation Gives Exponential Reach
From the deep-learning coursework on convolutional filters — including transpose convolution — recall dilation. A dilation rate tells a convolution to skip inputs: with rate two, the kernel reads every second sample; with rate four, every fourth. Reference texts define it as inserting zeros between kernel weights — a kernel of size three with rate two touches positions — so the kernel spans a wide region while keeping few weights. Nothing about causality changes; the skips point backward only.
Apply dilation inside the causal stack and the picture changes. Give layer one rate 1, layer two rate 2, layer three rate 4, layer four rate 8 — the rate doubles layer by layer, the standard scheme WaveNet uses to grow its field fast and evenly. Now a dilated unit connects to its immediate neighbor and one further out; the next layer skips wider still; the next wider again.
Worked example — counting the reach of a four-layer stack.
Plain causal stacking, kernel width two: layer 1 spans 2 samples, layer 2 spans 3, layer 3 spans 4, layer 4 spans 5. Total reach: 5 time points — matching with .
Dilated causal stacking, rates 1, 2, 4, 8: layer 1 spans 2, layer 2 spans 3, layer 3 skips and spans 5, layer 4 skips wider and spans 9. Summing the extra backward steps gives a total field of 15 past points (plus the current sample) — fitting with , instead of 5.
Final verdict: where plain stacking grew coverage linearly, dilated stacking grows it exponentially — sixteen times the history at barely more than triple the span-per-layer cost. Sense check: , and doubling the layers would roughly square the reach rather than merely doubling it.
Receptive-field growth under causal stacking, kernel width two:
Exponential reach means raw audio contexts of tens of thousands of samples become reachable with modest depth.
Visual intuition: sketch the two stacks side by side. On the left, a skinny triangle climbing straight up, one new sample per layer. On the right, a wide fan spreading rapidly leftward, each layer stretching twice as far as the one below. Same height, wildly different footprint — the fan hears the whole phrase; the triangle hears a blink.
5.5.4 Training Deep Stacks: Residual Connections
Wide receptive fields demand many layers, and many layers invite the classic failure. Class worked through it Socratically:
Q: With a very deep structure, what problem shows up, and which architectural trick addresses it? A: The problem is vanishing gradient — with it, you simply cannot train. First guesses were ReLU activation, then dropouts, then regularization. Each got pushed back: those address overfitting — dropout reduces overfitting — not the training-signal collapse. The wanted answer was residual connections: introduce the skip connections familiar from ResNet, residual blocks with skip connections, and deep stacks become trainable.
Worth pausing on why the wrong answers were wrong. ReLU keeps activations alive but does nothing about gradients shrinking across forty multiplications. Dropout and regularization fight memorization of training data — a different disease. Vanishing gradients are a plumbing failure: the learning signal itself thins out on its way back through many layers. Residual blocks fix the plumbing by adding a shortcut wire around each block, so the identity path lets gradients bypass the transformations entirely and reach early layers intact. That is why the recipe absorbs one more ingredient: skip connections from ResNet let deep dilated stacks actually train.
5.5.5 Gated Activations Borrowed from LSTM
Recall the LSTM goal — use lots of past information, while controlling what passes and what gets forgotten — and its mechanism: gates. WaveNet adopts the same trick. Sigma-activation gates decide whether to stop some information or pass it; tanh branches carry the actual content signal that the gates moderate. Combining them produces a gated unit of the standard form:
where denotes the causal convolution, and are learned filter weights, elementwise multiplication, the sigmoid gate, and the content branch. Read it as two opinions fused: tanh proposes what the audio content could be; sigmoid votes, sample by sample, how much of that proposal gets through. The parallel is direct: LSTM used gates to manage memory across time; WaveNet uses gates to manage which parts of a long receptive field influence the current prediction. Long audio carries bursts, silence, and noise, and the gate learns when to listen hard and when to shrug.
5.5.6 The Full WaveNet Recipe and Sampling
Assemble everything into the procedural recipe:
- Apply causal convolution so only past information enters.
- Stack dilated convolutions with growing rates so a large receptive field forms from few layers.
- Insert gated units — sigma gates plus tanh content — for information control.
- Wire residual (skip) connections so the deep structure trains.
- Finish with a softmax so outputs are probabilities between zero and one over the possible sample values.
Inputs and outputs: in goes a seed of audio samples; out comes, after training, a conditional distribution at every step. Once and friends are learned, generation loops: seed a value, sample from the predicted distribution, feed the sample back, and continue — sequential audio synthesis from a learned density. Complexity-wise, generation costs one network pass per output sample, which is why long clips take noticeable time even on strong hardware; the parallel-training advantage from Section 5.3.2 belongs to transformers, not here.
5.5.7 Applying WaveNet Ideas to Images
For illustration, WaveNet ran on image data despite being one-dimensional by design: read the image row by row, flatten it into a sequence, and process line after line. Nothing stops you from replacing the CNN with an RNN structure on data processed this way.
Q: Processing MNIST row by row — when you move to the second row, don't you lose the spatial dependency linking it to the first row? A: Sharp observation, and the answer separates pedagogy from engineering: the row-by-row rendering was for illustration. In practice you retrofit pictures into this framework by inventing an artificial ordering, and you can even append the x-y coordinates of each pixel as extra input. Models named PixelRNN — created before PixelCNN — did exactly this kind of thing for estimating image probability distributions and generating new images.
The deeper challenge got airtime too:
Q: Spatial data is not temporal. With masking you only ever look backward, so surely the density estimate stays poor until you reach the very last pixel — spatial neighborhoods include pixels after you, which you are refusing to mask in. Is that not fatal? A: Sit with this one — the invitation was to think more and comment next class. Three anchors to carry forward. First, the chain-rule expansion of over all pixels is exact, with no approximation whatsoever: . Second, in a typical image a pixel relates closely only to its neighborhood, so many factors contribute little — the product still holds. Third, the end goal is not the distribution for its own sake but the ability to sample it and create new data; the distribution is the intermediate step, the launchpad for generation. Whether the backward-only view limits that goal is worth continuing to think about — restricted, for now, to autoregressive models.
One more reminder from the RNN recap transfers here: future information is used only for fill-in-the-gap tasks, never in causal autoregressive modeling.
Recap: causal convolutions enforce autoregression, dilation buys exponential context, gates steer information, residuals make depth trainable. Next, PixelCNN moves these ideas fully into two dimensions and hits a geometric surprise called the blind spot.
5.6 PixelCNN and Gated PixelCNN
5.6.1 Raster Scan Ordering and Masked Convolutions
PixelCNN applies masked spatial convolution to image distributions. Pixels are the features, ordered through for an by image. One natural ordering scans left to right, row by row, top to bottom — exactly how old analog televisions illuminated screens along scan lines traced by cathode rays. History explains the layout: this is known as raster scan. Under that ordering:
Every pixel conditions on all pixels before it — including the previous line's pixels when a new row begins, which is what lets vertical structure propagate at all.
The twist versus WaveNet is spatial. Instead of an ordinary convolution centered on a pixel, use a masked convolution that consults only pixels occurring earlier in the ordering. For a three by three kernel this means holding specific entries at zero: the entire bottom row of the kernel is zeroed (those pixels come later), the center entry is zeroed (a pixel cannot see itself), and within the middle row only the entries left of center survive (same row, earlier columns). The top row stays fully visible — everything above the current pixel already happened. Only preceding pixels flow through. Beyond that masked kernel, the training stack mirrors the WaveNet-style structure already discussed.
Visual intuition: imagine the kernel as a nine-cell window sliding over the image, with shutters painted over its bottom row and its own center cell. As it slides across each row, the window reads a growing strip of the past — everything above, plus the finished part of the current line — and nothing else.
The fundamental limit stands, as raised in the spatial-dependency discussion of Section 5.5.7: quality caps out, and generation proceeds by biased, step-by-step sampling of the learned distribution — one pixel predicted, sampled, appended, then the next.
5.6.2 The Blind Spot Problem
Plain PixelCNN hides a geometric flaw: stacked masked kernels leave some regions permanently invisible to certain predictions. That is why standard PixelCNN achieves only low-quality NLL — the architecture cannot see everything it mathematically should.
See the flaw before fixing it. Estimate the distribution at some pixel using a three by three masked kernel. The mask admits earlier pixels only, so pixels below-right of the target never contribute — they sit inside the kernel's footprint but come later in raster order. Stack another masked layer hoping to widen the view, and the situation fails to improve. The previous layer, focused on its own target, likewise ignored its own future neighbors; passing those blind corners upward just passes blindness along. Trace the reachable set carefully and some lower-corner regions end up invisible to the receptive field, permanently — like a security camera whose housing blocks part of its own view no matter how many identical cameras you stack behind it.
Consequence: the NLL quality achievable by standard PixelCNN stays low. The chain-rule factorization says every pixel may condition on all earlier ones; the wiring quietly delivers less.
5.6.3 How Gated PixelCNN Fixes It
Gated PixelCNN imports the gate idea from the LSTM literature — sigma gating decides what to forget or remember, tanh controls how much information flows — and attacks the blind spot structurally. Instead of one two-dimensional masked convolution, it runs two separate one-dimensional streams:
- Vertical convolution. Computed over the whole image with padding arranged so the activation at row depends on inputs up to row — everything strictly above, nothing beside or below. Follow any vertical-stack unit through its inputs: all information from previous rows, no blind spot.
- Horizontal convolution. Sees the current row's past pixels and also consumes the gathered vertical-stack results, merging the two views.
Why does splitting kill the hole? Because "everything above" and "earlier on this row" together cover exactly the full causal past — the two streams partition the raster-scan predecessors between them without gaps. A single two-dimensional kernel cannot express that coverage cleanly; two stacked one-dimensional passes can. Splitting the masked operation into vertical and horizontal steps lets every target pixel, in effect, use all the information that has happened — closing the hole plain PixelCNN left open. Gated ResNet blocks then supply depth with trainable gradients and finer information control, borrowing once more from the residual recipe of Section 5.5.4.
5.6.4 NLL Results
Worked example — the binary MNIST-scale scoreboard. Lower NLL wins.
| Model | NLL |
|---|---|
| Mixture of multivariate Gaussians | much higher |
| Mixture of uniform distributions | much higher |
| Standard PixelCNN | 3.14 |
| PixelRNN | 3.14 |
| Gated PixelCNN | 3.03 |
Final verdict: gated PixelCNN reaches 3.03 against 3.14 for standard PixelCNN and PixelRNN. Relatively small — but at these near-the-floor values the gap matters, and structured autoregression with the right masking beats generic mixture modeling again. Sense check: both figures sit far below the mixture baselines, so the ranking is about masking quality among autoregressive models.
Next sessions continue the lineage — PixelCNN++ and further refinements — with recommended blog posts covering the details.
Recap: raster scan orders the pixels, masked kernels enforce causality, the blind spot caps plain PixelCNN's quality, and the vertical-plus-horizontal gated split restores full access to the past. Next, we zoom out to video generation, diffusion teasers, and study guidance.
UDL Lecture 5 notes · Building Autoregressive Models
Sections Breakdown
Why histograms collapse in high dimension and the three requirements every practical density model must satisfy.
Chain-rule factorization of a joint distribution, likelihood maximization, and a toy two-variable model with softmax outputs.
RNN, LSTM, GRU, attention, and transformer trade-offs, causal versus bidirectional variants, and RNN-generated handwritten digits.
Mask mechanics, random hidden numbering, type A versus type B masks, parallel training with sequential Bernoulli sampling, and MNIST results.
Causal convolutions, exponential receptive-field growth through dilation, residual connections, and sigmoid-tanh gated activations.
Raster-scan ordering, masked convolutions, the blind spot problem, and the vertical-plus-horizontal gated fix with NLL results.
Video generation, diffusion trade-offs, scoring your own samples, business value, homework prompts, and the reading list.
Consolidated exam intel: expected questions, mask mechanics, sampling narrations, and a five-step study order.
Where autoregressive modeling ships: language models, speech pipelines, video generation, handwriting synthesis, and tabular density estimation.
Exam Revision Notes
Below is the distilled, exam-ready core. Every entry comes from the full explanation above. Use this section for rapid review; return to the main notes when a point needs more context.
From Histograms to Learned Density Models
Must-know: Histograms fail in high dimension because cell counts grow like Bd while data stays finite; the three design requirements are accurate density, fast training, efficient sampling.
⚠️ Top pitfall: Assuming a histogram that worked in 1D can be extended by adding axes; empty cells make high-dimensional estimates useless.
Self-check: Why can no modern method satisfy accuracy, fast training, and fast sampling all at once?
Connects to: Section 5.2 (The Autoregressive Idea).
The Autoregressive Idea
Must-know: Chain-rule factorization is exact, not approximate; minimize NLL equals maximize log likelihood, and smaller NLL decides model selection.
⚠️ Top pitfall: Treating the factorization as an approximation or forgetting that sampling must walk the ordering one variable at a time.
Self-check: Why do softmax outputs always sum to one, and what happens to them when all logits are equal?
Connects to: Section 5.1 (From Histograms to Learned Density Models); Section 5.3 (Recurrent Networks as Autoregressive Engines); Section 5.4 (MADE: Masked Autoencoder for Density Estimation).
Recurrent Networks as Autoregressive Engines
Must-know: Transformer advantage = parallel training across the sequence vs sequential recurrent training; unidirectional is causal/autoregressive, bidirectional is anti-causal fill-in-the-gaps.
⚠️ Top pitfall: Answering 'large context' when asked for the main transformer advantage — the hunted answer is parallel training; also confusing bidirectional RNNs with autoregressive models.
Self-check: Why does a vanilla RNN lose far-away history, and which cell design fixes it?
Connects to: Section 5.2 (The Autoregressive Idea); Section 5.4 (MADE: Masked Autoencoder for Density Estimation).
MADE: Masked Autoencoder for Density Estimation
Must-know: Mask rule M(m,n)=1 iff m≥n between hidden layers; strict comparison at the output prevents leakage; MADE reaches NLL 86.64 on binary MNIST vs about 140 for a mixture of Bernoullis.
⚠️ Top pitfall: Letting an output see its own feature's input (self-inclusion) — that leaks the answer into its own predictor.
Self-check: Why must the third input's mask column be all zeros in the running example?
Connects to: Section 5.2 (The Autoregressive Idea); Section 5.3 (Recurrent Networks as Autoregressive Engines); Section 5.6 (PixelCNN and Gated PixelCNN).
WaveNet: Dilated Causal Convolutions for Audio
Must-know: Deep stacks fail by vanishing gradients, fixed by residual skip connections from ResNet — not ReLU, dropout, or regularization, which fight overfitting instead.
⚠️ Top pitfall: Reaching for dropout or regularization when asked how to fix untrainable depth; the trained answer is residual connections.
Self-check: How many past points do four layers reach with and without dilation rates that double?
Connects to: Section 5.3 (Recurrent Networks as Autoregressive Engines); Section 5.6 (PixelCNN and Gated PixelCNN).
PixelCNN and Gated PixelCNN
Must-know: Masked kernels zero the center and all future raster-order pixels; the blind spot is why plain PixelCNN stalls at NLL 3.14 while gated PixelCNN reaches 3.03.
⚠️ Top pitfall: Assuming stacking more masked layers widens coverage — each layer inherits and passes along the same blind corners.
Self-check: Which two one-dimensional streams replace the two-dimensional masked convolution in gated PixelCNN, and what does each see?
Connects to: Section 5.5 (WaveNet: Dilated Causal Convolutions for Audio); Section 5.4 (MADE: Masked Autoencoder for Density Estimation).
Beyond Images: Video, Diffusion Teasers, and Study Guidance
Must-know: Autoregressive models can score their own samples' probability — a free self-audit most generative families lack; video scales the same principles from 2D to 3D.
⚠️ Top pitfall: Forgetting that diffusion's slowness comes from many reverse-diffusion refinement steps, not from lack of parallelism.
Self-check: Why does a low probability score on a freshly generated sample matter in practice?
Connects to: Section 5.4 (MADE: Masked Autoencoder for Density Estimation); Section 5.6 (PixelCNN and Gated PixelCNN).
Exam Guidance Summary
Must-know: Five study targets in order: chain rule + NLL, recurrent-family comparisons, MADE mask mechanics with dependency traces, dilation counting, blind spot fix.
⚠️ Top pitfall: Rereading notes instead of re-doing the worked traces — exam questions test tracing and narration.
Self-check: Can you explain why the output mask must be strict without looking at the notes?
Connects to: Section 5.2 (The Autoregressive Idea); Section 5.3 (Recurrent Networks as Autoregressive Engines); Section 5.4 (MADE: Masked Autoencoder for Density Estimation); Section 5.5 (WaveNet: Dilated Causal Convolutions for Audio); Section 5.6 (PixelCNN and Gated PixelCNN).
Key Industry Applications
Must-know: Accurate learned densities enable three production capabilities: generating, scoring, and auditing data.
Self-check: Which two NLL numbers quantify MADE's edge over mixture models on binary MNIST?
Connects to: Section 5.4 (MADE: Masked Autoencoder for Density Estimation); Section 5.5 (WaveNet: Dilated Causal Convolutions for Audio); Section 5.7 (Beyond Images: Video, Diffusion Teasers, and Study Guidance).
Was this lecture useful?
BitsNotes AI Assistant
Subject Notes AssistantConfigure AI Chat
Choose how to access the chatbotSigned in as
Powered by BitsNotes — 20 messages per day. No API key needed. Want unlimited access? Use "Bring Your Own Key" mode.
Sign in to use AI Chat
Get 20 free AI messages per day to ask questions about your lecture notes. Sign in with Google or GitHub — it takes 5 seconds.
Sign In to BitsNotesSwitch to "Bring Your Own Key" tab above for unlimited access with any OpenAI-compatible provider.