Module contents
Lesson 2 of 28Core 95 min

Autoregressive models: the chain rule as a model

Factorize a distribution exactly into conditional distributions and parameterize them with a network for exact likelihood and parallel training. Develop FVSBN, NADE and MADE, whose masks enforce ordering in one pass. Study continuous outputs, sequential ancestral sampling and order-agnostic training.

After this lesson you can

  • Write the exact log-likelihood of an autoregressive model and train it with teacher forcing.
  • Build MADE masks from degrees and prove that the resulting Jacobian is strictly triangular.
  • Implement MADE from scratch and measure bits per dimension on binarized digits.
  • Calculate the cost of ancestral sampling compared with training.
  • Explain the benefits of random-order training and its connection to masked models.

Before you start

One image, one decision at a time

A binary image with DD pixels has 2D2^D configurations. A table giving one probability per configuration is valid but grows exponentially. The chain rule offers another representation: write the image probability as a sequence of decisions, each conditioned on previous ones. This does not assume independence. The compromise comes from choosing a manageable family of conditionals and an order in which to generate them.

Joint normalization follows by summing from right to left: first ∑xDp(xD∣x<D)=1\sum_{x_D}p(x_D\mid x_{<D})=1, then the next conditional disappears, and so on until the result is one. For densities, use integrals under the usual measurability assumptions. Valid conditionals produce a normalized joint without calculating a global partition function.

During training the entire image is known. The loss is the sum of decision cross-entropies, and all logits can be computed simultaneously if the network prevents logit dd from seeing xdx_d or later pixels. This is teacher forcing: context is the observed prefix, not a previously generated sample. In a recurrent network, shifting inputs correctly prevents leakage; in MADE, masks do so. An autoregressive language model uses the same rule for tokens.

For example, with two bits, the table can be written as p(x1)p(x2∣x1)p(x_1)p(x_2\mid x_1). Evaluating observation (1,0)(1,0) requires log⁡p(x1=1)+log⁡p(x2=0∣x1=1)\log p(x_1=1)+\log p(x_2=0\mid x_1=1). During training both terms can come from one pass because the first logit sees no bits and the second sees only the first. To generate, first decide x1x_1 and then evaluate the conditional of x2x_2. The network may receive a complete input vector in both procedures, provided its connections ensure unknown values do not influence the corresponding logit.

InteractiveGenerate a digit step by step

Blue: active. Purple border: next. Orange border: fixed by you.

Class probability after prefix
0
1
2
3
4
5
6
7
8
9

Bars show the latent class posterior. The next pixel averages class probabilities with those weights.

64 / 64

Verifiable model: a mixture of ten product Bernoullis fitted using load_digits training labels, threshold > 8 and Beta(1,1) smoothing. The class is marginalized, not revealed during generation. This is not MADE: pixels are independent within each class. Samples are schematic and can be noisy.

Next active pixelfinished
Most likely class given prefix0 (1.000)
Fixed pixels0
Advance through the conditionals and change a pixel: subsequent decisions depend on the prefix. The figure’s model and data are described in its explanation.

The figure uses a trained mixture of Bernoulli products with a latent class, not the MADE built later. Probabilities are estimated from scikit-learn digits and training labels with Beta smoothing; the class is marginalized to compute each conditional. Here a pixel is active when its intensity exceeds 8; the lab uses another threshold and its metrics are not directly comparable. The probability of an observed image is exact for the defined model even though that model imperfectly approximates the data. Exact evaluation does not mean one-step generation: sampling each conditional requires the previous decisions.

From a table to a shared network

For binary variables, a full conditional needs one probability for every prefix. A fully visible sigmoid belief network, FVSBN, instead uses p(xd=1∣x<d)=σ(bd+∑j<dwdjxj)p(x_d=1\mid x_{<d})=\sigma(b_d+\sum_{j<d}w_{dj}x_j). This is logistic regression per position: its mass function is evaluable, but its logit is linear in the prefix. To learn nonlinear interactions, one could build a different MLP per position, repeating much of the computation.

