Module contents
Lesson 23 of 28Core 115 min

Flow matching: learning the velocity field by regression

Derive conditional flow matching from probability paths, conditional and marginal fields, and regression; explore Gaussian paths and rectified flow, then compare numerical sampling and diffusion.

After this lesson you can

  • Explain probability paths and their continuity equation.
  • Derive the posterior-averaged marginal vector field.
  • Prove the conditional and marginal flow-matching gradient identity.
  • Analyze Gaussian paths and rectified-flow training.
  • Implement flow matching and compare its sampling cost with diffusion.

Before you start

Learn a velocity without solving an ODE during training

A continuous flow transforms an initial distribution by following an ODE. Likelihood training can require solving that ODE and differentiating through the solution. Can we choose velocities for which supervised examples can be generated and train by regression, leaving integration for sampling?

Flow matching makes exactly that separation. In this lesson time increases from noise at t=0t=0 to data at t=1t=1, opposite to the forward diffusion convention used earlier. We first learn a field from conditional paths; then solve the learned field’s ODE. Paths used to construct targets may be straight, while marginal-field trajectories can curve.

Probability paths and continuity

A probability path is a family of densities pt(x)p_t(x) between a base and a target distribution. A field ut(x)u_t(x) transporting that density satisfies the continuity equation

∂tpt(x)+∇⋅(pt(x)ut(x))=0.\partial_t p_t(x)+\nabla\cdot(p_t(x)u_t(x))=0.

The equation describes local mass conservation. It does not by itself determine a unique field: other fields can have the same weighted divergence. Going from a continuity solution to the law of solutions of X˙t=ut(Xt)\dot X_t=u_t(X_t) also requires assumptions ensuring existence and uniqueness of the flow and permitting change of variables; a formal divergence identity alone is insufficient.

Average conditional fields

Let ZZ be a conditioning variable with law qq independent of tt. For each zz, suppose a density pt(x∣z)p_t(x\mid z) and field ut(x∣z)u_t(x\mid z) satisfy continuity in 0<t<10<t<1. Also assume sufficient integrability to exchange derivative, divergence and integral, and define

pt(x)=∫pt(x∣z)q(dz),ut(x)=∫ut(x∣z)pt(x∣z)q(dz)pt(x)p_t(x)=\int p_t(x\mid z)q(dz),\qquad u_t(x)=\frac{\int u_t(x\mid z)p_t(x\mid z)q(dz)}{p_t(x)}

at points where pt(x)>0p_t(x)>0. That is, the marginal field is E[ut(Xt∣Z)∣Xt=x]\mathbb E[u_t(X_t\mid Z)\mid X_t=x]. Multiply by ptp_t and substitute into continuity:

∂tpt=∫∂tpt(x∣z)q(dz)=−∫∇⋅[pt(x∣z)ut(x∣z)]q(dz)=−∇⋅[pt(x)ut(x)].\begin{aligned} \partial_t p_t &=\int \partial_t p_t(x\mid z)q(dz)\\ &=-\int\nabla\cdot[p_t(x\mid z)u_t(x\mid z)]q(dz)\\ &=-\nabla\cdot[p_t(x)u_t(x)]. \end{aligned}

If the marginal field is also sufficiently regular and the ODE well posed, its flow reproduces that marginal path with the corresponding initial condition. We are not averaging equally: posterior probabilities pt(z∣x)p_t(z\mid x) weight velocities. When two conditional straight lines pass through the same point, their velocities may differ; the marginal field assigns one velocity to that point and time. Under ODE uniqueness, two solutions of the same field cannot cross at the same instant and later separate.

InteractiveConditional straight lines and marginal field

Two particular pairs follow straight lines that meet at t = 0.5. Gray arrows show the marginal field, which assigns one velocity to each position and time.

  • Pair moving right
  • Pair moving left
  • Marginal trajectories
  • Average at the marked point
  • Marginal field

At the marked point, two colored arrows show the mean velocities conditional on each mixture component. The third averages them with the displayed posterior probabilities. The two straight lines follow the individual pairs. Arrow lengths are compressed for readability while preserving direction.

The source x₀ is standard normal. The target x₁ is an equal-weight mixture of two Gaussians centered at (−1.4, 0) and (1.4, 0), with standard deviation 0.35. Within each component, xₜ has variance (1−t)²+0.35²t². The field and probabilities use exact Gaussian conditioning. The two example pairs were selected to cross. The marginal paths start at the same positions and use RK4 with 100 steps.

50
Time t
0.50
Left component posterior
0.018
Right component posterior
0.982
Change time and observe weights and field for the stated model.

Why conditional regression suffices

Let vθ(x,t)v_\theta(x,t) be a parameterized field and sample times from the same distribution r(t)r(t) in both objectives. Denote conditional velocity by U=ut(Xt∣Z)U=u_t(X_t\mid Z) and marginal velocity by Uˉ=E[U∣Xt,t]\bar U=\mathbb E[U\mid X_t,t]. Assume finite second moments, training distribution and targets independent of θ\theta, and that derivative and expectation can be exchanged. Define

LCFM=E∥vθ(Xt,t)−U∥2,LFM=E∥vθ(Xt,t)−Uˉ∥2.L_{\rm CFM}=\mathbb E\|v_\theta(X_t,t)-U\|^2,\qquad L_{\rm FM}=\mathbb E\|v_\theta(X_t,t)-\bar U\|^2.

Writing vθ−U=(vθ−Uˉ)+(Uˉ−U)v_\theta-U=(v_\theta-\bar U)+(\bar U-U), the cross term has zero expectation because vθ−Uˉv_\theta-\bar U depends only on (Xt,t)(X_t,t) and E[U−Uˉ∣Xt,t]=0\mathbb E[U-\bar U\mid X_t,t]=0. Therefore

