Normalizing flows: change of variables and coupling layers
Build normalizing flows as differentiable bijections with tractable density, sampling and latent inference. Develop planar flows, NICE and RealNVP affine coupling, multiscale architectures and Glow, then derive dequantization for discrete pixels.
After this lesson you can
- Write a composed flow's log-density as a sum of log-determinants and train by maximum likelihood.
- Prove the affine-coupling Jacobian is triangular and calculate its inverse and log-determinant.
- Implement RealNVP from scratch and numerically verify its inverse and determinant.
- Implement invertible 1×1 convolution with LU parameterization.
- Derive the uniform dequantization bound and correctly report bits per dimension.
Before you start
A transformation traversable in both directions
Imagine a Gaussian cloud drawn on an elastic sheet. Stretching near a point spreads the same probability over more area and lowers density; compressing another region raises it. A flow learns a reversible deformation: map data to a simple distribution to evaluate density, and traverse the deformation backward to generate a sample.
Reversibility imposes a trade-off. An arbitrary network can fold or squash regions, but may then lack a unique inverse or nonzero determinant. A flow gives up that local freedom for latent inference and evaluable density. Evaluation is exact for the model’s continuous density up to numerical error; converting it to a probability of discrete images requires another step.
Here use the data-to-latent convention. For , and ,
The chain rule multiplies Jacobians, and a product’s determinant multiplies determinants. Maximum-likelihood training minimizes the negative of this sum. To generate, draw and compute . Reversing a layer changes the sign of its log-determinant, evaluated at the corresponding point. Review change of variables and Jacobian composition to follow every step.
A general Jacobian matrix is expensive to form and factorize. We want layers that are invertible, have cheap log-determinants and combine into expressive transformations. The second property is an architectural choice, not an automatic consequence of the first.
A first step: low-rank transformations
For the planar layer, . The matrix determinant lemma reduces the computation to
For , enforcing ensures this determinant is positive everywhere. Equality requires care: the Jacobian can vanish and the inverse cease to be differentiable. This formula is cheap when is known, but evaluating external data first requires finding satisfying . For a generic planar layer this inverse is not an elementary analytic operation available for every input; an implicit problem must be solved. Transformation direction therefore matters when choosing an architecture for density estimation.
For the radial layer, with , tangential eigenvalues are and the radial eigenvalue is . There are of the former and one of the latter. Strict condition keeps them positive; at interpret them by continuity. Both types illustrate exploiting structure to compute determinants, but each individual layer deforms the distribution in a restricted manner. Rezende and Mohamed introduce them for variational inference.
Coupling: one half conditions the other
Differentiating in order gives a block-triangular matrix:
The determinant of the complicated lower-left block is unnecessary. Additive NICE uses and preserves volume; RealNVP adds scale. One layer leaves half unchanged, so alternate masks or permute coordinates to let all change. It is common to bound , for example using , to avoid huge initial exponentials. This improves numerical stability but does not by itself guarantee a good fit.
A diffeomorphism of a Gaussian with positive density throughout the plane cannot produce support consisting of exactly two disconnected components. It can concentrate density in two regions with a low-density bridge between them. Evaluate fit on held-out data, not only the appearance of a training sample.
Multiple scales and channel mixing
RealNVP alternates checkerboard and channel masks; after several layers it can split off channels as latents and continue transforming the rest. Log-density includes all split parts and the final part with their base distributions. Forgetting one changes the model. Squeeze adds no scale correction: it neither divides values nor changes volume, only rearranges them.
Glow uses steps consisting of ActNorm, invertible convolution and coupling. ActNorm learns a per-channel scale and shift, initialized once with a batch; its log-determinant multiplies the sum of log-scales by . On resumption, loading state must also preserve the initialization flag to avoid overwriting learned parameters.
The convolution applies the same matrix at every position. If , is a permutation, has unit diagonal and has nonzero diagonal, then
Parameterizing keeps that diagonal nonzero. Summing costs , although applying the transformation across the whole image still requires operations over channels and positions. The inverse can solve triangular systems instead of explicitly forming a matrix inverse. Fixed permutation and signs define a local parameterization, not every possible factorization of every matrix without changing chart.
Sampling temperature multiplies base-noise deviation. A temperature other than one changes the generated distribution; trained log-likelihood corresponds to the base declared during training. Compare samples with other decisions fixed.
From discrete pixels to continuous densities
Density at a pixel’s center is not its probability. A density can in fact concentrate ever more narrowly around each discrete datum and increase pointwise log-density without bound, without solving the problem of assigning mass to cells. The figure illustrates the difference with a model whose mass can be integrated.
By log concavity, whenever the integral exists,
Thus upper-bounds code length in nats per dimension; dividing by gives bits per dimension. For this yields . One Monte Carlo realization estimates the expectation but need not satisfy the inequality by itself. If the continuous model assigns mass outside , the pixel cells do not collect all its mass: declare how the exterior is treated or define a normalized model on the cube.
Variational dequantization uses density on , positive almost everywhere that . Expressing the integral as an expectation under that density and applying Jensen gives
Flow++ studies this alternative; reported improvement depends on architecture and protocol, so do not attribute the whole difference to one decision.
Lab: RealNVP from scratch
First implement two-coordinate couplings before working with images. Verify inverse and determinant against finite differences; then fit by maximum likelihood on training data and retain an independent validation sample. Lower loss is evidence of fit under that metric, not a visual guarantee of perfect two moons.
Here each subnetwork parameterizes the base-to-data direction, . Density evaluation uses its inverse , contributing to the log-determinant. Layers are also inverted in reverse order during generation. This convention differs from the general formula above and must give the same change of variables.
The density-evaluation direction maps data to a standard normal. Each coupling preserves one coordinate and transforms the other using a tanh-bounded scale and translation computed by a small network. Each parameter’s backward pass is written manually; central differences check it, and inverse and log-determinant are compared with a numerical Jacobian. Then Adam optimizes NLL and independent validation is reported. The experiment uses analytical two moons with Gaussian noise, requires no scikit-learn and uses fixed seeds.
The cell trains six layers for 1700 steps. Falling validation NLL is limited evidence for this distribution and does not guarantee all samples are good. EXPORT contains weights and points used by the figure; the figure applies the same equations without inventing samples. To use weights outside the browser, serialize EXPORT as JSON.
"""RealNVP 2D desde cero. Los parámetros se reproducen con la semilla indicada."""
import numpy as np
SEED = 1221
HIDDEN = 16
LAYERS = 6
STEPS = 1700
BATCH = 128
LEARNING_RATE = 0.008
NOISE = 0.06
SCALE_BOUND = 1.0
def moons(n, seed):
rng = np.random.default_rng(seed)
angle = rng.uniform(0.0, np.pi, n)
half = rng.integers(0, 2, n)
c, s = np.cos(angle), np.sin(angle)
x = np.column_stack((np.where(half == 0, c, 1 - c),
np.where(half == 0, s, 0.5 - s)))
return x + rng.normal(0, NOISE, x.shape)
def init_layers():
rng = np.random.default_rng(SEED)
return [{'axis': i % 2, 'w1': rng.normal(0, 0.4, HIDDEN),
'b1': rng.normal(0, 0.1, HIDDEN),
'w2': rng.normal(0, 0.03, (HIDDEN, 2)),
'b2': np.zeros(2)} for i in range(LAYERS)]
def conditioner(a, layer):
hidden = np.tanh(a[:, None] * layer['w1'] + layer['b1'])
raw = hidden @ layer['w2'] + layer['b2']
return hidden, raw, SCALE_BOUND * np.tanh(raw[:, 0]), raw[:, 1]
def to_base(x, layers, cache=False):
state = np.asarray(x, dtype=np.float64).copy()
log_det_inverse = np.zeros(len(state))
saved = []
for layer in layers:
a_idx = layer['axis']
b_idx = 1 - a_idx
a, b = state[:, a_idx].copy(), state[:, b_idx].copy()
hidden, raw, s, t = conditioner(a, layer)
u = (b - t) * np.exp(-s)
state[:, b_idx] = u
log_det_inverse -= s
if cache:
saved.append((a, u, hidden, raw, s))
return state, log_det_inverse, saved
def from_base(z, layers):
state = np.asarray(z, dtype=np.float64).copy()
log_det_forward = np.zeros(len(state))
for layer in reversed(layers):
a_idx = layer['axis']
b_idx = 1 - a_idx
_, _, s, t = conditioner(state[:, a_idx], layer)
state[:, b_idx] = state[:, b_idx] * np.exp(s) + t
log_det_forward += s
return state, log_det_forward
def nll(x, layers):
z, logdet, _ = to_base(x, layers)
return float(np.mean(0.5 * np.sum(z * z, axis=1) + np.log(2 * np.pi) - logdet))
def loss_and_grad(x, layers):
z, logdet, saved = to_base(x, layers, cache=True)
n = len(x)
loss = float(np.mean(0.5 * np.sum(z * z, axis=1) + np.log(2 * np.pi) - logdet))
upstream = z / n
gradients = [None] * len(layers)
for i in range(len(layers) - 1, -1, -1):
layer = layers[i]
a, u, hidden, raw, s = saved[i]
a_idx, b_idx = layer['axis'], 1 - layer['axis']
g_u = upstream[:, b_idx]
g_b = g_u * np.exp(-s)
g_s = 1 / n - g_u * u
g_raw = np.column_stack((g_s * SCALE_BOUND * (1 - np.tanh(raw[:, 0]) ** 2), -g_b))
gradients[i] = {'w2': hidden.T @ g_raw, 'b2': g_raw.sum(axis=0)}
g_hidden = (g_raw @ layer['w2'].T) * (1 - hidden ** 2)
gradients[i]['w1'] = (a[:, None] * g_hidden).sum(axis=0)
gradients[i]['b1'] = g_hidden.sum(axis=0)
previous = np.empty_like(upstream)
previous[:, a_idx] = upstream[:, a_idx] + g_hidden @ layer['w1']
previous[:, b_idx] = g_b
upstream = previous
return loss, gradients
def check_gradients(layers, x):
# Cada parámetro de ambas máscaras se coteja con diferencias centrales.
_, grads = loss_and_grad(x, layers)
epsilon, largest = 1e-5, 0.0
for layer, grad in zip(layers, grads):
for key in ('w1', 'b1', 'w2', 'b2'):
for index in np.ndindex(layer[key].shape):
original = layer[key][index]
layer[key][index] = original + epsilon
plus = nll(x, layers)
layer[key][index] = original - epsilon
minus = nll(x, layers)
layer[key][index] = original
numeric = (plus - minus) / (2 * epsilon)
largest = max(largest, abs(numeric - grad[key][index]))
return largest
def check_jacobian(layers, x):
z, logdet, _ = to_base(x[None], layers)
back, inverse_logdet = from_base(z, layers)
epsilon = 1e-5
jacobian = np.column_stack([(to_base((x + np.eye(2)[i] * epsilon)[None], layers)[0][0] -
to_base((x - np.eye(2)[i] * epsilon)[None], layers)[0][0]) / (2 * epsilon)
for i in range(2)])
return float(np.max(np.abs(back[0] - x))), float(abs(logdet[0] + inverse_logdet[0])), float(abs(np.linalg.slogdet(jacobian)[1] - logdet[0]))
layers = init_layers()
training = moons(2048, 1222)
validation = moons(1024, 1223)
gradient_error = check_gradients(layers, training[:7])
assert gradient_error < 1e-6
before_train, before_val = nll(training, layers), nll(validation, layers)
random = np.random.default_rng(1224)
first = [{key: np.zeros_like(layer[key]) for key in ('w1', 'b1', 'w2', 'b2')} for layer in layers]
second = [{key: np.zeros_like(layer[key]) for key in ('w1', 'b1', 'w2', 'b2')} for layer in layers]
for step in range(1, STEPS + 1):
indices = random.integers(0, len(training), BATCH)
_, grads = loss_and_grad(training[indices], layers)
for layer, grad, m, v in zip(layers, grads, first, second):
for key in ('w1', 'b1', 'w2', 'b2'):
m[key] = 0.9 * m[key] + 0.1 * grad[key]
v[key] = 0.999 * v[key] + 0.001 * grad[key] ** 2
mhat = m[key] / (1 - 0.9 ** step)
vhat = v[key] / (1 - 0.999 ** step)
layer[key] -= LEARNING_RATE * mhat / (np.sqrt(vhat) + 1e-8)
after_train, after_val = nll(training, layers), nll(validation, layers)
inverse_error, logdet_error, jacobian_error = check_jacobian(layers, validation[0])
assert max(inverse_error, logdet_error, jacobian_error) < 1e-6
sample_z = np.random.default_rng(1225).normal(size=(256, 2))
samples, _ = from_base(sample_z, layers)
print(f'NLL train: {before_train:.5f} → {after_train:.5f} nats; validación: {before_val:.5f} → {after_val:.5f} nats')
print(f'Error máximo de gradiente: {gradient_error:.2e}; inversa: {inverse_error:.2e}; logdet: {logdet_error:.2e}; jacobiano: {jacobian_error:.2e}')
EXPORT = {'schema': 1, 'seed': SEED, 'dataset': {'name': 'dos lunas analíticas',
'noise_std': NOISE, 'train_seed': 1222, 'validation_seed': 1223,
'normalization': 'ninguna', 'validation_points': validation[:256].tolist()},
'training': {'steps': STEPS, 'batch': BATCH, 'learning_rate': LEARNING_RATE,
'scale_bound': SCALE_BOUND, 'train_nll_before': before_train, 'train_nll_after': after_train,
'validation_nll_before': before_val, 'validation_nll_after': after_val},
'checks': {'gradient_error': gradient_error, 'inverse_error': inverse_error,
'logdet_error': logdet_error, 'jacobian_error': jacobian_error},
'sample_seed': 1225, 'base_samples': sample_z.tolist(),
'samples': samples.tolist(),
'layers': [{'axis': layer['axis'], 'w1': layer['w1'].tolist(), 'b1': layer['b1'].tolist(),
'w2': layer['w2'].tolist(), 'b2': layer['b2'].tolist()} for layer in layers]}
Exercises
Step 1 of 3. Which derivative block is zero?
Step 1 of 3. What factor does v=(q+u)/K introduce into the integral?
import torch
from torch import nn
class InvertibleConv1x1(nn.Module):
def __init__(self, W):
super().__init__()
# Factoriza W e inicializa parámetros y buffers.
def matrix(self):
pass
def forward(self, x, reverse=False):
passThe log-determinant calculation sums numbers. Applying and to spatial positions requires more work; do not infer from the sum’s cost that the entire convolution is linear in .
Lab: multiscale flow for images
The next experiment combines ActNorm, invertible convolution and couplings across two scales. The full run trains the reader’s model; quick mode checks the workflow and does not demonstrate sample quality or reproduce Glow numbers. Reserve validation for checkpoint selection and evaluate test only after choosing it.
Implement an educational two-scale PyTorch flow for MNIST and CIFAR-10. Each step contains ActNorm, LU-based invertible 1×1 convolution and affine coupling with bounded scale. Squeeze is a permutation and does not change log-determinant. Half the channels are split off at the first scale; both latent parts have independent standard-normal priors. That prior simplifies the model and does not reproduce the conditional prior or complete published Glow architecture.
Before training, check inverse, logdet sign and sum, LU determinant against torch.linalg.slogdet, the full Jacobian on a tiny input, gradients and preservation of ActNorm initialization on state reload. Convolution uses LU to compute logdet as a sum linear in channel count; building and applying the dense matrix has additional costs. Inversion solves two triangular systems.
Install torch, torchvision, numpy and pillow. MNIST runs by default; set ORYON_DATASET to cifar10 or both for the other dataset or both. ORYON_DATA_ROOT selects the data folder and ORYON_OUTPUT_DIR the results folder. The full protocol uses two scales, four steps per scale, width 64, batch 32 and 50 epochs per dataset. Reserve 5000 training images for checkpoint selection and evaluate official test only afterward. This does not replicate the paper’s budget or guarantee published figures.
To check the workflow, ORYON_QUICK=1 reduces training to 64 images, validation and test to 32 each, one epoch, one step per scale and width 8. Only in that mode, ORYON_CIFAR_PARQUET can point to a folder containing CIFAR-10 train-*.parquet and test-*.parquet; it requires pyarrow and avoids another test download. This uses the first 64 and next 32 training images, and first 32 test images; it is a functional check, not representative evaluation.
The entire image is dequantized with uniform noise and divided by 256, then logit is applied. The flow defines density over the whole continuous image cube, so 256-value cells per channel form a discrete distribution. The logit term and 8-bit correction per component appear in the calculation. Reported bpd uses one noise sample per image: it estimates an upper bound in expectation for discrete bpd, but one realization need not itself be a bound. The generator produces sigmoids in the cube; temperature other than 1 changes the sampling distribution. Grids show temperatures 0, 0.7 and 1 with a fixed seed.
ultimo.pt, mejor.pt, metrics and grids are saved per dataset. To resume, keep that folder and set ORYON_RESUME to ultimo.pt, with the same dataset and source; ORYON_EPOCHS is total epochs and must exceed the saved count. Optimizer, random generators and ActNorm buffers are restored. Seeds facilitate repetition but do not guarantee identical results across devices or libraries.
"""Flujo multiescala educativo: MNIST o CIFAR-10, PyTorch, sin dependencias de la lección.
ORYON_DATASET=mnist|cifar10|both; ORYON_DATA_ROOT; ORYON_OUTPUT_DIR;
ORYON_QUICK=1 para prueba corta; ORYON_RESUME para reanudar un dataset;
ORYON_EPOCHS define el número total de épocas, no las épocas adicionales.
ORYON_CIFAR_PARQUET permite verificar CIFAR con datos cacheados solo en quick.
"""
import copy
import csv
import io
import math
import os
from pathlib import Path
import numpy as np
import torch
from PIL import Image
from torch import nn
from torch.nn import functional as F
from torch.utils.data import DataLoader, Dataset, Subset
from torchvision import datasets, transforms
from torchvision.utils import save_image
torch.set_num_threads(2)
LOG2 = math.log(2.0)
LOG2PI = math.log(2.0 * math.pi)
def squeeze(x):
b, c, h, w = x.shape
if h % 2 or w % 2:
raise ValueError('La altura y la anchura deben ser pares')
return x.reshape(b, c, h // 2, 2, w // 2, 2).permute(0, 1, 3, 5, 2, 4).reshape(b, c * 4, h // 2, w // 2)
def unsqueeze(x):
b, c, h, w = x.shape
if c % 4:
raise ValueError('Los canales deben ser múltiplo de cuatro')
return x.reshape(b, c // 4, 2, 2, h, w).permute(0, 1, 4, 2, 5, 3).reshape(b, c // 4, h * 2, w * 2)
class ActNorm(nn.Module):
def __init__(self, channels):
super().__init__()
self.bias = nn.Parameter(torch.zeros(1, channels, 1, 1))
self.log_scale = nn.Parameter(torch.zeros(1, channels, 1, 1))
self.register_buffer('initialized', torch.tensor(False))
def forward(self, x, reverse=False):
if not bool(self.initialized):
if reverse or not self.training:
raise RuntimeError('ActNorm necesita inicialización con un lote de entrenamiento')
with torch.no_grad():
mean = x.mean((0, 2, 3), keepdim=True)
std = x.std((0, 2, 3), unbiased=False, keepdim=True).clamp_min(1e-4)
self.bias.copy_(-mean)
self.log_scale.copy_(-torch.log(std))
self.initialized.fill_(True)
ld = x.shape[2] * x.shape[3] * self.log_scale.sum()
if reverse:
return x * torch.exp(-self.log_scale) - self.bias, (-ld).expand(x.shape[0])
return (x + self.bias) * torch.exp(self.log_scale), ld.expand(x.shape[0])
class InvConv(nn.Module):
def __init__(self, channels):
super().__init__()
q, _ = torch.linalg.qr(torch.randn(channels, channels))
p, l, u = torch.linalg.lu(q)
diagonal = torch.diagonal(u)
self.register_buffer('permutation', p)
self.register_buffer('diagonal_sign', diagonal.sign())
self.register_buffer('identity', torch.eye(channels))
self.lower = nn.Parameter(torch.tril(l, diagonal=-1))
self.upper = nn.Parameter(torch.triu(u, diagonal=1))
self.log_diagonal = nn.Parameter(diagonal.abs().log())
def factors(self):
l = torch.tril(self.lower, diagonal=-1) + self.identity
u = torch.triu(self.upper, diagonal=1) + torch.diag(self.diagonal_sign * self.log_diagonal.exp())
return l, u
def matrix(self):
l, u = self.factors()
return self.permutation @ l @ u
def forward(self, x, reverse=False):
b, c, h, w = x.shape
l, u = self.factors()
ld = h * w * self.log_diagonal.sum()
if reverse:
rhs = x.permute(1, 0, 2, 3).reshape(c, -1)
rhs = self.permutation.T @ rhs
rhs = torch.linalg.solve_triangular(l, rhs, upper=False, unitriangular=True)
rhs = torch.linalg.solve_triangular(u, rhs, upper=True)
return rhs.reshape(c, b, h, w).permute(1, 0, 2, 3), (-ld).expand(b)
weight = self.permutation @ l @ u
return F.conv2d(x, weight[:, :, None, None]), ld.expand(b)
class Coupling(nn.Module):
def __init__(self, channels, width):
super().__init__()
if channels % 2:
raise ValueError('El acoplamiento necesita canales pares')
half = channels // 2
self.net = nn.Sequential(nn.Conv2d(half, width, 3, padding=1), nn.ReLU(),
nn.Conv2d(width, width, 1), nn.ReLU(),
nn.Conv2d(width, channels, 3, padding=1))
nn.init.zeros_(self.net[-1].weight)
nn.init.zeros_(self.net[-1].bias)
def forward(self, x, reverse=False):
a, b = x.chunk(2, dim=1)
raw, shift = self.net(a).chunk(2, dim=1)
scale = 1.5 * torch.tanh(raw)
ld = scale.flatten(1).sum(1)
if reverse:
return torch.cat((a, (b - shift) * torch.exp(-scale)), dim=1), -ld
return torch.cat((a, b * torch.exp(scale) + shift), dim=1), ld
class FlowStep(nn.Module):
def __init__(self, channels, width):
super().__init__()
self.layers = nn.ModuleList((ActNorm(channels), InvConv(channels), Coupling(channels, width)))
def forward(self, x, reverse=False):
ld = x.new_zeros(x.shape[0])
layers = reversed(self.layers) if reverse else self.layers
for layer in layers:
x, contribution = layer(x, reverse=reverse)
ld = ld + contribution
return x, ld
class MultiScaleGlow(nn.Module):
def __init__(self, channels, steps=4, width=64):
super().__init__()
self.channels, self.steps, self.width = channels, steps, width
self.first = nn.ModuleList(FlowStep(4 * channels, width) for _ in range(steps))
self.second = nn.ModuleList(FlowStep(8 * channels, width) for _ in range(steps))
@staticmethod
def apply_level(x, level, reverse=False):
ld = x.new_zeros(x.shape[0])
for layer in reversed(level) if reverse else level:
x, delta = layer(x, reverse=reverse)
ld = ld + delta
return x, ld
def encode(self, x):
x, logdet = self.apply_level(squeeze(x), self.first)
z1, x = x.chunk(2, dim=1)
z2, ld = self.apply_level(squeeze(x), self.second)
return (z1, z2), logdet + ld
def decode(self, latents):
z1, z2 = latents
x, logdet = self.apply_level(z2, self.second, reverse=True)
x = torch.cat((z1, unsqueeze(x)), dim=1)
x, ld = self.apply_level(x, self.first, reverse=True)
return unsqueeze(x), logdet + ld
def log_prob(self, x):
zs, logdet = self.encode(x)
log_prior = sum((-0.5 * (z.square() + LOG2PI)).flatten(1).sum(1) for z in zs)
return log_prior + logdet
def sample(self, batch, height, width, temperature, device):
z1 = temperature * torch.randn(batch, 2 * self.channels, height // 2, width // 2, device=device)
z2 = temperature * torch.randn(batch, 8 * self.channels, height // 4, width // 4, device=device)
y, _ = self.decode((z1, z2))
return torch.sigmoid(y)
def dequantize(pixels, noise_generator, device):
# float64 evita que 255 + u se redondee a 256 antes de logit.
raw = pixels.to(dtype=torch.float64, device='cpu')
u = torch.rand(raw.shape, dtype=torch.float64, generator=noise_generator)
v = ((raw + u) / 256.0).clamp(torch.finfo(torch.float64).eps, 1 - torch.finfo(torch.float64).eps)
logit = torch.log(v) - torch.log1p(-v)
log_jac = -(torch.log(v) + torch.log1p(-v)).flatten(1).sum(1)
return logit.to(device=device, dtype=torch.float32), log_jac.to(device=device, dtype=torch.float32)
def bpd(model, pixels, noise_generator, device):
y, log_jac = dequantize(pixels, noise_generator, device)
dimension = pixels[0].numel()
return 8.0 - (model.log_prob(y) + log_jac) / (dimension * LOG2)
def verify_flow(device):
torch.manual_seed(200)
fresh = ActNorm(2).to(device).eval()
try:
fresh(torch.ones(1, 2, 2, 2, device=device), reverse=True)
except RuntimeError:
pass
else:
raise AssertionError('La inversa de ActNorm no inicializada debe fallar')
model = MultiScaleGlow(1, steps=1, width=8).to(device).double().train()
x = torch.randn(2, 1, 4, 4, device=device, dtype=torch.float64)
assert torch.equal(unsqueeze(squeeze(x)), x)
model.encode(x) # Inicializa ActNorm antes de probar un acoplamiento no trivial.
with torch.no_grad():
for step in list(model.first) + list(model.second):
step.layers[2].net[-1].weight.normal_(0, 0.02)
step.layers[2].net[-1].bias.normal_(0, 0.02)
z, ld = model.encode(x)
restored, inverse_ld = model.decode(z)
assert sum(t[0].numel() for t in z) == x[0].numel()
assert torch.allclose(restored, x, rtol=1e-8, atol=1e-8)
assert torch.allclose(ld + inverse_ld, torch.zeros_like(ld), atol=1e-8)
for step in list(model.first) + list(model.second):
conv = step.layers[1]
assert torch.allclose(torch.linalg.slogdet(conv.matrix())[1], conv.log_diagonal.sum(), atol=1e-8)
def packed(t):
zs, _ = model.encode(t.reshape(1, 1, 4, 4))
return torch.cat([z.flatten() for z in zs])
jac = torch.autograd.functional.jacobian(packed, x[0].flatten())
assert torch.allclose(torch.linalg.slogdet(jac)[1], ld[0], atol=1e-8, rtol=1e-8)
loss = -model.log_prob(x).mean()
loss.backward()
assert all(p.grad is not None and torch.isfinite(p.grad).all() for p in model.parameters())
snapshot = copy.deepcopy(model.state_dict())
clone = MultiScaleGlow(1, steps=1, width=8).to(device).double().train()
clone.load_state_dict(snapshot)
original_flags = [p.initialized.clone() for p in clone.modules() if isinstance(p, ActNorm)]
shifted = x + 30
clone.encode(shifted)
assert all(bool(flag) for flag in original_flags)
for key in snapshot:
assert torch.equal(snapshot[key], clone.state_dict()[key])
print('Pruebas: squeeze, inversa, suma de logdet, LU, jacobiano completo, gradientes y estado ActNorm correctos.')
del fresh, model, clone, x, z, restored, jac, loss, snapshot
if device.type == 'cuda':
torch.cuda.empty_cache()
class ParquetCifar(Dataset):
def __init__(self, folder, split, start, count):
import pyarrow.parquet as pq
rows = []
for file in sorted(Path(folder).glob(f'{split}-*.parquet')):
for batch in pq.ParquetFile(file).iter_batches(batch_size=128, columns=['img']):
rows.extend(batch.to_pylist())
if len(rows) >= start + count:
break
if len(rows) >= start + count:
break
self.rows = rows[start:start + count]
if len(self.rows) != count:
raise ValueError('El parquet CIFAR no contiene el número de imágenes solicitado')
def __len__(self):
return len(self.rows)
def __getitem__(self, i):
with Image.open(io.BytesIO(self.rows[i]['img']['bytes'])) as image:
return transforms.PILToTensor()(image.convert('RGB')), 0
def get_data(kind, root, quick, parquet):
if kind == 'cifar10' and quick and parquet:
return (ParquetCifar(parquet, 'train', 0, 64), ParquetCifar(parquet, 'train', 64, 32),
ParquetCifar(parquet, 'test', 0, 32))
cls = datasets.MNIST if kind == 'mnist' else datasets.CIFAR10
train_all = cls(root, train=True, download=True, transform=transforms.PILToTensor())
test_all = cls(root, train=False, download=True, transform=transforms.PILToTensor())
indices = torch.randperm(len(train_all), generator=torch.Generator().manual_seed(311)).tolist()
val = indices[:32 if quick else 5000]
train = indices[32:96] if quick else indices[5000:]
return Subset(train_all, train), Subset(train_all, val), Subset(test_all, range(32 if quick else len(test_all)))
def mean_bpd(model, loader, seed, device):
model.eval()
random = torch.Generator().manual_seed(seed)
total, count = 0.0, 0
with torch.no_grad():
for pixels, _ in loader:
values = bpd(model, pixels, random, device)
if not torch.isfinite(values).all():
raise FloatingPointError('El bpd de evaluación no es finito')
total += values.sum().item()
count += len(pixels)
return total / count
def train_one(kind, device, quick, root, outroot, parquet, resume):
channels, side = (1, 28) if kind == 'mnist' else (3, 32)
source = 'parquet' if kind == 'cifar10' and quick and parquet else 'torchvision'
train, val, test = get_data(kind, root, quick, parquet)
batch, steps, width, default_epochs = (8, 1, 8, 1) if quick else (32, 4, 64, 50)
epochs = int(os.environ.get('ORYON_EPOCHS', str(default_epochs)))
if epochs < 1:
raise ValueError('ORYON_EPOCHS debe ser positivo')
output = Path(outroot) / kind
output.mkdir(parents=True, exist_ok=True)
torch.manual_seed(320)
if device.type == 'cuda':
torch.cuda.manual_seed_all(320)
order_rng = torch.Generator().manual_seed(321)
noise_rng = torch.Generator().manual_seed(322)
train_loader = DataLoader(train, batch_size=batch, shuffle=True, generator=order_rng, num_workers=0)
val_loader = DataLoader(val, batch_size=batch, shuffle=False, num_workers=0)
test_loader = DataLoader(test, batch_size=batch, shuffle=False, num_workers=0)
model = MultiScaleGlow(channels, steps=steps, width=width).to(device)
optimizer = torch.optim.Adam(model.parameters(), lr=0.0001)
start, best = 0, float('inf')
if resume:
saved = torch.load(resume, map_location=device, weights_only=True)
if saved['kind'] != kind or saved['config'] != [channels, steps, width] or saved['source'] != source:
raise ValueError('El checkpoint no corresponde al conjunto o arquitectura')
model.load_state_dict(saved['model'])
optimizer.load_state_dict(saved['optimizer'])
start, best = saved['epoch'], saved['best']
order_rng.set_state(saved['order_rng'].cpu())
noise_rng.set_state(saved['noise_rng'].cpu())
torch.set_rng_state(saved['torch_rng'].cpu())
if device.type == 'cuda' and saved['cuda_rng'] is not None:
torch.cuda.set_rng_state_all([s.cpu() for s in saved['cuda_rng']])
if epochs <= start:
raise ValueError('ORYON_EPOCHS debe superar la época guardada para reanudar')
if not (output / 'mejor.pt').is_file():
raise FileNotFoundError('Para reanudar conserva mejor.pt en la carpeta de salida del conjunto')
history = []
for epoch in range(start + 1, epochs + 1):
model.train()
total, count = 0.0, 0
for pixels, _ in train_loader:
optimizer.zero_grad(set_to_none=True)
loss = bpd(model, pixels, noise_rng, device).mean()
if not torch.isfinite(loss):
raise FloatingPointError('La pérdida no es finita')
loss.backward()
nn.utils.clip_grad_norm_(model.parameters(), 5.0, error_if_nonfinite=True)
optimizer.step()
total += float(loss.detach()) * len(pixels)
count += len(pixels)
val_bpd = mean_bpd(model, val_loader, 323, device)
print(f'{kind} época {epoch}: train={total/count:.4f} bpd, validación={val_bpd:.4f} bpd', flush=True)
history.append((epoch, total / count, val_bpd))
improved = val_bpd < best
best = min(best, val_bpd)
checkpoint = {'model': model.state_dict(), 'optimizer': optimizer.state_dict(), 'kind': kind,
'config': [channels, steps, width], 'epoch': epoch, 'best': best, 'quick': quick, 'source': source,
'order_rng': order_rng.get_state(), 'noise_rng': noise_rng.get_state(),
'torch_rng': torch.get_rng_state(),
'cuda_rng': torch.cuda.get_rng_state_all() if device.type == 'cuda' else None}
torch.save(checkpoint, output / 'ultimo.pt')
if improved:
torch.save(checkpoint, output / 'mejor.pt')
history_path = output / 'entrenamiento.csv'
append = bool(resume) and history_path.exists()
with history_path.open('a' if append else 'w', newline='', encoding='utf-8') as file:
writer = csv.writer(file)
if not append:
writer.writerow(('epoca', 'train_bpd', 'validacion_bpd'))
writer.writerows(history)
saved = torch.load(output / 'mejor.pt', map_location=device, weights_only=True)
model.load_state_dict(saved['model'])
assert all(bool(layer.initialized) for layer in model.modules() if isinstance(layer, ActNorm))
test_bpd = mean_bpd(model, test_loader, 324, device)
print(f'{kind} test separado: {test_bpd:.4f} bpd estimados; checkpoint época {saved["epoch"]}', flush=True)
model.eval()
with torch.no_grad():
for temperature in (0.0, 0.7, 1.0):
torch.manual_seed(325)
samples = model.sample(16, side, side, temperature, device)
assert torch.isfinite(samples).all()
save_image(samples, output / f'muestras-T{temperature:.1f}.png', nrow=4)
del model, optimizer, train_loader, val_loader, test_loader, train, val, test, saved, checkpoint
if device.type == 'cuda':
torch.cuda.empty_cache()
def main():
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
quick = os.environ.get('ORYON_QUICK') == '1'
kinds = os.environ.get('ORYON_DATASET', 'mnist').lower()
if kinds not in ('mnist', 'cifar10', 'both'):
raise ValueError('ORYON_DATASET debe ser mnist, cifar10 o both')
resume = os.environ.get('ORYON_RESUME')
if resume and kinds == 'both':
raise ValueError('Reanuda un solo conjunto cada vez')
parquet = os.environ.get('ORYON_CIFAR_PARQUET')
if parquet and not quick:
raise ValueError('ORYON_CIFAR_PARQUET está reservado a la prueba corta')
root = os.environ.get('ORYON_DATA_ROOT', './data')
output = os.environ.get('ORYON_OUTPUT_DIR', './glow-results')
verify_flow(device)
for kind in ('mnist', 'cifar10') if kinds == 'both' else (kinds,):
train_one(kind, device, quick, root, output, parquet, resume)
if __name__ == '__main__':
main()
npm run lab and open the connection link.A flow trades architectural freedom for tractable density and inverse calculations. The determinant describes local deformation; quantization treatment determines how continuous density relates to discrete images.