The update reuses the previous prefix sum. With HH hidden units, traversing DD positions costs O(DH)\bigO(DH) in this formulation, instead of recomputing DD sums of up to DD inputs from scratch, which would cost O(D2H)\bigO(D^2H). The output has its own parameters per position. Larochelle and Murray introduced this estimator as a tractable distribution. Sharing parameters does not force all conditionals to be identical.

MADE: causality is encoded in the connections

For matrices with destination rows and source columns, the hidden mask is Mji=1[m(i)≤m(j)]M_{ji}=\mathbf 1[m(i)\le m(j)] and the output mask is Mdiout=1[m(i)<m(xd)]M^{\mathrm{out}}_{di}=\mathbf 1[m(i)<m(x_d)]. Biases are constant and introduce no dependencies. Masks multiply weights on every evaluation; initializing forbidden weights to zero is insufficient if they are then updated without masking.

Proof

An allowed input-to-hidden connection can come only from an input whose degree does not exceed that unit’s degree. By induction, if a unit of degree kk receives only units of degree at most kk, all its input dependencies have degree at most kk. An output of degree dd receives only units of degree below dd, so none of its dependencies has degree dd or higher. Changing such an input leaves the logit unchanged and its partial derivative is zero where defined. Triangularity refers to the chosen ordering, not necessarily the original column indices. An allowed path may have zero weight or cancel out: possible structural dependence does not imply a nonzero derivative.

∎
InteractiveBuilding the masks
  • Path to chosen output
  • Allowed connection
  • Forbidden dependency
x1x2x3x412231233y1y2y3y4InputHidden 1Hidden 2OutputHidden numbers are degrees, not activations
Possible dependencies: rows = outputs, columns = inputs
x1x2x3x4y10000y21000y31100y41110

A marked cell means an allowed path exists, not that the derivative must be nonzero: weights or activations may cancel it. Connections are allowed when degree does not decrease, except at output where it must strictly increase.

Hidden layer
Hidden unit
1
Highlighted output
Possible forbidden dependencies0
Inputs that can affect highlighted outputx1, x2, x3
Change the degrees of two layers and trace input-output paths. Activate the incorrect output connection to observe a potentially forbidden dependency.

If an output sees its own pixel, one may still multiply numbers between zero and one, but they are no longer necessarily normalized conditionals in the predicted variable. Loss on observed images can drop by copying the target. That value is not the NLL of the intended distribution. Germain and colleagues construct these masks and allow several masks for the same network.

A one-bit counterexample makes the failure visible. Let the predicted probability of one be q(1∣x)=σ(c(2x−1))q(1\mid x)=\sigma(c(2x-1)), with c>0c>0. If the observed value is evaluated within its own prediction, the supposed factor is q(x=1∣1)=σ(c)q(x=1\mid1)=\sigma(c) for x=1x=1 and q(x=0∣0)=1−σ(−c)=σ(c)q(x=0\mid0)=1-\sigma(-c)=\sigma(c) for x=0x=0. Their sum is 2σ(c)>12\sigma(c)>1: this is not a probability distribution over the bit. As cc grows, apparent loss for both values approaches zero precisely because each prediction has seen the answer. This does not claim every forbidden weight will learn to copy; it shows why allowing the path invalidates the structural guarantee.

Order, capacity and continuous outputs

The chain rule holds in every order, but a finite parameterized family need not approximate every factorization equally well. A simple conditional may represent one direction well and require a rich mixture in the reverse direction. Changing order also changes what information is available at each step.

InteractiveOrder changes the task

The target chooses X uniformly from −3 to 3; then Y equals |X| with probability 0.9 and is uniform from 0 to 3 with probability 0.1.

Target distribution
3
13.2
0.4
0.4
0.4
0.4
0.4
13.2
2
0.4
13.2
0.4
0.4
0.4
13.2
0.4
1
0.4
0.4
13.2
0.4
13.2
0.4
0.4
0
0.4
0.4
0.4
13.2
0.4
0.4
0.4
−3−2−10123
Rows: y. Columns: x. Each number is a probability percentage; darker blue indicates higher probability.
Fitted distribution
3
13.7
0.2
0.2
0.2
0.2
0.2
13.7
2
0.2
13.7
0.2
0.2
0.2
13.7
0.2
1
0.2
0.2
13.7
0.2
13.7
0.2
0.2
0
0.2
0.2
0.2
13.7
0.2
0.2
0.2
−3−2−10123
Rows: y. Columns: x. Each number is a probability percentage; darker blue indicates higher probability.