LCFM=LFM+E∥U−Uˉ∥2,∇θLCFM=∇θLFM.L_{\rm CFM}=L_{\rm FM}+\mathbb E\|U-\bar U\|^2, \qquad \nabla_\theta L_{\rm CFM}=\nabla_\theta L_{\rm FM}.

This is the conditional flow matching theorem in regression form: the easy and marginal losses have the same gradient, but not necessarily the same value. The final term is irreducible conditional variance. It can be positive even with a perfect model; if conditional velocity is determined by (Xt,t)(X_t,t), it can be zero. Gradient equality also does not guarantee a finite architecture reaches the exact field. See Lipman and colleagues and conditional expectation projection. Albergo and Vanden-Eijnden develop a related perspective via stochastic interpolants; guides by Lipman and colleagues and Holderrieth and Erives expand the formulation and diffusion connections.

Gaussian paths

For a family of conditional Gaussian paths, assume ϵ∼N(0,I)\epsilon\sim\Normal(0,I) and, conditioned on x1x_1,

Xt=αtx1+σtϵ,pt(x∣x1)=N(αtx1,σt2I).X_t=\alpha_t x_1+\sigma_t\epsilon, \qquad p_t(x\mid x_1)=\Normal(\alpha_t x_1,\sigma_t^2 I).

If αt,σt\alpha_t,\sigma_t are differentiable and σt>0\sigma_t>0, differentiating the same noise sample gives

ut(x∣x1)=α˙tx1+σ˙tσt(x−αtx1).u_t(x\mid x_1)=\dot\alpha_t x_1+ \frac{\dot\sigma_t}{\sigma_t}(x-\alpha_t x_1).

This field generates the Gaussian family under the usual assumptions. Division by σt\sigma_t requires separate treatment of an endpoint where the deviation vanishes: the conditional density there may be a delta and the pointwise formula is undefined. The VP diffusion case follows from suitable coefficients and reversed time convention; a cosine or linear path chooses different functions. The visualization compares their fields and densities for an explicit model.

InteractivePath families

Both curves in each pair start at the same point. One interpolates a noise–data pair, and the other integrates the exact marginal velocity. Dots mark the selected time.

  • Conditional interpolation
  • Marginal ODE
  • Exact density of x₁

Noise z is N(0,I) and the data come from two equally weighted Gaussians with means (±1.4, 0) and standard deviation 0.35. The path xₜ = α(t)x₁ + σ(t)z uses α = t and σ = 1 − t for the linear family, or α = sin(πt/2) and σ = cos(πt/2) for the cosine family. Reverse VP uses α = exp(−B(1 − t)/2), σ = √(1 − α²), and B(u) = 0.1u + 4.95u². Its starting state has a small residual signal at t = 0.

The density is the exact mixture projected onto x₁. The field uses the posterior probabilities of both components. Six trajectories use RK4 over 100 intervals up to t = 0.98 and seed 2320. Stopping short avoids the singular derivative of σ at the VP endpoint. The turning angle sums absolute changes of direction between consecutive segments on the first marginal trajectory. It is a discrete diagnostic and cannot determine how easy sampling will be.

Path family
0.50
Displayed time
0.500
α / σ
0.500 / 0.500
Marginal turning angle, curve 1
168.7°
Change interpolation and observe what stays the same and what changes.

Rectified flow and straight paths

In rectified flow, take a pair (x0,x1)(x_0,x_1) from a chosen joint distribution and define

Xt=(1−t)x0+tx1,U=x1−x0.X_t=(1-t)x_0+t x_1,\qquad U=x_1-x_0.

If x0x_0 is normal and independent of fixed datum x1x_1, this matches αt=t\alpha_t=t, σt=1−t\sigma_t=1-t. For t<1t<1, the conditional field can also be written (x1−x)/(1−t)(x_1-x)/(1-t); representing it as a pair velocity avoids evaluating that division at t=1t=1. The practical objective samples tt, x0x_0 and x1x_1 and fits vθ(Xt,t)v_\theta(X_t,t) to x1−x0x_1-x_0. Endpoint coupling matters: pairing noise and data independently is a choice, not a guarantee of globally optimal transport.

Training straight lines can cross. The marginal ODE averages velocities compatible with each point, so its solutions need not be straight. One Euler step exactly reproduces only a trajectory with constant velocity throughout the interval; velocity changing in time or position introduces discretization error. Liu, Gong and Liu study rectified flow and additional rectification procedures. A higher-order solver can reduce error under smoothness conditions and sufficient budget, without automatically correcting a poorly learned field.

InteractiveFlow matching live

Compare target points with samples generated from the same noise at different step counts. The plot shows the field at the selected time and traces eight full trajectories.

  • Target data
  • Samples and eight Euler trajectories
  • Network field
  • Test CFM loss

Each update draws 64 fresh pairs with standard normal z, data x₁ and uniform t. The input is xₜ = (1 − t)z + tx₁ and the target is x₁ − z. The 3 → 24 → 2 network uses tanh and Adam with learning rate 0.004. Training runs for 1500 interruptible updates. Initialization and batches use seeds 2301 and 2302. Test loss sums squared error across coordinates and averages over 256 fixed independent pairs with seed 2303. The 64 generated samples use fixed noise with seed 2304. Target points use seed 2305.

The moons are two semicircles with Gaussian noise of standard deviation 0.08. The checkerboard chooses one of eight alternating squares and a uniform point within it. The minimum CFM loss can be positive because conditional velocities vary, and a short run cannot identify that minimum. Test loss alone cannot establish sample quality, and additional integration steps may not fix an inaccurate field. The plot clips points outside its axes.

Target data
Euler steps
0.50
Updates
0 / 1500
Test CFM loss
4.323
Evaluations per sample
5
Train the figure’s model and compare loss, trajectories and Euler budgets.

