Module contents
Lesson 13 of 28Advanced 110 min

Autoregressive, spline, residual and continuous flows

Increase per-layer flow expressivity while studying the cost of inverse evaluation. Compare MAF and IAF, rational-quadratic splines, residual flows and continuous flows including FFJORD, then examine topological limits and the motivation for flow matching.

After this lesson you can

  • Compare MAF and IAF density-evaluation and sampling costs and choose each for appropriate uses.
  • Implement a monotone rational-quadratic transformation with inverse and log-derivative.
  • Prove invertibility of a contractive residual flow and derive its log-determinant series.
  • Train a continuous flow with Hutchinson trace estimation and measure solver cost.
  • Identify flow failures caused by topology rather than training.

Before you start

More expressivity has a cost

A coupling layer leaves some coordinates unchanged. Composition addresses that limitation, but there are other ways to obtain expressive transformations: condition each coordinate on earlier ones, replace a line with a monotone function, constrain a residual block or integrate a continuous velocity field. Each choice moves cost between density evaluation, sampling and differential-equation solving.

Recall the flow change-of-variables convention: if x=f(z)x=f(z), then log⁡pX(x)=log⁡pZ(z)−log⁡∣det⁡Jf(z)∣\log p_X(x)=\log p_Z(z)-\log|\det J_f(z)|, with z=f−1(x)z=f^{-1}(x). Writing down which variable the network knows avoids confusing a cheap determinant formula with a cheap inverse.

MAF and IAF: direction determines parallelism

To evaluate a known observation, all its prefixes are available: one network pass computes μi\mu_i and σi\sigma_i simultaneously, and zi=(xi−μi)/σiz_i=(x_i-\mu_i)/\sigma_i. The Jacobian of x↦zx\mapsto z is triangular with diagonal 1/σi1/\sigma_i, so its log-determinant is −∑ilog⁡σi-\sum_i\log\sigma_i. To generate, however, xix_i needs previously generated values x<ix_{<i}: the standard autoregressive implementation requires DD sequential network evaluations per batch.

Density of a sample whose latent path is already known can be accumulated during generation; that does not make evaluation of arbitrary xx equally cheap. IAF is therefore useful for constructing a flexible variational posterior from noise, whereas MAF favors data density estimation. Call count also depends on architecture, batch and implementation optimizations, not just DD. Papamakarios and colleagues develop MAF; Kingma and colleagues develop IAF. Parallel WaveNet distills into a fast generator: its authors report synthesis over 20 times real-time speed on their system. It uses a particular objective and teacher; it does not make every IAF a parallel external-density evaluator.

InteractiveMAF versus IAF, pass by pass

All conditioner inputs are available. One pass computes all six coordinates together.

1
waiting
2
waiting
3
waiting
4
waiting
5
waiting
6
waiting
Pass 0 of 1

This diagram shows one layer and one vector. Each pass counts one full evaluation of the masked network. In MAF, complete data allow parallel density evaluation, while generation computes coordinates in sequence. IAF reverses that trade-off. Some implementations optimize the first coordinate separately. Here we count all D calls in the standard loop. Each pass can process a batch of vectors, and additional layers multiply the cost.

Flow
Operation
Completed passes
0 / 1
Computed coordinates
0 / 6
Compare which coordinates are available in each operation and count conditioner calls under the stated algorithm.

A line per segment is not the only option

The derivative within the segment is

f′(x)=δ2[dk+1θ2+2δθ(1−θ)+dk(1−θ)2][δ+(dk+1+dk−2δ)θ(1−θ)]2.f'(x)=\frac{\delta^2\left[d_{k+1}\theta^2+2\delta\theta(1-\theta)+d_k(1-\theta)^2\right]}{\left[\delta+(d_{k+1}+d_k-2\delta)\theta(1-\theta)\right]^2}.

Positive widths, heights and derivatives give a strictly increasing function. In practice, normalize widths and heights with positive minima and parameterize derivatives to stay nonzero. To invert, locate the output segment and define r=(y−yk)/hr=(y-y_k)/h and A=dk+dk+1−2δA=d_k+d_{k+1}-2\delta. Unknown θ∈[0,1]\theta\in[0,1] satisfies

(δ−dk+rA)θ2+(dk−rA)θ−rδ=0.(\delta-d_k+rA)\theta^2+(d_k-rA)\theta-r\delta=0.

Choose the root inside the interval and handle the linear case as the quadratic coefficient approaches zero. Segment endpoints and the discriminant also need numerical care. Outside a bounded region identity tails can be used; boundary derivatives must be one for a continuously differentiable join. Durkan and colleagues derive this family and its inverse. A monotone spline can represent a 1D deformation no single affine transform reproduces exactly.

InteractiveMonotone spline editor

The interior knots stay in order along both axes. The endpoints and their derivatives stay fixed to join the identity tails.

  • Spline y derivada
  • Nudos y densidad transformada
  • Punto de prueba

