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 pixels has 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 , 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 from seeing 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 . Evaluating observation requires . 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 and then evaluate the conditional of . The network may receive a complete input vector in both procedures, provided its connections ensure unknown values do not influence the corresponding logit.
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 . 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 hidden units, traversing positions costs in this formulation, instead of recomputing sums of up to inputs from scratch, which would cost . 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 and the output mask is . 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 receives only units of degree at most , all its input dependencies have degree at most . An output of degree receives only units of degree below , so none of its dependencies has degree 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.
∎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 , with . If the observed value is evaluated within its own prediction, the supposed factor is for and for . Their sum is : this is not a probability distribution over the bit. As 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.
For a Gaussian mixture, , with , and . 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 can be changed to for . Except when , 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 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.
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.
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 ; backpropagation multiplies each weight gradient by its mask again.
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 . 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.
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.
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.
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()npm run lab and open the connection link.The likelihood of a mixture of orders is , 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
Step 1 of 2. Which inputs can reach a hidden unit of degree k?
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):
passThe 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.