Module contents
Stage 7 of 9Research 100 min

Flow matching and rectified flow

Learn flow matching and reflow, measure trajectory straightness, and compare generation quality at equal compute.

After this lesson you can

  • Derive the conditional flow-matching objective and marginal velocity.
  • Train and rectify flows, measuring velocity deviation and sample quality.
  • Compare diffusion and flow on CIFAR-10 at matched compute and NFE.

Before you start

A path is a decision too

In diffusion we train a noise predictor then integrate a reverse field. Flow matching can train a velocity field directly. Drawing straight segments between point pairs is easy; converting them into one ODE is subtler, because different segments can cross at the same time and demand different velocities at the same location.

InteractiveStraightening trajectories
-3-3-2-22233x₁x₂
  • Euler with selected steps
  • Reference: 128-step Euler
  • Data modes (radius 2σ)
  • Initial noise
Network
1
100
Mean final error versus 128 steps1.791
Velocity deviation (128 steps)1.2184
Displayed step1 of 1
The same 64 initial noise points transported by the three 2D networks trained in this lesson's cells. Readouts come from the 'Measure velocity and integration error' cell: they measure integration relative to the network itself, not distribution quality.

Conditional flow-matching training regresses a known velocity along endpoint-conditioned paths. Reflow retrains on pairs formed by a starting point and the endpoint produced by the previous model. First do everything on the 2D mixture from 2D diffusion, where every trajectory can be drawn and measured. Then bring the same loss to the CIFAR-10 U-Net from DDPM on CIFAR-10 and compare against diffusion at equal compute using the FID versus NFE curve (number of function evaluations). The plane explains the mechanism; the CIFAR lab, not the mixture, decides image comparison.

In the viewer each blue line is the Euler trajectory of the same initial noise at the selected step count, and each dashed gray line is that network’s 128-step reference. With the initial network and one step, nearly all points land near the origin: velocity at t=0t=0 averages directions toward the four modes. After one reflow, the reference becomes nearly straight and one Euler step already reaches near its endpoint.

The field transporting a density

Let X0X_0 be noise and X1X_1 a data point, with a joint coupling of finite second moments. For t∈[0,1]t\in[0,1], set

Xt=(1−t)X0+tX1,U=X1−X0.X_t=(1-t)X_0+tX_1,\qquad U=X_1-X_0.

Each pair-conditioned path is straight with velocity UU. Network vθ(x,t)v_\theta(x,t) sees only position and time, not endpoints. The best population squared-error predictor is v∗(x,t)=E[U∣Xt=x,T=t]v^*(x,t)=\E[U\mid X_t=x,T=t]. When several pairs meet near one point, the field averages their possible velocities. Marginal ODE paths therefore need not match training segments.

Under sufficient integrability and regularity, density satisfies ∂tpt+∇⋅(ptv∗)=0\partial_t p_t+\nabla\cdot(p_tv^*)=0, the continuity equation. Solving x˙=v∗(x,t)\dot x=v^*(x,t) from the initial distribution reproduces its marginals if a well-defined flow exists. A learned field or few-step integration adds errors. Lipman and colleagues present the conditional objective as an alternative to directly calculating the marginal field; Albergo and Vanden-Eijnden reach the same regression using stochastic interpolants, and Liu and colleagues call it rectified flow for straight paths.

ProofFrom pairs to the marginal field
Prove: Let UU and XTX_T have finite second moments, with time TT independent of pair (X0,X1)(X_0,X_1), and define v∗(XT,T)=E[U∣XT,T]v^*(X_T,T)=\E[U\mid X_T,T]. Assume vθv_\theta is square-integrable and gradient and expectation can be exchanged. Prove E∥vθ(XT,T)−U∥2\E\norm{v_\theta(X_T,T)-U}^2 and E∥vθ(XT,T)−v∗(XT,T)∥2\E\norm{v_\theta(X_T,T)-v^*(X_T,T)}^2 have the same gradient in θ\theta.
0
Write vθ−U=(vθ−v∗)+(v∗−U)v_\theta-U=(v_\theta-v^*)+(v^*-U) and expand the square.

Step 1 of 3. What is the property of residual U−v*?

Practical loss is E∥vθ(Xt,t)−(X1−X0)∥2\E\norm{v_\theta(X_t,t)-(X_1-X_0)}^2. No ODE is simulated during regression: each example costs one forward and one backward pass, as in diffusion. Its minimum is not zero. With independent coupling, segments of different velocities pass through the same xx, and conditional variance E∥U−v∗(Xt,t)∥2\E\norm{U-v^*(X_t,t)}^2 remains as the loss floor. The cells show initial-field loss plateauing and reflow losses nearly vanishing.

Which times are sampled

With uniform TT, every instant weighs equally. Difficulty is not uniform: near t=0t=0, XtX_t is almost noise and v∗(x,t)≈E[X1]−xv^*(x,t)\approx\E[X_1]-x nearly linear; near t=1t=1, X0=(Xt−tX1)/(1−t)X_0=(X_t-tX_1)/(1-t) gives v∗(x,t)=(E[X1∣Xt=x]−x)/(1−t)v^*(x,t)=(\E[X_1\mid X_t=x]-x)/(1-t), pointing toward the data posterior mean (for a finite sample, nearly the nearest point). Intermediate times, where each point’s destination mode is decided, are hardest to learn. Esser and colleagues compare time distributions for image rectified flow and obtain their best results with logit-normal T=σ(Z)T=\sigma(Z) where Z∼N(m,s2)Z\sim\Normal(m,s^2) and σ\sigma is sigmoid, concentrating mass centrally. Changing density π\pi of TT weights uniform loss by π(t)\pi(t); optimizing the uniform objective while sampling with π\pi requires division by π(t)\pi(t), which requires π>0\pi>0 wherever reference weight is positive. The lab uses uniform times so comparison with diffusion changes one thing at a time; logit-normal is the first ablation worth trying.

Proof

If XtX_t determines X0X_0, it also determines X1=Φ(X0)X_1=\Phi(X_0), so U=X1−X0U=X_1-X_0 is a measurable function of XtX_t. Conditional expectation of a variable already a function of the condition is itself: v∗(Xt,t)=E[U∣Xt]=Uv^*(X_t,t)=\E[U\mid X_t]=U almost surely. Along segment x(t)=(1−t)x0+tx1x(t)=(1-t)x_0+tx_1, x˙(t)=x1−x0=v∗(x(t),t)\dot x(t)=x_1-x_0=v^*(x(t),t), so the segment is a field trajectory. At t=0t=0, X0X_0 determines the pair and v∗(x0,0)=Φ(x0)−x0v^*(x_0,0)=\Phi(x_0)-x_0, hence x0+1⋅v∗(x0,0)=Φ(x0)x_0+1\cdot v^*(x_0,0)=\Phi(x_0). If v∗v^* is also locally Lipschitz, the solution is unique and flow coincides with the segment.

∎

The theorem explains reflow’s aim. An ODE of a regular field has noncrossing trajectories, so its coupling (x0,Φ(x0))(x_0,\Phi(x_0)) is deterministic. Straight segments joining those pairs may still cross, but far less than in independent coupling; retraining on them brings the field closer to the theorem’s assumption. The theorem does not promise it is reached in finitely many rectifications or inherited error-free by a learned model.

Train a checkable mixture

Use p07-l01’s four centers and standard deviation 0.3, with standard normal initial noise. The NumPy network takes (x1,x2,t,sin⁡πt,cos⁡πt)(x_1,x_2,t,\sin\pi t,\cos\pi t), a tanh layer and two outputs. Loss is mean half squared norm per example; one manually computed gradient entry is checked with finite differences before training. Initialization, training pairs, reflow pairs and evaluation have explicit generators; reflow pairs come from integrating the previous model, not clean data. The mixture is a synthetic control experiment, not a real image.