To sample with Euler, initialize xx in the base and repeat x←x+vθ(x,t)/Nx\leftarrow x+v_\theta(x,t)/N at t=0,1/N,…,(N−1)/Nt=0,1/N,\ldots,(N-1)/N. Midpoint uses an intermediate prediction and two evaluations per step. Compare NFE, not just steps. Choosing uniform tt is simple; a different distribution can emphasize regions but changes the weighted objective unless importance is adjusted. Do not automatically attribute poor one-step results to failed training: compare the same network with more evaluations and a numerical reference.

Lab: flow matching with NumPy

The target distribution is a known mixture of two 2D Gaussians. Generate 1024 finite examples for training and another 1024 independent pairs for evaluation; the exact comparison field is for the population mixture, not the empirical training distribution. Squares are averaged over coordinates and samples. Regression loss need not vanish because multiple conditional velocities can coincide at one point.

[ ]CFM and marginal field in NumPyBrowser
"""CFM en una mezcla gaussiana 2D con campo marginal exacto."""
import numpy as np

CENTERS = np.array([[-1.4,0.],[1.4,0.]])
SIGMA = .35
rng = np.random.default_rng(2301)

def draw_target(rng,n):
    component = rng.integers(0,2,size=n)
    return CENTERS[component] + SIGMA*rng.normal(size=(n,2))

def marginal(x,t):
    x=np.asarray(x); t=np.asarray(t).reshape(-1,1)
    variance=(1-t)**2+(SIGMA*t)**2
    delta=x[:,None,:]-t[:,None,:]*CENTERS[None,:,:]
    logits=-(delta**2).sum(axis=-1)/(2*variance)
    logits-=logits.max(axis=1,keepdims=True)
    weights=np.exp(logits); weights/=weights.sum(axis=1,keepdims=True)
    k=(-(1-t)+SIGMA**2*t)/variance
    conditional=CENTERS[None,:,:]+k[:,None,:]*delta
    return (weights[:,:,None]*conditional).sum(axis=1)

def x_and_target(x0,x1,t):
    return (1-t)*x0+t*x1, x1-x0

train_x1=draw_target(np.random.default_rng(2302),1024)
test_rng=np.random.default_rng(2303)
test_x1=draw_target(test_rng,1024); test_x0=test_rng.normal(size=(1024,2))
test_t=test_rng.uniform(size=(1024,1)); test_x,test_velocity=x_and_target(test_x0,test_x1,test_t)
test_features=np.concatenate((test_x,2*test_t-1),axis=1)

width=32
weights=[rng.normal(scale=np.sqrt(1/3),size=(3,width)),np.zeros(width),
         rng.normal(scale=np.sqrt(1/width),size=(width,width)),np.zeros(width),
         rng.normal(scale=np.sqrt(1/width),size=(width,2)),np.zeros(2)]

def forward(inp,params):
    W1,b1,W2,b2,W3,b3=params
    h1=np.tanh(inp@W1+b1); h2=np.tanh(h1@W2+b2)
    return h2@W3+b3,(inp,h1,h2)

def loss_grad(inp,target,params):
    prediction,(inp,h1,h2)=forward(inp,params)
    error=prediction-target; loss=np.mean(error**2)
    d=2*error/error.size
    dW3=h2.T@d; db3=d.sum(axis=0)
    d=(d@params[4].T)*(1-h2*h2)
    dW2=h1.T@d; db2=d.sum(axis=0)
    d=(d@params[2].T)*(1-h1*h1)
    return loss,[inp.T@d,d.sum(axis=0),dW2,db2,dW3,db3]

# Una derivada de cada matriz y sesgo frente a diferencias centrales.
check_in=test_features[:8]; check_target=test_velocity[:8]
_,grad=loss_grad(check_in,check_target,weights); h=1e-5
max_error=0.
for j,param in enumerate(weights):
    index=tuple(0 for _ in param.shape); before=param[index]
    param[index]=before+h; plus=loss_grad(check_in,check_target,weights)[0]
    param[index]=before-h; minus=loss_grad(check_in,check_target,weights)[0]
    param[index]=before
    max_error=max(max_error,abs((plus-minus)/(2*h)-grad[j][index]))
assert max_error < 1e-8

def evaluate():
    pred,_=forward(test_features,weights)
    return np.mean((pred-test_velocity)**2),np.mean((pred-marginal(test_x,test_t))**2)

initial=evaluate(); moments=[np.zeros_like(p) for p in weights]; squares=[np.zeros_like(p) for p in weights]
for step in range(1,1001):
    x1=train_x1[rng.integers(0,len(train_x1),size=96)]
    x0=rng.normal(size=(96,2)); t=rng.uniform(size=(96,1)); xt,target=x_and_target(x0,x1,t)
    inp=np.concatenate((xt,2*t-1),axis=1)
    _,grads=loss_grad(inp,target,weights)
    for j,(param,g) in enumerate(zip(weights,grads)):
        moments[j]=.9*moments[j]+.1*g; squares[j]=.999*squares[j]+.001*g*g
        param-=.003*(moments[j]/(1-.9**step))/(np.sqrt(squares[j]/(1-.999**step))+1e-8)
final=evaluate()
oracle=np.mean((marginal(test_x,test_t)-test_velocity)**2)
print(f'Diferencias finitas, error máximo: {max_error:.2e}')
print(f'Test independiente, MSE CFM inicial/final: {initial[0]:.6f}/{final[0]:.6f}')
print(f'Test independiente, MSE frente al campo marginal poblacional inicial/final: {initial[1]:.6f}/{final[1]:.6f}')
print(f'MSE CFM del campo marginal exacto sobre el mismo test finito: {oracle:.6f}')
print('Semillas 2301/2302/2303; 1024 datos train y 1024 pares de test distintos.')