The first marginal is fitted exactly. Each conditional combines a uniform background of weight 0.05 with up to K atoms; we choose the K most likely values and optimize their weights over the complete distribution. Order and capacity change the best representable distribution. Figures are exact expectations in this example, not training or test-data results.

Order
1
Show
Expected log likelihood
−2.310 nats per pair
KL from target to model
0.015 nats
Change the order and conditional capacity. Compare likelihood and the resulting distribution: the chain rule remains exact, but the fit may not.

For a Gaussian mixture, p(xd∣x<d)=∑k=1KπkN(xd;μk,σk2)p(x_d\mid x_{<d})=\sum_{k=1}^K\pi_k\Normal(x_d;\mu_k,\sigma_k^2), with πk≥0\pi_k\ge0, ∑kπk=1\sum_k\pi_k=1 and σk>0\sigma_k>0. The network produces parameters for each component; softmax supplies weights and a positive transformation supplies scales. For quantized values, integrating a density over each category interval gives mass. Comparing log-densities with discrete probabilities without specifying this conversion changes the problem.

The temperature of a Bernoulli with logit aa can be changed to σ(a/T)\sigma(a/T) for T>0T>0. Except when T=1T=1, this defines different conditionals and thus a different joint distribution. A sample with altered temperature is not a sample from the original model. A parallel prediction with every pixel initialized to zero is not ancestral sampling either: it ignores decisions not yet made.

Parallel training also has a memory cost: each layer’s activations are stored to compute gradients, and multiplying a dense mask by dense weights does not automatically make the library use sparse multiplication. When timing a generator, distinguish batch latency, samples per batch and cost per pass. A cache reusing states can change cost per step without changing logical dependence between decisions.

Training with different orders may allow different prefixes or subsets and create an ensemble, but does not guarantee better NLL for every dataset or budget: orders share capacity. Uria and colleagues study deep order-agnostic NADE. Masked diffusion models, studied later, also learn to complete partially observed information, although their process and objective differ from autoregressive MADE.

An arbitrary observed set is not automatically a prefix of a fixed order. If known pixels are interspersed with unknown ones, generating missing pixels from the beginning while keeping observed pixels fixed does not generally produce the exact conditional distribution: future observed pixels also inform earlier missing ones. An order placing observed pixels first makes the set a prefix if the model supports and has learned that order. This matters for completion as well as joint probabilities.

Lab: MADE from scratch in NumPy

Use the 8×88\times8 images from the previous lesson’s dataset. Binarize with a fixed threshold and split before training; use the same split and binarization for the model and independent baseline. Comparison with dynamically binarized MNIST would be a different task. Array indices start at zero, whereas mathematical degrees start at one.

[ ]Data and masksBrowser
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split

digits = load_digits()
x = (digits.data >= 8).astype(np.float64)
train_i, test_i = train_test_split(np.arange(len(x)), test_size=0.2,
                                   random_state=7, stratify=digits.target)
train_x, test_x = x[train_i], x[test_i]
D, H = 64, 32
rng = np.random.default_rng(19)
degree_in = np.arange(1, D+1)
degree_hidden = rng.integers(1, D, H)
mask1 = (degree_in[:, None] <= degree_hidden[None, :]).astype(float)
mask2 = (degree_hidden[:, None] < degree_in[None, :]).astype(float)
print('Entrenamiento, evaluación:', train_x.shape, test_x.shape)
print('Conexiones ocultas y de salida:', int(mask1.sum()), int(mask2.sum()))

The opening figure can be reproduced with the same indices. Its threshold is strictly greater than 8, labels fit one component per class, and the latent class is summed out at evaluation. Smoothing adds one success and one failure per pixel and class. The next cell prints this model’s parameters and score, separately from the MADE trained later.

[ ]Reconstruct the model in the figureBrowser
figure_x = (digits.data > 8).astype(float)
class_counts = np.bincount(digits.target[train_i], minlength=10)
prior = class_counts / class_counts.sum()
pixel_prob = np.array([(figure_x[train_i][digits.target[train_i] == c].sum(axis=0) + 1) /
                       (class_counts[c] + 2) for c in range(10)])