[ ]Flow-matching network and trainingBrowser
import numpy as np, json

means=np.array([[2.,0.],[-2.,0.],[0.,2.],[0.,-2.]])
hidden=32
def data(n,rng):
    return means[rng.integers(0,4,n)]+.3*rng.standard_normal((n,2))
def init_net(seed):
    rng=np.random.default_rng(seed)
    params=[rng.normal(0,1/np.sqrt(5),(5,hidden)),np.zeros(hidden),
            rng.normal(0,.05,(hidden,2)),np.zeros(2)]
    return {"p":params,"m":[np.zeros_like(p) for p in params],
            "v":[np.zeros_like(p) for p in params],"step":0}
def features(x,t):
    t=np.broadcast_to(t,(len(x),))
    return np.column_stack((x,t,np.sin(np.pi*t),np.cos(np.pi*t)))
def velocity(net,x,t):
    w1,b1,w2,b2=net["p"]
    return np.tanh(features(x,t)@w1+b1)@w2+b2
def loss_grads(params,x,t,target):
    f=features(x,t)
    w1,b1,w2,b2=params
    h=np.tanh(f@w1+b1)
    error=h@w2+b2-target
    d=error/len(x)
    dh=([email protected])*(1-h*h)
    return .5*np.mean(np.sum(error*error,axis=1)),[f.T@dh,dh.sum(0),h.T@d,d.sum(0)]
def train_steps(net,rng,steps,pairs=None):
    for _ in range(steps):
        if pairs is None:
            x0=rng.standard_normal((128,2))
            x1=data(128,rng)
        else:
            index=rng.integers(0,len(pairs[0]),128)
            x0,x1=pairs[0][index],pairs[1][index]
        t=rng.random(128)
        x=(1-t[:,None])*x0+t[:,None]*x1
        target=x1-x0
        loss,grads=loss_grads(net["p"],x,t,target)
        net["step"]+=1
        n=net["step"]
        for p,m,v,g in zip(net["p"],net["m"],net["v"],grads):
            m[:]=.9*m+.1*g
            v[:]=.999*v+.001*g*g
            p-=.001*(m/(1-.9**n))/(np.sqrt(v/(1-.999**n))+1e-8)
    return float(loss)
def integrate(net,x,steps,keep=False):
    x=np.array(x,dtype=float,copy=True)
    path=[x.copy()] if keep else None
    for i in range(steps):
        x+=velocity(net,x,i/steps)/steps
        if keep: path.append(x.copy())
    return np.asarray(path) if keep else x

net0=init_net(101)
train_rng0=np.random.default_rng(2027)
check_x=np.array([[.2,-.3],[.6,.4]])
check_t=np.array([.2,.8])
check_target=np.array([[.1,.7],[-.2,.3]])
_,grad=loss_grads(net0["p"],check_x,check_t,check_target)
h=1e-5
original=net0["p"][0][0,0]
net0["p"][0][0,0]=original+h
plus=loss_grads(net0["p"],check_x,check_t,check_target)[0]
net0["p"][0][0,0]=original-h
minus=loss_grads(net0["p"],check_x,check_t,check_target)[0]
net0["p"][0][0,0]=original
gradient_error=abs((plus-minus)/(2*h)-grad[0][0,0])
assert gradient_error<1e-7
print("Error de gradiente por diferencias finitas:",gradient_error)
print("Inicialización: ancho",hidden,"lote 128; actualización Adam .001")
print("Primera tanda:",train_steps(net0,train_rng0,1250),"pasos",net0["step"])
[ ]Continue the first fieldBrowser
print("Continuación:",train_steps(net0,train_rng0,1250),"pasos",net0["step"])
[ ]Complete the first fieldBrowser
print("Tercera tanda:",train_steps(net0,train_rng0,1250),"pasos",net0["step"])
[ ]Fourth batch of the first fieldBrowser
print("Cuarta tanda:",train_steps(net0,train_rng0,1250),"pasos",net0["step"])

The printed loss is for the last batch of each run: after 5,000 updates it is around 2.0 and stops falling. This is not a lack of training, but the floor 12E∥U−v∗(Xt,t)∥2\tfrac12\E\norm{U-v^*(X_t,t)}^2 from the previous exercise: with independent noise and data, segments to all four modes pass through each point, and no field can follow them all.

For the first rectification, we take new noise samples and propagate them through the previous field using 64 Euler steps. We save the teacher’s pairs (x0,x^1)(x_0,\hat x_1) and use them to train another field from a new initialization. We repeat the process once more. The teacher’s pairs and trajectories are approximate: increasing the teacher integration accuracy or number of pairs changes the experiment.

[ ]First reflow and first batchBrowser
pair_rng1=np.random.default_rng(3001)
source1=pair_rng1.standard_normal((2048,2))
target1=integrate(net0,source1,64)
pairs1=(source1,target1)
net1=init_net(102)
train_rng1=np.random.default_rng(2028)
print("Pares reflow 1:",len(source1),"pasos del profesor 64")
print("Primera tanda:",train_steps(net1,train_rng1,1250,pairs1),"pasos",net1["step"])
[ ]Continue the first reflowBrowser
print("Continuación:",train_steps(net1,train_rng1,1250,pairs1),"pasos",net1["step"])
[ ]Complete the first reflowBrowser
print("Tercera tanda:",train_steps(net1,train_rng1,1250,pairs1),"pasos",net1["step"])
[ ]Fourth batch of the first reflowBrowser
print("Cuarta tanda:",train_steps(net1,train_rng1,1250,pairs1),"pasos",net1["step"])
[ ]Second reflow and first batchBrowser
pair_rng2=np.random.default_rng(3002)
source2=pair_rng2.standard_normal((2048,2))
target2=integrate(net1,source2,64)
pairs2=(source2,target2)
net2=init_net(103)
train_rng2=np.random.default_rng(2029)
print("Pares reflow 2:",len(source2),"pasos del profesor 64")
print("Primera tanda:",train_steps(net2,train_rng2,1250,pairs2),"pasos",net2["step"])
[ ]Continue the second reflowBrowser
print("Continuación:",train_steps(net2,train_rng2,1250,pairs2),"pasos",net2["step"])
[ ]Complete the second reflowBrowser
print("Tercera tanda:",train_steps(net2,train_rng2,1250,pairs2),"pasos",net2["step"])
[ ]Fourth batch of the second reflowBrowser
print("Cuarta tanda:",train_steps(net2,train_rng2,1250,pairs2),"pasos",net2["step"])

The viewer uses the same parameters rounded to four decimal places. The following hidden cells publish those weights and the 64 evaluation starting points without changing the trained networks; the viewer’s measurements use their rounded copies for reproducibility. The next function measures the mean squared velocity deviation from the chord between the start and end of each numerical trajectory. Zero would mean constant velocity on the grid; a visually straight trajectory traversed at varying speed can have a positive value. This is not geometric curvature independent of parameterization. We also compare one-step Euler with 128-step Euler for each network and the same starting points; that error measures discretization against the network’s own reference, not quality against the data.