Each segment is rational quadratic, with positive width, height and derivatives. The segments join with a continuous derivative, and the spline is strictly increasing. Outside [−3, 3], the map is the identity. The inverse solves the segment’s quadratic equation with a numerically stable root. For standard normal Z, pX(f(z)) = pZ(z)/f′(z). The vertical scales adjust to the current state so changes remain visible.

1.0
1.0
0.35
x = f(z)
0.3500
f′(z)
1.0000
f⁻¹(x)
0.3500
pX(x)
0.3752
Adjust knots and compare function, derivative and transformed density. Also check inversion at the selected point.

A residual block can also be invertible

Since TyT_y is a contraction on complete Euclidean space, Banach’s theorem gives a unique fixed point; iterating xn+1=y−g(xn)x_{n+1}=y-g(x_n) converges to the inverse. If gg is differentiable and ∥Jg(x)∥2≤L<1\|J_g(x)\|_2\leq L<1, the matrix series converges and

log⁡det⁡(I+Jg)=tr⁡log⁡(I+Jg)=∑k=1∞(−1)k+1ktr⁡(Jgk).\log\det(I+J_g)=\operatorname{tr}\log(I+J_g) =\sum_{k=1}^{\infty}\frac{(-1)^{k+1}}{k}\operatorname{tr}(J_g^k).

The determinant is positive: path I+tJgI+tJ_g is nonsingular for t∈[0,1]t\in[0,1] and starts with determinant one. The equality uses the matrix series and does not require JgJ_g to be symmetric. Behrmann and colleagues study invertible residual networks.

Forming every power is too costly in high dimensions. For a probe ϵ\epsilon with E[ϵϵ⊤]=I\mathbb E[\epsilon\epsilon^\top]=I, the Hutchinson estimator satisfies E[ϵ⊤Aϵ]=tr⁡A\mathbb E[\epsilon^\top A\epsilon]=\operatorname{tr}A when the expectation exists. Jacobian products estimate terms without constructing the full matrix. Fixed series truncation introduces bias. Random truncation weighted by survival probability can remove it under positive probabilities and suitable integrability, at the cost of random variance and computation; randomly cutting the series alone is insufficient. Residual Flows studies this estimation. An unbiased estimated log-density does not imply its exponential unbiasedly estimates density.

Density along a trajectory

Divergence measures local expansion: if positive, density decreases along the path. To evaluate final data, integrate state and log-density correction toward the base; to generate, integrate forward from the base. FFJORD uses Hutchinson to estimate trace. Keep the same probe fixed during a numerical solve: redrawing it on every evaluation changes the field the solver attempts to integrate.

InteractiveParticles in a continuous flow

Each point tracks a particle from the experiment. Its color compares its log density with the median at that time. The shaded squares show the support of the target checkerboard.

  • Log density at or above the median
  • Log density below the median
  • Selected trajectories
  • Target checkerboard support

The field was trained for 1000 updates. The checkpoint at step 1000 had the best validation NLL with an exact trace, as recorded by train_cnf_widget.py. Seeds: model 1330, training 1331, validation 1332, test 1333, minibatches 1334, probes 1335, and 64 particles with seed 1336. Mean exact-trace test NLL in nats per example: 3.104 initially and 2.714 at the end. Of these 64 particles, 22 start in the target squares, 44 finish inside them, and 20 finish outside. The result comes from a short run and approximates the target checkerboard.

The density uses an exact trace in two dimensions. DOPRI5 uses rtol = 0.00001 and atol = 0.00001. The evaluation count accumulates across 20 solver runs restarted between saved times. Lines connect those saved times. Color is relative to the median at each time, so it cannot be compared on an absolute scale across times. The mean log density summarizes these particles. Test NLL is reported separately.

0.000
Time
0.000
Cumulative field evaluations
0
Mean particle log density
−2.728 nats
Follow particles and their densities during integration. Trajectories, tolerances and evaluation counts correspond to the stated experiment.

An adaptive solver selects steps according to tolerance and evaluates the field a number of times depending on problem and point. Looser tolerance can change numerical result and estimated log-density; number of field evaluations, or NFE, helps explain cost. Trace estimation, solver numerical error and variation across training runs are distinct sources of uncertainty. Review Neural ODEs and adaptive steps before comparing times; a continuous method need not require only one network evaluation.

What a bijection can and cannot separate

A mixture of two Gaussians, however far apart their means, has positive density throughout RD\mathbb R^D: its support is not disconnected and it is no topological counterexample. Two separated regions with exactly zero density between them do create an exact impossibility for a Gaussian base and global diffeomorphism. This does not prevent approximation with a very-low-mass intermediate region. Mode separation, bridge mass and determinant magnitudes depend on model and parameters; no universal bound follows without further assumptions.

InteractiveA flow cannot tear a Gaussian
Comparison

The plot shows 256 generated samples. The shaded strip marks |x₁| < 0.35. Each circle marks one component’s standard deviation.

  • Flow samples
  • One-standard-deviation circles
  • Bridge strip