log_terms = (np.log(prior)[None, :] +
             figure_x[test_i] @ np.log(pixel_prob).T +
             (1-figure_x[test_i]) @ np.log1p(-pixel_prob).T)
maximum = log_terms.max(axis=1)
logp = maximum + np.log(np.exp(log_terms-maximum[:, None]).sum(axis=1))
print('Ejemplos por clase:', class_counts)
print('Parámetros por clase:', pixel_prob.shape)
print('bpd de la mezcla de la figura en test:', round(-logp.mean()/(64*np.log(2)), 5))

Weights are stored as input-by-output matrices so a row of examples multiplies on the right. The stable logaddexp function evaluates Bernoulli loss from logits. The derivative of mean loss per example with respect to the logit is σ(a)−x\sigma(a)-x; backpropagation multiplies each weight gradient by its mask again.

[ ]Forward pass, backward pass and updateBrowser
W1 = rng.normal(0, 0.08, (D, H))
W2 = rng.normal(0, 0.08, (H, D))
b1 = np.zeros(H)
b2 = np.zeros(D)

def forward(batch):
    h = np.maximum(0, batch @ (W1*mask1) + b1)
    logits = h @ (W2*mask2) + b2
    return h, logits

def update(batch, lr):
    global W1, W2, b1, b2
    h, logits = forward(batch)
    probability = np.exp(-np.logaddexp(0, -logits))
    delta = (probability - batch) / len(batch)
    dw2 = (h.T @ delta) * mask2
    dh = (delta @ (W2*mask2).T) * (h > 0)
    dw1 = (batch.T @ dh) * mask1
    W1 -= lr * dw1
    W2 -= lr * dw2
    b1 -= lr * dh.sum(axis=0)
    b2 -= lr * delta.sum(axis=0)

def bpd(batch):
    _, z = forward(batch)
    return np.mean(np.logaddexp(0, z) - batch*z) / np.log(2)

initial = bpd(test_x)
for step in range(240):
    ix = rng.integers(0, len(train_x), 48)
    update(train_x[ix], 0.035)
print('bpd inicial:', round(initial, 4))
print('bpd MADE de evaluación:', round(bpd(test_x), 4))

The loss sums dimensions before averaging examples; bits per dimension also divides by Dln⁡2D\ln 2. The independent-pixel control estimates probabilities from training alone and clips to avoid infinite logarithms. Comparing scores is unfair if the threshold, split or denominator changes.

[ ]Baseline and causality testBrowser
prob = np.clip(train_x.mean(axis=0), 1e-5, 1-1e-5)
independent_bpd = -np.mean(test_x*np.log(prob) + (1-test_x)*np.log(1-prob)) / np.log(2)
probe = test_x[:1].copy()
_, before = forward(probe)
probe[0, 30] = 1-probe[0, 30]
_, after = forward(probe)
print('bpd independiente de evaluación:', round(independent_bpd, 4))
print('Cambio máximo en logits hasta la posición perturbada:', round(float(np.max(np.abs(before[:, :31]-after[:, :31]))), 10))

The perturbation checks one input and one example; the structural proof of masks covers every path, even if a weight is zero. A numerical derivative check helps detect implementation errors but does not replace that proof. Now generate a vector one decision at a time, recomputing all logits for clarity.

[ ]Ancestral samplingBrowser
sample = np.zeros((1, D))
for d in range(D):
    _, logits = forward(sample)
    p = 1 / (1 + np.exp(-np.clip(logits[0, d], -30, 30)))
    sample[0, d] = rng.random() < p
print('Forma de la muestra:', sample.reshape(8, 8).shape)
print(sample.reshape(8, 8).astype(int))

A small run illustrates the mechanism and can detect leakage; it does not demonstrate competitive quality. Check stability with more steps and seeds, inspect unselected samples and retain probabilities and splits when comparing. In Pyodide do not assume the speed of NumPy linked to BLAS on your computer.

Local lab: multiple orders on MNIST