[ ]Measure velocity and integration errorBrowser
eval_rng=np.random.default_rng(4021)
starts=np.round(eval_rng.standard_normal((64,2)),4)
for i,net in enumerate(rounded):
    path=integrate(net,starts,128,keep=True)
    avg=path[-1]-path[0]
    velocities=np.diff(path,axis=0)*128
    straightness=float(np.mean(np.sum((velocities-avg[None,:,:])**2,axis=2)))
    one=integrate(net,starts,1)
    error=float(np.mean(np.linalg.norm(one-path[-1],axis=1)))
    print("Campo",i,"desviación de velocidad",straightness,"error medio Euler 1 frente a 128",error)
print("Semilla de evaluación 4021, 64 inicios redondeados a cuatro decimales; referencia de 128 pasos")

For the initial network, the velocity deviation is about 1.2 and one Euler step lands, on average, about 1.8 units from the reference endpoint: the point ends up near the origin because at t=0t=0 the ideal field is E[X1]−x=−x\E[X_1]-x=-x, and one step takes any xx to E[X1]=0\E[X_1]=0. After the first reflow, the deviation falls to a few thousandths and the one-step error to about 0.14; the second reflow reduces it a little more, to about 0.12. These are the figures reproduced by the viewer with the same 64 starts.

These figures come from one run and a finite set of points. A lower value on this metric does not prove greater distribution quality or imply that every trajectory has straightened. In approximate reflow, a flawed teacher produces flawed endpoints; the student learns that distribution, with additional regression and integration errors.

To test that last claim, we also compute MMD² with a Gaussian kernel of bandwidth 1 on evaluation samples separate from the reflow pairs. This unbiased estimator excludes diagonals and can be negative due to finite-sample variation, as explained by Gretton and colleagues. We compare it with two independent mixture samples; a single realization does not establish equivalence or a statistically robust improvement. The cell specifies the sample count and seed.

[ ]Control MMD² in two dimensionsBrowser
def mmd2(x,y,width=1.):
    def kernel(a,b):
        return np.exp(-((a[:,None,:]-b[None,:,:])**2).sum(axis=2)/(2*width**2))
    xx=kernel(x,x); yy=kernel(y,y); xy=kernel(x,y)
    return ((xx.sum()-np.trace(xx))/(len(x)*(len(x)-1))
            +(yy.sum()-np.trace(yy))/(len(y)*(len(y)-1))-2*xy.mean())
quality_rng=np.random.default_rng(6061)
real=data(256,quality_rng)
real2=data(256,quality_rng)
noise=quality_rng.standard_normal((256,2))
print("MMD² referencia real-real:",mmd2(real,real2))
for i,net in enumerate(rounded):
    print("MMD² campo",i,"128 pasos frente a mezcla:",mmd2(real,integrate(net,noise,128)))
print("Semilla 6061, 256 puntos por conjunto, kernel RBF ancho 1, estimador sin diagonales.")

In this realization, the reference MMD² between mixture samples is approximately 0.00033; for the three fields, with 128 steps, it is 0.00191, 0.00397 and 0.00449. Velocity deviation fell sharply after reflow, while these three MMD² values increased. One pair of samples does not establish a population-level decline, but it does show why a straighter curve alone cannot certify quality. The viewer makes this visible: with Reflow 1, several reference endpoints lie between two modes, outside the data circles, and a single Euler step lands almost in the same place: the network accurately integrates a transport that does not end exactly in the correct distribution.

Two reflows are no guarantee

In the theory of Liu, Gong and Liu, under their exact-flow assumptions, rectification preserves marginals and does not increase convex transport costs; the work also studies straightening under repetition. Those results do not guarantee that a finite student improves FID at every iteration or outperforms its teacher for any number of steps. Insufficient teacher integration, too few pairs, incomplete optimization and accumulated error can worsen the result.

The connection to diffusion follows from the continuity equation: an SDE with drift ff, scalar diffusion g(t)g(t) and exact score can be expressed using the probability-flow field v=f−12g2∇log⁡ptv=f-\tfrac12g^2\nabla\log p_t. This identity relates density trajectories under assumptions; it does not make the losses, couplings or individual trajectories identical. Flow matching also permits paths different from diffusion marginals.

For straight interpolation with X0∼N(0,I)X_0\sim\Normal(0,I) independent of X1X_1, the interior marginal score lets us write v∗(x,t)=[x+(1−t)st(x)]/tv^*(x,t)=[x+(1-t)s_t(x)]/t for 0<t<10<t<1. This follows by applying the Gaussian identity to Xt=tX1+(1−t)X0X_t=tX_1+(1-t)X_0 and substituting the conditional expectation of the endpoints. The explicit formula divides by tt; do not evaluate it at zero without studying the limit. Nor does it transfer unchanged to a dependent coupling such as reflow-generated pairs. The conditional OT path of Lipman and colleagues retains positive final noise σmin⁡\sigma_{\min} in its formulation; the path reaching the data exactly is the limiting case with σmin⁡=0\sigma_{\min}=0. For an empirical distribution, that endpoint may lack a smooth density.

In their unconditional CIFAR-10 table, Liu and colleagues report one-step Euler FID of 378, 12.21 and 8.15 for the first three rectifications without distillation. In the same table, RK45 yields 2.58, 3.36 and 3.96 with 127, 110 and 104 NFE respectively. Thus, in that experiment the few-step approximation improved while quality with the finer integrator did not improve monotonically. Those figures use the DDPM++ network, 4 million pairs per rectification and 300,000 fine-tuning updates of the preceding model at each stage; they indicate the pattern to look for, not the exact number to expect with a smaller budget.

Comparison at equal compute

To make the FID-versus-NFE curve reflect methods rather than budgets, the lab fixes everything else relative to DDPM on CIFAR-10: the same U-Net, 200,000 updates with microbatch 32, Adam at learning rate 2⋅10−42\cdot10^{-4}, EMA decay 0.9999, horizontal flipping, bf16 precision, the same evaluation reference and the same initial-noise seeds as the p07-l04 sampler sweep. Only the objective changes: noise at a discrete index versus velocity X1−X0X_1-X_0 at a continuous time. Since both use one forward and one backward pass of the same network per example, equal update counts mean equal training compute here; different architectures would require declaring FLOPs.

For sampling, compare equal NFE and integrators of the same order: Euler with Euler (or DDIM, which is also first-order) and Heun with Heun. This lab’s Heun uses 2n2n NFE for nn steps because it also corrects the last interval. Reflow adds a cost the curve does not show: generating PP pairs with SS teacher steps costs PSPS forward evaluations, and retraining for KK updates with microbatch BB costs about 3KB3KB equivalent evaluations if a backward pass counts as two forward passes. The full recipe (P=50.000P=50.000, S=128S=128, K=50.000K=50.000, B=32B=32) therefore costs about 11.2 million evaluations per reflow, against about 19.2 million for the initial stage (3⋅200.000⋅323\cdot200.000\cdot32). Report that total alongside any few-step improvement.

The image lab

The first local cell gathers what the recipe needs from earlier lessons so this page’s kernel is self-contained: the p07-l02 U-Net as defined in p07-l03, unchanged; tensor flow-matching loss; and an Euler and Heun sampler that counts NFE. The U-Net receives time as 1000*t so its sinusoidal embedding operates on the same scale as diffusion indices; no diffusion weights are reused. For images, the loss averages over channels and pixels, like the p07-l03 MSE; it differs from half the squared norm in the 2D example by a constant factor, which barely matters with Adam. The checks use artificial fields with known solutions: the zero field and v(x,t)=xv(x,t)=x, where Euler with 4 steps gives 1.254x1.25^4x and Heun with 2 steps gives 1.6252x1.625^2x.

[ ]U-Net, loss and sampler in PyTorchLocal GPU
import math, io, os, json, uuid, shutil, base64, hashlib, inspect, pathlib, importlib.metadata
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F
from PIL import Image