Three separate RealNVP fits use 6 layers, 16 hidden units, 1700 steps, and batch size 128. Each uses 2048 training examples and 1024 test examples. The means are (±a, 0) and each component has covariance 0.35² I. The seeds are 1221 for initialization, 1311 for training, 1312 for testing, 1313 for minibatches, and 1314 for latents. The fits share seeds and latents so the separations can be compared. In this fit the mean test NLL goes from 3.093 to 1.453 nats. Source: train-topology.py and topology-trained.json, based on the previous lesson’s RealNVP.

There are 45 hits in the full strip out of 8192 independent samples. The reported uncertainty uses a Wilson interval. The plot shows the first 256 samples. The target mass is calculated analytically for the same strip. The log determinant is local to the noise-to-data map and is evaluated at the latent point that maps to the origin. Its sign and magnitude depend on the fit. The measured frequency alone cannot establish zero probability. Both Gaussians have positive density throughout the plane, so the mixture has full support even when the bridge is tiny. The analytical comparison shows the exact obstruction for disconnected support.

Positions of the means ±a
Flow bridge frequency
0.005493
95% Wilson interval
[0.004108, 0.007342]
Exact target bridge mass
0.000509
Generation log |det J| at the center
−1.3420
Compare an explicit deformation with two targets: separated Gaussians and genuinely disconnected support. Distinguish this example from exact impossibility.

An ordinary flow also preserves dimension between base and data. If data concentrate exactly on a lower-dimensional manifold, they have no ordinary density with respect to ambient volume; model and evaluation criterion must recognize that difference. Good likelihood also does not alone guarantee perceptual sample quality: revisit the metric comparison.

Lab: constructing a spline

Implement the piecewise formula with defined tails, verify forward and inverse at knots and outside the interval, and compare log-derivative with finite differences. Compare distributions produced by a spline and an affine transformation from the same standard normal.

Implement a monotone spline with three intervals. Outside endpoints use the identity; boundary values and derivatives ensure a continuous differentiable join. Within each interval the inverse solves a quadratic using a stable root form. The cell checks knots, tails, monotonicity, inversion, logdet signs and finite differences; it also rejects parameters violating assumptions.

For expressivity comparison, deterministic quadrature transforms a standard normal and measures its moments. An affine transformation of a normal remains normal with zero skewness and excess kurtosis. The example shows a family that can change those moments; it is not training or proof of general quality.

[ ]Rational-quadratic spline and its inverseBrowser
"""Spline racional cuadrático monótono de Durkan et al., implementado con NumPy."""
import numpy as np


def validate(x_knots, y_knots, derivatives):
    x = np.asarray(x_knots, dtype=np.float64)
    y = np.asarray(y_knots, dtype=np.float64)
    d = np.asarray(derivatives, dtype=np.float64)
    if x.ndim != 1 or len(x) < 2 or x.shape != y.shape or x.shape != d.shape:
        raise ValueError('Se necesita un vector de cada tipo por nudo')
    if not all(np.isfinite(v).all() for v in (x, y, d)):
        raise ValueError('Los parámetros deben ser finitos')
    if np.any(np.diff(x) <= 0) or np.any(np.diff(y) <= 0) or np.any(d <= 0):
        raise ValueError('Anchos, alturas y derivadas deben ser positivos')
    if x[0] != y[0] or x[-1] != y[-1] or d[0] != 1 or d[-1] != 1:
        raise ValueError('Los extremos y sus derivadas deben conectar con las colas identidad')
    return x, y, d


def rational_quadratic(values, x_knots, y_knots, derivatives, inverse=False):
    """Devuelve salida y log |derivada|, con colas identidad en ambas direcciones."""
    x_knots, y_knots, derivatives = validate(x_knots, y_knots, derivatives)
    original = np.asarray(values, dtype=np.float64)
    if not np.isfinite(original).all():
        raise ValueError('Las entradas deben ser finitas')
    flat = original.reshape(-1)
    result = flat.copy()
    logdet = np.zeros_like(flat)
    knots = y_knots if inverse else x_knots
    inside = (flat >= knots[0]) & (flat <= knots[-1])
    v = flat[inside]
    if len(v):
        index = np.clip(np.searchsorted(knots, v, side='right') - 1, 0, len(knots) - 2)
        x0, y0 = x_knots[index], y_knots[index]
        width = x_knots[index + 1] - x0
        height = y_knots[index + 1] - y0
        slope = height / width
        d0, d1 = derivatives[index], derivatives[index + 1]
        delta = d0 + d1 - 2 * slope
        if inverse:
            dy = v - y0
            a = dy * delta + height * (slope - d0)
            b = height * d0 - dy * delta
            c = -slope * dy
            discriminant = b * b - 4 * a * c
            tolerance = 1e-12 * np.maximum(1.0, b * b + np.abs(4 * a * c))
            if np.any(discriminant < -tolerance):
                raise FloatingPointError('Discriminante negativo fuera del error numérico')
            denominator = -b - np.sqrt(np.maximum(discriminant, 0))
            if np.any(denominator == 0):
                raise FloatingPointError('Raíz inversa numéricamente indeterminada')
            theta = 2 * c / denominator
            if np.any((theta < -1e-10) | (theta > 1 + 1e-10)):
                raise FloatingPointError('La raíz inversa sale de su intervalo')
            theta = np.clip(theta, 0, 1)
            result[inside] = x0 + width * theta
        else:
            theta = (v - x0) / width
            denominator = slope + delta * theta * (1 - theta)
            numerator = slope * theta ** 2 + d0 * theta * (1 - theta)
            result[inside] = y0 + height * numerator / denominator
        denominator = slope + delta * theta * (1 - theta)
        derivative = (slope ** 2 * (d1 * theta ** 2 + 2 * slope * theta * (1 - theta) +
                      d0 * (1 - theta) ** 2) / denominator ** 2)
        logdet[inside] = (-1 if inverse else 1) * np.log(derivative)
    return result.reshape(original.shape), logdet.reshape(original.shape)