The population field above has a closed formula because the generating mixture is known. The finite training dataset defines another distribution: for each of its 1024 points, weight its conditional velocity by the posterior probability of that point given the noisy state. This average is exact for the empirical distribution when t < 1. At t = 1 each component is a point mass and the formula becomes singular, so the following comparison uses independent states with t < 0,95.

[ ]Exact empirical dataset fieldBrowser
"""Campo exacto de la distribución empírica para t < 1."""
def empirical_field(x,t,points):
    x=np.asarray(x); t=np.asarray(t).reshape(-1,1)
    if x.ndim!=2 or x.shape[1]!=2 or len(x)!=len(t) or np.any(t<0) or np.any(t>=1):
        raise ValueError('Se requieren posiciones 2D y tiempos 0 ≤ t < 1')
    variance=(1-t)**2
    delta=x[:,None,:]-t[:,None,:]*points[None,:,:]
    logweight=-(delta*delta).sum(axis=2)/(2*variance)
    logweight-=logweight.max(axis=1,keepdims=True)
    weight=np.exp(logweight);weight/=weight.sum(axis=1,keepdims=True)
    mean=weight@points
    return (mean-x)/(1-t)

# Comprobación separada por suma escalar, incluida la identidad del extremo t=0.
check_x=test_x[:4];check_t=np.array([[0.],[.2],[.5],[.9]])
measured=empirical_field(check_x,check_t,train_x1)
manual=[]
for point,time in zip(check_x,check_t[:,0]):
    terms=[-float(((point-time*y)**2).sum())/(2*(1-time)**2) for y in train_x1]
    maximum=max(terms);weights_scalar=[np.exp(v-maximum) for v in terms]
    posterior_mean=sum((w*y for w,y in zip(weights_scalar,train_x1)),np.zeros(2))/sum(weights_scalar)
    manual.append((posterior_mean-point)/(1-time))
error=np.max(np.abs(measured-np.asarray(manual)))
assert error<1e-10
assert np.allclose(measured[0],train_x1.mean(axis=0)-check_x[0],atol=1e-12)

# El extremo t=1 es singular para puntos discretos; evaluar antes evita una división por cero.
selected=np.flatnonzero(test_t[:,0]<.95)[:256]
empirical=empirical_field(test_x[selected],test_t[selected],train_x1)
population=marginal(test_x[selected],test_t[selected])
prediction=forward(test_features[selected],weights)[0]
empirical_mse=np.mean((prediction-empirical)**2)
population_mse=np.mean((prediction-population)**2)
gap=np.mean((population-empirical)**2)
print(f'Comprobación por suma escalar: error máximo {error:.2e}; extremo t=0 verificado.')
print(f'Test independiente, {len(selected)} pares con t<0,95: MSE red/campo empírico = {empirical_mse:.6f}')
print(f'Misma selección: MSE red/campo poblacional = {population_mse:.6f}; entre ambos campos = {gap:.6f}')
print('El campo empírico usa los 1024 puntos de train y es singular en t=1; no sustituye al campo poblacional.')

Sampling uses 512 starting points and 512 independent targets. Compare Euler and midpoint also with the same number of evaluations; one seed and this projected distance do not guarantee any quality ordering.

[ ]Euler and midpointBrowser
"""Euler y punto medio con igual número de evaluaciones de campo."""
def model_field(x,t):
    inp=np.concatenate((x,np.full((len(x),1),2*t-1)),axis=1)
    return forward(inp,weights)[0]

def solve(initial,steps,method):
    x=initial.copy(); dt=1/steps; evaluations=0
    for k in range(steps):
        t=k*dt
        v=model_field(x,t); evaluations+=1
        if method=='midpoint':
            v=model_field(x+.5*dt*v,t+.5*dt); evaluations+=1
        elif method!='euler':
            raise ValueError('Método desconocido')
        x=x+dt*v
    return x,evaluations

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)))

initial=np.random.default_rng(2304).normal(size=(512,2))
reference=draw_target(np.random.default_rng(2305),512)
for method,steps in [('euler',1),('euler',64),('midpoint',32)]:
    generated,nfe=solve(initial,steps,method)
    assert np.isfinite(generated).all()
    print(f'{method}, {steps} pasos, {nfe} NFE: sliced W1 empírica = {sliced_w1(generated,reference):.6f}')
print('W1 es una media de 32 proyecciones, 512 muestras por grupo y una sola semilla; no establece un ranking universal.')

Local lab: flow matching versus diffusion

Train two copies of lesson 18’s U-Net with the same architecture, initialization, train set and attempt budget. In the first, x0∼N(0,I)x_0\sim\mathcal N(0,I) is noise, x1x_1 is an image and xt=(1−t)x0+tx1x_t=(1-t)x_0+t x_1; the network learns velocity x1−x0x_1-x_0 by MSE with uniform tt. In the second, diffusion time goes from data to noise and the network predicts ϵ\epsilon with the DDPM linear schedule. Losses have different targets and scales: do not compare them directly as quality measures. Each branch maintains its own EMA and saves checkpoint, optimizer, history and effective step count. States are saved for inspection; this cell does not automatically resume training.

For CIFAR you can initialize both networks with the same lesson 18 linear ϵ\epsilon EMA using ORYON_PREVIOUS_CKPT; width and schedule must match. The steps that produced the checkpoint are an additional prior budget and its hash is recorded in the report. Without the variable both branches start from the same random initialization. On MNIST both start from scratch. ORYON_DATASET selects mnist, cifar or both; MNIST is enlarged to 32×3232\times32 and repeated in RGB so U-Net and extractor are the same. Test images do not participate in training.

