Module contents
Lesson 12 of 28Core 110 min

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 h0=xh_0=x, hi=fi(hi−1)h_i=f_i(h_{i-1}) and z=hLz=h_L,

log⁡pX(x)=log⁡pZ(z)+∑i=1Llog⁡∣det⁡Jfi(hi−1)∣.\log p_X(x)=\log p_Z(z)+\sum_{i=1}^{L}\log\left|\det J_{f_i}(h_{i-1})\right|.

The chain rule multiplies Jacobians, and a product’s determinant multiplies determinants. Maximum-likelihood training minimizes the negative of this sum. To generate, draw z∼pZz\sim p_Z and compute x=f1−1∘⋯∘fL−1(z)x=f_1^{-1}\circ\cdots\circ f_L^{-1}(z). 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.

InteractiveDensity follows volume

The control points stay in order to keep the transformation invertible.

  • Transformation and density of Z
  • Control points and density of X
  • Probe

Z is standard normal. The function interpolates linearly between knots z = −2, −1, 0, 1, 2 and extends the outermost slopes. The outer heights are fixed and the inner heights are separated by at least 0.15. Each segment therefore has positive slope and the function is a bijection from ℝ to ℝ. Away from the knots, pX(f(z)) = pZ(z)/f′(z). A small slope concentrates density, and a large slope disperses it. The derivative can be undefined at a knot. An isolated density value does not affect any probability.

0.35
x = f(z)
0.350
Slope f′(z)
1.000
Density pZ(z)
0.375
Density pX(x)
0.375
Modify an increasing bijection and compare its slope with transformed density. At the knots of a piecewise function, use one-sided derivatives.

A general DD 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, Jf=I+uw⊤h′(w⊤z+b)J_f=I+u w^\top h'(w^\top z+b). The matrix determinant lemma reduces the computation to

det⁡Jf=1+h′(w⊤z+b)w⊤u.\det J_f=1+h'(w^\top z+b)w^\top u.

For h=tanh⁡h=\tanh, enforcing w⊤u>−1w^\top u>-1 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 zz is known, but evaluating external data xx first requires finding zz satisfying x=f(z)x=f(z). 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 r=∥z−z0∥r=\|z-z_0\|, tangential eigenvalues are 1+β/(α+r)1+\beta/(\alpha+r) and the radial eigenvalue is 1+βα/(α+r)21+\beta\alpha/(\alpha+r)^2. There are D−1D-1 of the former and one of the latter. Strict condition β>−α\beta>-\alpha keeps them positive; at r=0r=0 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 (A,B)(A,B) gives a block-triangular matrix:

J=(I0∂zB/∂xAdiag⁡(exp⁡s(xA))),log⁡∣det⁡J∣=∑jsj(xA).J=\begin{pmatrix}I&0\\ \partial z_B/\partial x_A&\operatorname{diag}(\exp s(x_A))\end{pmatrix}, \qquad \log|\det J|=\sum_j s_j(x_A).

The determinant of the complicated lower-left block is unnecessary. Additive NICE uses s=0s=0 and preserves volume; RealNVP adds scale. One layer leaves half AA unchanged, so alternate masks or permute coordinates to let all change. It is common to bound ss, for example using ctanh⁡(r)c\tanh(r), to avoid huge initial exponentials. This improves numerical stability but does not by itself guarantee a good fit.

InteractiveWarping a Gaussian into two moons

Start from 256 standard Gaussian points and apply the inverse layers in reverse order.

  • Local expansion: log |det J| > 0
  • Local contraction: log |det J| < 0
  • Transformed samples

The lab trains six affine layers with 16-unit networks on synthetic two-moons data with a noise standard deviation of 0.06. It uses an independent validation set and leaves the data unnormalized. The parameters and samples come from a recorded run in Pyodide (seed 1221, 1700 steps). The mean NLL shows the full model before and after training, independently of the selected layer. The color of each cell uses the sum of log |det J| at the original cell center, a local measure. Line segments approximate the boundaries, the color saturates at magnitude 3, and the frame clips points outside the displayed domain.

Direction
0
Applied layers
0 / 6
Initial validation NLL
2.540 nats
Final validation NLL
0.683 nats
Traverse layers in both directions and observe local volume change. The grid and samples use parameters of the indicated experiment.

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 1×11\times1 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 HWH W. On resumption, loading state must also preserve the initialization flag to avoid overwriting learned parameters.

The convolution applies the same matrix W∈RC×CW\in\mathbb R^{C\times C} at every position. If W=PLUW=PLU, PP is a permutation, LL has unit diagonal and UU has nonzero diagonal, then