Keep the same idea in PyTorch, using MNIST and two hidden layers. The fixed model has raster order and a fixed mask; the second receives a new order and degrees for every batch. Evaluation of the latter averages probabilities from several masks fixed before inspecting test data. The comparison changes both training and evaluation: it reports the outcome of the procedure, without attributing causality to the ensemble alone. An additional comparison within the same model between one mask and its mixture would better isolate the ensemble effect.

The code downloads MNIST to ./data, uses a fixed 0.5 threshold for both sets and selects CUDA when available. Full training is the default. To check the entire workflow using less data and fewer steps, set ORYON_QUICK=1 in your environment before starting the process. This lesson’s short test checks operation only and does not estimate full-training quality. The seed controls initialization, masks and data order; platforms may differ slightly numerically.

[ ]MADE with one order and an order ensembleLocal GPU
import math
import os
import random
from pathlib import Path
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader, Subset
from torchvision import datasets, transforms

quick = os.environ.get('ORYON_QUICK') == '1'
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
seed = 41
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
if device.type == 'cuda':
    torch.cuda.manual_seed_all(seed)

D = 28 * 28
hidden = (64, 64) if quick else (512, 512)
epochs = 1 if quick else 12
batch_size = 128
n_masks_eval = 4 if quick else 16
root = Path(os.environ.get('ORYON_MNIST_ROOT', './data'))
transform = transforms.ToTensor()
train_all = datasets.MNIST(root, train=True, download=True, transform=transform)
test_all = datasets.MNIST(root, train=False, download=True, transform=transform)
train_data = Subset(train_all, range(1024)) if quick else train_all
test_data = Subset(test_all, range(512)) if quick else test_all

def make_masks(order, hidden_sizes, generator):
    d = len(order)
    if sorted(order.tolist()) != list(range(d)):
        raise ValueError('order debe ser una permutación de 0 a d-1')
    ranks = torch.empty(d, dtype=torch.long)
    ranks[order] = torch.arange(1, d + 1)
    degrees = [ranks]
    for width in hidden_sizes:
        degrees.append(torch.randint(1, d, (width,), generator=generator))
    masks = [(degrees[k + 1][:, None] >= degrees[k][None, :]).float()
             for k in range(len(hidden_sizes))]
    masks.append((ranks[:, None] > degrees[-1][None, :]).float())
    return masks

class MaskedLinear(nn.Linear):
    def __init__(self, inputs, outputs):
        super().__init__(inputs, outputs)
        self.register_buffer('mask', torch.ones(outputs, inputs))

    def forward(self, x):
        return F.linear(x, self.weight * self.mask, self.bias)

class MADE(nn.Module):
    def __init__(self, d, hidden_sizes):
        super().__init__()
        dims = (d, *hidden_sizes, d)
        self.layers = nn.ModuleList(MaskedLinear(a, b) for a, b in zip(dims[:-1], dims[1:]))

    def set_masks(self, masks):
        for layer, mask in zip(self.layers, masks):
            layer.mask.copy_(mask.to(layer.mask.device))

    def forward(self, x):
        for layer in self.layers[:-1]:
            x = torch.relu(layer(x))
        return self.layers[-1](x)

def binary_batch(images):
    return (images.flatten(1).to(device) >= 0.5).float()

def train_model(multi_order):
    torch.manual_seed(seed)
    model = MADE(D, hidden).to(device)
    optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
    order_rng = torch.Generator().manual_seed(seed + 1)
    mask_rng = torch.Generator().manual_seed(seed + 2)
    data_rng = torch.Generator().manual_seed(seed + 3)
    loader = DataLoader(train_data, batch_size=batch_size, shuffle=True,
                        generator=data_rng, num_workers=0)
    fixed = make_masks(torch.arange(D), hidden, mask_rng)
    model.set_masks(fixed)
    model.train()
    for epoch in range(epochs):
        total = count = 0
        for images, _ in loader:
            if multi_order:
                order = torch.randperm(D, generator=order_rng)
                model.set_masks(make_masks(order, hidden, mask_rng))
            x = binary_batch(images)
            optimizer.zero_grad(set_to_none=True)
            loss = F.binary_cross_entropy_with_logits(model(x), x, reduction='sum') / x.shape[0]
            loss.backward()
            optimizer.step()
            total += loss.item() * x.shape[0]
            count += x.shape[0]
        print(('varios órdenes' if multi_order else 'orden fijo'),
              'época', epoch + 1, 'NLL entrenamiento, nats/imagen:', round(total / count, 3))
    return model, fixed