X = np.array([-3.0, -1.0, 1.0, 3.0])
Y = np.array([-3.0, -1.5, 1.4, 3.0])
D = np.array([1.0, 0.7, 1.6, 1.0])

# Identidad y extremos exactos, incluidas las colas.
test_points = np.array([-5, -3, -2, -1, 0, 1, 2, 3, 5], dtype=float)
identity, identity_ld = rational_quadratic(test_points, X, X, np.ones_like(X))
assert np.allclose(identity, test_points, atol=1e-14)
assert np.allclose(identity_ld, 0, atol=1e-14)
mapped_knots, knot_ld = rational_quadratic(X, X, Y, D)
assert np.allclose(mapped_knots, Y, atol=1e-14)
assert np.allclose(np.exp(knot_ld), D, atol=1e-14)
tail, tail_ld = rational_quadratic(np.array([-5., 5.]), X, Y, D)
assert np.array_equal(tail, np.array([-5., 5.])) and np.array_equal(tail_ld, [0., 0.])

# Barrido de nudos, vecindad de fronteras e inversa tanto dentro como fuera.
grid = np.linspace(-5, 5, 2001)
near_knots = (X[:, None] + np.array([-1e-10, 0, 1e-10])).flatten()
points = np.concatenate((grid, near_knots))
mapped, logdet = rational_quadratic(points, X, Y, D)
restored, inverse_ld = rational_quadratic(mapped, X, Y, D, inverse=True)
roundtrip_error = float(np.max(np.abs(restored - points)))
logdet_error = float(np.max(np.abs(logdet + inverse_ld)))
assert roundtrip_error < 1e-12 and logdet_error < 1e-12
assert np.all(np.diff(rational_quadratic(grid, X, Y, D)[0]) > 0)

# Derivada analítica frente a diferencias centrales, lejos de los nudos.
interior = np.array([-2.5, -1.4, -0.2, 0.5, 1.5, 2.6])
epsilon = 1e-5
above = rational_quadratic(interior + epsilon, X, Y, D)[0]
below = rational_quadratic(interior - epsilon, X, Y, D)[0]
numeric_derivative = (above - below) / (2 * epsilon)
analytical_derivative = np.exp(rational_quadratic(interior, X, Y, D)[1])
derivative_error = float(np.max(np.abs(numeric_derivative - analytical_derivative)))
assert derivative_error < 1e-8

# En este ejemplo las raíces cuadráticas se reducen también a una ecuación lineal.
linear_x = np.array([-1., 1.])
linear_d = np.array([1., 1.])
linear_y = rational_quadratic(grid, linear_x, linear_x, linear_d)[0]
assert np.allclose(rational_quadratic(linear_y, linear_x, linear_x, linear_d, inverse=True)[0], grid, atol=1e-14)
for invalid_y, invalid_d in (([ -3, -1.5, -1.5, 3 ], D), (Y, [1, .7, 0, 1]), (Y, [1, .7, 1.6, 2])):
    try:
        validate(X, invalid_y, invalid_d)
    except ValueError:
        pass
    else:
        raise AssertionError('Los parámetros inválidos deben rechazarse')

# Cuadratura determinista bajo una base normal. Una afín de una normal tiene
# asimetría y exceso de curtosis teóricos cero; el spline puede cambiarlos.
base = np.linspace(-8, 8, 8193)
weights = np.exp(-0.5 * base ** 2)
weights /= weights.sum()
values, curve_ld = rational_quadratic(base, X, Y, D)
mean = float(np.dot(weights, values))
variance = float(np.dot(weights, (values - mean) ** 2))
skewness = float(np.dot(weights, (values - mean) ** 3) / variance ** 1.5)
excess = float(np.dot(weights, (values - mean) ** 4) / variance ** 2 - 3)
print(f'Inversa: error máximo {roundtrip_error:.2e}; suma de logdet: {logdet_error:.2e}; derivada: {derivative_error:.2e}')
print(f'Spline: media={mean:.5f}, desviación={np.sqrt(variance):.5f}, asimetría={skewness:.5f}, exceso de curtosis={excess:.5f}')
print('Una transformación afín de una normal tiene asimetría y exceso de curtosis 0.')

