Autoregressive models for images and audio: PixelCNN, WaveNet and bits per dimension
Apply autoregression to spatial and temporal data. Build PixelCNN masked convolutions, diagnose the blind spot and address it with Gated PixelCNN, derive PixelCNN++ discretized logistic-mixture likelihood, and study WaveNet dilated causal convolutions. Interpret bits per dimension as a compression rate.
After this lesson you can
- Implement type A and B masked convolutions and verify causality with automated tests.
- Explain the original PixelCNN blind spot and how vertical and horizontal stacks remove it.
- Derive and implement a stable discretized logistic-mixture likelihood.
- Convert NLL in nats per image into bits per dimension and interpret it as compression rate.
- Calculate the receptive field of a stack of dilated causal convolutions.
- Train a class-conditioned Gated PixelCNN on the local GPU.
Before you start
An image as a sequence
A CIFAR-10 image has pixels and three color channels: discrete values. An autoregressive model can assign an exact image probability by multiplying conditional probabilities in an order. The question is how to share spatial information without letting a pixel see the future. An ordinary convolution shares weights, but its centered kernel also looks right and down, causing leakage when predicting the center.
In MADE we zero connections according to their degrees. Here kernel positions are zeroed according to raster order: rows from top to bottom and, within each row, columns from left to right. The network can evaluate all conditionals of a known image simultaneously; generation retains sequential decisions. This distinction appeared in the autoregressive factorization.
Spatial and color masks
For a monochrome image, use A in the first layer and B afterwards. A first-layer B output can depend directly on the target value and artificially lower the loss. Using A in every layer does not usually leak the future, but blocks the central path through already safe states and reduces connectivity. Causality follows by composition: if each position’s representation depends only on its past, a later B combines representations from previous positions and the same position, all already causal. A residual connection is safe only if its input is safe too.
RGB adds a second order within each pixel, for example . The first layer’s central connections may allow an output group to receive only earlier channels: predicting G may use R, while predicting B may use R and G. In later layers, central permissions depend on the input and output channel groups that have already been filtered; the same spatial mask for every channel is insufficient. Another option, used by PixelCNN++, lets the spatial network condition on previous complete pixels and puts dependencies among channels of the current pixel in the output distribution.
The blind spot and two stacks
A small raster-masked kernel cannot reach the entire past through a finite stack: paths from the target pixel upward and rightward are constrained by every layer’s order. The following map propagates connectivity rather than drawing a hand-picked region. Distinguish an allowed path from an effective derivative: weights or activations can cancel it.
The vertical stack can collect context from both sides of rows already in the past; the horizontal stack incorporates it while preserving causality on the current row. A class vector can be projected and added to both branches’ preactivations: it is known during generation, not a future pixel. The architecture and conditioning appear in Conditional Image Generation with PixelCNN Decoders. Actual reach depends on kernel size, layer count and boundaries: removing the structural blind spot does not mean a finite network sees an arbitrarily large image in full.
One mass per intensity
A 256-category softmax directly defines discrete mass for each intensity. Another option parameterizes a mixture of continuous logistic distributions and assigns each integer the mass of its quantization interval. This shares structure across nearby intensities and gives a compact representation, though not every discrete distribution is necessarily easy to express with few components.
Boundaries between consecutive intervals coincide. Summing from 0 to 255 cancels every interior term, leaving for each component, so the mixture sums to one. The half-width is because the 256 intensities lie between and at spacing ; do not replace it by without changing the quantization convention.
Directly subtracting two nearby sigmoids can lose precision. If , the identity
allows logaddexp for log-sigmoids and log(-expm1(b-a)) for a difference close to zero. Tails use log-sigmoids directly; the mixture is combined with log-sum-exp. Avoid subtracting CDFs in single precision and then taking the logarithm of a rounded zero. PixelCNN++ uses this likelihood family and also changes the architecture; differences in results cannot be attributed to just one modification.
Bits per dimension and compression
The ideal code length of a discrete observation under is ; arithmetic coding can approximate it over long sequences with finite overhead. This is the relationship between model and compressor. Encoder and decoder must use identical probabilities available in the same order.
A mass already integrated over quantization intervals is a discrete probability: do not add another bin-width term. When starting from a continuous density evaluated at a point, its logarithm depends on units; approximating mass requires the cell width and the assumptions of that approximation. Confusing the operations shifts the bpd comparison. Converting nats to bits requires division by , in addition to division by .
WaveNet: time replaces raster order
An audio sequence has a one-dimensional past. In a causal convolution with kernel and dilation , the output at a time step uses positions separated by that are not in the future. With stride 1, a stack with dilations has receptive-field extent
This formula gives the distance between endpoints plus one; an arbitrary dilation pattern may leave holes inside that extent. With kernel 2 and dilations successively doubling from 1, sums of offsets cover every position in the interval. A repeated block adds its contribution to the total reach.
WaveNet uses nonlinear -law quantization to represent audio with categories. For and , compression is ; its range is then quantized. The transformation allocates more resolution to small amplitudes than uniform quantization with the same number of levels. Generation remains sequential even though training can evaluate positions in parallel.
Causal transformers apply the same chain rule to sequences of pixels or discrete tokens. A learned tokenizer can shorten spatial length, but introduces a representation stage and its own information loss. We return to that distinction with discrete-code models. Raster order also introduces a bias: it favors one particular dependency and does not itself solve large-scale coherence.
Lab: build and verify causality
Start with monochrome images and kernels. Code indices start at zero. The following operation computes cross-correlation, like most neural-network libraries; we call it convolution by common deep-learning convention. Zero padding preserves shape.
import numpy as np
def raster_mask(kind):
if kind not in ('A', 'B'):
raise ValueError('tipo desconocido')
mask = np.zeros((3, 3))
mask[0, :] = 1
mask[1, 0] = 1
if kind == 'B':
mask[1, 1] = 1
return mask
def masked_conv(x, kernel, kind):
padded = np.pad(x, 1)
w = kernel * raster_mask(kind)
result = np.zeros_like(x, dtype=float)
for i in range(x.shape[0]):
for j in range(x.shape[1]):
result[i, j] = np.sum(padded[i:i+3, j:j+3] * w)
return result
print('Máscara A:')
print(raster_mask('A').astype(int))
print('Máscara B:')
print(raster_mask('B').astype(int))The next experiment perturbs every input of a small image and records which outputs change. In the first A layer no output can depend on its own pixel or later pixels. An isolated B layer can see the diagonal by design: it is usable only after a causal representation. With positive selected weights and identity activation, every permitted path contributes and is not hidden by cancellation.
shape = (5, 5)
kernel = np.ones((3, 3))
base = np.zeros(shape)
def dependencies(kinds):
def run(x):
for kind in kinds:
x = masked_conv(x, kernel, kind)
return x
baseline = run(base)
dep = np.zeros((25, 25), dtype=bool)
for n in range(25):
x = base.copy()
x.flat[n] = 1
dep[:, n] = (run(x) != baseline).ravel()
return dep
one = dependencies(['A'])
stack = dependencies(['A', 'B', 'B'])
print('Dependencias prohibidas con A:', int(np.triu(one).sum()))
print('Dependencias prohibidas con A, B, B:', int(np.triu(stack).sum()))
target = 3*5 + 1
print('Alcance de la fila anterior, hacia la izquierda:', bool(stack[target, 2*5]))
print('Alcance de la fila anterior, dos columnas a la derecha:', bool(stack[target, 2*5 + 3]))The numerical test is exhaustive for this image, parameters and linear operation; the structural proof covers all weights. The final pair compares two previous positions in the immediately preceding row: the kernel reaches the one on the left, but the one two columns to the right remains in this stack’s blind spot. Image boundaries and padding reduce the receptive field near the edges.
For RGB, the next mask has shape (canal_salida, canal_entrada, fila, columna), meaning output channel, input channel, row and column. At earlier spatial positions all three channels pass. At the center, A passes only channels earlier than the output channel; B also allows the same group, assuming its input was already causally filtered. The test traverses every subpixel in raster order followed by R, G and B.
def rgb_mask(kind):
mask = np.zeros((3, 3, 3, 3))
mask[:, :, 0, :] = 1
mask[:, :, 1, 0] = 1
for out in range(3):
for inp in range(3):
mask[out, inp, 1, 1] = inp < out or (kind == 'B' and inp == out)
return mask
def rgb_conv(x, kind):
h, w, _ = x.shape
padded = np.pad(x, ((1, 1), (1, 1), (0, 0)))
mask = rgb_mask(kind)
result = np.zeros_like(x, dtype=float)
for row in range(h):
for col in range(w):
patch = padded[row:row+3, col:col+3].transpose(2, 0, 1)
for out in range(3):
result[row, col, out] = np.sum(patch * mask[out])
return result
zero = np.zeros((2, 2, 3))
rgb_dep = np.zeros((12, 12), dtype=bool)
rgb_stack_dep = np.zeros((12, 12), dtype=bool)
for j in range(12):
sample = zero.copy()
sample.flat[j] = 1
first = rgb_conv(sample, 'A')
rgb_dep[:, j] = first.ravel() != 0
rgb_stack_dep[:, j] = rgb_conv(first, 'B').ravel() != 0
print('Centro de la máscara RGB A:')
print(rgb_mask('A')[:, :, 1, 1].astype(int))
print('Dependencias RGB prohibidas:', int(np.triu(rgb_dep).sum()))
print('Dependencias RGB prohibidas tras A y B:', int(np.triu(rgb_stack_dep).sum()))The test uses nonzero weights equal to one so no allowed path cancels; the central matrix permits , and , but not the diagonal or reverse direction. An implementation with hidden channels must assign consistent causal groups and preserve them in B layers and residual connections.
A stable logistic mass function
The next cell computes log-probabilities for discrete intensities. It receives component arrays that may broadcast over the batch: the last axis enumerates components. This implementation is monochrome; for RGB with shared components, sum the conditional log-probabilities of R, G and B inside each component before summing the mixture.
def log_sigmoid(x):
return -np.logaddexp(0, -x)
def logistic_logmass(value, mean, log_scale):
value = np.asarray(value)[..., None]
scale = np.exp(log_scale)
center = 2*value/255 - 1
a = (center + 1/255 - mean) / scale
b = (center - 1/255 - mean) / scale
# Esta diferencia se calcula sin restar dos números próximos a uno.
interior = log_sigmoid(a) + log_sigmoid(-b) + np.log(-np.expm1(b-a))
return np.where(value == 0, log_sigmoid(a),
np.where(value == 255, log_sigmoid(-b), interior))
def mixture_logmass(value, logits, mean, log_scale):
logits = np.asarray(logits)
m = np.max(logits, axis=-1, keepdims=True)
log_weights = logits - (m + np.log(np.exp(logits-m).sum(axis=-1, keepdims=True)))
terms = log_weights + logistic_logmass(value, np.asarray(mean), np.asarray(log_scale))
top = np.max(terms, axis=-1, keepdims=True)
return (top + np.log(np.exp(terms-top).sum(axis=-1, keepdims=True)))[..., 0]
values = np.arange(256)
log_mass = mixture_logmass(values, np.array([0., 0.]), np.array([-0.4, 0.5]), np.log([0.2, 0.3]))
print('Suma de las 256 masas:', round(float(np.exp(log_mass).sum()), 12))
print('Masas en los extremos:', np.round(np.exp(log_mass[[0, 255]]), 6))Stability does not remove every precision limit: extreme scales or non-finite values require explicit parameter validation. In a neural model limit the log-scale range and check logits, means and losses are finite. Numerically summing masses is a check; the telescoping proof explains why the sum must be one in exact arithmetic.
Local lab: two heads and two datasets
Train a network with vertical and horizontal stacks, gates and class conditioning. Compare a 256-value categorical head with a discretized logistic mixture on Fashion-MNIST and CIFAR-10 using their official splits. This lab’s RGB case factorizes channels independently given the spatial past: an explicit simplification of PixelCNN++ channel dependencies. The perturbation test checks that changing the output pixel and future pixels leaves its output unchanged.
The full experiment is the default. To check the workflow without full training, set ORYON_QUICK=1: it reduces data, resolution, depth and epochs, so its bpd cannot be compared with the full run. Code downloads official datasets to ./data and uses CUDA if available. Optionally, ORYON_CIFAR_PARQUET can point to a folder containing CIFAR-10 parquet splits; that route requires pyarrow. The timing ratio is measured in your run and changes with batch, hardware and load, so do not treat it as an architectural constant.
import math
import os
import time
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
import matplotlib.pyplot as plt
quick = os.environ.get('ORYON_QUICK') == '1'
root = Path(os.environ.get('ORYON_DATA_ROOT', './data'))
torch.manual_seed(13)
np.random.seed(13)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
if device.type == 'cuda':
torch.cuda.manual_seed_all(13)
# Cuatro experimentos: misma arquitectura y partición para cada par de cabezas.
epochs = 1 if quick else 20
width = 12 if quick else 64
blocks = 2 if quick else 8
batch_size = 32 if quick else 64
mixtures = 5 if quick else 10
transform = transforms.ToTensor()
class ParquetCIFAR(torch.utils.data.Dataset):
"""Alternativa opcional con parquet locales de uoft-cs/cifar10."""
def __init__(self, folder, train, transform):
from io import BytesIO
import pyarrow.parquet as pq
from PIL import Image
self._bytes_io, self._image = BytesIO, Image
split = 'train' if train else 'test'
files = sorted(Path(folder).glob(f'{split}-*.parquet'))
if not files:
raise FileNotFoundError(f'No hay parquet para {split} en {folder}')
self.rows = []
limit = (128 if train else 64) if quick else None
for path in files:
reader = pq.ParquetFile(path)
for batch in reader.iter_batches(batch_size=limit or 1024, columns=['img', 'label']):
if limit is not None:
batch = batch.slice(0, max(0, limit - len(self.rows)))
self.rows.extend(batch.to_pylist())
if limit is not None and len(self.rows) >= limit:
break
if limit is not None and len(self.rows) >= limit:
break
self.transform = transform
def __len__(self):
return len(self.rows)
def __getitem__(self, index):
row = self.rows[index]
image = self._image.open(self._bytes_io(row['img']['bytes'])).convert('RGB')
return self.transform(image), row['label']
class CausalConv(nn.Conv2d):
def __init__(self, inputs, outputs, stream, first):
kernel = (3, 3) if stream == 'vertical' else (1, 3)
super().__init__(inputs, outputs, kernel, padding=(kernel[0] // 2, 1))
mask = torch.zeros_like(self.weight)
if stream == 'vertical':
mask[:, :, 0, :] = 1
if not first:
# Las características verticales de esta fila ya solo ven filas anteriores.
mask[:, :, 1, :] = 1
else:
mask[:, :, 0, 0] = 1
if not first:
mask[:, :, 0, 1] = 1
self.register_buffer('mask', mask)
def forward(self, x):
return F.conv2d(x, self.weight * self.mask, self.bias, padding=self.padding)
def gate(z):
a, b = z.chunk(2, dim=1)
return torch.tanh(a) * torch.sigmoid(b)
class GatedBlock(nn.Module):
def __init__(self, inputs, width, first=False):
super().__init__()
self.first = first
self.v = CausalConv(inputs, 2 * width, 'vertical', first)
self.h = CausalConv(inputs, 2 * width, 'horizontal', first)
self.v_to_h = nn.Conv2d(2 * width, 2 * width, 1)
self.cond = nn.Embedding(10, 4 * width)
self.h_out = nn.Conv2d(width, width, 1)
def forward(self, vertical, horizontal, labels):
vc, hc = self.cond(labels).unsqueeze(-1).unsqueeze(-1).chunk(2, dim=1)
va = self.v(vertical) + vc
ha = self.h(horizontal) + self.v_to_h(va) + hc
v_next = gate(va)
h_next = self.h_out(gate(ha))
if not self.first:
h_next = h_next + horizontal
return v_next, h_next
class PixelCNN(nn.Module):
def __init__(self, channels, head):
super().__init__()
self.channels, self.head = channels, head
self.stack = nn.ModuleList([GatedBlock(channels, width, first=True)] +
[GatedBlock(width, width) for _ in range(blocks - 1)])
out = channels * (256 if head == 'softmax' else 3 * mixtures)
self.output = nn.Sequential(nn.ReLU(), nn.Conv2d(width, width, 1), nn.ReLU(), nn.Conv2d(width, out, 1))
def forward(self, x, labels):
v = h = x
for block in self.stack:
v, h = block(v, h, labels)
return self.output(h)
def unpack_logistics(raw, channels):
b, _, h, w = raw.shape
z = raw.reshape(b, channels, 3, mixtures, h, w)
return z[:, :, 0], z[:, :, 1], z[:, :, 2].clamp(-7, 7)
def pixel_nll(raw, pixels, head):
b, channels, h, w = pixels.shape
if head == 'softmax':
logits = raw.reshape(b, channels, 256, h, w)
return F.cross_entropy(logits.reshape(b * channels, 256, h, w),
pixels.reshape(b * channels, h, w), reduction='none').reshape(b, channels, h, w)
weights, mu, log_s = unpack_logistics(raw, channels)
x = (pixels.float() / 127.5 - 1).unsqueeze(2)
inv_s = torch.exp(-log_s)
upper = (x + 1 / 255 - mu) * inv_s
lower = (x - 1 / 255 - mu) * inv_s
# log(sigmoid(upper) - sigmoid(lower)), sin restar dos CDF casi iguales.
interior = F.logsigmoid(upper) + F.logsigmoid(-lower) + torch.log(-torch.expm1(-2 * inv_s / 255))
log_mass = torch.where(pixels.unsqueeze(2) == 0, F.logsigmoid(upper), interior)
log_mass = torch.where(pixels.unsqueeze(2) == 255, F.logsigmoid(-lower), log_mass)
return -torch.logsumexp(F.log_softmax(weights, dim=2) + log_mass, dim=2)
def as_pixels(images):
if quick:
images = images[:, :, ::4, ::4]
return (images.to(device) * 255).round().clamp(0, 255).long()
def check_causality(model, channels):
# Cambiar el píxel objetivo y todos sus futuros no debe afectar su salida.
model.eval()
x = torch.randn(1, channels, 6, 6, device=device)
y = x.clone()
y[:, :, 2, 3:] += 1.7
y[:, :, 3:, :] -= 2.1
labels = torch.zeros(1, dtype=torch.long, device=device)
with torch.no_grad():
a = model(x, labels)[:, :, 2, 3]
b = model(y, labels)[:, :, 2, 3]
assert torch.allclose(a, b, atol=1e-6, rtol=0), 'fuga en el orden raster'
@torch.no_grad()
def generate(model, labels, shape):
model.eval()
n, channels, h, w = shape
canvas = torch.zeros(shape, dtype=torch.long, device=device)
for row in range(h):
for col in range(w):
raw = model(canvas.float() / 127.5 - 1, labels)
if model.head == 'softmax':
logits = raw.reshape(n, channels, 256, h, w)[:, :, :, row, col]
choice = torch.multinomial(torch.softmax(logits.reshape(-1, 256), dim=1), 1)
canvas[:, :, row, col] = choice.reshape(n, channels)
else:
weights, mu, log_s = unpack_logistics(raw, channels)
weights, mu, log_s = (z[:, :, :, row, col] for z in (weights, mu, log_s))
k = torch.multinomial(torch.softmax(weights.reshape(-1, mixtures), dim=1), 1)
mean = mu.reshape(-1, mixtures).gather(1, k).reshape(n, channels)
scale = log_s.reshape(-1, mixtures).gather(1, k).reshape(n, channels).exp()
u = torch.rand(n, channels, device=device).clamp(1e-6, 1 - 1e-6)
sample = mean + scale * (torch.log(u) - torch.log1p(-u))
canvas[:, :, row, col] = ((sample + 1) * 127.5).round().clamp(0, 255).long()
return canvas
def sync():
if device.type == 'cuda':
torch.cuda.synchronize()
def experiment(dataset_name, head):
parquet_folder = os.environ.get('ORYON_CIFAR_PARQUET')
if dataset_name == 'CIFAR-10' and parquet_folder:
train_all = ParquetCIFAR(parquet_folder, train=True, transform=transform)
test_all = ParquetCIFAR(parquet_folder, train=False, transform=transform)
else:
dataset = datasets.FashionMNIST if dataset_name == 'Fashion-MNIST' else datasets.CIFAR10
train_all = dataset(root, train=True, transform=transform, download=True)
test_all = dataset(root, train=False, transform=transform, download=True)
train = Subset(train_all, range(128)) if quick else train_all
test = Subset(test_all, range(64)) if quick else test_all
generator = torch.Generator().manual_seed(17)
train_loader = DataLoader(train, batch_size=batch_size, shuffle=True, generator=generator, num_workers=0)
test_loader = DataLoader(test, batch_size=batch_size, shuffle=False, num_workers=0)
images, _ = next(iter(train_loader))
channels = images.shape[1]
torch.manual_seed(13)
model = PixelCNN(channels, head).to(device)
check_causality(model, channels)
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
model.train()
sync()
start = time.perf_counter()
processed = 0
for epoch in range(epochs):
for images, labels in train_loader:
pixels = as_pixels(images)
labels = labels.to(device)
optimizer.zero_grad(set_to_none=True)
raw = model(pixels.float() / 127.5 - 1, labels)
loss = pixel_nll(raw, pixels, head).mean()
loss.backward()
optimizer.step()
processed += len(pixels)
print(dataset_name, head, 'época', epoch + 1, 'última NLL por dimensión:', round(loss.item(), 4))
sync()
train_per_image = (time.perf_counter() - start) / processed
total_nll = dimensions = 0
model.eval()
with torch.no_grad():
for images, labels in test_loader:
pixels = as_pixels(images)
raw = model(pixels.float() / 127.5 - 1, labels.to(device))
total_nll += pixel_nll(raw, pixels, head).sum().item()
dimensions += pixels.numel()
print(dataset_name, head, 'test bpd condicionado a clase:', round(total_nll / (dimensions * math.log(2)), 4))
h, w = as_pixels(images).shape[-2:]
labels = torch.tensor([0, 1], device=device)
sync()
start = time.perf_counter()
samples = generate(model, labels, (len(labels), channels, h, w))
sync()
sample_per_image = (time.perf_counter() - start) / len(labels)
print('Cociente muestreo / entrenamiento por imagen en esta ejecución:', round(sample_per_image / train_per_image, 2))
fig, axes = plt.subplots(1, len(labels), figsize=(5, 2.5))
for i, ax in enumerate(axes):
image = samples[i].cpu().numpy().transpose(1, 2, 0) / 255
ax.imshow(image[:, :, 0], cmap='gray', vmin=0, vmax=1) if channels == 1 else ax.imshow(image)
ax.set_title(f'Clase {int(labels[i])}')
ax.axis('off')
plt.show()
del model, optimizer, samples
if device.type == 'cuda':
torch.cuda.empty_cache()
print('Dispositivo:', device, '| prueba corta:', quick)
for dataset_name in ('Fashion-MNIST', 'CIFAR-10'):
for head in ('softmax', 'logistica'):
experiment(dataset_name, head)npm run lab and open the connection link.Each head defines normalized discrete probabilities. NLL is summed over channels and pixels and divided by their count and by ln(2) to report bpd conditioned on the known class: it is not directly comparable to unconditional bpd. To generate, the network calculates a distribution for the next pixel from the partial canvas. In the logistic head, clipping uniforms avoids infinite logarithms and approximates sampling tails; evaluation mass is calculated separately. Perturbation may hide paths through cancellation or saturation, so the guarantee comes from the causal structure of masks and connections. Comparing training-batch cost with one ancestral sample is not just counting identical operations: evaluation repeats per position, and batch size and backward-pass work differ.
Exercises
Step 1 of 3. What is the mass of an interior level?
discretized_logistic_mixture_nll(x, logit_pi, mu, log_s) with NumPy. x contains integers from 0 to 255 and parameters have K components on the final axis, with standard NumPy broadcasting. Rescale to [-1,1], accumulate tails at the endpoints, calculate interior log-masses with expm1, and combine components using logsumexp. Return NLL per observation. Tests use finite parameters and moderate positive scales.import numpy as np
def discretized_logistic_mixture_nll(x, logit_pi, mu, log_s):
passMasks make a convolution causal; two stacks improve connectivity without looking into the future. A discrete intensity distribution must assign mass to intervals and tails, and bits per dimension measure that mass in comparable units. In audio, dilation expands the visible past without removing sequential generation.