# U-Net de p07-l02, idéntica a la de p07-l03.
def time_embedding(t,dim):
    half=dim//2
    scales=torch.exp(-math.log(10000)*torch.arange(half,device=t.device,dtype=torch.float32)/(half-1))
    phase=t.float()[:,None]*scales[None,:]
    return torch.cat((phase.sin(),phase.cos()),dim=1)

class Residual(nn.Module):
    def __init__(self,cin,cout,tdim):
        super().__init__()
        self.n1=nn.GroupNorm(32,cin)
        self.c1=nn.Conv2d(cin,cout,3,padding=1)
        self.time=nn.Linear(tdim,cout)
        self.n2=nn.GroupNorm(32,cout)
        self.c2=nn.Conv2d(cout,cout,3,padding=1)
        self.skip=nn.Identity() if cin==cout else nn.Conv2d(cin,cout,1)
    def forward(self,x,t):
        h=self.c1(F.silu(self.n1(x)))
        h=h+self.time(F.silu(t))[:,:,None,None]
        return self.skip(x)+self.c2(F.silu(self.n2(h)))

class Attention(nn.Module):
    def __init__(self,channels,heads=4):
        super().__init__()
        assert channels%heads==0
        self.heads=heads
        self.norm=nn.GroupNorm(32,channels)
        self.qkv=nn.Conv2d(channels,3*channels,1)
        self.out=nn.Conv2d(channels,channels,1)
    def forward(self,x):
        b,c,h,w=x.shape
        q,k,v=self.qkv(self.norm(x)).reshape(b,3,self.heads,c//self.heads,h*w).unbind(1)
        q,k,v=(z.transpose(-1,-2) for z in (q,k,v))
        h1=F.scaled_dot_product_attention(q,k,v).transpose(-1,-2).reshape(b,c,h,w)
        return x+self.out(h1)

class DiffusionUNet(nn.Module):
    def __init__(self,width=224):
        super().__init__()
        a,b,c=width,2*width,3*width
        self.width=width
        self.temb=nn.Sequential(nn.Linear(width,4*width),nn.SiLU(),nn.Linear(4*width,4*width))
        self.stem=nn.Conv2d(3,a,3,padding=1)
        self.down0=Residual(a,a,4*width)
        self.reduce0=nn.Conv2d(a,a,3,stride=2,padding=1)
        self.down1=Residual(a,b,4*width)
        self.attn_down=Attention(b)
        self.reduce1=nn.Conv2d(b,b,3,stride=2,padding=1)
        self.down2=Residual(b,c,4*width)
        self.mid=Residual(c,c,4*width)
        self.up1=Residual(c+b,b,4*width)
        self.attn_up=Attention(b)
        self.up0=Residual(b+a,a,4*width)
        self.final=nn.Sequential(nn.GroupNorm(32,a),nn.SiLU(),nn.Conv2d(a,3,3,padding=1))
    def forward(self,x,t):
        if x.ndim!=4 or x.shape[1:]!=(3,32,32) or t.shape!=(x.shape[0],):
            raise ValueError("Se esperan imágenes (B,3,32,32) y tiempos (B,)")
        t=self.temb(time_embedding(t,self.width))
        h0=self.down0(self.stem(x),t)
        h1=self.attn_down(self.down1(self.reduce0(h0),t))
        h2=self.mid(self.down2(self.reduce1(h1),t),t)
        up=F.interpolate(h2,scale_factor=2,mode="nearest")
        up=self.attn_up(self.up1(torch.cat((up,h1),dim=1),t))
        up=F.interpolate(up,scale_factor=2,mode="nearest")
        return self.final(self.up0(torch.cat((up,h0),dim=1),t))

class ImageFlow(nn.Module):
    def __init__(self,net):
        super().__init__()
        self.net=net
    def forward(self,x,t):
        return self.net(x,1000*t)

def cfm_loss_torch(model,x0,x1,t):
    a=t.reshape((len(x0),)+(1,)*(x0.ndim-1))
    xt=(1-a)*x0+a*x1
    return (model(xt,t).float()-(x1-x0)).square().mean()

@torch.no_grad()
def sample_flow(model,x,steps,method="euler"):
    if steps<1 or method not in ("euler","heun"): raise ValueError("Solver o pasos inválidos")
    x=x.clone().float()
    cuda=x.device.type=="cuda"
    def v(y,s):
        t=torch.full((len(y),),s,device=y.device)
        with torch.autocast(device_type=y.device.type,dtype=torch.bfloat16,enabled=cuda):
            return model(y,t).float()
    nfe=0
    for i in range(steps):
        k1=v(x,i/steps); nfe+=1
        if method=="euler":
            x=x+k1/steps
        else:
            k2=v(x+k1/steps,(i+1)/steps); nfe+=1
            x=x+(k1+k2)/(2*steps)
    return x,nfe

class ZeroVelocity(nn.Module):
    def forward(self,x,t): return torch.zeros_like(x)
class Identity(nn.Module):
    def forward(self,x,t): return x

toy0=torch.zeros(2,1,2,2); toy1=torch.ones_like(toy0); toy_t=torch.tensor([.3,.7])
assert torch.isclose(cfm_loss_torch(ZeroVelocity(),toy0,toy1,toy_t),torch.tensor(1.))
assert torch.equal(sample_flow(ZeroVelocity(),toy1,4)[0],toy1)
euler,nfe_e=sample_flow(Identity(),toy1,4,"euler")
heun,nfe_h=sample_flow(Identity(),toy1,2,"heun")
assert torch.allclose(euler,toy1*1.25**4) and torch.allclose(heun,toy1*1.625**2)
print("Pérdida con campo nulo:",float(cfm_loss_torch(ZeroVelocity(),toy0,toy1,toy_t)))
print("v=x: Euler 4 pasos",float(euler[0,0,0,0]),"con",nfe_e,"NFE; Heun 2 pasos",
      float(heun[0,0,0,0]),"con",nfe_h,"NFE; exacto",math.e)
net=ImageFlow(DiffusionUNet())
with torch.no_grad():
    y=net(torch.zeros(2,3,32,32),torch.tensor([0.,.5]))
assert y.shape==(2,3,32,32)
print("Parámetros de la U-Net:",sum(p.numel() for p in net.parameters()),"salida",tuple(y.shape))
del net,y
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The second cell brings in the FID evaluation from p07-l03: it reads the reference directory generated in p07-l02 (cifar10_reference.npz, train_features.npy, fid_results.json and inception-2015-12-05.pt), checks their hashes and computes the Fréchet distance in float64 using positive-semidefinite matrix square roots.

[ ]Reference and FID from p07-l02Local GPU
def file_sha(path):
    with open(path,"rb") as f:
        return hashlib.file_digest(f,"sha256").hexdigest()

def load_fid_reference(path,device):
    from cleanfid.inception_torchscript import InceptionV3W
    from cleanfid.resize import build_resizer
    path=pathlib.Path(path)
    record=json.loads((path/"fid_results.json").read_text(encoding="utf-8"))
    if record["protocol"]!="cifar10-train-bootstrap-clean-fid-0.1.35":
        raise ValueError("Protocolo de referencia incompatible")
    if file_sha(path/"inception-2015-12-05.pt")!=record["extractor_sha256"]:
        raise ValueError("Huella del extractor distinta")
    if file_sha(path/"train_features.npy")!=record["train_sha256"]:
        raise ValueError("Huella de características train distinta")
    stats=np.load(path/"cifar10_reference.npz")
    if str(stats["train_sha256"])!=record["train_sha256"]:
        raise ValueError("La referencia no corresponde a las características")
    features=np.load(path/"train_features.npy",mmap_mode="r")
    if features.shape!=(50000,2048):
        raise ValueError("Forma de referencia inesperada")
    mean=torch.zeros(2048,device=device,dtype=torch.float64)
    for start in range(0,len(features),4096):
        chunk=torch.as_tensor(np.array(features[start:start+4096],copy=True),device=device,dtype=torch.float64)
        mean+=chunk.sum(0)
    mean/=len(features)
    cov=torch.zeros((2048,2048),device=device,dtype=torch.float64)
    for start in range(0,len(features),4096):
        chunk=torch.as_tensor(np.array(features[start:start+4096],copy=True),device=device,dtype=torch.float64)-mean
        cov+=chunk.T@chunk
    cov/=len(features)-1
    if not np.allclose(mean.cpu().numpy(),stats["mean_train"],rtol=1e-7,atol=1e-7):
        raise ValueError("Media de referencia no coincide")
    if not np.allclose(cov.cpu().numpy(),stats["cov_train"],rtol=1e-7,atol=1e-7):
        raise ValueError("Covarianza de referencia no coincide")
    del chunk,features
    extractor=InceptionV3W(str(path),download=False).eval().to(device)
    return mean,cov,extractor,build_resizer("clean"),record

def feature_fid(samples,mean,cov):
    z=torch.as_tensor(samples,device=mean.device,dtype=torch.float64)
    m=z.mean(0); centered=z-m
    c=centered.T@centered/(len(z)-1)
    def eig(x):
        values,vectors=torch.linalg.eigh((x+x.T)/2)
        scale=max(1.,float(values.abs().max()))
        if float(values.min()) < -1e-8*scale:
            raise ValueError("Covarianza no positiva")
        return values.clamp_min(0),vectors
    values,vectors=eig(c)
    root=(vectors*values.sqrt())@vectors.T
    middle,_=eig(root@cov@root)
    result=float((m-mean).square().sum()+torch.trace(c)+torch.trace(cov)-2*middle.sqrt().sum())
    if result < -1e-7*max(1.,float(torch.trace(c)+torch.trace(cov))):
        raise ArithmeticError("FID negativo fuera de tolerancia")
    return max(0.,result)

def image_grid(pixels):
    canvas=Image.new("RGB",(128,128))
    for i,image in enumerate(pixels[:16]):
        canvas.paste(Image.fromarray(image),(32*(i%4),32*(i//4)))
    stream=io.BytesIO()
    canvas.save(stream,format="PNG")
    return "data:image/png;base64,"+base64.b64encode(stream.getvalue()).decode("ascii")

check=feature_fid(np.array([[-1.,0.],[1.,0.]]),torch.zeros(2,dtype=torch.float64),torch.eye(2,dtype=torch.float64))
assert np.isclose(check,4-2*np.sqrt(2),atol=1e-10)
print("FID de control con covarianza singular:",check,"esperado",4-2*np.sqrt(2))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The third cell trains one stage per run. Stage 0 is flow matching on CIFAR-10 with independent noise; stages 1 and 2 are reflows. Each reflow loads the EMA from the previous stage’s model.pt, uses it to generate PP pairs (x0,x^1)(x_0,\hat x_1) with SS Euler steps and fixed-seed noise, saves them with the teacher’s fingerprint and fine-tunes a copy of the teacher on those pairs, as Liu and colleagues do. The pairs never use real images as targets: reflow learns the model’s coupling, not the data’s. There is no flipping during reflow because flipping x^1\hat x_1 would break its pairing with x0x_0.

ModeWidthStage 0Each reflowPairs PPTeacher steps SSCheckpoint
full224200,000 updates × 3250,000 updates × 3250,000 (1.2 GB on disk)128every 10,000
smoke6430 updates × 430 updates × 4644every 10

The smoke mode only checks that the chain works end to end, in a few minutes and with a narrow U-Net; full mode is the experiment, using the p07-l03 U-Net. Each complete stage occupies about 0.6 GB for its checkpoint and 0.3 GB for its final model, and checkpoints require 2 GiB free before writing. Set the variables before starting the local kernel, one stage at a time. For example, from the project root in PowerShell, with the p07-l02 p07-evaluacion directory:

$env:P07_L02_REF=(Resolve-Path ./p07-evaluacion).Path
$env:PYTHONPATH=Join-Path $env:P07_L02_REF "vendor"
$env:P07_L07_MODE="full"
$env:P07_L07_STAGE="0"
$env:P07_L07_OUT=Join-Path (Get-Location) "p07-flow/etapa0"
$env:P07_L07_TRAIN="1"
npm run lab

For the first reflow, change P07_L07_STAGE to 1, P07_L07_OUT to an etapa1 directory and set P07_L07_TEACHER to the absolute path of etapa0/model.pt; the second reflow is analogous with stage 2 and the etapa1 model. P07_L07_CACHE is optional and changes the Hugging Face cache, which the recipe uses for the same CIFAR-10 revision as p07-l02 and p07-l03. Each latest.pt checkpoint saves the network, EMA, Adam, step and all four random generators; if the run is interrupted, keep the directory and add P07_L07_RESUME=1. Previously published pairs are reused after their fingerprint is checked, and a nonempty directory is not overwritten without that variable.

To estimate the budget, first measure on your GPU the update rate rr per second with microbatch 32 in bf16 and the time τ\tau for one network evaluation on a batch of 64; stage 0 takes about 200.000/r200.000/r seconds and each reflow about 50.000/r+782⋅128 τ50.000/r+782\cdot128\,\tau seconds plus pair writing. This is the same order as p07-l03 training because the budget is the same.

[ ]Train an image stageLocal GPU
CONFIGS={"full":{"width":224,"steps":(200000,50000,50000),"batch":32,"lr":2e-4,"ema_decay":.9999,
                 "pairs":50000,"teacher_steps":128,"pair_batch":64,"checkpoint_every":10000,"log_every":100},
         "smoke":{"width":64,"steps":(30,30,30),"batch":4,"lr":2e-4,"ema_decay":.9,"pairs":64,
                  "teacher_steps":4,"pair_batch":32,"checkpoint_every":10,"log_every":10}}
REVISION="0b2714987fa478483af9968de7c934580d0bb9a2"

def publish_file(path,writer):
    path=pathlib.Path(path)
    temp=path.parent/("pending-"+uuid.uuid4().hex+".tmp")
    owned=False
    try:
        with temp.open("xb") as f:
            owned=True
            writer(f)
        os.link(temp,path)
    finally:
        if owned: temp.unlink(missing_ok=True)

def load_cifar(cache=None):
    from datasets import load_dataset
    ds=load_dataset("uoft-cs/cifar10",revision=REVISION,cache_dir=str(cache) if cache else None,split="train")
    images=np.stack([np.asarray(im.convert("RGB")) for im in ds["img"]])
    if images.shape!=(50000,32,32,3): raise ValueError("Partición inesperada")
    return images

@torch.no_grad()
def generate_pairs(teacher,cfg,stage,device):
    generator=torch.Generator(device=device).manual_seed(7000+stage)
    starts=np.empty((cfg["pairs"],3,32,32),np.float32); ends=np.empty_like(starts)
    for offset in range(0,cfg["pairs"],cfg["pair_batch"]):
        count=min(cfg["pair_batch"],cfg["pairs"]-offset)
        x0=torch.randn((count,3,32,32),device=device,generator=generator)
        x1,_=sample_flow(teacher,x0,cfg["teacher_steps"],"euler")
        starts[offset:offset+count]=x0.cpu().numpy(); ends[offset:offset+count]=x1.cpu().numpy()
        if (offset//cfg["pair_batch"])%100==0: print("Pares generados:",offset+count,flush=True)
    return starts,ends

def image_training_digest():
    sources=[time_embedding,Residual,Attention,DiffusionUNet,ImageFlow,cfm_loss_torch,sample_flow,
             generate_pairs,train_image_stage]
    text="\n".join(inspect.getsource(f) for f in sources if inspect.isfunction(f))
    text+=json.dumps(CONFIGS,sort_keys=True)+"".join(
        inspect.getsource(m) for c in sources if inspect.isclass(c) for m in vars(c).values() if inspect.isfunction(m))
    return hashlib.sha256(text.encode("utf-8")).hexdigest()

def train_image_stage(stage,mode,output,teacher_path=None,resume=False,cache=None):
    if stage not in (0,1,2) or mode not in CONFIGS: raise ValueError("Etapa o modo inválidos")
    cfg,output=CONFIGS[mode],pathlib.Path(output)
    if not output.is_absolute(): raise ValueError("La salida debe ser una ruta absoluta")
    if (stage>0)!=bool(teacher_path): raise ValueError("Las etapas 1 y 2 necesitan profesor; la 0, no")
    if teacher_path:
        teacher_path=pathlib.Path(teacher_path)
        if not teacher_path.is_absolute(): raise ValueError("El profesor debe ser una ruta absoluta")
    if (output/"model.pt").exists(): raise FileExistsError("El modelo final de esta etapa ya existe")
    if output.exists() and any(output.iterdir()) and not resume:
        raise FileExistsError("Usa un directorio vacío o P07_L07_RESUME=1")
    if not torch.cuda.is_available(): raise RuntimeError("Esta receta requiere CUDA")
    output.mkdir(parents=True,exist_ok=True)
    device,steps,b=torch.device("cuda"),cfg["steps"][stage],cfg["batch"]
    model=ema=optimizer=teacher=saved=images=pairs=start_weights=x0=x1=t=loss=None
    try:
        source_sha=image_training_digest()
        teacher_sha=pairs_sha=None
        if stage==0:
            images=torch.from_numpy(load_cifar(cache))
            train_sha=hashlib.sha256(images.numpy().tobytes()).hexdigest()
        else:
            teacher_sha=file_sha(teacher_path)
            saved=torch.load(teacher_path,map_location="cpu",weights_only=True)
            previous=saved["identity"]
            if previous["stage"]!=stage-1 or previous["mode"]!=mode or previous["source_sha256"]!=source_sha:
                raise ValueError("Profesor de otra etapa, de otro modo o de otro código")
            train_sha,start_weights,saved=previous["train_images_sha256"],saved["ema"],None
            pair_path=output/"pairs.npz"
            if not pair_path.exists():
                teacher=ImageFlow(DiffusionUNet(cfg["width"])).to(device).eval()
                teacher.load_state_dict(start_weights,strict=True)
                teacher.requires_grad_(False)
                starts,ends=generate_pairs(teacher,cfg,stage,device)
                publish_file(pair_path,lambda f:np.savez(f,x0=starts,x1=ends,teacher_sha256=teacher_sha,
                                                         stage=stage,seed=7000+stage,steps=cfg["teacher_steps"]))
                teacher=starts=ends=None
                torch.cuda.empty_cache()
            shape=(cfg["pairs"],3,32,32)
            with np.load(pair_path,allow_pickle=False) as data:
                if (str(data["teacher_sha256"])!=teacher_sha or int(data["stage"])!=stage
                    or int(data["steps"])!=cfg["teacher_steps"] or data["x0"].shape!=shape or data["x1"].shape!=shape):
                    raise ValueError("Pares de otro profesor o de otra configuración")
                pairs=(torch.from_numpy(data["x0"]),torch.from_numpy(data["x1"]))
            if not (pairs[0].isfinite().all() and pairs[1].isfinite().all()): raise ValueError("Pares no finitos")
            pairs_sha=file_sha(pair_path)
        identity={"mode":mode,"stage":stage,"width":cfg["width"],"steps":steps,"batch":b,"lr":cfg["lr"],"ema_decay":cfg["ema_decay"],
                  "seed":51+stage,"dataset_revision":REVISION,"train_images_sha256":train_sha,
                  "source_sha256":source_sha,"teacher_sha256":teacher_sha,"pairs_sha256":pairs_sha,
                  "pair_count":cfg["pairs"] if stage else None,"teacher_steps":cfg["teacher_steps"] if stage else None,
                  "flip":stage==0,"precision":"autocast bf16","time_input":"1000*t",
                  "versions":{n:importlib.metadata.version(n) for n in ("torch","numpy","datasets")}}
        torch.manual_seed(51+stage)
        rngs={"index":torch.Generator().manual_seed(151+stage),"time":torch.Generator().manual_seed(251+stage),
              "flip":torch.Generator().manual_seed(451+stage),
              "noise":torch.Generator(device=device).manual_seed(351+stage)}
        model=ImageFlow(DiffusionUNet(cfg["width"])).to(device)
        if start_weights is not None: model.load_state_dict(start_weights,strict=True)
        ema=ImageFlow(DiffusionUNet(cfg["width"])).to(device).eval()
        ema.load_state_dict(model.state_dict()); ema.requires_grad_(False)
        start_weights=None
        optimizer=torch.optim.Adam(model.parameters(),lr=cfg["lr"])
        start,losses,checkpoint=0,[],output/"latest.pt"
        if resume and checkpoint.exists():
            saved=torch.load(checkpoint,map_location="cpu",weights_only=True)
            if saved["identity"]!=identity: raise ValueError("Checkpoint de otra configuración")
            model.load_state_dict(saved["model"]); ema.load_state_dict(saved["ema"])
            optimizer.load_state_dict(saved["optimizer"])
            for name,g in rngs.items(): g.set_state(saved["rng_"+name])
            start,losses,saved=int(saved["step"]),saved["losses"],None
            print("Reanudando desde el paso",start,flush=True)
        def save_checkpoint(step):
            if shutil.disk_usage(output).free<2*1024**3: raise OSError("Se requieren 2 GiB libres")
            state={"identity":identity,"step":step,"model":model.state_dict(),"ema":ema.state_dict(),
                   "optimizer":optimizer.state_dict(),"losses":losses,
                   **{"rng_"+name:g.get_state() for name,g in rngs.items()}}
            temporary=output/("checkpoint-"+uuid.uuid4().hex+".tmp")
            try:
                torch.save(state,temporary)
                os.replace(temporary,checkpoint)
            finally:
                temporary.unlink(missing_ok=True)
        model.train()
        for step in range(start+1,steps+1):
            t=torch.rand(b,generator=rngs["time"]).to(device)
            if stage==0:
                index=torch.randint(len(images),(b,),generator=rngs["index"])
                x1=images[index].to(device).permute(0,3,1,2).float()/127.5-1
                flip=(torch.rand(b,generator=rngs["flip"])<.5).to(device)
                x1=torch.where(flip[:,None,None,None],x1.flip(-1),x1)
                x0=torch.randn(x1.shape,device=device,generator=rngs["noise"])
            else:
                index=torch.randint(cfg["pairs"],(b,),generator=rngs["index"])
                x0,x1=pairs[0][index].to(device),pairs[1][index].to(device)
            optimizer.zero_grad(set_to_none=True)
            with torch.autocast(device_type="cuda",dtype=torch.bfloat16):
                loss=cfm_loss_torch(model,x0,x1,t)
            loss.backward()
            optimizer.step()
            with torch.no_grad():
                for e,p in zip(ema.parameters(),model.parameters()): e.lerp_(p,1-cfg["ema_decay"])
            if step%cfg["log_every"]==0:
                losses.append({"step":step,"loss":float(loss.detach())})
                print("Etapa",stage,"paso",step,"pérdida",losses[-1]["loss"],flush=True)
            if step%cfg["checkpoint_every"]==0: save_checkpoint(step)
        final={"identity":identity,"model":model.state_dict(),"ema":ema.state_dict(),"losses":losses}
        publish_file(output/"model.pt",lambda f:torch.save(final,f))
        print("Modelo guardado:",output/"model.pt")
    finally:
        model=ema=optimizer=teacher=saved=images=pairs=start_weights=x0=x1=t=loss=None
        torch.cuda.empty_cache()

if os.environ.get("P07_L07_TRAIN")=="1":
    train_image_stage(int(os.environ["P07_L07_STAGE"]),os.environ.get("P07_L07_MODE","full"),
                      os.environ["P07_L07_OUT"],os.environ.get("P07_L07_TEACHER"),
                      os.environ.get("P07_L07_RESUME")=="1",os.environ.get("P07_L07_CACHE"))
else:
    print("Entrenamiento definido. Para lanzarlo: P07_L07_TRAIN=1, P07_L07_STAGE y P07_L07_OUT.")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Evaluation: FID versus NFE and velocity deviation

The fourth cell evaluates the EMA of a model.pt. It generates 10,000 images (256 in smoke mode) in batches of 32 with seed seed+inicio per batch, the same construction as p07-l04: with the default seed, 10701, flow and diffusion start from the same noise. It clips only the final output to [−1,1][-1,1], quantizes it to 8 bits and computes FID-10k against the p07-l02 reference. Set P07_L07_MODEL and P07_L07_RESULT (a new JSON file) to absolute paths, P07_L07_STEPS, P07_L07_SOLVER (euler or heun), and P07_L07_EVAL=1; the reference is read from P07_L02_REF. For the few-step curve, evaluate each stage with 1, 2 and 4 Euler steps and with 1 and 2 Heun steps (2 and 4 NFE); for the fine-integration endpoint, use 128 Euler steps.

The cell also measures stage velocity deviation with 64 independent noise samples (8 in smoke) and 128 Euler steps, averaged per pixel: the same quantity as in 2D. The trajectory need not be stored because, with Euler, the mean velocity is exactly the chord, 1N∑ivi=xN−x0\tfrac1N\sum_i v_i=x_N-x_0, and the deviation is 1N∑i∥vi∥2−∥xN−x0∥2\tfrac1N\sum_i\norm{v_i}^2-\norm{x_N-x_0}^2, a variance that cannot be negative.

[ ]FID and velocity deviation of one stageLocal GPU
EVAL={"full":{"samples":10000,"dispersion":64},"smoke":{"samples":256,"dispersion":8}}

@torch.no_grad()
def velocity_dispersion(model,device,count):
    total=0.
    for start in range(0,count,8):
        n=min(8,count-start)
        generator=torch.Generator(device=device).manual_seed(51000+start)
        x0=torch.randn((n,3,32,32),device=device,generator=generator)
        x=x0.clone()
        speed2=torch.zeros(n,device=device,dtype=torch.float64)
        for i in range(128):
            t=torch.full((n,),i/128,device=device)
            with torch.autocast(device_type="cuda",dtype=torch.bfloat16):
                v=model(x,t).float()
            speed2+=v.double().square().flatten(1).mean(1)/128
            x=x+v/128
        chord=(x-x0).double().square().flatten(1).mean(1)
        total+=float((speed2-chord).sum())
    value=total/count
    if value < -1e-6: raise ArithmeticError("Desviación negativa fuera de tolerancia")
    return max(0.,value)

def evaluate_flow(model_path,reference,result_path,steps,method,seed=10701):
    model_path,reference,result_path=map(pathlib.Path,(model_path,reference,result_path))
    if not all(p.is_absolute() for p in (model_path,reference,result_path)):
        raise ValueError("Rutas absolutas obligatorias")
    if result_path.exists() or not result_path.parent.is_dir(): raise ValueError("El resultado debe ser un archivo nuevo")
    if steps<1 or method not in ("euler","heun"): raise ValueError("Solver inválido")
    if not torch.cuda.is_available(): raise RuntimeError("La evaluación requiere CUDA")
    device=torch.device("cuda")
    saved=model=mean=cov=extractor=x=sample=pixels=features=None
    try:
        saved=torch.load(model_path,map_location="cpu",weights_only=True)
        identity=saved["identity"]
        if identity["source_sha256"]!=image_training_digest():
            raise ValueError("El código de las celdas difiere del que entrenó el modelo")
        plan=EVAL[identity["mode"]]
        model=ImageFlow(DiffusionUNet(identity["width"])).to(device).eval()
        model.load_state_dict(saved["ema"],strict=True)
        saved=None
        dispersion=velocity_dispersion(model,device,plan["dispersion"])
        mean,cov,extractor,resize,record=load_fid_reference(reference,device)
        if record["dataset_revision"]!=identity["dataset_revision"]:
            raise ValueError("Revisión de CIFAR incompatible")
        chunks,grid=[],None
        for start in range(0,plan["samples"],32):
            count=min(32,plan["samples"]-start)
            generator=torch.Generator(device=device).manual_seed(seed+start)
            x=torch.randn((count,3,32,32),device=device,generator=generator)
            sample,nfe=sample_flow(model,x,steps,method)
            pixels=((sample.clamp(-1,1)+1)*127.5).round().byte().permute(0,2,3,1).cpu().numpy()
            if grid is None: grid=image_grid(pixels)
            resized=np.stack([resize(im) for im in pixels]).transpose(0,3,1,2)
            with torch.no_grad():
                features=extractor(torch.from_numpy(resized).to(device)).cpu().numpy()
            chunks.append(features)
            x=sample=pixels=features=None
            if start%3200==0: print("Imágenes evaluadas:",start+count,flush=True)
        fid=feature_fid(np.concatenate(chunks),mean,cov)
        sources=[sample_flow,velocity_dispersion,evaluate_flow,load_fid_reference,feature_fid,image_grid]
        eval_sha=hashlib.sha256("\n".join(inspect.getsource(f) for f in sources).encode("utf-8")).hexdigest()
        result={"family":"flow","mode":identity["mode"],"stage":identity["stage"],"solver":method,"steps":steps,
                "nfe":nfe,"fid":fid,"velocity_dispersion":dispersion,"dispersion_samples":plan["dispersion"],
                "dispersion_steps":128,"samples":plan["samples"],"batch":32,"seed":seed,"weights":"ema",
                "model_sha256":file_sha(model_path),"training_identity":identity,
                "train_sha256":record["train_sha256"],"extractor_sha256":record["extractor_sha256"],
                "grid_png":grid,"eval_source_sha256":eval_sha,"precision":"CUDA autocast bf16",
                "device":torch.cuda.get_device_name(device),"cuda_version":torch.version.cuda,
                "versions":{name:importlib.metadata.version(name) for name in
                            ("torch","numpy","datasets","clean-fid","Pillow")}}
        publish_file(result_path,lambda f:f.write(json.dumps(result,ensure_ascii=False,indent=2).encode("utf-8")))
        print("Etapa",identity["stage"],method,steps,"pasos,",nfe,"NFE: FID",fid,
              "desviación",dispersion,"archivo",result_path)
    finally:
        saved=model=mean=cov=extractor=x=sample=pixels=features=None
        torch.cuda.empty_cache()

if os.environ.get("P07_L07_EVAL")=="1":
    evaluate_flow(os.environ["P07_L07_MODEL"],os.environ["P07_L02_REF"],
                  os.environ["P07_L07_RESULT"],int(os.environ["P07_L07_STEPS"]),
                  os.environ.get("P07_L07_SOLVER","euler"),int(os.environ.get("P07_L07_SEED","10701")))
else:
    print("Evaluación definida. Para lanzarla: P07_L07_EVAL=1, P07_L07_MODEL, P07_L07_RESULT y P07_L07_STEPS.")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

What to expect and how to check it

With the full recipe, check four things, each with its own measurement:

  1. The loss has a floor. In stage 0 the loss falls and stabilizes well above zero, as in 2D; in reflow it should be well below that floor because the teacher’s coupling is deterministic and its segments rarely cross. If it does not fall, inspect the pairs before the network.
  2. Velocity deviation falls after reflow. This directly measures straightening; compare it across stages using the same 64 noise samples.
  3. Few-step FID improves greatly after reflow. This is the central result of Liu and colleagues: with one Euler step, 378 before reflow and 12.21 after the first. With a smaller network and budget, your figures will be worse, but the pattern to reproduce is a drop of an order of magnitude or more at 1 to 4 NFE.
  4. FID with fine integration need not improve. In the same table, RK45 went from 2.58 to 3.36 and 3.96. If your 128-step Euler result worsens somewhat after each reflow, that alone is not a code failure: the student inherits the teacher’s error and adds its own.

The recipe was checked with a real short smoke run: all three stages, pair generation, a simulated interruption at step 20 of the first reflow with resumption from the step-10 checkpoint (the final EMA matched the uninterrupted run bit for bit), and evaluation of all three stages. With 30 updates, stage-0 loss fell from 0.91 to 0.60 and reflow losses were around 0.02 and 0.008; FID with 256 samples and one Euler step was between 367 and 372 across the three stages, characteristic of a model that has not learned to generate images. Those figures only certify that the chain works end to end; full mode determines quality.

The last cell overlays your flow and diffusion measurements. Collect the paths to their JSON files from this lesson and p07-l04 in a JSON list in P07_L07_POINTS and choose a new PNG path in P07_L07_PLOT. Before plotting, the cell requires the same reference, extractor, sample count, batch, seed and shared versions; each figure contains one seed and repeats are saved separately. The p07-l04 JSON does not record the Pillow version or a fingerprint of its evaluation code, so that equality cannot be checked and the cell warns about it. Equal NFE also does not mean equal wall-clock time or endpoint: p07-l04 ends with a data estimate from index 1 (one additional NFE, already counted), whereas flow integrates to t=1t=1.

[ ]Compare measured curvesLocal GPU
def plot_fid_curves(paths,output):
    import matplotlib.pyplot as plt
    paths=[pathlib.Path(p) for p in paths]
    output=pathlib.Path(output)
    if len(paths)<2 or not all(p.is_absolute() for p in paths) or not output.is_absolute():
        raise ValueError("Se requieren rutas absolutas y varios puntos")
    if output.exists() or not output.parent.is_dir(): raise ValueError("Figura debe ser nueva")
    rows=[json.loads(path.read_text(encoding="utf-8")) for path in paths]
    keys=("train_sha256","extractor_sha256","batch","seed")
    if any([r[k] for k in keys]!=[rows[0][k] for k in keys] for r in rows):
        raise ValueError("Las referencias o muestras no coinciden")
    counts=[r["samples"] if r.get("family")=="flow" else r["count"] for r in rows]
    if len(set(counts))!=1: raise ValueError("Los tamaños de muestra no coinciden")
    for name in ("torch","numpy","clean-fid"):
        if any(r["versions"][name]!=rows[0]["versions"][name] for r in rows):
            raise ValueError("Las versiones comunes no coinciden")
    if not any(r.get("family")=="flow" for r in rows) or not any(r.get("family")!="flow" for r in rows):
        raise ValueError("Faltan puntos de flow o difusión")
    grouped={}
    for row in rows:
        if not np.isfinite(row["fid"]) or row["fid"]<0 or row["nfe"]<1:
            raise ValueError("Punto inválido")
        label=("flow etapa "+str(row["stage"])+" "+row["solver"]) if row.get("family")=="flow" else (
            "difusión "+row["method"]+" "+str(row["grid"])+" "+str(row["variance"]))
        grouped.setdefault(label,[]).append(row)
    for label,group in grouped.items():
        if len({r["nfe"] for r in group})!=len(group): raise ValueError("NFE duplicado en "+label)
        hashes={r["model_sha256"] if r.get("family")=="flow" else r["checkpoint_sha256"] for r in group}
        if len(hashes)!=1: raise ValueError("Modelos distintos en "+label)
        if group[0].get("family")=="flow" and len({r["eval_source_sha256"] for r in group})!=1:
            raise ValueError("Evaluadores distintos en "+label)
    fig,ax=plt.subplots()
    for label,group in sorted(grouped.items()):
        group.sort(key=lambda r:r["nfe"])
        ax.plot([r["nfe"] for r in group],[r["fid"] for r in group],marker="o",label=label)
    ax.set(xscale="log",xlabel="NFE por imagen",ylabel="FID-10k")
    ax.legend()
    fig.tight_layout()
    import io
    if output.suffix.lower()!=".png": raise ValueError("La figura debe ser PNG")
    buffer=io.BytesIO()
    fig.savefig(buffer,format="png")
    plt.close(fig)
    publish_file(output,lambda f:f.write(buffer.getvalue()))
    print("Curva guardada:",output,"puntos:",len(rows))
    print("Aviso: el JSON de p07-l04 no registra Pillow ni la huella de su evaluador; esa igualdad no se verifica.")

if os.environ.get("P07_L07_POINTS"):
    plot_fid_curves(json.loads(os.environ["P07_L07_POINTS"]),os.environ["P07_L07_PLOT"])
else:
    print("Comparación definida. Para trazarla: P07_L07_POINTS (lista JSON de rutas) y P07_L07_PLOT.")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

NumericVelocity of a segment
For x₀=(0,0), x₁=(2,1) and t=0.3, what is the first component of the target velocity?
NumericSecond component
With the same pair, what is the second component of the target velocity?
NumericThe field averages
In one dimension, X₁ is +1 or −1 with probability 1/2 and X₀ ~ N(0,1) is independent. With straight interpolation, compute v*(x,t)=E[X₁−X₀ | Xₜ=x] at x=0.25 and t=0.5 (three decimal places).
CodeFlow loss and sampling
Implement cfm_loss(model,x0,x1,t) and euler_flow(model,x0,steps). Arrays have one example per row; t is a vector of B times. The loss is the mean of half the squared norm per example. Euler integrates from 0 to 1, evaluates at the start of each interval and does not modify x0.
import numpy as np
def cfm_loss(model,x0,x1,t):
  pass
def euler_flow(model,x0,steps):
  pass
Shift+Enter to run
Quiz
After several reflows, regression loss falls but FID worsens. Which explanation is compatible with the procedure?
Quiz
You want to compare flow matching with p07-l04 diffusion at a budget of 4 NFE per image. Which comparison is fair?
Quiz
You train with logit-normal rather than uniform T and do not reweight the loss. With a sufficiently expressive network, what changes?
Key idea

Flow matching learns the conditional average of pair velocities; reflow changes the coupling using generated endpoints. Its potential straightening is useful for integration with few steps, but quality and cost must be measured separately.