CHECK = {'x': X.tolist(), 'y': Y.tolist(), 'derivatives': D.tolist(),
         'test_points': test_points.tolist(),
         'test_values': rational_quadratic(test_points, X, Y, D)[0].tolist(),
         'test_logdet': rational_quadratic(test_points, X, Y, D)[1].tolist(),
         'roundtrip_error': roundtrip_error, 'logdet_error': logdet_error,
         'derivative_error': derivative_error, 'mean': mean, 'variance': variance,
         'skewness': skewness, 'excess_kurtosis': excess}

Exercises

ProofInverse and residual series
Prove: Prove the inverse of f(x)=x+g(x) exists if g is contractive and derive the log-determinant series under differentiability and Jacobian norm below one.
0
For each y, consider T_y(x)=y−g(x).

Step 1 of 3. What property does T_y have?

ProofTriangularity and cost
Prove: Prove the MAF log-determinant in the data-to-base direction and explain why sampling traverses coordinates in order.
0
Assume each μ_i and positive σ_i depends only on x_1 through x_(i−1).

Step 1 of 3. What does z_i=(x_i−μ_i)/σ_i depend on?

NumericSampling in batches
You sample 1000 vectors of dimension 784 with a standard MAF layer in batches of 100. How many conditioner evaluations are required in total?
CodeA MADE layer for MAF
Implement MADEMAF(D, H, seed). Use a tanh hidden layer with degrees 1 through D−1 and autoregressive masks: an input of degree i reaches a neuron of degree m if i≤m, and it reaches output i if m<i. Produce two outputs per coordinate: mean and log-scale bounded with tanh. parameters_for(x) returns (mean, log_scale); to_base(x) returns (z, x-to-z logdet); log_prob(x) uses a standard normal; sample(z) recovers coordinates in D conditioner calls. Accept matrices shaped (batch,D), D≥2 and H≥D−1.
import numpy as np

class MADEMAF:
  def __init__(self, D, H, seed=0):
      pass

  def parameters_for(self, x):
      pass

  def to_base(self, x):
      pass

  def log_prob(self, x):
      pass

  def sample(self, z):
      pass
Shift+Enter to run
QuizChoosing a direction
You want to evaluate many external data, enrich a variational posterior and generate in parallel. Which initial choice fits each case best?

Lab: comparing families in 2D and tabular data

The experiment must separate training and evaluation, use identical splits and state dimension, sample count, architecture, device and seeds. Compare NLL and generation cost; for a continuous solver also record NFE and tolerances. Shared-machine timings vary and are not a universal family property.

Compare a custom MADE-masked MAF, a rational-spline autoregressive flow from nflows, and an FFJORD-like continuous flow solved with torchdiffeq. All three use the same splits, batch-index sequence and update count, but differ in parameter count and work per step. This is a controlled comparison for this experiment, not a universal architecture ranking.

The first dataset is lesson m19-l01’s checkerboard, generated with independent training, validation and test seeds. The second is Wine from scikit-learn: standardization is fitted only on training. Wine NLLs use standardized coordinates and are not directly comparable to 2D NLLs. Wine splits are fixed before training; do not use test to select architecture or hyperparameters.

MAF runs from data to latents, evaluating density coordinates in parallel while the inverse reconstructs each sequentially. The nflows spline uses eight intervals and linear tails outside [−4, 4], accepting values outside that range. FFJORD integrates the field using adaptive Dopri5. During each density integration one Rademacher Hutchinson probe remains fixed; NLL is an estimate also dependent on tolerances and numerical error. Sampling integrates only the field, without trace calculation.

Install torch, numpy, scikit-learn, nflows==0.14 and torchdiffeq==0.2.5. By default use 1000 updates per model and dataset. ORYON_QUICK=1 uses three updates, batch 16 and small networks to check functionality; results do not demonstrate convergence. ORYON_OUTPUT_DIR selects output. For quick-mode debugging only, ORYON_QUICK_MODEL accepts maf, spline or ffjord and ORYON_QUICK_DATASET accepts tablero or wine; ORYON_QUICK_SKIP_TESTS=1 skips preliminary tests only if already run. Full mode always runs all six combinations and tests.

Before training, test MAF inverse and logdet against an autograd Jacobian, spline inverse and tails, and FFJORD sign against an analytically solved linear field. Metrics are written to CSV with checkpoints. Measure validation and test NLL, training time and time for 64 samples, parameter count and FFJORD field evaluations. The training counter sums field evaluations in forward solves; it does not count autograd cost as additional calls. Times are machine observations and vary; they do not mean equal compute budgets or extrapolate to other implementations.