@torch.no_grad()
def test_nll(model, mask_set):
    model.eval()
    total = count = 0
    for images, _ in DataLoader(test_data, batch_size=batch_size, shuffle=False, num_workers=0):
        x = binary_batch(images)
        log_probs = []
        for masks in mask_set:
            model.set_masks(masks)
            log_probs.append(-F.binary_cross_entropy_with_logits(model(x), x, reduction='none').sum(dim=1))
        mixture_logp = torch.logsumexp(torch.stack(log_probs), dim=0) - math.log(len(mask_set))
        total -= mixture_logp.sum().item()
        count += len(x)
    return total / count

single, single_mask = train_model(False)
multi, _ = train_model(True)
eval_order_rng = torch.Generator().manual_seed(101)
eval_mask_rng = torch.Generator().manual_seed(102)
eval_masks = [make_masks(torch.randperm(D, generator=eval_order_rng), hidden, eval_mask_rng)
              for _ in range(n_masks_eval)]
single_nll = test_nll(single, [single_mask])
multi_one_nll = test_nll(multi, [eval_masks[0]])
ensemble_nll = test_nll(multi, eval_masks)
print('Dispositivo:', device, '| prueba corta:', quick)
print('Test, orden fijo, nats/imagen:', round(single_nll, 3),
      '| bits/dimensión:', round(single_nll / (D * math.log(2)), 4))
print('Test, modelo multiorden con una máscara, nats/imagen:', round(multi_one_nll, 3))
print('Test, ensamble de', n_masks_eval, 'máscaras, nats/imagen:', round(ensemble_nll, 3),
      '| bits/dimensión:', round(ensemble_nll / (D * math.log(2)), 4))
print('Diferencia ensamble - fijo, nats/imagen:', round(ensemble_nll - single_nll, 3))
del single, multi
if device.type == 'cuda':
    torch.cuda.empty_cache()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The likelihood of a mixture of orders is log⁡(1K∑kpk(x))\log(\frac1K\sum_k p_k(x)), computed without overflow using logsumexp. The mean of individual NLLs is a different quantity. Models do not see MNIST labels or update weights using test data. Since short-run size and duration differ, do not compare its figures with full training.

By logarithm concavity, the mixture NLL for an example is at most the mean NLL of its components. This does not mean it beats every component: the best mask for an example can assign higher probability than the average. Evaluating many masks and selecting the best directly on test also uses test to choose a model; choose with validation and reserve test for final comparison. The difference between a mask of the multi-order model and its mixture helps interpret averaging without confusing it with the difference between training procedures.

Exercises

ProofWhy there is no leakage
Prove: Prove that a degree-d logit does not depend on inputs of degree d or higher.
0
Degrees do not decrease between hidden layers, and the final connection requires strict inequality.

Step 1 of 2. Which inputs can reach a hidden unit of degree k?

NumericA batch of digits
One network pass takes 2 ms for a batch of 64 images. Without caching, how many seconds do the 784 sequential evaluations needed to generate that batch of 28×28 images take? Ignore all additional costs.
QuizA result too good to be true
A mask allows each output to see its own pixel during training. Which conclusion is correct?
QuizChanging the order
You replace raster order with a fixed random order and retrain under the same budget. What can you conclude before measuring?
CodeMasks for any order
Implement make_made_masks(D, hidden_sizes, order, rng). order lists input indices from 0 to D-1 in generation order. Return masks shaped (destino, origen) (destination, source); assign hidden degrees with rng.integers(1, D, size=...), allow the previous degree to be less than or equal in hidden layers, and require hidden degree strictly less than the output rank. Assume D ≥ 2, at least one hidden layer and a valid order.
import numpy as np

def make_made_masks(D, hidden_sizes, order, rng):
  pass
Shift+Enter to run
Key idea

The chain rule turns normalized conditionals into an evaluable joint distribution. MADE masks ensure that each conditional sees only its prefix; generation retains sequential dependence. Order, capacity, binarization and evaluation procedure are all part of the experiment.