log⁡∣det⁡J∣=HWlog⁡∣det⁡W∣=HW∑j=1Clog⁡∣Ujj∣.\log|\det J|=HW\log|\det W|=HW\sum_{j=1}^{C}\log|U_{jj}|.

Parameterizing Ujj=sign⁡jexp⁡(aj)U_{jj}=\operatorname{sign}_j\exp(a_j) keeps that diagonal nonzero. Summing aja_j costs O(C)O(C), 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.

InteractiveInfinite likelihood on discrete data

The integer observations are 0, 1 and 2. The curve is a mixture of three Gaussians with equal weights and a common standard deviation σ.

  • Continuous density
  • Observed integers

The mixture has positive density on the whole real line. Its inverse CDF gives a monotone flow. This widget defines it directly, with no training. Mean log p(k) grows without bound as σ tends to zero. The density at a point can exceed one. For u uniform on [−½, ½), Jensen’s inequality gives Eᵤ log p(k + u) ≤ log P(k), where P(k) is the density integral over the cell. Both values are averaged over the three integers. The widget approximates the integrals with 2048 midpoints per cell. The bound applies to the expectation and may fail for one noise sample. The slider ranges from 0.05 to 0.8.

0.25
Observations
Mean log p at the integers
−0.631 nats
Mean with uniform noise
−1.229 nats
Mean log discrete mass
−1.114 nats
Compare pointwise density, noisy average and integrated mass. Jensen’s inequality concerns the expectation, not every individual noise sample.

By log concavity, whenever the integral exists,

Eu[log⁡pV((q+u)/K)]−Dlog⁡K≤log⁡P(q).\mathbb E_u\left[\log p_V((q+u)/K)\right]-D\log K\leq\log P(q).

Thus log⁡K−Eu[log⁡pV(v)]/D\log K-\mathbb E_u[\log p_V(v)]/D upper-bounds code length in nats per dimension; dividing by log⁡2\log2 gives bits per dimension. For K=256K=256 this yields 8−Eu[log⁡pV(v)]/(Dlog⁡2)8-\mathbb E_u[\log p_V(v)]/(D\log2). One Monte Carlo realization estimates the expectation but need not satisfy the inequality by itself. If the continuous model assigns mass outside [0,1]D[0,1]^D, the KDK^D 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 qϕ(u∣q)q_\phi(u\mid q) on [0,1)D[0,1)^D, positive almost everywhere that pV((q+u)/K)>0p_V((q+u)/K)>0. Expressing the integral as an expectation under that density and applying Jensen gives

Eu∼qϕ(⋅∣q) ⁣[log⁡pV((q+u)/K)−log⁡qϕ(u∣q)]−Dlog⁡K≤log⁡P(q).\mathbb E_{u\sim q_\phi(\cdot\mid q)}\!\left[\log p_V((q+u)/K)-\log q_\phi(u\mid q)\right]-D\log K\leq\log P(q).

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, b′=bexp⁡s(a)+t(a)b'=b\exp s(a)+t(a). Density evaluation uses its inverse b=(b′−t(a))exp⁡[−s(a)]b=(b'-t(a))\exp[-s(a)], contributing −s(a)-s(a) 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.

[ ]Train an affine flow in two dimensionsBrowser
"""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

ProofThe block you do not need to calculate
Prove: Prove the inverse and log-determinant of an affine coupling layer using the data-to-latent convention.
0
Split coordinates into A and B and assume differentiable s and t.

Step 1 of 3. Which derivative block is zero?

ProofThe bound is an expectation
Prove: Prove the uniform-dequantization inequality for a cell of volume K^(−D).
0
Integrate density over the cell and change to uniform variable u.

Step 1 of 3. What factor does v=(q+u)/K introduce into the integral?

NumericOne matrix at each position
An invertible 1×1 convolution has determinant 2 and is applied at 16×16 positions. Calculate its total log-determinant in nats.
CodeInvertible convolution with LU
Implement InvertibleConv1x1(W). It receives a square invertible matrix, preserves its factorization with fixed P and signs, and parameterizes the diagonal of U using signs and log-magnitudes. forward(x, reverse=False) returns output and per-example log-determinant for (B,C,H,W) tensors. Use triangular solves in the inverse and calculate log-determinant by summing the diagonal, without calling det or slogdet during forward. Expose matrix() to check the result.
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):
      pass
Shift+Enter to run

The log-determinant calculation sums CC numbers. Applying LL and UU to spatial positions requires more work; do not infer from the sum’s cost that the entire convolution is linear in CC.

QuizChoosing flow direction
A planar layer is defined by x=f(z), and its determinant is cheap when z is known. What difficulty appears when evaluating external datum x?

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.

[ ]Multiscale flow with LULocal GPU
"""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()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
Key idea

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.