[ ]MAF, splines and FFJORDLocal GPU
"""MAF, splines de nflows y FFJORD educativo sobre tablero y Wine.

Dependencias: torch, numpy, scikit-learn, nflows==0.14, torchdiffeq==0.2.5.
ORYON_QUICK=1 comprueba el recorrido; ORYON_OUTPUT_DIR cambia el destino.
En quick, ORYON_QUICK_MODEL=maf|spline|ffjord y ORYON_QUICK_DATASET=tablero|wine
permiten comprobar una rama por proceso. ORYON_QUICK_SKIP_TESTS=1 omite solo
los autotests, si ya se ejecutaron por separado; el modo completo no cambia.
"""
import csv
import math
import os
import time
from pathlib import Path

import numpy as np
import torch
from torch import nn
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from nflows.distributions.normal import StandardNormal
from nflows.flows.base import Flow
from nflows.transforms.autoregressive import MaskedPiecewiseRationalQuadraticAutoregressiveTransform
from nflows.transforms.base import CompositeTransform
from nflows.transforms.permutations import ReversePermutation
from torchdiffeq import odeint

torch.set_num_threads(2)
LOG2PI = math.log(2 * math.pi)


def board(n, seed):
    # Mismo modelo de tablero que m19-l01, con semillas independientes.
    rng = np.random.default_rng(seed)
    i = rng.integers(0, 4, n)
    j = 2 * rng.integers(0, 2, n) + i % 2
    return (np.column_stack((i, j)) + rng.uniform(size=(n, 2)) - 2).astype('float32')


def datasets(quick):
    board_train, board_val, board_test = ((board(128, 1310), board(64, 1311), board(64, 1312))
                                           if quick else (board(4096, 1310), board(1024, 1311), board(1024, 1312)))
    wine = load_wine().data.astype('float32')
    train, test = train_test_split(wine, test_size=0.2, random_state=1313)
    train, val = train_test_split(train, test_size=0.25, random_state=1314)
    scaler = StandardScaler().fit(train)
    train, val, test = (scaler.transform(x).astype('float32') for x in (train, val, test))
    return {'tablero': (board_train, board_val, board_test), 'wine': (train, val, test)}


class MaskedLinear(nn.Linear):
    def __init__(self, in_features, out_features, mask):
        super().__init__(in_features, out_features)
        self.register_buffer('mask', mask.to(dtype=torch.float32))
    def forward(self, x):
        return nn.functional.linear(x, self.weight * self.mask, self.bias)


class MADE(nn.Module):
    def __init__(self, dimension, width):
        super().__init__()
        if dimension < 2:
            raise ValueError('MADE necesita al menos dos dimensiones en esta implementación')
        inputs = torch.arange(1, dimension + 1)
        hidden = torch.arange(width) % (dimension - 1) + 1
        outputs = inputs.repeat(2)
        self.net = nn.Sequential(MaskedLinear(dimension, width, hidden[:, None] >= inputs[None, :]), nn.Tanh(),
                                 MaskedLinear(width, width, hidden[:, None] >= hidden[None, :]), nn.Tanh(),
                                 MaskedLinear(width, 2 * dimension, outputs[:, None] > hidden[None, :]))
        nn.init.zeros_(self.net[-1].weight)
        nn.init.zeros_(self.net[-1].bias)
    def forward(self, x):
        shift, raw = self.net(x).chunk(2, dim=1)
        return shift, 1.5 * torch.tanh(raw)


class MAF(nn.Module):
    def __init__(self, dimension, width=32, layers=3):
        super().__init__()
        self.dimension = dimension
        self.layers = nn.ModuleList(MADE(dimension, width) for _ in range(layers))
    def encode(self, x):
        total = x.new_zeros(len(x))
        for layer in self.layers:
            shift, scale = layer(x)
            x = (x - shift) * torch.exp(-scale)
            total = total - scale.sum(dim=1)
            x = x.flip(1)
        return x, total
    def decode(self, z):
        for layer in reversed(self.layers):
            z = z.flip(1)
            x = torch.zeros_like(z)
            for index in range(self.dimension):
                shift, scale = layer(x)
                new = z[:, index] * torch.exp(scale[:, index]) + shift[:, index]
                x = torch.cat((x[:, :index], new[:, None], x[:, index + 1:]), dim=1)
            z = x
        return z
    def log_prob(self, x):
        z, logdet = self.encode(x)
        return (-0.5 * (z.square() + LOG2PI)).sum(1) + logdet
    def sample(self, n):
        p = next(self.parameters())
        return self.decode(torch.randn(n, self.dimension, device=p.device, dtype=p.dtype))


def spline_flow(dimension, width, layers):
    transforms = []
    for _ in range(layers):
        transforms.extend((MaskedPiecewiseRationalQuadraticAutoregressiveTransform(
            features=dimension, hidden_features=width, num_bins=8, tails='linear', tail_bound=4.0,
            num_blocks=2, use_batch_norm=False), ReversePermutation(features=dimension)))
    return Flow(CompositeTransform(transforms), StandardNormal([dimension]))