Generate samples from the same initial latents and calculate FID against the same test set. Flow uses Euler and Heun in increasing time; diffusion uses ancestral DDPM with jumps, DDIM, Heun and DPM-Solver++ 2M following lesson 20 conventions. The plot uses actual network evaluations per batch: diffusion Heun omits the second evaluation in the last interval, so some nominal budgets yield lower NFE. Images are clipped for display and feature extraction, and the pre-clipping fraction outside range is reported. FID uses clean-fid==0.1.35 InceptionV3W, 8-bit RGB and bicubic resizing. For MNIST repeated in RGB this FID describes that protocol and is not comparable to a natural CIFAR benchmark. Few-sample FID is biased and does not establish reliable model or solver ranking.

Install PyTorch, torchvision, NumPy, SciPy, Pillow, Matplotlib and clean-fid==0.1.35. Set ORYON_INCEPTION_PT to inception-2015-12-05.pt, ORYON_DATA_ROOT for data and ORYON_OUTPUT_DIR for results. Full mode proposes 4096 train images, 128 test images and 10,000 attempts per branch; change ORYON_TRAIN_COUNT, ORYON_EVAL_COUNT and ORYON_UPDATES as needed. Plots, images, features and each dataset’s report.json include NFE, seeds, Inception hash, checkpoints and data selection. That run is an experiment for the reader, not a result measured here.

With ORYON_QUICK=1, use 64 train images, eight test images, width 8 and two attempts per branch. ORYON_CIFAR_PARQUET reuses CIFAR parquet only in this mode with pyarrow; MNIST is loaded through torchvision. In a check with MNIST from scratch and CIFAR initialized for both branches from the same reduced lesson 18 EMA, both branches completed two updates per dataset. For budgets 4 and 8, flow Euler and Heun consumed 4 and 8 NFE; diffusion Heun consumed 3 and 7. Observed FIDs ranged approximately 502–521 for MNIST and 563–571 for CIFAR. These results with eight images and barely trained models check the pipeline, not quality. In that mode 20-step DDPM leaves αˉT≈0,816777\bar\alpha_T\approx0,816777: starting from a standard normal is a particularly poor approximation. The full 1000-step schedule ends at αˉT≈0,00004036\bar\alpha_T\approx0,00004036; even then the terminal prior must be stated.

[ ]Flow matching and DDPM on MNIST and CIFAR-10Local GPU
"""CIFAR y MNIST: flow matching y difusion con la misma U-Net."""
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 DataLoader,Dataset,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 grid(T, n):
    if n < 2 or n > T:
        raise ValueError('Los pasos deben estar entre 2 y T')
    ids = np.rint(np.linspace(T, 1, n)).astype(int)
    if len(set(ids)) != n:
        raise ValueError('La malla contiene tiempos repetidos')
    return ids.tolist()


def estimate(model, x, t, abar, T, parameterization):
    a, s = math.sqrt(abar), math.sqrt(1 - abar)
    raw = model(x, torch.full((len(x),), float(t), device=x.device), T)
    if parameterization == 'epsilon':
        if a == 0:
            raise ValueError('Salida epsilon no admite α terminal cero')
        eps, x0 = raw, (x - s * raw) / a
    elif parameterization == 'v':
        x0, eps = a * x - s * raw, s * x + a * raw
    else:
        raise ValueError('Salida desconocida')
    return x0, eps


def get_bar(bars, t):
    # Interpolación de log ᾱ entre índices ruidosos válidos; nunca extrapola.
    if not 1 <= t <= len(bars)-1:
        raise ValueError('Tiempo fuera de la tabla de entrenamiento')
    low = int(math.floor(t)); high = min(low + 1, len(bars)-1)
    if abs(t-low) < 1e-12:
        if bars[low] <= 0: raise ValueError('α es cero en ese tiempo')
        return bars[low]
    if bars[low] <= 0 or bars[high] <= 0:
        raise ValueError('La malla continua no admite α terminal cero')
    return math.exp((high-t)*math.log(bars[low]) + (t-low)*math.log(bars[high])) if high != low else bars[low]


def time_for_ratio(bars, ratio):
    finite = bars[1:][bars[1:] > 0]
    ratios = np.sqrt((1-finite)/finite)
    if ratio < ratios[0]-1e-10 or ratio > ratios[-1]+1e-10:
        raise ValueError('σ/α fuera de la tabla')
    # Interpolación consistente con log ᾱ, no con σ/α.
    target_bar = 1/(1+ratio**2)
    return float(np.interp(math.log(target_bar), np.log(finite[::-1]), np.arange(len(finite), 0, -1)))


