Flow matching in depth: unification with diffusion, couplings and straight paths
Relate scores, diffusion and flow velocities; study timestep weighting, stochastic interpolants, minibatch optimal transport, stable Sinkhorn, reflow and their measured costs.
After this lesson you can
- Convert Gaussian-path scores, noise and velocities under explicit conventions.
- Relate deterministic DDIM to Euler in rescaled coordinates.
- Analyze time distributions and stochastic interpolants.
- Implement minibatch optimal transport and stabilized Sinkhorn coupling.
- Evaluate reflow and compare DDIM with Euler using a diffusion checkpoint.
Before you start
- 19Conditional flow matchingGaussian conditional pathsRectified flowDiffusion loss weightingv-parameterizationNFE versus quality tradeoff
- 04Wasserstein distanceCoupling
- 06Lagrange dual functionDual problem and weak dualityStrong duality and Slater's condition
- 26Brownian bridgeDoob h-transform and conditioned diffusions
One path, several parameterizations
Diffusion and flow matching can describe the same field on Gaussian paths, but changing a name does not make two experiments identical. Signal and noise functions, time direction, network output, loss weighting and solver must be aligned. We fix conventions and derive conversions before comparing couplings and reflow.
Use for the base and for data, and write , with independent of . Formulas dividing by or apply only where those coefficients are positive; singular endpoints use limits or separate rules.
From score to velocity field
Let and assume a differentiable density, valid exchange of derivative and integral, and sufficient moments. For the conditional Gaussian mixture,
Marginal velocity is . Substituting both identities gives
This is an equivalence between diffusion and flow matching for this Gaussian family: with the same marginals and conventions, score and velocity convert algebraically wherever the transformation is invertible. A diffusion probability-flow ODE corresponds to suitable coefficients and time direction. It does not imply that every stochastic process has the same sample trajectories as an ODE or that approximate networks trained with different losses produce exactly the same result. See Gao and colleagues.
When , a common diffusion parameterization defines . Do not confuse this symbol with time velocity . The rotation inverts as
Also . A prediction of any of these quantities can construct the others using suitable coefficients; we cannot divide by a zero coefficient. Conversions preserve algebraic information, not guarantee a learned output is exact.
DDIM as Euler in rescaled coordinates
For , define and . A deterministic DDIM update between two levels with the same noise prediction is
This is Euler for in that coordinate, with the field evaluated at the start. Equality is an update identity when the same predictor, grid and scale are used in both expressions. It does not say Euler uniform in original time is identical to DDIM on a different grid. Stochastic noise, clipping or differently applied guidance also change the compared rules. The DDIM lesson derived this change of variables.
Distribute effort over time
Training with minimizes an integral weighted by ; changing without compensation changes the objective and budget devoted to each level. A parameterization transformation can also introduce a -dependent factor in MSE. Matching update count alone does not match two recipes’ effective weights.
A logit-normal is obtained with and . For and ,
On the linear path with and , natural log SNR is , so under this distribution . A density per unit of and one per unit of include different Jacobians. A time shift also changes that density: state coordinate, time direction and whether training or only sampling changes. Esser and colleagues study time distributions and resolution-dependent shifts for their flow model; there is no universal optimal shift.
In table 2, Esser and colleagues report FID 49.70 for rf and 45.78 for rf/lognorm(0,1) for ImageNet-trained variants with 25 steps. They calculate FID on CLIP features and evaluate on COCO-2014, so those figures are not directly comparable with the local lab’s Inception FID. These are results of their configuration, not a guarantee for every time distribution.
Stochastic interpolants
A stochastic interpolant can combine two variables with extra perturbation:
with independent and appropriate endpoint conditions, for example , and . If and are differentiable and expectations exist, marginal velocity is obtained by conditioning on . Changing the coupling or noise amplitude changes the path and field. An ODE and different SDEs can share marginals under compatible constructions, though individual trajectories differ. Albergo, Boffi and Vanden-Eijnden develop this framework.
Couple a minibatch with optimal transport
Given points and with masses , a plan satisfies , and . For quadratic cost , OT minimizes . For two batches of equal size, an optimal assignment can be represented by a permutation. Independent and optimal couplings preserve batch marginals but propose different pairs and paths.
A useful property follows by swapping two pairs of an optimal plan. Quadratic optimality implies . If two distinct segments coincided at the same , we would have , whose dot product is negative unless both pairs coincide. Thus those segments do not cross at the same time. This is a property of optimal coupling for that cost, not a guarantee that a learned MLP follows perfectly straight lines or paths from different batches do not cross.
Minibatch OT solves a finite problem for each batch. Its solution can differ greatly from population optimal coupling, especially in high dimensions or small batches. Pooladian and colleagues and Tong and colleagues study this approximation and its tradeoffs. Improvement in a 2D example does not prove one or two steps suffice for ImageNet or text-to-image.
As a reference for one experiment, Pooladian and colleagues’ table 2 reports on ImageNet with Euler FID 7.71 for BatchOT and 63.08 for their DDPM baseline at 20 NFE. At 40 NFE it reports 5.94 and 19.56 respectively. These are study models and protocol: they are not measurements from our lab and do not prove BatchOT always wins.
Sinkhorn without numerical overflow
Entropic regularization adds to the cost, for . The optimal plan has form , with . Directly updating can underflow if is small. In log space, for positive marginals , updates are
Numerical stabilization does not guarantee convergence in a fixed iteration count: check residuals of both marginals. The entropic plan is usually diffuse; sampling pairs by mass and converting it to a permutation are different operations. Matrix construction and plan solution costs are also part of the budget. See Cuturi and Peyré and Cuturi.
Reflow and distillation
In reflow, a first model generates pairs between a base and its own outputs; a new regression learns the field associated with those pairs. These data inherit the first model’s distribution and errors. Rectification can reduce trajectory curvature under specific assumptions and measures, but a small sample, inexact integration or limited student can prevent empirical improvement. Reflow requires pair generation and training another model; it is not a free training acceleration.
Distillation can train a network to imitate a multistep map in fewer steps. It is related to reflow, but not every reflow round is the same operation as one-step distillation. To compare, fix held-out data, seeds, metric and generator NFE. Liu, Gong and Liu analyze rectification and distillation; the next experiment shows only what its own run produced.
Bridges and other geometries
A Schrödinger bridge seeks a stochastic process between endpoint distributions minimizing relative divergence to a reference process, usually diffusive. Endpoint distributions and reference must be specified; conditioning a Brownian process between two points alone does not solve the problem between two distributions. These bridges connect transport and diffusion, but high-dimensional approximation requires models, samples and computation; applying Sinkhorn to a small batch does not yield an exact solution. See De Bortoli and colleagues.
In audio one can transport signal representations; molecules and materials have symmetries, permutations or geometries that the field must respect. In robotic policies, the target may be an action-sequence distribution conditioned on observations. On manifolds a generic Euclidean sum need not remain in the space: tangent fields, maps or compatible integrators are needed. The Euclidean Gaussian formula does not transfer without assumptions.
Lab: OT-CFM and reflow in two dimensions
The quadratic cost matrix and entropic plan are calculated in log space. Assignment minimizes cost within the minibatch. With finite iterations, plan marginals are approximate; normalizing rows to sample can leave columns deviating from the desired distribution even in expectation.
"""Acoplamientos 2D y red de velocidades para OT-CFM."""
import numpy as np
from scipy.special import logsumexp
from scipy.optimize import linear_sum_assignment
CENTERS=np.array([[-1.5,-.4],[-.4,1.4],[1.5,.4],[.4,-1.4]])
def target(rng,n):
return CENTERS[rng.integers(0,4,n)]+.25*rng.normal(size=(n,2))
def sinkhorn(cost,eps,iters):
if eps<=0 or cost.ndim!=2:raise ValueError('Coste o regularización inválidos')
n,m=cost.shape; loga=-np.log(n);logb=-np.log(m)
logk=-cost/eps;u=np.zeros(n);v=np.zeros(m)
for _ in range(iters):
u=loga-logsumexp(logk+v[None,:],axis=1)
v=logb-logsumexp(logk+u[:,None],axis=0)
return np.exp(logk+u[:,None]+v[None,:])
def cost_matrix(a,b):return ((a[:,None,:]-b[None,:,:])**2).sum(axis=2)
sinkhorn_residuals=[]
def pair(x,y,kind,rng):
cost=cost_matrix(x,y)
if kind=='independent':return y[rng.permutation(len(y))],None
if kind=='exact':
rows,cols=linear_sum_assignment(cost)
assert np.array_equal(rows,np.arange(len(x)))
return y[cols],None
if kind=='sinkhorn':
plan=sinkhorn(cost,.6,20)
# La convergencia finita es aproximada; normalizar filas para muestrear
# puede alterar la marginal de columnas incluso en esperanza.
probs=plan/plan.sum(axis=1,keepdims=True)
sinkhorn_residuals.append(float(np.max(np.abs(probs.mean(axis=0)-1/len(y)))))
indices=(rng.random(len(x))[:,None]>np.cumsum(probs,axis=1)).sum(axis=1)
indices=np.minimum(indices,len(y)-1)
return y[indices],plan
raise ValueError('Acoplamiento desconocido')
def initialize(seed):
r=np.random.default_rng(seed);d=32
return [r.normal(scale=np.sqrt(1/3),size=(3,d)),np.zeros(d),
r.normal(scale=np.sqrt(1/d),size=(d,d)),np.zeros(d),
r.normal(scale=np.sqrt(1/d),size=(d,2)),np.zeros(2)]
def forward(x,t,params):
inp=np.concatenate((x,2*t-1),axis=1)
h1=np.tanh(inp@params[0]+params[1]);h2=np.tanh(h1@params[2]+params[3])
return h2@params[4]+params[5],(inp,h1,h2)
def gradient(x,t,y,params):
out,(inp,h1,h2)=forward(x,t,params);error=out-y
d=2*error/error.size; w3=h2.T@d;b3=d.sum(0)
d=(d@params[4].T)*(1-h2*h2);w2=h1.T@d;b2=d.sum(0)
d=(d@params[2].T)*(1-h1*h1)
return np.mean(error**2),[inp.T@d,d.sum(0),w2,b2,w3,b3]
def train(kind,seed,steps=350,pairs=None):
rng=np.random.default_rng(seed);params=initialize(2410)
moments=[np.zeros_like(p) for p in params];squares=[np.zeros_like(p) for p in params]
losses=[]
for step in range(1,steps+1):
if pairs is None:
a=rng.normal(size=(32,2));b=target(rng,32);b,_=pair(a,b,kind,rng)
else:
idx=rng.integers(0,len(pairs[0]),size=32);a=pairs[0][idx];b=pairs[1][idx]
t=rng.random((32,1));x=(1-t)*a+t*b
loss,grads=gradient(x,t,b-a,params)
for j,(p,g) in enumerate(zip(params,grads)):
moments[j]=.9*moments[j]+.1*g;squares[j]=.999*squares[j]+.001*g*g
p-=.003*(moments[j]/(1-.9**step))/(np.sqrt(squares[j]/(1-.999**step))+1e-8)
if step%50==0:losses.append(float(loss))
return params,losses
def solve(model,initial,steps,method='euler',track=False):
x=initial.copy();dt=1/steps;path=[x.copy()]
for k in range(steps):
t=k*dt;v=forward(x,np.full((len(x),1),t),model)[0]
if method=='midpoint':v=forward(x+.5*dt*v,np.full((len(x),1),t+.5*dt),model)[0]
elif method!='euler':raise ValueError('Método inválido')
x=x+dt*v
if track:path.append(x.copy())
return (x,np.stack(path)) if track else x
def sliced_w1(a,b):
angles=np.arange(32)*np.pi/32
directions=np.stack((np.cos(angles),np.sin(angles)),axis=0)
return np.mean(np.abs(np.sort(a@directions,axis=0)-np.sort(b@directions,axis=0)))
rng=np.random.default_rng(2401);a=rng.normal(size=(32,2));b=target(rng,32);C=cost_matrix(a,b)
plan=sinkhorn(C,.6,250)
rowerr=np.max(np.abs(plan.sum(1)-1/32));colerr=np.max(np.abs(plan.sum(0)-1/32))
assert rowerr<1e-8 and colerr<1e-8
ind,_=pair(a,b,'independent',rng);opt,_=pair(a,b,'exact',rng)
optcost=np.mean(((a-opt)**2).sum(1));indcost=np.mean(((a-ind)**2).sum(1));softcost=(plan*C).sum()
assert optcost<=indcost+1e-12 and optcost<=softcost+1e-8
print(f'Sinkhorn: error filas {rowerr:.2e}, columnas {colerr:.2e}; coste asignación/independiente/plan {optcost:.6f}/{indcost:.6f}/{softcost:.6f}')First train with independent pairs.
independent,loss_independent=train('independent',2411)
print('CFM independiente: 350 actualizaciones; pérdidas cada 50:',*[f'{v:.6f}' for v in loss_independent])Recalculate optimal assignment in each batch.
exact,loss_exact=train('exact',2412)
print('CFM asignación exacta: 350 actualizaciones; pérdidas cada 50:',*[f'{v:.6f}' for v in loss_exact])Sample entropic coupling from the Sinkhorn plan.
entropic,loss_entropic=train('sinkhorn',2413,steps=250)
print('CFM plan entrópico: 250 actualizaciones y 20 iteraciones de Sinkhorn por lote; pérdidas cada 50:',*[f'{v:.6f}' for v in loss_entropic])
print(f'Residual máximo de la marginal de columnas esperada tras normalizar filas: {max(sinkhorn_residuals):.6f}')The first reflow student learns pairs generated by the first field.
reflow_rng=np.random.default_rng(2414)
teacher_start=reflow_rng.normal(size=(1024,2))
teacher_end=solve(independent,teacher_start,32,method='midpoint')
reflow1,loss_reflow1=train('independent',2415,pairs=(teacher_start,teacher_end))
print('Reflow ronda 1: 1024 pares del maestro, 64 NFE por punto; pérdidas cada 50:',*[f'{v:.6f}' for v in loss_reflow1])The second student repeats the process with the first round.
reflow2_rng=np.random.default_rng(2416)
teacher2_start=reflow2_rng.normal(size=(1024,2))
teacher2_end=solve(reflow1,teacher2_start,32,method='midpoint')
reflow2,loss_reflow2=train('independent',2417,pairs=(teacher2_start,teacher2_end))
print('Reflow ronda 2: 1024 pares de la ronda 1, 64 NFE por punto; pérdidas cada 50:',*[f'{v:.6f}' for v in loss_reflow2])Curvature is measured as RMS deviation from each trajectory’s chord, sampled at 33 times. Euler uses one or two NFE and midpoint 64; distance is a mean of one-dimensional Wasserstein distances over 32 projections. Evaluation samples and seeds are independent of training.
"""Evaluación con ruido y datos nuevos para las cinco redes."""
test_rng=np.random.default_rng(2420)
initial=test_rng.normal(size=(256,2));reference=target(np.random.default_rng(2421),256)
models={'independiente':independent,'asignación':exact,'entrópico':entropic,'reflow 1':reflow1,'reflow 2':reflow2}
measurements={}
for name,model in models.items():
end,path=solve(model,initial,32,method='midpoint',track=True)
times=np.arange(33)[:,None,None]/32
chord=(1-times)*initial[None,:,:]+times*end[None,:,:]
curvature=np.sqrt(np.mean(np.sum((path-chord)**2,axis=2)))
one=solve(model,initial,1);two=solve(model,initial,2)
measurements[name]={'curvature':float(curvature),'w1_1':float(sliced_w1(one,reference)),
'w1_2':float(sliced_w1(two,reference)), 'w1_64':float(sliced_w1(end,reference))}
print(f'{name}: desviación RMS de cuerda {curvature:.6f}; sliced W1 1/2/64 NFE = '
f'{measurements[name]["w1_1"]:.6f}/{measurements[name]["w1_2"]:.6f}/{measurements[name]["w1_64"]:.6f}')
print('32 proyecciones, 256 muestras independientes, semilla de ruido 2420 y de datos 2421; no prueba un ranking universal.')Local lab: a diffusion model as a flow field
Retrieve the EMA of a lesson 18 ε checkpoint for CIFAR-10, with strictly positive terminal SNR. U-Net and schedule come from that checkpoint. The VP path is linearly interpolated in log between table indices. Use increasing time from noise to data: if and , construct and convert the noise network to . The CFM objective is MSE against . Its derivatives are piecewise; knots have zero probability when sampling continuous times. To avoid the singularity at , training is restricted to the segment between indices and 1. The sampler’s last step, from 1 to 0, uses the discrete formula without evaluating that derivative.
Fine-tune two copies of the same EMA with identical architecture, attempts, images and Gaussian noise: one distributes uniformly on that segment and the other applies a sigmoid to a normal with mean 0 and standard deviation 1, rescaled to the same segment. These are not two trainings from scratch: both inherit the checkpoint’s prior budget. Changing time law changes objective weighting; this experiment does not attribute effects exclusively to a method name. Velocity loss is not directly comparable in magnitude to noise MSE either: expressing both in errors introduces a time-dependent factor. The logit-normal variant follows the idea studied by Esser and colleagues, but here applies to this VP path and does not reproduce Stable Diffusion 3 training. Conditional-field regression is based on Lipman and colleagues.
For each model compare deterministic DDIM and Euler in coordinates and : . Each pair uses the same latents, levels and network evaluations. Per-step algebraic equality does not require bitwise equality: record maximum difference across complete trajectories. FID uses clean-fid==0.1.35 InceptionV3W features, 8-bit RGB input and PIL bicubic resizing; test images do not enter training. Also record NFE, seeds, sample clipping, weight fingerprints and, in parquet mode, data-file fingerprints, alongside features and fid-nfe.png. Few-image FID is highly biased and cannot confidently rank methods.
Install PyTorch, torchvision, NumPy, SciPy, Pillow, Matplotlib and clean-fid==0.1.35. Set ORYON_PREVIOUS_CKPT to the lesson 18 diffusion.pt path, ORYON_INCEPTION_PT to inception-2015-12-05.pt, ORYON_DATA_ROOT and ORYON_OUTPUT_DIR. Full mode proposes 4096 training images, 128 test images and 10,000 optimization attempts per arm; adjust ORYON_TRAIN_IMAGES, ORYON_TEST_IMAGES and ORYON_UPDATES. The save includes EMA, network and history, but does not automatically resume the optimizer. The full run is for the reader, not a result measured here.
With ORYON_QUICK=1, use 64 train images, eight test images and two attempts per arm; ORYON_CIFAR_PARQUET accepts the CIFAR parquet directory and requires PyArrow. In the protected test with lesson 18’s reduced checkpoint, both arms completed two updates without overflow. For four and eight NFE, maximum difference between DDIM and Euler trajectories was between and ; FIDs were about 592.7–593.2 and near 38% of components required clipping. This checks operation, not quality: there are only eight images and the short schedule ends at , making a standard-normal start a particularly poor approximation. The report retains the actual figure for your checkpoint.
"""Equivalencia de DDIM y Euler, y entrenamiento CFM con tiempos diferentes."""
import copy, hashlib, io, json, math, os
from pathlib import Path
os.environ.setdefault('OPENBLAS_NUM_THREADS','1')
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
from torch.utils.data import Dataset, DataLoader, Subset
from torchvision import datasets, transforms
from torchvision.utils import save_image
from PIL import Image
from cleanfid.inception_torchscript import InceptionV3W
from cleanfid.resize import build_resizer
torch.set_num_threads(2)
def groups(channels):
return math.gcd(32, channels)
class AdaResidual(nn.Module):
def __init__(self, channels, embedding):
super().__init__()
self.norm1 = nn.GroupNorm(groups(channels), channels)
self.conv1 = nn.Conv2d(channels, channels, 3, padding=1)
self.norm2 = nn.GroupNorm(groups(channels), channels, affine=False)
self.condition = nn.Linear(embedding, 2 * channels)
self.conv2 = nn.Conv2d(channels, channels, 3, padding=1)
def forward(self, x, embedding):
h = self.conv1(F.silu(self.norm1(x)))
scale, shift = self.condition(embedding).chunk(2, dim=1)
h = self.norm2(h) * (1 + scale[:, :, None, None]) + shift[:, :, None, None]
return x + self.conv2(F.silu(h))
class SpatialAttention(nn.Module):
"""Atención de producto escalar solo en mapas de 16×16 y 8×8."""
def __init__(self, channels, head_dim=32):
super().__init__()
self.heads = max(1, channels // min(head_dim, channels))
if channels % self.heads:
raise ValueError('Los canales deben dividirse entre las cabezas')
self.norm = nn.GroupNorm(groups(channels), channels)
self.qkv = nn.Conv2d(channels, 3 * channels, 1)
self.output = nn.Conv2d(channels, channels, 1)
def forward(self, x):
batch, channels, height, width = x.shape
q, k, v = self.qkv(self.norm(x)).chunk(3, dim=1)
def arrange(z):
return z.reshape(batch, self.heads, channels // self.heads, height * width).transpose(2, 3)
h = F.scaled_dot_product_attention(arrange(q), arrange(k), arrange(v))
h = h.transpose(2, 3).reshape(batch, channels, height, width)
return x + self.output(h)
class DiffusionUNet(nn.Module):
"""CIFAR 32×32, niveles 32/16/8; ancho 128 en el modo completo."""
def __init__(self, width=128):
super().__init__()
if width < 8 or width % 8:
raise ValueError('El ancho debe ser un múltiplo de ocho')
embedding = 4 * width
self.width = width
self.time = nn.Sequential(nn.Linear(width, embedding), nn.SiLU(), nn.Linear(embedding, embedding))
self.input = nn.Conv2d(3, width, 3, padding=1)
self.enc32a = AdaResidual(width, embedding)
self.enc32b = AdaResidual(width, embedding)
self.down16 = nn.Conv2d(width, 2 * width, 3, stride=2, padding=1)
self.enc16a = AdaResidual(2 * width, embedding)
self.enc16b = AdaResidual(2 * width, embedding)
self.attn16_down = SpatialAttention(2 * width)
self.down8 = nn.Conv2d(2 * width, 3 * width, 3, stride=2, padding=1)
self.mid8a = AdaResidual(3 * width, embedding)
self.attn8 = SpatialAttention(3 * width)
self.mid8b = AdaResidual(3 * width, embedding)
self.up16 = nn.ConvTranspose2d(3 * width, 2 * width, 4, stride=2, padding=1)
self.merge16 = nn.Conv2d(4 * width, 2 * width, 1)
self.dec16a = AdaResidual(2 * width, embedding)
self.dec16b = AdaResidual(2 * width, embedding)
self.attn16_up = SpatialAttention(2 * width)
self.up32 = nn.ConvTranspose2d(2 * width, width, 4, stride=2, padding=1)
self.merge32 = nn.Conv2d(2 * width, width, 1)
self.dec32a = AdaResidual(width, embedding)
self.dec32b = AdaResidual(width, embedding)
self.out_norm = nn.GroupNorm(groups(width), width)
self.output = nn.Conv2d(width, 3, 3, padding=1)
def forward(self, x, t, T):
half = self.width // 2
freq = torch.exp(torch.linspace(0, -math.log(10000), half, device=x.device, dtype=x.dtype))
phase = (t.to(x.dtype) * (1000. / T))[:, None] * freq[None]
emb = self.time(torch.cat((phase.sin(), phase.cos()), dim=1))
h = self.input(x)
s32 = self.enc32b(self.enc32a(h, emb), emb)
h = self.down16(s32)
s16 = self.attn16_down(self.enc16b(self.enc16a(h, emb), emb))
h = self.mid8a(self.down8(s16), emb)
h = self.mid8b(self.attn8(h), emb)
h = self.merge16(torch.cat((self.up16(h), s16), dim=1))
h = self.attn16_up(self.dec16b(self.dec16a(h, emb), emb))
h = self.merge32(torch.cat((self.up32(h), s32), dim=1))
h = self.dec32b(self.dec32a(h, emb), emb)
return self.output(F.silu(self.out_norm(h)))
def make_schedule(kind, T, device, zero_terminal=False):
if T < 2 or kind not in ('linear', 'cosine'):
raise ValueError('Calendario o número de pasos inválidos')
if kind == 'linear':
beta = torch.linspace(1e-4, .02, T, dtype=torch.float64, device=device)
else:
t = torch.arange(T + 1, dtype=torch.float64, device=device) / T
f = torch.cos((t + .008) / 1.008 * math.pi / 2).square()
beta = (1 - f[1:] / f[:-1]).clamp(max=.999)
bar = torch.cumprod(1 - beta, dim=0)
if zero_terminal:
a = bar.sqrt()
# Preserva el primer nivel ruidoso, no el índice t=0 que se añade después.
a = (a - a[-1]) * a[0] / (a[0] - a[-1])
bar = a.square()
previous = torch.cat((torch.ones(1, dtype=bar.dtype, device=device), bar[:-1]))
beta = 1 - bar / previous
beta = torch.cat((torch.zeros(1, dtype=beta.dtype, device=device), beta))
bar = torch.cat((torch.ones(1, dtype=bar.dtype, device=device), bar))
previous = torch.cat((bar[:1], bar[:-1]))
return {'T': T, 'kind': kind, 'beta': beta, 'bar': bar, 'previous': previous,
'zero_terminal': zero_terminal}
def sha256(path):
d=hashlib.sha256()
with open(path,'rb') as f:
for block in iter(lambda:f.read(1024*1024),b''):d.update(block)
return d.hexdigest()
class ParquetCifar(Dataset):
def __init__(self,folder,split,count):
import pyarrow.parquet as pq
self.rows=[];self.files=[]
for path in sorted(Path(folder).glob(f'{split}-*.parquet')):
self.files.append(str(path))
for batch in pq.ParquetFile(path).iter_batches(batch_size=128,columns=['img']):
self.rows.extend(row['img']['bytes'] for row in batch.to_pylist())
if len(self.rows)>=count:break
if len(self.rows)>=count:break
if len(self.rows)<count:raise ValueError('Faltan imágenes en parquet')
self.rows=self.rows[:count]
def __len__(self):return len(self.rows)
def __getitem__(self,index):
with Image.open(io.BytesIO(self.rows[index])) as img:
return transforms.ToTensor()(img.convert('RGB')),0
def get_data(root,quick,parquet,n_train,n_test):
if parquet:
if not quick:raise ValueError('Parquet solo se admite en quick')
train=ParquetCifar(parquet,'train',n_train);test=ParquetCifar(parquet,'test',n_test)
return train,test,{'source':'parquet CIFAR-10','train':'primeras filas','test':'primeras filas',
'files':[{'name':Path(p).name,'sha256':sha256(p)} for p in train.files+test.files]}
train=datasets.CIFAR10(root,train=True,download=True,transform=transforms.ToTensor())
test=datasets.CIFAR10(root,train=False,download=True,transform=transforms.ToTensor())
ids=torch.randperm(len(train),generator=torch.Generator().manual_seed(2410))[:n_train].tolist()
return Subset(train,ids),Subset(test,range(n_test)),{'source':'torchvision CIFAR-10',
'train':'subconjunto permutado con semilla 2410','test':'primeras filas'}
def continuous_coefficients(tau,bars):
# τ crece de ruido a datos; interpolamos log ᾱ de la tabla discreta.
T=len(bars)-1
td=(1-tau)*T
if torch.any(td<1) or torch.any(td>T):raise ValueError('τ fuera del rango VP positivo')
lo=torch.floor(td).long().clamp(1,T-1);hi=lo+1
frac=td-lo
logbar=bars.log()
L=(1-frac)*logbar[lo]+frac*logbar[hi]
dL=-T*(logbar[hi]-logbar[lo])
alpha=torch.exp(.5*L);sigma=torch.sqrt(-torch.expm1(L))
dalpha=.5*alpha*dL;dsigma=-.5*torch.exp(L)*dL/sigma
return td,alpha,sigma,dalpha,dsigma
def epsilon_to_velocity(xt,eps,alpha,sigma,dalpha,dsigma):
a=alpha[:,None,None,None];s=sigma[:,None,None,None]
clean=(xt-s*eps)/a
return dalpha[:,None,None,None]*clean+dsigma[:,None,None,None]*eps
def time_samples(kind,count,T,generator,device,mu=0.,spread=1.):
if kind=='uniform':u=torch.rand((count,),generator=generator,device=device)
elif kind=='logit-normal':u=torch.sigmoid(mu+spread*torch.randn((count,),generator=generator,device=device))
else:raise ValueError('Distribución temporal desconocida')
# Evita redondear al extremo determinista cuando sigmoid se satura en float32.
u=u.clamp(min=1e-7,max=1-1e-7)
return u*((T-1)/T)
def fid(real,fake):
a,b=np.asarray(real,np.float64),np.asarray(fake,np.float64)
x,y=a-a.mean(0),b-b.mean(0)
cross=np.linalg.svd(x@y.T,compute_uv=False).sum()/math.sqrt((len(x)-1)*(len(y)-1))
value=np.square(a.mean(0)-b.mean(0)).sum()+(x*x).sum()/(len(x)-1)+(y*y).sum()/(len(y)-1)-2*cross
if value < -1e-7:raise ValueError('FID negativo fuera de tolerancia')
return max(float(value),0.)
def image_features(images,inception,device):
resize=build_resizer('clean');out=[]
with torch.inference_mode():
for i in range(0,len(images),4):
pixels=(images[i:i+4].clamp(0,1)*255).round().to(torch.uint8)
arrays=pixels.permute(0,2,3,1).cpu().numpy()
resized=np.stack([resize(a).transpose(2,0,1) for a in arrays])
out.append(inception(torch.from_numpy(resized).to(device)).cpu().numpy())
return np.concatenate(out)
def grid(T,n):
if n<2 or n>T:raise ValueError('Cantidad de pasos inválida')
ids=np.rint(np.linspace(T,1,n)).astype(int).tolist()
if len(set(ids))!=n:raise ValueError('Tiempos duplicados')
return ids+[0]
def ddim_step(x,eps,bt,bs):
a,s=math.sqrt(bt),math.sqrt(1-bt)
clean=(x-s*eps)/a
return math.sqrt(bs)*clean+math.sqrt(1-bs)*eps
def euler_step(x,eps,bt,bs):
a,s=math.sqrt(bt),math.sqrt(1-bt)
next_a,next_s=math.sqrt(bs),math.sqrt(1-bs)
r,next_r=s/a,next_s/next_a
return next_a*(x/a+(next_r-r)*eps)
@torch.no_grad()
def sample(model,bars,initial,ids,method):
x=initial.clone();T=len(bars)-1
for t,s in zip(ids[:-1],ids[1:]):
times=torch.full((len(x),),t,device=x.device,dtype=torch.long)
eps=model(x,times,T)
if method=='ddim':x=ddim_step(x,eps,bars[t],bars[s])
elif method=='euler':x=euler_step(x,eps,bars[t],bars[s])
else:raise ValueError('Sampler desconocido')
if not torch.isfinite(x).all():raise FloatingPointError('La trayectoria dejó de ser finita')
return x,len(ids)-1
def verify(device):
T=20;bars=make_schedule('linear',T,'cpu')['bar']
tau=torch.tensor([.123,.417,.781],dtype=torch.float64)
td,a,s,da,ds=continuous_coefficients(tau,bars)
h=1e-6
_,ap,sp,_,_=continuous_coefficients(tau+h,bars)
_,am,sm,_,_=continuous_coefficients(tau-h,bars)
assert torch.allclose((ap-am)/(2*h),da,atol=1e-8,rtol=1e-6)
assert torch.allclose((sp-sm)/(2*h),ds,atol=1e-8,rtol=1e-6)
gen=torch.Generator(device=device).manual_seed(2401)
x=torch.randn((3,3,4,4),device=device,generator=gen)
e=torch.randn(x.shape,device=device,generator=gen)
b=float(bars[10]);aa=math.sqrt(b);ss=math.sqrt(1-b)
clean=(x-ss*e)/aa;v=aa*e-ss*clean;score=-e/ss
assert torch.allclose(aa*x-ss*v,clean,atol=1e-6)
assert torch.allclose(ss*x+aa*v,e,atol=1e-6)
assert torch.allclose(-ss*score,e,atol=1e-6)
direct=ddim_step(x,e,b,float(bars[4]));reparam=euler_step(x,e,b,float(bars[4]))
assert torch.allclose(direct,reparam,atol=1e-6,rtol=1e-6)
td,alpha,sigma,dalpha,dsigma=continuous_coefficients(tau,bars)
tau_x=torch.randn((3,3,4,4),generator=gen,device=device)
tau_e=torch.randn(tau_x.shape,generator=gen,device=device)
alpha,sigma,dalpha,dsigma=[v.to(device,dtype=tau_x.dtype) for v in (alpha,sigma,dalpha,dsigma)]
xt=alpha[:,None,None,None]*tau_x+sigma[:,None,None,None]*tau_e
expected=dalpha[:,None,None,None]*tau_x+dsigma[:,None,None,None]*tau_e
assert torch.allclose(epsilon_to_velocity(xt,tau_e,alpha,sigma,dalpha,dsigma),expected,atol=1e-6)
with torch.device('meta'):full=DiffusionUNet(128)
assert sum(p.numel() for p in full.parameters())==18_477_315
print('Controles: derivadas α/σ por diferencias finitas, conversiones y paso DDIM/Euler.',flush=True)
def train_model(initial,bars,dataset,kind,device,quick,out,mu,spread):
torch.manual_seed(2412)
model=copy.deepcopy(initial).to(device).train()
ema=copy.deepcopy(model).eval().requires_grad_(False)
optimizer=torch.optim.AdamW(model.parameters(),lr=2e-4)
scaler=torch.amp.GradScaler('cuda',enabled=device.type=='cuda')
generator=torch.Generator(device=device).manual_seed(2414)
noise_generator=torch.Generator(device=device).manual_seed(2416)
loader=DataLoader(dataset,batch_size=4 if quick else 8,shuffle=True,
generator=torch.Generator().manual_seed(2413),num_workers=0,drop_last=True)
batches=iter(loader);updates=2 if quick else int(os.environ.get('ORYON_UPDATES','10000'))
accumulation=1 if quick else 4
completed=0;skipped=0;history=[];T=len(bars)-1
for step in range(updates):
optimizer.zero_grad(set_to_none=True);loss_sum=0.
for _ in range(accumulation):
try: clean,_=next(batches)
except StopIteration:
batches=iter(loader);clean,_=next(batches)
clean=clean.to(device)*2-1
tau=time_samples(kind,len(clean),T,generator,device,mu,spread)
td,a,s,da,ds=continuous_coefficients(tau,bars)
noise=torch.randn(clean.shape,generator=noise_generator,device=device)
xt=a[:,None,None,None]*clean+s[:,None,None,None]*noise
target=da[:,None,None,None]*clean+ds[:,None,None,None]*noise
with torch.autocast(device_type=device.type,enabled=device.type=='cuda'):
pred=model(xt,td,T)
velocity=epsilon_to_velocity(xt,pred,a,s,da,ds)
loss=F.mse_loss(velocity.float(),target.float())/accumulation
if not torch.isfinite(loss):raise FloatingPointError('Pérdida no finita')
scaler.scale(loss).backward();loss_sum+=float(loss.detach())
old_scale=scaler.get_scale();scaler.step(optimizer);scaler.update()
if scaler.get_scale()<old_scale:skipped+=1
else:
completed+=1
decay=min(.9999,(1+completed)/(10+completed))
with torch.no_grad():
for avg,param in zip(ema.parameters(),model.parameters(),strict=True):
avg.lerp_(param,1-decay)
for avg,param in zip(ema.buffers(),model.buffers(),strict=True):avg.copy_(param)
if step==0 or (step+1)%max(1,updates//10)==0:
history.append({'attempt':step+1,'loss':loss_sum,'effective_updates':completed,'skipped':skipped})
print(f'{kind}: paso {step+1}/{updates}, pérdida {loss_sum:.5f}, saltados {skipped}',flush=True)
result={'ema':{k:v.detach().cpu() for k,v in ema.state_dict().items()},
'model':{k:v.detach().cpu() for k,v in model.state_dict().items()},'kind':kind,
'attempts':updates,'effective_updates':completed,'skipped':skipped,'history':history,
'seed_data':2413,'seed_times':2414,'seed_noise':2416,'logit_mu':mu,'logit_spread':spread}
torch.save(result,out/f'{kind}.pt')
del model,ema,optimizer,scaler,batches,loader
if device.type=='cuda':torch.cuda.empty_cache()
return result
def main():
quick=os.environ.get('ORYON_QUICK','0')=='1'
previous_path=Path(os.environ['ORYON_PREVIOUS_CKPT'])
inception_path=Path(os.environ['ORYON_INCEPTION_PT'])
if inception_path.name!='inception-2015-12-05.pt':
raise ValueError('El extractor debe llamarse inception-2015-12-05.pt')
out=Path(os.environ.get('ORYON_OUTPUT_DIR','oryon-l24'));out.mkdir(parents=True,exist_ok=True)
device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
verify(device)
previous=torch.load(previous_path,map_location='cpu',weights_only=True)
if previous['parameterization']!='epsilon' or previous.get('zero_terminal',False):
raise ValueError('Se necesita checkpoint épsilon de m19-l18 con SNR terminal positiva')
T=int(previous['T']);width=int(previous['width'])
schedule=make_schedule(previous['schedule'],T,device)
bars=schedule['bar'].to(torch.float32)
if bars[-1]<=0:raise ValueError('Alfa terminal cero: la conversión épsilon es singular')
model=DiffusionUNet(width).cpu();model.load_state_dict(previous['ema']);model.eval()
n_train=64 if quick else int(os.environ.get('ORYON_TRAIN_IMAGES','4096'))
n_test=8 if quick else int(os.environ.get('ORYON_TEST_IMAGES','128'))
if n_test<2:raise ValueError('FID necesita al menos dos muestras por conjunto')
train,test,data_info=get_data(os.environ.get('ORYON_DATA_ROOT','./data'),quick,
os.environ.get('ORYON_CIFAR_PARQUET'),n_train,n_test)
mu=float(os.environ.get('ORYON_LOGIT_MEAN','0'));spread=float(os.environ.get('ORYON_LOGIT_STD','1'))
if spread<=0:raise ValueError('La desviación logit-normal debe ser positiva')
uniform=train_model(model,bars,train,'uniform',device,quick,out,mu,spread)
logistic=train_model(model,bars,train,'logit-normal',device,quick,out,mu,spread)
reference=torch.stack([test[i][0] for i in range(n_test)])
inception=InceptionV3W(str(inception_path.parent),download=False,resize_inside=False).to(device).eval()
real=image_features(reference,inception,device)
feature_data={'real':real};rows=[]
budgets=[4,8] if quick else [10,20,50]
for label,state in [('previo',previous['ema']),('uniforme',uniform['ema']),('logit-normal',logistic['ema'])]:
model.load_state_dict(state);model.to(device).eval()
for nfe in budgets:
if nfe>T:continue
gen=torch.Generator(device=device).manual_seed(2415)
ddim=[];euler=[]
for start in range(0,n_test,4):
count=min(4,n_test-start)
noise=torch.randn((count,3,32,32),device=device,generator=gen)
x1,c1=sample(model,bars,noise,grid(T,nfe),'ddim')
x2,c2=sample(model,bars,noise,grid(T,nfe),'euler')
assert c1==c2==nfe
ddim.append(x1.cpu());euler.append(x2.cpu())
d=torch.cat(ddim);e=torch.cat(euler)
err=float((d-e).abs().max());clipped=float(((d<-1)|(d>1)).float().mean())
features=image_features((d+1)/2,inception,device)
features_euler=image_features((e+1)/2,inception,device)
feature_data[f'{label}_{nfe}_ddim']=features
feature_data[f'{label}_{nfe}_euler']=features_euler
row={'model':label,'nfe':nfe,'fid_ddim':fid(real,features),
'fid_euler':fid(real,features_euler),'trajectory_max_abs_error':err,
'fraction_clipped':clipped}
rows.append(row)
save_image(((d[:8]+1)/2).clamp(0,1),out/f'{label}-{nfe}.png',nrow=4)
print(json.dumps(row,ensure_ascii=False),flush=True)
model.cpu()
if device.type=='cuda':torch.cuda.empty_cache()
np.savez_compressed(out/'features.npz',**feature_data)
report={'quick':quick,'checkpoint_sha256':sha256(previous_path),'inception_sha256':sha256(inception_path),
'checkpoint':{'width':width,'T':T,'schedule':previous['schedule'],
'effective_updates':previous.get('effective_updates'),'terminal_alpha_bar':float(bars[-1])},
'data':data_info,'train_count':n_train,'test_count':n_test,'logit_mu':mu,'logit_spread':spread,
'tau_interval':[0.,(T-1)/T],'seed_data':2413,'seed_times':2414,'seed_noise':2416,'seed_sample':2415,
'uniform_history':uniform['history'],'logit_normal_history':logistic['history'],
'uniform_skipped':uniform['skipped'],'logit_normal_skipped':logistic['skipped'],
'fid_protocol':'clean-fid InceptionV3W, RGB uint8, PIL float bicúbico 299',
'evaluation':'mismo ruido inicial en todos los brazos; muestras de test distintas de entrenamiento',
'results':rows}
(out/'report.json').write_text(json.dumps(report,ensure_ascii=False,indent=2),encoding='utf-8')
import matplotlib.pyplot as plt
fig,ax=plt.subplots(figsize=(6,4))
for label in ('previo','uniforme','logit-normal'):
selected=[r for r in rows if r['model']==label]
ax.plot([r['nfe'] for r in selected],[r['fid_ddim'] for r in selected],marker='o',label=label)
ax.set(xlabel='Evaluaciones de red (NFE)',ylabel='FID Inception',title=f'FID de {n_test} muestras; sesgo elevado')
ax.legend();fig.tight_layout();fig.savefig(out/'fid-nfe.png',dpi=140);plt.close(fig)
del inception,model
if device.type=='cuda':torch.cuda.empty_cache()
print('Informe guardado en',out/'report.json',flush=True)
if __name__=='__main__':main()
npm run lab and open the connection link.Exercises
Step 1 of 3. What relation links score and conditional noise expectation?
Step 1 of 2. What inequality does optimality require?
import numpy as np
from scipy.special import logsumexp
def sinkhorn(C, eps, n_iters):
pass
def sample_pairs(P, x, y, n, rng):
pass
Score, noise and velocity can parameterize the same Gaussian field under compatible conventions. Coupling, weighting and solving are additional decisions that change the practical problem.