class VectorField(nn.Module):
    def __init__(self, dimension, width):
        super().__init__()
        self.net = nn.Sequential(nn.Linear(dimension + 1, width), nn.Tanh(),
                                 nn.Linear(width, width), nn.Tanh(), nn.Linear(width, dimension))
        nn.init.normal_(self.net[-1].weight, std=0.01)
        nn.init.zeros_(self.net[-1].bias)
    def forward(self, t, x):
        return self.net(torch.cat((x, torch.ones_like(x[:, :1]) * t), dim=1))


class DensityRHS(nn.Module):
    def __init__(self, field, epsilon, create_graph):
        super().__init__()
        self.field, self.epsilon, self.create_graph, self.nfe = field, epsilon, create_graph, 0
    def forward(self, t, state):
        self.nfe += 1
        x, _ = state
        with torch.enable_grad():
            x = x.requires_grad_(True)
            velocity = self.field(t, x)
            jte = torch.autograd.grad(velocity, x, self.epsilon, create_graph=self.create_graph,
                                      retain_graph=True)[0]
            trace = (jte * self.epsilon).sum(1)
        return velocity, trace


class SampleRHS(nn.Module):
    def __init__(self, field):
        super().__init__()
        self.field, self.nfe = field, 0
    def forward(self, t, x):
        self.nfe += 1
        return self.field(t, x)


class FFJORD(nn.Module):
    def __init__(self, dimension, width=32, rtol=1e-4, atol=1e-4):
        super().__init__()
        self.dimension, self.field = dimension, VectorField(dimension, width)
        self.rtol, self.atol, self.nfe = rtol, atol, 0
    def log_prob(self, x, epsilon=None):
        if epsilon is None:
            epsilon = torch.randint(0, 2, x.shape, device=x.device).to(x.dtype) * 2 - 1
        rhs = DensityRHS(self.field, epsilon, create_graph=self.training)
        # Integra datos t=1 hacia base t=0; integral de tr(J) es log|dz/dx|.
        ts = x.new_tensor([1.0, 0.0])
        z, logdet = odeint(rhs, (x, x.new_zeros(len(x))), ts, method='dopri5', rtol=self.rtol, atol=self.atol)
        self.nfe = rhs.nfe
        return (-0.5 * (z[-1].square() + LOG2PI)).sum(1) + logdet[-1]
    def sample(self, n):
        p = next(self.parameters())
        z = torch.randn(n, self.dimension, dtype=p.dtype, device=p.device)
        rhs = SampleRHS(self.field)
        values = odeint(rhs, z, z.new_tensor([0.0, 1.0]), method='dopri5', rtol=self.rtol, atol=self.atol)
        self.nfe = rhs.nfe
        return values[-1]


def verify_models(device):
    torch.manual_seed(1315)
    maf = MAF(3, width=12, layers=2).to(device).double()
    # Hacer no triviales las escalas antes de verificar el jacobiano.
    for layer in maf.layers:
        nn.init.normal_(layer.net[-1].weight, std=0.05)
    x = torch.randn(4, 3, device=device, dtype=torch.float64)
    z, logdet = maf.encode(x)
    assert torch.allclose(maf.decode(z), x, atol=1e-9, rtol=1e-9)
    jac = torch.autograd.functional.jacobian(lambda u: maf.encode(u[None])[0][0], x[0])
    assert torch.allclose(torch.linalg.slogdet(jac)[1], logdet[0], atol=1e-9)
    spl = spline_flow(3, 12, 2).to(device)
    u = torch.randn(5, 3, device=device)
    z, ld = spl._transform(u)
    restored, inverse_ld = spl._transform.inverse(z)
    assert torch.allclose(restored, u, atol=2e-5, rtol=2e-5)
    assert torch.allclose(ld + inverse_ld, torch.zeros_like(ld), atol=2e-5)
    outside = torch.full((2, 3), 6.0, device=device)
    assert torch.isfinite(spl.log_prob(outside)).all()
    class DiagonalField(nn.Module):
        def forward(self, t, v):
            return v * v.new_tensor([0.25, -0.4])
    cnf = FFJORD(2, width=8, rtol=1e-7, atol=1e-7).to(device).double().eval()
    cnf.field = DiagonalField()
    point = torch.tensor([[0.7, -0.2]], dtype=torch.float64, device=device)
    lp = cnf.log_prob(point, torch.ones_like(point))
    diagonal = point.new_tensor([0.25, -0.4])
    expected_z = point * torch.exp(-diagonal)
    expected = (-0.5 * (expected_z.square() + LOG2PI)).sum(1) - diagonal.sum()
    assert torch.allclose(lp, expected, rtol=2e-6, atol=2e-6)
    print('Pruebas: MADE e inversa, jacobiano MAF, spline y colas, signo FFJORD en campo lineal: correctos.', flush=True)
    del maf, spl, cnf, x, z, jac, point, lp
    if device.type == 'cuda':
        torch.cuda.empty_cache()


def synchronize(device):
    if device.type == 'cuda':
        torch.cuda.synchronize(device)