@torch.no_grad()
def generate(model, bars, parameterization, ids, method, initial, generator):
    T = len(bars)-1
    x = initial.clone()
    nfe = 0
    previous_x0, previous_lambda = None, None
    for j, t in enumerate(ids):
        nxt = ids[j+1] if j+1 < len(ids) else 0
        a_t, s_t = math.sqrt(bars[t]), math.sqrt(1-bars[t])
        a_n, s_n = math.sqrt(bars[nxt]), math.sqrt(1-bars[nxt])
        x0, eps = estimate(model, x, t, bars[t], T, parameterization)
        nfe += 1
        if nxt == 0:
            x = x0
        elif method == 'ddim':
            x = a_n*x0 + s_n*eps
        elif method == 'ddpm':
            # Posterior q(x_s|x_t,x0) de una transición saltada.
            ratio = bars[t]/bars[nxt]
            variance = (1-bars[nxt])/(1-bars[t])*(1-ratio)
            mean = a_n*(1-ratio)/(1-bars[t])*x0 + math.sqrt(ratio)*(1-bars[nxt])/(1-bars[t])*x
            x = mean + math.sqrt(max(0., variance))*torch.randn(x.shape, device=x.device, generator=generator)
        elif method == 'heun':
            # VE reescalada y=x/α, r=σ/α, dy/dr=εθ.
            r_t, r_n = s_t/a_t, s_n/a_n
            y = x/a_t
            proposal = y + (r_n-r_t)*eps
            _, eps_next = estimate(model, a_n*proposal, nxt, bars[nxt], T, parameterization)
            nfe += 1
            x = a_n*(y + .5*(r_n-r_t)*(eps+eps_next))
        elif method == 'dpmpp2m':
            # DPM-Solver++ multistep segundo orden, midpoint, λ=log(α/σ).
            lam_t, lam_n = math.log(a_t/s_t), math.log(a_n/s_n)
            h = lam_n-lam_t
            corrected = x0
            if previous_x0 is not None:
                r = (lam_t-previous_lambda)/h
                corrected = x0 + .5*(x0-previous_x0)/r
            x = (s_n/s_t)*x - a_n*math.expm1(-h)*corrected
            previous_x0, previous_lambda = x0, lam_t
        else:
            raise ValueError('Sampler desconocido')
        if not torch.isfinite(x).all():
            raise FloatingPointError('Muestra no finita')
    return x, nfe


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(name,root,quick,parquet,n_train,n_test):
    if name=='cifar' and parquet:
        if not quick:raise ValueError('Parquet está permitido solo 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]}
    if name=='cifar':
        train=datasets.CIFAR10(root,train=True,download=True,transform=transforms.ToTensor())
        test=datasets.CIFAR10(root,train=False,download=True,transform=transforms.ToTensor())
    elif name=='mnist':
        transform=transforms.Compose([transforms.Resize((32,32)),transforms.Grayscale(num_output_channels=3),transforms.ToTensor()])
        train=datasets.MNIST(root,train=True,download=True,transform=transform)
        test=datasets.MNIST(root,train=False,download=True,transform=transform)
    else:raise ValueError('Dataset desconocido')
    indices=torch.randperm(len(train),generator=torch.Generator().manual_seed(2310))[:n_train].tolist()
    return Subset(train,indices),Subset(test,range(n_test)),{'source':name+' torchvision',
           'train':'subconjunto permutado con semilla 2310','test':'primeras filas'}


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');features=[]
    with torch.inference_mode():
        for start in range(0,len(images),4):
            pixels=(images[start:start+4].clamp(0,1)*255).round().to(torch.uint8)
            arr=pixels.permute(0,2,3,1).cpu().numpy()
            resized=np.stack([resize(a).transpose(2,0,1) for a in arr])
            features.append(inception(torch.from_numpy(resized).to(device)).cpu().numpy())
    return np.concatenate(features)


@torch.no_grad()
def flow_sample(model,initial,method,intervals):
    x=initial.clone();dt=1/intervals;calls=0
    for i in range(intervals):
        t=torch.full((len(x),),i*dt*1000,device=x.device)
        v=model(x,t,1000);calls+=1
        if method=='euler':x=x+dt*v
        elif method=='heun':
            nxt=torch.full((len(x),),(i+1)*dt*1000,device=x.device)
            v_next=model(x+dt*v,nxt,1000);calls+=1
            x=x+.5*dt*(v+v_next)
        else:raise ValueError('Solver de flujo desconocido')
    if not torch.isfinite(x).all():raise FloatingPointError('Flujo no finito')
    return x,calls


def verify(device):
    # Para x1=3 fijo, en x=.5*x0+.5*x1 y x=1.5, x0=0 y la velocidad es 3.
    x1=torch.tensor([3.],device=device);x0=torch.tensor([0.],device=device);t=.5
    xt=(1-t)*x0+t*x1
    assert torch.allclose(xt,torch.tensor([1.5],device=device)) and torch.allclose(x1-x0,torch.tensor([3.],device=device))
    class Constant(nn.Module):
        def forward(self,x,t,T):return torch.ones_like(x)*.25
    initial=torch.zeros((1,3,4,4),device=device)
    for method,intervals,nfe in [('euler',4,4),('heun',4,8)]:
        result,calls=flow_sample(Constant(),initial,method,intervals)
        assert calls==nfe and torch.allclose(result,torch.full_like(initial,.25))
    with torch.device('meta'):full=DiffusionUNet(128)
    assert sum(p.numel() for p in full.parameters())==18_477_315
    del full
    print('Controles: tiempo ruido→datos, campo constante, NFE y U-Net completa.',flush=True)


def train_model(name,network,train,model_kind,T,quick,device,output):
    attempts=2 if quick else int(os.environ.get('ORYON_UPDATES','10000'))
    if attempts<1:raise ValueError('ORYON_UPDATES debe ser positivo')
    micro=4 if quick else 8;accum=1 if quick else 4
    ema=copy.deepcopy(network).eval().requires_grad_(False)
    optimizer=torch.optim.AdamW(network.parameters(),lr=.0002)
    scaler=torch.amp.GradScaler('cuda',enabled=device.type=='cuda')
    loader=DataLoader(train,batch_size=micro,shuffle=True,drop_last=True,num_workers=0,
                      generator=torch.Generator().manual_seed(2313))
    batches=iter(loader);rng=torch.Generator(device=device).manual_seed(2314)
    bars=make_schedule('linear',T,'cpu')['bar'].numpy()
    bar_tensor=torch.as_tensor(bars,device=device,dtype=torch.float32)
    effective=skipped=0;history=[]
    for attempt in range(1,attempts+1):
        optimizer.zero_grad(set_to_none=True);average=0.
        for _ in range(accum):
            try:images,_=next(batches)
            except StopIteration:batches=iter(loader);images,_=next(batches)
            clean=images.to(device)*2-1
            if model_kind=='flow':
                t=torch.rand((len(clean),),device=device,generator=rng)
                noise=torch.randn(clean.shape,device=device,generator=rng)
                xt=(1-t[:,None,None,None])*noise+t[:,None,None,None]*clean
                target=clean-noise;time=t*1000;time_max=1000
            else:
                t=torch.randint(1,T+1,(len(clean),),device=device,generator=rng)
                noise=torch.randn(clean.shape,device=device,generator=rng)
                bar=bar_tensor[t,None,None,None]
                xt=bar.sqrt()*clean+(1-bar).sqrt()*noise
                target=noise;time=t;time_max=T
            with torch.autocast(device_type=device.type,dtype=torch.float16,enabled=device.type=='cuda'):
                predicted=network(xt,time,time_max)
                loss=F.mse_loss(predicted.float(),target.float())
            if not torch.isfinite(loss):raise FloatingPointError('Pérdida no finita')
            scaler.scale(loss/accum).backward();average+=loss.item()/accum
        scaler.unscale_(optimizer);torch.nn.utils.clip_grad_norm_(network.parameters(),1.)
        old=scaler.get_scale();scaler.step(optimizer);scaler.update()
        if scaler.get_scale()<old:skipped+=1
        else:
            effective+=1;decay=min(.9999,(1+effective)/(10+effective))
            with torch.no_grad():
                for avg,current in zip(ema.parameters(),network.parameters(),strict=True):avg.mul_(decay).add_(current,alpha=1-decay)
        if attempt in (1,attempts) or attempt%500==0:
            history.append({'attempt':attempt,'loss':average,'effective':effective,'skipped':skipped})
            print(f'{name}/{model_kind} intento {attempt}: pérdida={average:.6f}, efectivos={effective}, saltados={skipped}',flush=True)
    if effective==0:raise RuntimeError('Ningún paso efectivo')
    ckpt={'model':network.state_dict(),'ema':ema.state_dict(),'optimizer':optimizer.state_dict(),
          'scaler':scaler.state_dict(),'T':T,'kind':model_kind,'width':network.width,
          'effective':effective,'attempts':attempts,'history':history}
    path=output/f'{model_kind}.pt';torch.save(ckpt,path)
    loaded=torch.load(path,map_location='cpu',weights_only=True)
    assert torch.equal(loaded['ema']['output.weight'],ema.output.weight.cpu())
    del network,optimizer,scaler,ckpt,loaded,batches,loader,loss,xt,noise,predicted
    return ema,history,effective,skipped,path


def compare_one(name,root,quick,parquet,output,inception,device,previous_path,inception_hash):
    n_train,n_test=(64,8) if quick else (int(os.environ.get('ORYON_TRAIN_COUNT','4096')),
                                          int(os.environ.get('ORYON_EVAL_COUNT','128')))
    if not 8<=n_train<=50000 or not 2<=n_test<=1000:raise ValueError('Tamaños de muestra inválidos')
    train,test,selection=get_data(name,root,quick,parquet,n_train,n_test)
    folder=output/name;folder.mkdir(parents=True,exist_ok=True)
    width,T=(8,20) if quick else (128,1000)
    torch.manual_seed(2312)
    initial=DiffusionUNet(width).state_dict()
    prior_hash=None
    if name=='cifar' and previous_path:
        previous=torch.load(previous_path,map_location='cpu',weights_only=True)
        if previous['width']!=width or previous['T']!=T or previous['schedule']!='linear' or previous['parameterization']!='epsilon' or previous.get('zero_terminal',False):
            raise ValueError('El checkpoint l18 debe ser EMA ε/lineal con ancho y T compatibles')
        initial=previous['ema'];prior_hash=sha256(previous_path)
        print('Ambas ramas CIFAR parten de la misma EMA l18 previa; el entrenamiento anterior se contabiliza aparte.',flush=True)
    def new_network():
        net=DiffusionUNet(width);net.load_state_dict(initial);return net.to(device)
    flow,fh,fc,fs,flow_path=train_model(name,new_network(),train,'flow',T,quick,device,folder)
    flow=flow.cpu();torch.cuda.empty_cache() if device.type=='cuda' else None
    ddpm,dh,dc,ds,ddpm_path=train_model(name,new_network(),train,'diffusion',T,quick,device,folder)
    ddpm=ddpm.cpu();torch.cuda.empty_cache() if device.type=='cuda' else None
    real=torch.stack([test[i][0] for i in range(n_test)])
    reference=image_features(real,inception,device)
    bars=make_schedule('linear',T,'cpu')['bar'].numpy()
    cases=[];all_features={'reference':reference};budgets=[4,8] if quick else [10,20,50]
    for model_name,method in [('flow','euler'),('flow','heun'),('diffusion','ddpm'),
                              ('diffusion','ddim'),('diffusion','heun'),('diffusion','dpmpp2m')]:
        model=(flow if model_name=='flow' else ddpm).to(device).eval()
        for budget in budgets:
            intervals=max(2,budget//2) if method=='heun' else budget
            pieces=[];nfe=None;gen=torch.Generator(device=device).manual_seed(2315)
            for offset in range(0,n_test,4):
                size=min(4,n_test-offset)
                start=torch.randn((size,3,32,32),device=device,generator=gen)
                if model_name=='flow':out,calls=flow_sample(model,start,method,intervals)
                else:
                    noise=torch.Generator(device=device).manual_seed(2320+offset)
                    out,calls=generate(model,bars,'epsilon',grid(T,intervals),method,start,noise)
                if nfe is not None:assert nfe==calls
                nfe=calls;pieces.append(out.cpu())
            samples=torch.cat(pieces);outside=float(((samples < -1)|(samples > 1)).float().mean())
            fake=image_features((samples+1)/2,inception,device)
            value=fid(reference,fake);key=f'{model_name}-{method}-{budget}'
            all_features[key]=fake
            save_image(((samples[:8]+1)/2).clamp(0,1),folder/f'{key}.png',nrow=4)
            cases.append({'model':model_name,'sampler':method,'requested_budget':budget,
                          'intervals':intervals,'nfe_per_batch':nfe,'fid':value,'outside_fraction':outside})
            print(f'{name}/{key}: NFE={nfe}, FID={value:.4f}, fuera={outside:.3f}',flush=True)
        model.cpu()
        if device.type=='cuda':torch.cuda.empty_cache()
    np.savez_compressed(folder/'features.npz',**all_features)
    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    fig,ax=plt.subplots()
    for model_name,method in [('flow','euler'),('flow','heun'),('diffusion','ddpm'),
                              ('diffusion','ddim'),('diffusion','heun'),('diffusion','dpmpp2m')]:
        rows=[r for r in cases if r['model']==model_name and r['sampler']==method]
        ax.plot([r['nfe_per_batch'] for r in rows],[r['fid'] for r in rows],'o-',label=f'{model_name}/{method}')
    ax.set(xlabel='Evaluaciones de red por lote',ylabel='FID Inception',title=f'{name}: {n_test} muestras por lado')
    ax.legend(fontsize='small');fig.tight_layout();fig.savefig(folder/'fid-vs-nfe.png',dpi=150);plt.close(fig)
    report={'dataset':name,'data_selection':selection,'quick':quick,'train_count':n_train,'test_count':n_test,
            'width':width,'T_ddpm':T,'alpha_bar_terminal':float(bars[-1]),
            'flow_attempts':2 if quick else int(os.environ.get('ORYON_UPDATES','10000')),
            'ddpm_attempts':2 if quick else int(os.environ.get('ORYON_UPDATES','10000')),
            'flow_effective':fc,'ddpm_effective':dc,'flow_skipped_amp':fs,'ddpm_skipped_amp':ds,
            'flow_history':fh,'ddpm_history':dh,'common_initialization_seed':2312,
            'data_seed':2313,'training_noise_seed':2314,'sample_seed':2315,'ddpm_noise_seed_base':2320,
            'prior_checkpoint_sha256':prior_hash,'flow_checkpoint_sha256':sha256(flow_path),
            'ddpm_checkpoint_sha256':sha256(ddpm_path),'cases':cases,
            'preprocess':'MNIST ampliado a 32 y replicado en RGB; CIFAR RGB nativo',
            'inception_sha256':inception_hash,
            'fid_protocol':'InceptionV3W clean-fid 0.1.35, RGB uint8, PIL bicúbico 299',
            'notice':'FID finito sesgado; calidad de MNIST en Inception no equivale a benchmark natural.'}
    (folder/'report.json').write_text(json.dumps(report,ensure_ascii=False,indent=2),encoding='utf-8')
    del flow,ddpm,train,test,real
    if device.type=='cuda':torch.cuda.empty_cache()


def main():
    quick=os.environ.get('ORYON_QUICK')=='1'
    device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    print(f'dispositivo {device}; quick {quick}',flush=True)
    verify(device)
    name=os.environ.get('ORYON_DATASET','both')
    if name not in ('both','mnist','cifar'):raise ValueError('ORYON_DATASET debe ser both, mnist o cifar')
    root=os.environ.get('ORYON_DATA_ROOT','./data')
    parquet=os.environ.get('ORYON_CIFAR_PARQUET')
    output=Path(os.environ.get('ORYON_OUTPUT_DIR','./flow-comparison'));output.mkdir(parents=True,exist_ok=True)
    path=Path(os.environ['ORYON_INCEPTION_PT'])
    if path.name!='inception-2015-12-05.pt' or not path.is_file():raise ValueError('Ruta Inception inválida')
    inception=InceptionV3W(str(path.parent),download=False,resize_inside=False).to(device).eval()
    for dataset in (['mnist','cifar'] if name=='both' else [name]):
        compare_one(dataset,root,quick,parquet,output,inception,device,os.environ.get('ORYON_PREVIOUS_CKPT'),sha256(path))
    print('Mismas particiones y presupuestos por rama; FID reducido no demuestra una clasificación fiable.',flush=True)
    del inception
    if device.type=='cuda':torch.cuda.empty_cache()


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.

Exercises

ProofPreserve the mixture
Prove: Prove the averaged field satisfies the marginal density continuity equation.
0
Each pₜ(x|z), uₜ(x|z) satisfies continuity; q does not depend on t and integral and derivatives may be exchanged.

Step 1 of 2. What is pₜ(x)uₜ(x) for the marginal field defined in the text?

ProofThe term independent of θ
Prove: Prove gradient equality between marginal and conditional losses.
0
Targets have finite second moments; the distribution and U do not depend on θ.

Step 1 of 2. Why does the cross term vanish when expanding ‖v−U‖²?

NumericA conditional velocity
With x₀∼N(0,1), fixed datum x₁=3 and path xₜ=(1−t)x₀+tx₁, calculate marginal velocity at x=1.5 and t=0.5.
QuizDoes positive loss imply an incorrect field?
The model matches the marginal field, but CFM loss is still positive. What explanation is compatible with this?
CodeRegression and Euler in PyTorch
Implement cfm_loss(model,x1,x0=None,t=None,generator=None) and euler_sample(model,x0,n_steps). x1 and x0 are floating-point tensors of shape (B,D), with the same dtype and device. If x0 or t are omitted, independently sample normal x0 and uniform t using generator; t is floating-point with shape (B,1). Loss is the mean square between model((1−t)x0+t x1,t) and x1−x0. Euler integrates from 0 to 1 with n_steps evaluations, starting from a copy of x0. Preserve loss gradients, reject n_steps<1 and do not modify inputs.
import torch

def cfm_loss(model, x1, x0=None, t=None, generator=None):
  pass

def euler_sample(model, x0, n_steps):
  pass
Shift+Enter to run
Key idea

Flow matching trains using known conditional velocities and learns their expectation given position and time. Marginal field, irreducible regression error and numerical integration error are distinct concepts.