def compare(dataset_name, arrays, device, quick, output, model_filter=None):
    train, val, test = (torch.from_numpy(x).to(device) for x in arrays)
    dimension = train.shape[1]
    width, layers, updates, batch = (12, 2, 3, 16) if quick else (32, 3, 1000, 64)
    constructors = {'MAF propio': lambda: MAF(dimension, width, layers),
                    'Spline nflows': lambda: spline_flow(dimension, width, layers),
                    'FFJORD': lambda: FFJORD(dimension, width)}
    if model_filter:
        chosen = {'maf': 'MAF propio', 'spline': 'Spline nflows', 'ffjord': 'FFJORD'}[model_filter]
        constructors = {chosen: constructors[chosen]}
    rows = []
    for name, construct in constructors.items():
        torch.manual_seed(1320)
        model = construct().to(device)
        optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
        batch_rng = torch.Generator().manual_seed(1321)
        model.train()
        train_nfe = 0
        synchronize(device)
        start = time.perf_counter()
        for _ in range(updates):
            indices = torch.randint(len(train), (batch,), generator=batch_rng).to(device)
            optimizer.zero_grad(set_to_none=True)
            loss = -model.log_prob(train[indices]).mean()
            if not torch.isfinite(loss):
                raise FloatingPointError('La NLL no es finita')
            if name == 'FFJORD':
                train_nfe += model.nfe
            loss.backward()
            nn.utils.clip_grad_norm_(model.parameters(), 10.0, error_if_nonfinite=True)
            optimizer.step()
        synchronize(device)
        train_seconds = time.perf_counter() - start
        model.eval()
        # FFJORD requiere autograd para la traza incluso en evaluación.
        torch.manual_seed(1322)
        val_nll = float(-model.log_prob(val).detach().mean())
        torch.manual_seed(1323)
        test_nll = float(-model.log_prob(test).detach().mean())
        eval_nfe = model.nfe if name == 'FFJORD' else None
        torch.manual_seed(1324)
        synchronize(device)
        start = time.perf_counter()
        with torch.no_grad():
            samples = model.sample(64)
        synchronize(device)
        sample_seconds = time.perf_counter() - start
        sample_nfe = model.nfe if name == 'FFJORD' else None
        if not torch.isfinite(samples).all() or not np.isfinite([val_nll, test_nll]).all():
            raise FloatingPointError('Las muestras o métricas no son finitas')
        row = {'conjunto': dataset_name, 'modelo': name, 'dimension': dimension,
               'actualizaciones': updates, 'parametros': sum(p.numel() for p in model.parameters()),
               'nll_val': val_nll, 'nll_test': test_nll, 'entrenamiento_s': train_seconds,
               'muestreo_64_s': sample_seconds, 'nfe_train_total': train_nfe if name == 'FFJORD' else None,
               'nfe_test': eval_nfe, 'nfe_muestreo': sample_nfe}
        print(row, flush=True)
        rows.append(row)
        torch.save({'model': model.state_dict(), 'dataset': dataset_name, 'name': name,
                    'dimension': dimension, 'width': width, 'layers': layers,
                    'updates': updates, 'quick': quick}, output / f'{dataset_name}-{name.split()[0]}.pt')
        del model, optimizer, loss, samples
        if device.type == 'cuda':
            torch.cuda.empty_cache()
    return rows


def main():
    quick = os.environ.get('ORYON_QUICK') == '1'
    model_filter = os.environ.get('ORYON_QUICK_MODEL')
    dataset_filter = os.environ.get('ORYON_QUICK_DATASET')
    skip_tests = os.environ.get('ORYON_QUICK_SKIP_TESTS') == '1'
    if not quick and (model_filter or dataset_filter or skip_tests):
        raise ValueError('Los filtros y la omisión de pruebas solo se permiten con ORYON_QUICK=1')
    if model_filter not in (None, 'maf', 'spline', 'ffjord') or dataset_filter not in (None, 'tablero', 'wine'):
        raise ValueError('Filtros quick desconocidos')
    output = Path(os.environ.get('ORYON_OUTPUT_DIR', './comparacion-flujos'))
    output.mkdir(parents=True, exist_ok=True)
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    if not skip_tests:
        verify_models(device)
    rows = []
    for name, arrays in datasets(quick).items():
        if dataset_filter is None or dataset_filter == name:
            rows.extend(compare(name, arrays, device, quick, output, model_filter))
    with (output / 'metricas.csv').open('w', encoding='utf-8', newline='') as file:
        writer = csv.DictWriter(file, fieldnames=list(rows[0]))
        writer.writeheader()
        writer.writerows(rows)
    print('La NLL de FFJORD es una estimación con una sonda fija por integración y tolerancias del solver.', flush=True)


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

Flow expressivity does not remove inverse cost or support limits. Splines increase flexibility, residual blocks require controlled inversion and continuous flows pay to solve an ODE. Later lessons study training transport fields with objectives that need not simulate that ODE at every step.