Module contents
Lesson 25 of 28Research 115 min

Few-step generation: distillation, consistency models and mean flows

Study progressive distillation, consistency models, distribution matching and flow maps for few-step generation, including their training costs and evaluation limits.

After this lesson you can

  • Explain progressive distillation and the accumulation of teacher and student costs.
  • Derive the boundary condition for consistency models and distinguish their training methods.
  • Describe adversarial and distribution-matching distillation.
  • Derive the MeanFlow average-velocity identity along a trajectory.
  • Compare few-step models with explicit inference and training budgets.

Before you start

Pass through the network fewer times

A diffusion sampler may need many successive evaluations of a large network. A better solver reduces some of that cost; another option is to train a network to learn longer jumps or directly learn a trajectory’s result. Faster inference does not eliminate prior work: count teacher training, target generation and training each student.

Quality is not one number either. A plausible image may belong to a distribution with little diversity; FID can change with extractor, reference set and sample count. We compare methods with explicit protocols and distinguish this lesson’s short runs from published results.

Progressive distillation

In progressive distillation, a deterministic teacher takes two short steps and the student learns to approximate their composition with one long step. After a round the student becomes teacher and the operation repeats. If the initial step count is a power of two and each round halves it exactly, NN becomes N/2kN/2^k after kk rounds. Going from 1024 to 4 takes 8 rounds.

The objective can be formulated as a clean-data prediction that, inserted into the student update, reaches the state produced by two teacher steps. Parameterization must be compatible with the schedule; Salimans and Ho study a velocity parameterization that improves behavior at extreme levels. State equality is a training target, not a guarantee the student satisfies it everywhere. Error can accumulate when the student becomes the next teacher.

In their experiments, Salimans and Ho report 50,000 updates per round except rounds toward two and one step, which use 100,000. Those budgets belong to their configuration and add to original-model cost. They cannot be inferred from inference NFE.

InteractiveProgressive distillation rounds

This diagram shows 256 → 1 distillation. In each round the student learns to approximate two consecutive teacher steps with one step. The animation tracks the rounds of the theoretical schedule.

Teacher: 256 steps

Initial state → intermediate → target
Two evaluations for the pair

Student: 128 steps

Initial state → predicted target
One evaluation for the step

Round 1 of 8
Recorded trial: 8 NFEEight recorded samples from round 0
Cumulative student cost

Teacher forward passes: 0 examples
Student forward passes: 0 examples
Student backward passes: 0 examples

The reproducible trial uses 64 CIFAR-10 training images and 8 test images. Its ε teacher has width 8, T = 20, and only 2 prior updates. The 8 → 4 → 2 → 1 NFE measurements share eight latents from seed 2540, with two student updates per round. Processing counts are in examples and exclude teacher training and FID evaluation.

FID uses clean-fid InceptionV3W with uint8 RGB and bicubic resizing to 299 pixels. Eight images on each side give a 2,048-dimensional covariance of rank at most 7 and a strongly biased estimate. kNN precision and recall with k = 3 were zero, which does not establish a lack of diversity. The teacher and students received very little training. The forward process has a terminal distribution far from the initial sampling Gaussian, and clipping affects many RGB values. Outputs look like noise and cannot support a ranking. See distillation-results.json for measurements, hashes and protocol, and progressive_distillation.py for code.

Measured round
Sampling NFE
8
Eight-sample FID
562.20
Fraction clipped
38.1 %
Follow step composition and measurements whose provenance is stated in the figure.

Consistency models

A consistency model seeks a function f(xt,t)f(x_t,t) mapping points on the same probability-flow ODE trajectory to a common endpoint at ε>0\varepsilon>0. Ideally, if xtx_t and xsx_s lie on the same trajectory, f(xt,t)=f(xs,s)f(x_t,t)=f(x_s,s). Boundary condition f(x,ε)=xf(x,\varepsilon)=x identifies that endpoint and prevents an arbitrary constant function from satisfying equality alone.

A practical parameterization is

fθ(x,t)=cskip(t)x+cout(t)Fθ(x,t),cskip(ε)=1,cout(ε)=0.f_\theta(x,t)=c_{\rm skip}(t)x+c_{\rm out}(t)F_\theta(x,t), \quad c_{\rm skip}(\varepsilon)=1,\quad c_{\rm out}(\varepsilon)=0.

Substituting t=εt=\varepsilon immediately proves fθ(x,ε)=xf_\theta(x,\varepsilon)=x, provided FθF_\theta is finite there. This does not prove the network is consistent at interior times: that requires an objective and sufficient training.

InteractiveWhere each point goes

Drag the large point. The teacher’s inverse rotation gives the exact endpoint. The student applies its trained network to the same state. The curves show four teacher trajectories.

  • State xₜ
  • Exact endpoint
  • Student
  • Held-out MSE

The explicit teacher is xₜ = R(1.25t²)x₀, starting at the data at t = 0 and ending at the rotated mixture at t = 1, with inverse R(−1.25t²)xₜ. The terminal distribution is the rotated mixture. Test points are colored by the closest original center. The plot shows 128 of the 1,024 held-out observations.

The fitted student is f(x,t) = x + t·MLP(x,t), with layers 3 → 32 → 32 → 2 and EMA decay 0.995. Training used 1600 updates with batch size 96. The MSE curve uses all 1,024 test samples at 21 times with seed 2530. The point’s error is computed live and can increase when dragged outside the training region. At t = 0, f(x,0) = x exactly. See export_fewstep.py and fewstep-data.json.

0.50
Error at the draggable point
0.1146
Test MSE per coordinate
0.0067
Compare the learned map with teacher integration under the stated protocol.

In consistency distillation, a teacher approximates an ODE step between neighboring levels and a target network, often an EMA, supplies the value the student should match. The EMA is treated as a stop-gradient target for that update. Solver and teacher errors enter the targets. In consistency training, noisy pairs and targets are constructed without that pretrained teacher; each variant’s assumptions, schedule and corrections are needed. Boundary equality alone does not replace that procedure.

Song and colleagues report on CIFAR-10 FID 3.55 with one evaluation and 2.93 with two for their distilled model; direct training in their table gives 8.70 and 5.83. These are published results for specific networks and protocols, not our 2D experiment. Song and Dhariwal study training, schedule and objective changes that improve the direct variant.

Continuous time and stability

In the small-interval limit, output differences can be related to a directional derivative along the field. But taking that limit in an implementation does not automatically eliminate instability: parameterization, time weighting, gradient treatment and Jacobian–vector product precision matter. Lu and Song study a simplified continuous formulation and strategies to stabilize and scale it. A continuous objective can need specific techniques; simply making the interval smaller does not ensure the same numerical result.

Adversarial and distribution matching

Adversarial distillation combines a diffusion-model signal with a discriminator distinguishing real from generated samples. Sauer and colleagues combine score distillation and adversarial loss for one- to four-step generation. This is a recipe with extra components and training costs, not merely a different solver.

In distribution matching distillation, or DMD, noise-perturbed generator and teacher distributions are compared at multiple levels. Reverse KL direction KL(pθ,t∥pmaestro,t)\mathrm{KL}(p_{\theta,t}\|p_{{\rm maestro},t}) requires a score for the current generator distribution at that level as well as the teacher score; the objective combines levels with chosen weights. DMD fits a second score model on generator samples to estimate it; using only the teacher score does not generally give the same KL gradient. As studied in forward and reverse KL, reverse KL can favor high-probability regions and neglect modes, depending on distributions and generator family.

Yin and colleagues add regression loss to distribution matching to stabilize training. In their ablation, removing regression is associated with lower diversity; it does not prove every reverse-KL use collapses. Their table 1 reports FID 2.62 on 64×6464\times64 ImageNet for one-pass DMD versus 2.32 for their 512-pass EDM teacher. For their text model, the paper describes about 36 hours of training on 72 A100s; that cost belongs to that configuration and is not a time measured here.

Flow maps and average velocity

Flow-map models try to learn a jump between two instants instead of approximating only instantaneous velocity. A shortcut model conditions the network on jump size and trains targets relating long and short jumps; its assumptions and training differ from repeating Euler with an already trained network. See Frans and colleagues.

For MeanFlow, consider an ODE with a unique trajectory on the interval, z˙τ=v(zτ,τ)\dot z_\tau=v(z_\tau,\tau), and r<tr<t. Also assume the flow-defined average velocity is differentiable as a function of (z,r,t)(z,r,t). Define that velocity along the trajectory by

u(zt,r,t)=1t−r∫rtv(zτ,τ) dτ=zt−zrt−r.u(z_t,r,t)=\frac{1}{t-r}\int_r^t v(z_\tau,\tau)\,d\tau =\frac{z_t-z_r}{t-r}.

By the fundamental theorem of calculus, differentiating (t−r)u(zt,r,t)(t-r)u(z_t,r,t) with respect to tt with rr fixed gives

u+(t−r)ddtu(zt,r,t)=v(zt,t),u=v−(t−r)ddtu.u+(t-r)\frac{d}{dt}u(z_t,r,t)=v(z_t,t),\qquad u=v-(t-r)\frac{d}{dt}u.

The derivative is total along the trajectory: du/dt=∂tu+Jzu vd u/dt=\partial_tu+J_z u\,v when rr is fixed. A Jacobian–vector product can calculate that direction without forming the entire matrix. Limit r→tr\to t recovers u=vu=v under continuity; do not divide by zero in the integral definition. An approximate network need not satisfy the identity exactly. Training by Geng and colleagues uses this relation as a target and details JVP calculation.

InteractiveAverage and instantaneous velocity

Step backward from zₜ to r. The blue chord uses mean velocity, and the dashed line uses instantaneous velocity at t.

  • Exact trajectory
  • Mean-velocity step
  • Euler with instantaneous velocity
  • State zₜ

Mean velocity = (−0.755, 1.668). Instantaneous velocity = (−2.152, 2.090). By definition, the mean-velocity step gives zₜ−(t−r)u(zₜ,r,t)=zᵣ. Euler uses v(zₜ,t) in place of u.

The lab uses zₜ=R(1.25·t²)(1.5, 0), with rotation R. The trajectory, derivative and both endpoints are obtained directly. The controls keep r<t so the quotient is defined.

20
80
Interval
0.20 → 0.80
Euler error
0.8755
Mean-velocity step error
0
Choose endpoints and compare the average jump with the tangent of the stated trajectory.

The paper reports conditional 256×256256\times256 ImageNet FID 3.43 with one NFE for MeanFlow-XL/2, trained from scratch for 240 epochs in its table 2 configuration. It also reports 2.20 with two NFE for an XL/2+ configuration trained for more epochs. The work applies guidance and distinguishes NFE from a conventional double pass; these numbers are not results from this lesson’s small model.

Compare the whole system

For each result record what counts as a network evaluation, whether guidance needs two branches, sampler steps, architecture, teacher and extra training, as well as dataset, resolution, extractor, sample count and diversity measure. A step with a larger network need not cost the same as an evaluation of a smaller one. If a paper does not declare a quantity, mark it unknown: do not infer it from step count.

InteractiveFew-step methods

Song et al.: unconditional CIFAR-10

Published FID. Lower scores are better by this metric. Bars share a scale within the selected study.

Consistency distillation (CD)FID 3.55
1 NFE · Teacher: Yes · 800,000 updates, batch size 512, teacher training separate
Consistency distillation (CD)FID 2.93
2 NFE · Teacher: Yes · 800,000 updates, batch size 512, teacher training separate
Consistency training (CT)FID 8.70
1 NFE · Teacher: No · 800,000 updates, batch size 512
Consistency training (CT)FID 5.83
2 NFE · Teacher: No · 800,000 updates, batch size 512
Progressive distillation in this studyFID 8.34
1 NFE · Teacher: Yes · Total cost per row unspecified
Progressive distillation in this studyFID 5.58
2 NFE · Teacher: Yes · Total cost per row unspecified

Table 1 and Appendix C. CD distills a pretrained EDM. CT learns without that teacher. Each uses 800,000 updates with batch size 512. The PD values come from this study’s comparison. Primary study.

One NFE counts one network evaluation. Its cost varies by architecture. Update counts likewise depend on batch size, hardware and teacher cost. FID describes one aspect of output quality. Study protocols, conditioning and architectures differ, so rankings are only meaningful within a study.

Study
Maximum NFE
Visible results
6
Evaluation
Unconditional
Filter published results and compare their protocols before interpreting FID.

Lab: consistency and MeanFlow in 2D

The teacher ODE rotates samples using a known solution: the noisy endpoint in this example is a rotated mixture, not a standard normal. Check the boundary condition and central JVP against an analytical derivative, all in float64.

[ ]Consistency and MeanFlow, part 1Browser
"""Maestro de rotación exacta y red NumPy en float64."""
import numpy as np

OMEGA=1.25
CENTERS=np.array([[-1.5,-.3],[-.3,1.5],[1.5,.3],[.3,-1.5]])

def data_sample(rng,n):
    return CENTERS[rng.integers(0,4,n)]+.3*rng.normal(size=(n,2))

def rotate(x,angle):
    c=np.cos(angle);s=np.sin(angle)
    return np.concatenate((c*x[:,0:1]-s*x[:,1:2],s*x[:,0:1]+c*x[:,1:2]),axis=1)

def state(x0,t):return rotate(x0,OMEGA*t*t)
def velocity(x,t):return 2*OMEGA*t*np.column_stack((-x[:,1],x[:,0]))

def initialize(seed,dim):
    r=np.random.default_rng(seed);h=32
    return [r.normal(scale=np.sqrt(1/dim),size=(dim,h)),np.zeros(h),
            r.normal(scale=np.sqrt(1/h),size=(h,h)),np.zeros(h),
            r.normal(scale=np.sqrt(1/h),size=(h,2)),np.zeros(2)]

def network(z,p):
    h1=np.tanh(z@p[0]+p[1]);h2=np.tanh(h1@p[2]+p[3])
    return h2@p[4]+p[5],(z,h1,h2)

def grad(cache,output_gradient,p):
    z,h1,h2=cache;d=output_gradient
    W3=h2.T@d;b3=d.sum(0)
    d=(d@p[4].T)*(1-h2*h2);W2=h1.T@d;b2=d.sum(0)
    d=(d@p[2].T)*(1-h1*h1)
    return [z.T@d,d.sum(0),W2,b2,W3,b3]

def adam(params,grads,moments,squares,step):
    for i,(p,g) in enumerate(zip(params,grads)):
        moments[i]=.9*moments[i]+.1*g;squares[i]=.999*squares[i]+.001*g*g
        p-=.002*(moments[i]/(1-.9**step))/(np.sqrt(squares[i]/(1-.999**step))+1e-8)

def consistency(x,t,p):
    out,cache=network(np.concatenate((x,t),axis=1),p)
    return x+t*out,cache

def meanfield(x,r,t,p):
    return network(np.concatenate((x,r,t),axis=1),p)

def exact_mean(x,r,t):
    # Media entre r y t; en la diagonal se usa el límite instantáneo.
    dt=t-r
    back=rotate(x,OMEGA*(r*r-t*t))
    return np.where(dt!=0,(x-back)/np.where(dt==0,1,dt),velocity(x,t))

# Gradiente direccional de la red frente al JVP central, sin precisión mixta.
probe=initialize(2500,4);r=np.full((6,1),.2);t=np.full((6,1),.7)
x=np.random.default_rng(2500).normal(size=(6,2));v=velocity(x,t)
inputs=np.concatenate((x,r,t),axis=1);direction=np.concatenate((v,np.zeros_like(r),np.ones_like(t)),axis=1)
_,(z,h1,h2)=network(inputs,probe)
j1=(direction@probe[0])*(1-h1*h1);j2=(j1@probe[2])*(1-h2*h2);analytic=j2@probe[4]
h=1e-5;jvp=(network(inputs+h*direction,probe)[0]-network(inputs-h*direction,probe)[0])/(2*h)
err=np.max(np.abs(jvp-analytic));assert err<1e-8
assert np.array_equal(consistency(x,np.zeros_like(t),initialize(2501,3))[0],x)
print(f'JVP central float64 frente a derivada analítica: error máximo {err:.2e}; condición de contorno exacta.')

Distill the exact ODE using consecutive steps and an EMA copy; the student maintains exact identity at t=0.

[ ]Consistency and MeanFlow, part 2Browser
"""Destilación de consistencia con maestro exacto y alumno EMA."""
crng=np.random.default_rng(2510);train_data=data_sample(crng,2048)
cons_params=initialize(2511,3);cons_ema=[p.copy() for p in cons_params]
moments=[np.zeros_like(p) for p in cons_params];squares=[np.zeros_like(p) for p in cons_params]
cons_loss=[]
for step in range(1,1601):
    clean=train_data[crng.integers(0,len(train_data),96)]
    k=crng.integers(1,11,size=(96,1));t=k/10;s=(k-1)/10
    xt=state(clean,t)
    xs=rotate(xt,OMEGA*(s*s-t*t))
    pred,cache=consistency(xt,t,cons_params)
    target,_=consistency(xs,s,cons_ema)
    error=pred-target;loss=np.mean(error**2)
    grads=grad(cache,2*error/error.size*t,cons_params)
    adam(cons_params,grads,moments,squares,step)
    for average,current in zip(cons_ema,cons_params):average*=.995;average+=.005*current
    if step%400==0:cons_loss.append(float(loss))
print('Consistencia: 1600 actualizaciones, maestro exacto, EMA 0,995; pérdidas cada 400:',*[f'{v:.6f}' for v in cons_loss])

MeanFlow uses the total derivative with fixed r and a stop-gradient target. JVP is evaluated by central float64 differences, not mixed precision.

[ ]Consistency and MeanFlow, part 3Browser
"""MeanFlow con JVP central y objetivo detenido, todo en float64."""
mrng=np.random.default_rng(2520);mean_data=data_sample(mrng,2048)
mean_params=initialize(2521,4)
moments=[np.zeros_like(p) for p in mean_params];squares=[np.zeros_like(p) for p in mean_params]
mean_loss=[];jvp_step=1e-4
for step in range(1,1601):
    clean=mean_data[mrng.integers(0,len(mean_data),96)]
    t=mrng.uniform(.02,1,size=(96,1));r=mrng.uniform(size=(96,1))*t
    r=np.where(mrng.uniform(size=(96,1))<.25,0.,r)
    xt=state(clean,t);vt=velocity(xt,t)
    prediction,cache=meanfield(xt,r,t,mean_params)
    # Derivada total d/dt con r fijo y dz_t/dt=v_t; objetivo sin gradiente.
    plus=meanfield(xt+jvp_step*vt,r,t+jvp_step,mean_params)[0]
    minus=meanfield(xt-jvp_step*vt,r,t-jvp_step,mean_params)[0]
    jvp=(plus-minus)/(2*jvp_step)
    detached_target=vt-(t-r)*jvp
    error=prediction-detached_target;loss=np.mean(error**2)
    grads=grad(cache,2*error/error.size,mean_params)
    adam(mean_params,grads,moments,squares,step)
    if step%400==0:mean_loss.append(float(loss))
print('MeanFlow: 1600 actualizaciones, JVP central h=1e−4 y objetivo detenido; pérdidas cada 400:',*[f'{v:.6f}' for v in mean_loss])

Evaluation uses 1024 independent trajectories. For two consistency calls, an exact projection of the first output to t=0.5 is also used: that extra cost is stated and is not treated as an equal-NFE comparison. The two MeanFlow calls use two intervals.

[ ]Consistency and MeanFlow, part 4Browser
"""Evaluación sobre trayectorias que no aparecen en el entrenamiento."""
test_rng=np.random.default_rng(2530);test_clean=data_sample(test_rng,1024)
ones=np.ones((len(test_clean),1));zeros=np.zeros_like(ones);half=ones*.5
test_noisy=state(test_clean,ones)
c_one=consistency(test_noisy,ones,cons_ema)[0]
# Control de dos llamadas: el maestro exacto proyecta la primera predicción a t=0,5.
c_half=state(c_one,half);c_two=consistency(c_half,half,cons_ema)[0]
u_one=test_noisy-meanfield(test_noisy,zeros,ones,mean_params)[0]
u_half=test_noisy-.5*meanfield(test_noisy,half,ones,mean_params)[0]
u_two=u_half-.5*meanfield(u_half,zeros,half,mean_params)[0]
def mse(x):return np.mean((x-test_clean)**2)
print(f'Test independiente (1024): consistencia 1/2 llamadas MSE {mse(c_one):.6f}/{mse(c_two):.6f}; '
      'el control de dos llamadas usa además una proyección exacta del maestro.')
print(f'Test independiente (1024): MeanFlow 1/2 NFE MSE {mse(u_one):.6f}/{mse(u_two):.6f}.')
probe_t=test_rng.uniform(.02,1,(1024,1));probe_r=test_rng.uniform(size=(1024,1))*probe_t
probe_x=state(test_clean,probe_t)
pred=meanfield(probe_x,probe_r,probe_t,mean_params)[0]
true=exact_mean(probe_x,probe_r,probe_t)
print(f'Test independiente: MSE velocidad media contra mapa exacto {np.mean((pred-true)**2):.6f}.')
print('Una muestra finita y un maestro explícito no establecen un ranking general ni calidad de imágenes.')

Local lab: distill CIFAR-10 diffusion

Load the EMA of a lesson 18 ε checkpoint with positive terminal SNR and its original schedule. One round uses a grid of NN deterministic DDIM steps: for each consecutive pair t→m→st\to m\to s, the teacher calculates two predictions and produces xsmaestrox_s^{\rm maestro}. The student starts with the same weights and learns a noise prediction taking xtx_t to ss in one step. Its loss is final-state MSE against xsmaestrox_s^{\rm maestro}, with the teacher target stopped. This equals a time-dependent weighting of effective-noise loss; it does not exactly reproduce the parameterization, weighting or budget of Salimans and Ho. The teacher is frozen; after each effective update a student EMA is maintained and used as teacher in the next round.

Training points xtx_t are built with train images and Gaussian noise according to the checkpoint’s forward process; tt starts one grid step pair. Grids are nested: starting with 256 steps yields rounds of 128, 64, 32, 16, 8, 4, 2 and 1. The checkpoint must have at least 256 levels and αˉT>0\bar\alpha_T>0; another power of two can be chosen with ORYON_INITIAL_STEPS. The final step ends at the clean level without adding noise. AMP-skipped steps do not update EMA. Network and EMA states for each round are saved, but code does not automatically resume optimizers.

Each version generates from the same latents and is compared with held-out test images. Record actual network evaluations per image, Inception FID and precision/coverage with three-neighbor balls in the same feature space. The extractor is clean-fid==0.1.35 InceptionV3W with 8-bit RGB input and PIL bicubic resizing; few-sample estimators are highly biased. Also save the fraction of components outside [−1,1][-1,1] before image clipping. The report separates images processed by teacher forward and student forward and backward for each round; these are counts, not FLOPs or times. Teacher pretraining is an extra cost: its update count is in the checkpoint, but these counters do not reconstruct its full compute.

Install PyTorch, torchvision, NumPy, SciPy, Pillow, Matplotlib and clean-fid==0.1.35. Set ORYON_PREVIOUS_CKPT to lesson 18’s diffusion.pt and ORYON_INCEPTION_PT to inception-2015-12-05.pt. ORYON_DATA_ROOT and ORYON_OUTPUT_DIR determine data input and report, feature, sample and checkpoint output. Full mode proposes 4096 train images, 128 test images, 10,000 attempts per round and 256 initial steps; ORYON_TRAIN_IMAGES, ORYON_TEST_IMAGES, ORYON_UPDATES and ORYON_INITIAL_STEPS adjust the experiment. Full training is run by the reader; it is not a result measured here.

To check the pipeline, ORYON_QUICK=1 uses 64 train images, eight test images, a reduced checkpoint and two attempts per round, from 8 to 4, 2 and 1 steps. ORYON_CIFAR_PARQUET reuses CIFAR parquet only in quick mode and requires PyArrow. In a protected run, each student completed two updates without overflow; per round, 16 images were processed in teacher forward, eight in student forward and eight in student backward. FIDs of the four versions were approximately 562.20, 562.55, 562.21 and 562.16; three-neighbor precision and coverage were 0 and 0 throughout. These are not quality results: only eight images were evaluated, the teacher was barely trained too, αˉT≈0,8168\bar\alpha_T\approx0,8168 makes a standard-normal prior a poor approximation and about 38% of components were clipped. Do not infer a winner from these figures.

[ ]Progressive distillation on CIFAR-10Local GPU
"""Destilación progresiva de una EMA de difusión CIFAR con evaluación reproducible."""
import copy, hashlib, io, json, math, os
from pathlib import Path
os.environ.setdefault('OPENBLAS_NUM_THREADS','1')
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
from torch.utils.data import Dataset, DataLoader, Subset
from torchvision import datasets, transforms
from torchvision.utils import save_image
from PIL import Image
from cleanfid.inception_torchscript import InceptionV3W
from cleanfid.resize import build_resizer
torch.set_num_threads(2)

def groups(channels):
    return math.gcd(32, channels)


class AdaResidual(nn.Module):
    def __init__(self, channels, embedding):
        super().__init__()
        self.norm1 = nn.GroupNorm(groups(channels), channels)
        self.conv1 = nn.Conv2d(channels, channels, 3, padding=1)
        self.norm2 = nn.GroupNorm(groups(channels), channels, affine=False)
        self.condition = nn.Linear(embedding, 2 * channels)
        self.conv2 = nn.Conv2d(channels, channels, 3, padding=1)

    def forward(self, x, embedding):
        h = self.conv1(F.silu(self.norm1(x)))
        scale, shift = self.condition(embedding).chunk(2, dim=1)
        h = self.norm2(h) * (1 + scale[:, :, None, None]) + shift[:, :, None, None]
        return x + self.conv2(F.silu(h))


class SpatialAttention(nn.Module):
    """Atención de producto escalar solo en mapas de 16×16 y 8×8."""
    def __init__(self, channels, head_dim=32):
        super().__init__()
        self.heads = max(1, channels // min(head_dim, channels))
        if channels % self.heads:
            raise ValueError('Los canales deben dividirse entre las cabezas')
        self.norm = nn.GroupNorm(groups(channels), channels)
        self.qkv = nn.Conv2d(channels, 3 * channels, 1)
        self.output = nn.Conv2d(channels, channels, 1)

    def forward(self, x):
        batch, channels, height, width = x.shape
        q, k, v = self.qkv(self.norm(x)).chunk(3, dim=1)
        def arrange(z):
            return z.reshape(batch, self.heads, channels // self.heads, height * width).transpose(2, 3)
        h = F.scaled_dot_product_attention(arrange(q), arrange(k), arrange(v))
        h = h.transpose(2, 3).reshape(batch, channels, height, width)
        return x + self.output(h)


class DiffusionUNet(nn.Module):
    """CIFAR 32×32, niveles 32/16/8; ancho 128 en el modo completo."""
    def __init__(self, width=128):
        super().__init__()
        if width < 8 or width % 8:
            raise ValueError('El ancho debe ser un múltiplo de ocho')
        embedding = 4 * width
        self.width = width
        self.time = nn.Sequential(nn.Linear(width, embedding), nn.SiLU(), nn.Linear(embedding, embedding))
        self.input = nn.Conv2d(3, width, 3, padding=1)
        self.enc32a = AdaResidual(width, embedding)
        self.enc32b = AdaResidual(width, embedding)
        self.down16 = nn.Conv2d(width, 2 * width, 3, stride=2, padding=1)
        self.enc16a = AdaResidual(2 * width, embedding)
        self.enc16b = AdaResidual(2 * width, embedding)
        self.attn16_down = SpatialAttention(2 * width)
        self.down8 = nn.Conv2d(2 * width, 3 * width, 3, stride=2, padding=1)
        self.mid8a = AdaResidual(3 * width, embedding)
        self.attn8 = SpatialAttention(3 * width)
        self.mid8b = AdaResidual(3 * width, embedding)
        self.up16 = nn.ConvTranspose2d(3 * width, 2 * width, 4, stride=2, padding=1)
        self.merge16 = nn.Conv2d(4 * width, 2 * width, 1)
        self.dec16a = AdaResidual(2 * width, embedding)
        self.dec16b = AdaResidual(2 * width, embedding)
        self.attn16_up = SpatialAttention(2 * width)
        self.up32 = nn.ConvTranspose2d(2 * width, width, 4, stride=2, padding=1)
        self.merge32 = nn.Conv2d(2 * width, width, 1)
        self.dec32a = AdaResidual(width, embedding)
        self.dec32b = AdaResidual(width, embedding)
        self.out_norm = nn.GroupNorm(groups(width), width)
        self.output = nn.Conv2d(width, 3, 3, padding=1)

    def forward(self, x, t, T):
        half = self.width // 2
        freq = torch.exp(torch.linspace(0, -math.log(10000), half, device=x.device, dtype=x.dtype))
        phase = (t.to(x.dtype) * (1000. / T))[:, None] * freq[None]
        emb = self.time(torch.cat((phase.sin(), phase.cos()), dim=1))
        h = self.input(x)
        s32 = self.enc32b(self.enc32a(h, emb), emb)
        h = self.down16(s32)
        s16 = self.attn16_down(self.enc16b(self.enc16a(h, emb), emb))
        h = self.mid8a(self.down8(s16), emb)
        h = self.mid8b(self.attn8(h), emb)
        h = self.merge16(torch.cat((self.up16(h), s16), dim=1))
        h = self.attn16_up(self.dec16b(self.dec16a(h, emb), emb))
        h = self.merge32(torch.cat((self.up32(h), s32), dim=1))
        h = self.dec32b(self.dec32a(h, emb), emb)
        return self.output(F.silu(self.out_norm(h)))


def make_schedule(kind, T, device, zero_terminal=False):
    if T < 2 or kind not in ('linear', 'cosine'):
        raise ValueError('Calendario o número de pasos inválidos')
    if kind == 'linear':
        beta = torch.linspace(1e-4, .02, T, dtype=torch.float64, device=device)
    else:
        t = torch.arange(T + 1, dtype=torch.float64, device=device) / T
        f = torch.cos((t + .008) / 1.008 * math.pi / 2).square()
        beta = (1 - f[1:] / f[:-1]).clamp(max=.999)
    bar = torch.cumprod(1 - beta, dim=0)
    if zero_terminal:
        a = bar.sqrt()
        # Preserva el primer nivel ruidoso, no el índice t=0 que se añade después.
        a = (a - a[-1]) * a[0] / (a[0] - a[-1])
        bar = a.square()
        previous = torch.cat((torch.ones(1, dtype=bar.dtype, device=device), bar[:-1]))
        beta = 1 - bar / previous
    beta = torch.cat((torch.zeros(1, dtype=beta.dtype, device=device), beta))
    bar = torch.cat((torch.ones(1, dtype=bar.dtype, device=device), bar))
    previous = torch.cat((bar[:1], bar[:-1]))
    return {'T': T, 'kind': kind, 'beta': beta, 'bar': bar, 'previous': previous,
            'zero_terminal': zero_terminal}


def sha256(path):
    d=hashlib.sha256()
    with open(path,'rb') as f:
        for block in iter(lambda:f.read(1024*1024),b''):d.update(block)
    return d.hexdigest()


class ParquetCifar(Dataset):
    def __init__(self,folder,split,count):
        import pyarrow.parquet as pq
        self.rows=[];self.files=[]
        for path in sorted(Path(folder).glob(f'{split}-*.parquet')):
            self.files.append(str(path))
            for batch in pq.ParquetFile(path).iter_batches(batch_size=128,columns=['img']):
                self.rows.extend(row['img']['bytes'] for row in batch.to_pylist())
                if len(self.rows)>=count:break
            if len(self.rows)>=count:break
        if len(self.rows)<count:raise ValueError('Faltan imágenes en parquet')
        self.rows=self.rows[:count]
    def __len__(self):return len(self.rows)
    def __getitem__(self,index):
        with Image.open(io.BytesIO(self.rows[index])) as img:
            return transforms.ToTensor()(img.convert('RGB')),0


def get_data(root,quick,parquet,n_train,n_test):
    if parquet:
        if not quick:raise ValueError('Parquet solo se admite en quick')
        train=ParquetCifar(parquet,'train',n_train);test=ParquetCifar(parquet,'test',n_test)
        return train,test,{'source':'parquet CIFAR-10','train':'primeras filas','test':'primeras filas',
                          'files':[{'name':Path(p).name,'sha256':sha256(p)} for p in train.files+test.files]}
    train=datasets.CIFAR10(root,train=True,download=True,transform=transforms.ToTensor())
    test=datasets.CIFAR10(root,train=False,download=True,transform=transforms.ToTensor())
    ids=torch.randperm(len(train),generator=torch.Generator().manual_seed(2410))[:n_train].tolist()
    return Subset(train,ids),Subset(test,range(n_test)),{'source':'torchvision CIFAR-10',
        'train':'subconjunto permutado con semilla 2410','test':'primeras filas'}


def fid(real,fake):
    a,b=np.asarray(real,np.float64),np.asarray(fake,np.float64)
    x,y=a-a.mean(0),b-b.mean(0)
    cross=np.linalg.svd(x@y.T,compute_uv=False).sum()/math.sqrt((len(x)-1)*(len(y)-1))
    value=np.square(a.mean(0)-b.mean(0)).sum()+(x*x).sum()/(len(x)-1)+(y*y).sum()/(len(y)-1)-2*cross
    if value < -1e-7:raise ValueError('FID negativo fuera de tolerancia')
    return max(float(value),0.)


def image_features(images,inception,device):
    resize=build_resizer('clean');out=[]
    with torch.inference_mode():
        for i in range(0,len(images),4):
            pixels=(images[i:i+4].clamp(0,1)*255).round().to(torch.uint8)
            arrays=pixels.permute(0,2,3,1).cpu().numpy()
            resized=np.stack([resize(a).transpose(2,0,1) for a in arrays])
            out.append(inception(torch.from_numpy(resized).to(device)).cpu().numpy())
    return np.concatenate(out)


def make_grid(T,steps):
    if steps<1 or steps>T or steps&(steps-1):
        raise ValueError('El número de pasos debe ser potencia de dos y no superar T')
    ids=np.rint(np.linspace(T,0,steps+1)).astype(int).tolist()
    if len(set(ids))!=len(ids):raise ValueError('La malla tiene niveles repetidos')
    return ids


def ddim_step(x,eps,bt,bs):
    a,s=bt.sqrt(),(1-bt).sqrt()
    an,sn=bs.sqrt(),(1-bs).sqrt()
    while a.ndim<x.ndim:a=a.unsqueeze(-1);s=s.unsqueeze(-1);an=an.unsqueeze(-1);sn=sn.unsqueeze(-1)
    clean=(x-s*eps)/a
    return an*clean+sn*eps


@torch.no_grad()
def sample(model,bars,noise,ids):
    x=noise.clone();T=len(bars)-1
    for t,s in zip(ids[:-1],ids[1:]):
        times=torch.full((len(x),),t,device=x.device,dtype=torch.long)
        x=ddim_step(x,model(x,times,T),bars[t],bars[s])
    if not torch.isfinite(x).all():raise FloatingPointError('Muestreo no finito')
    return x


def precision_recall(real,fake,k=3):
    a,b=np.asarray(real,np.float64),np.asarray(fake,np.float64)
    if min(len(a),len(b))<=k:raise ValueError('Se necesitan más de k muestras')
    def distance(x,y):
        return np.maximum((x*x).sum(1)[:,None]+(y*y).sum(1)[None,:]-2*x@y.T,0.)
    aa=distance(a,a);bb=distance(b,b);ab=distance(a,b)
    np.fill_diagonal(aa,np.inf);np.fill_diagonal(bb,np.inf)
    ar=np.partition(aa,k-1,axis=1)[:,k-1];br=np.partition(bb,k-1,axis=1)[:,k-1]
    return float(np.mean((ab<=ar[:,None]).any(axis=0))),float(np.mean((ab<=br[None,:]).any(axis=1)))


def verify(device):
    bars=make_schedule('linear',20,device)['bar']
    gen=torch.Generator(device=device).manual_seed(2501)
    x=torch.randn((3,3,4,4),device=device,generator=gen)
    eps=torch.randn(x.shape,device=device,generator=gen)
    t,m,s=20,10,0
    y=ddim_step(ddim_step(x,eps,bars[t],bars[m]),eps,bars[m],bars[s])
    direct=ddim_step(x,eps,bars[t],bars[s])
    assert torch.allclose(y,direct,atol=1e-6,rtol=1e-6)
    a,b=np.array([[0.],[1.],[2.],[3.]]),np.array([[0.],[1.],[2.],[3.]])
    assert precision_recall(a,b,k=1)==(1.,1.)
    assert make_grid(20,8)[::2]==make_grid(20,4)
    with torch.device('meta'):full=DiffusionUNet(128)
    assert sum(p.numel() for p in full.parameters())==18_477_315
    print('Controles: dos pasos DDIM y un paso, mallas anidadas, precisión/cobertura y parámetros.',flush=True)


def distill_round(initial,bars,train,steps,device,quick,out,round_number):
    teacher=copy.deepcopy(initial).to(device).eval().requires_grad_(False)
    student=copy.deepcopy(initial).to(device).train().requires_grad_(True)
    ema=copy.deepcopy(student).eval().requires_grad_(False)
    optimizer=torch.optim.AdamW(student.parameters(),lr=2e-4)
    scaler=torch.amp.GradScaler('cuda',enabled=device.type=='cuda')
    data_gen=torch.Generator().manual_seed(2510+round_number)
    t_gen=torch.Generator(device=device).manual_seed(2520+round_number)
    noise_gen=torch.Generator(device=device).manual_seed(2530+round_number)
    loader=DataLoader(train,batch_size=4 if quick else 8,shuffle=True,generator=data_gen,num_workers=0,drop_last=True)
    batches=iter(loader);attempts=2 if quick else int(os.environ.get('ORYON_UPDATES','10000'))
    accumulation=1 if quick else 4;T=len(bars)-1;ids=torch.tensor(make_grid(T,steps),device=device)
    effective=skipped=teacher_evals=student_evals=0;history=[]
    for step in range(attempts):
        optimizer.zero_grad(set_to_none=True);loss_total=0.
        for _ in range(accumulation):
            try:clean,_=next(batches)
            except StopIteration:batches=iter(loader);clean,_=next(batches)
            clean=clean.to(device)*2-1;n=len(clean)
            index=2*torch.randint(steps//2,(n,),device=device,generator=t_gen)
            t,m,s=ids[index],ids[index+1],ids[index+2]
            noise=torch.randn(clean.shape,device=device,generator=noise_gen)
            a=bars[t].sqrt()[:,None,None,None];sigma=(1-bars[t]).sqrt()[:,None,None,None]
            xt=a*clean+sigma*noise
            with torch.no_grad():
                ymid=ddim_step(xt,teacher(xt,t,T),bars[t],bars[m])
                target=ddim_step(ymid,teacher(ymid,m,T),bars[m],bars[s])
            with torch.autocast(device_type=device.type,enabled=device.type=='cuda'):
                prediction=ddim_step(xt,student(xt,t,T),bars[t],bars[s])
                loss=F.mse_loss(prediction.float(),target.float())/accumulation
            if not torch.isfinite(loss):raise FloatingPointError('Pérdida no finita')
            scaler.scale(loss).backward();loss_total+=float(loss.detach())
            teacher_evals+=2*n;student_evals+=n
        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,param in zip(ema.parameters(),student.parameters(),strict=True):avg.lerp_(param,1-decay)
                for avg,param in zip(ema.buffers(),student.buffers(),strict=True):avg.copy_(param)
        if step==0 or (step+1)%max(1,attempts//10)==0:
            history.append({'attempt':step+1,'loss':loss_total,'effective_updates':effective,'skipped':skipped})
            print(f'Ronda {round_number}, {steps}→{steps//2}, paso {step+1}/{attempts}, pérdida {loss_total:.6f}',flush=True)
    checkpoint={'ema':{k:v.detach().cpu() for k,v in ema.state_dict().items()},
        'model':{k:v.detach().cpu() for k,v in student.state_dict().items()},'teacher_steps':steps,
        'student_steps':steps//2,'history':history,'attempts':attempts,'effective_updates':effective,'skipped':skipped,
        'teacher_forward_images':teacher_evals,'student_forward_images':student_evals,
        'student_backward_images':student_evals,'data_seed':2510+round_number,
        'time_seed':2520+round_number,'noise_seed':2530+round_number}
    torch.save(checkpoint,out/f'round-{round_number}.pt')
    del teacher,student,ema,optimizer,scaler,batches,loader
    if device.type=='cuda':torch.cuda.empty_cache()
    return checkpoint


def main():
    quick=os.environ.get('ORYON_QUICK','0')=='1'
    ckpt_path=Path(os.environ['ORYON_PREVIOUS_CKPT'])
    inception_path=Path(os.environ['ORYON_INCEPTION_PT'])
    if inception_path.name!='inception-2015-12-05.pt':raise ValueError('Nombre de extractor inesperado')
    out=Path(os.environ.get('ORYON_OUTPUT_DIR','oryon-l25'));out.mkdir(parents=True,exist_ok=True)
    device=torch.device('cuda' if torch.cuda.is_available() else 'cpu');verify(device)
    prior=torch.load(ckpt_path,map_location='cpu',weights_only=True)
    if prior['parameterization']!='epsilon' or prior.get('zero_terminal',False):
        raise ValueError('Hace falta EMA épsilon de m19-l18 con SNR terminal positiva')
    T=int(prior['T']);width=int(prior['width']);bars=make_schedule(prior['schedule'],T,device)['bar'].float()
    if bars[-1]<=0:raise ValueError('La conversión de ruido requiere alfa terminal positiva')
    start=8 if quick else int(os.environ.get('ORYON_INITIAL_STEPS','256'));make_grid(T,start)
    n_train=64 if quick else int(os.environ.get('ORYON_TRAIN_IMAGES','4096'))
    n_test=8 if quick else int(os.environ.get('ORYON_TEST_IMAGES','128'))
    if n_test<4:raise ValueError('Precisión/cobertura k=3 requieren al menos 4 ejemplos')
    train,test,data=get_data(os.environ.get('ORYON_DATA_ROOT','./data'),quick,
        os.environ.get('ORYON_CIFAR_PARQUET'),n_train,n_test)
    model=DiffusionUNet(width).cpu();model.load_state_dict(prior['ema']);model.eval()
    snapshots=[{'round':0,'steps':start,'state':prior['ema'],'training':None}]
    steps=start;number=0
    while steps>1:
        number+=1;result=distill_round(model,bars,train,steps,device,quick,out,number)
        snapshots.append({'round':number,'steps':steps//2,'state':result['ema'],
            'training':{key:value for key,value in result.items() if key not in ('ema','model')}})
        model.load_state_dict(result['ema']);steps//=2
        del result
    reference=torch.stack([test[i][0] for i in range(n_test)])
    inception=InceptionV3W(str(inception_path.parent),download=False,resize_inside=False).to(device).eval()
    real=image_features(reference,inception,device);features={'reference':real};rows=[]
    for snap in snapshots:
        model.load_state_dict(snap['state']);model.to(device).eval()
        generator=torch.Generator(device=device).manual_seed(2540);outputs=[]
        for start_i in range(0,n_test,4):
            n=min(4,n_test-start_i)
            noise=torch.randn((n,3,32,32),device=device,generator=generator)
            outputs.append(sample(model,bars,noise,make_grid(T,snap['steps'])).cpu())
        generated=torch.cat(outputs);clip=float(((generated<-1)|(generated>1)).float().mean())
        feature=image_features((generated+1)/2,inception,device);features[f'round_{snap["round"]}']=feature
        precision,recall=precision_recall(real,feature,3)
        image_name=f'round-{snap["round"]}.png'
        save_image(((generated[:8]+1)/2).clamp(0,1),out/image_name,nrow=4)
        row={'round':snap['round'],'nfe':snap['steps'],'fid':fid(real,feature),
             'precision_k3':precision,'recall_k3':recall,'fraction_clipped':clip,
             'image':image_name,'training':snap['training']}
        rows.append(row);print(json.dumps(row,ensure_ascii=False),flush=True)
        model.cpu()
        if device.type=='cuda':torch.cuda.empty_cache()
    np.savez_compressed(out/'features.npz',**features)
    report={'quick':quick,'teacher_sha256':sha256(ckpt_path),'inception_sha256':sha256(inception_path),
        'teacher':{'width':width,'T':T,'schedule':prior['schedule'],'parameterization':'epsilon',
            'effective_updates':prior.get('effective_updates'),'terminal_alpha_bar':float(bars[-1])},
        'data':data,'train_count':n_train,'test_count':n_test,'sample_seed':2540,
        'fid_protocol':'clean-fid InceptionV3W, RGB uint8, PIL float bicúbico 299',
        'diversity_protocol':'precisión y cobertura con bolas 3 vecinos en características Inception',
        'cost_note':'número de ejemplos en forward maestro, forward alumno y backward alumno; no son FLOPs ni tiempo',
        'rounds':rows}
    (out/'report.json').write_text(json.dumps(report,ensure_ascii=False,indent=2),encoding='utf-8')
    import matplotlib.pyplot as plt
    fig,ax=plt.subplots(figsize=(6,4));ax.plot([r['nfe'] for r in rows],[r['fid'] for r in rows],marker='o')
    ax.set(xscale='log',xlabel='Evaluaciones de red por imagen',ylabel='FID Inception',
           title=f'FID con {n_test} imágenes: sesgo elevado');fig.tight_layout()
    fig.savefig(out/'fid-nfe.png',dpi=140);plt.close(fig)
    del inception,model
    if device.type=='cuda':torch.cuda.empty_cache()
    print('Informe:',out/'report.json',flush=True)


if __name__=='__main__':main()


This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

ProofThe boundary condition
Prove: Prove the residual parameterization satisfies f(x,ε)=x.
0
c_skip(ε)=1, c_out(ε)=0 and F(x,ε) is finite.

Step 1 of 2. What happens when substituting t=ε?

ProofDerive average velocity
Prove: Derive the MeanFlow identity for a differentiable trajectory.
0
For r<t, (t−r)u(zₜ,r,t)=∫ᵣᵗv(zτ,τ)dτ and r stays fixed.

Step 1 of 2. What is the derivative of the left side with respect to t?

NumericCount rounds
If each round halves the steps, how many rounds go from 1024 to 4?
CodeA consistency target
Implement consistency_loss(student,ema,teacher,x,t,r). x is a NumPy array, t>r are scalars. teacher(x,s) returns ODE velocity; approximate the state at r from (x,t) with one Heun step: evaluate the initial slope, predict with Euler and evaluate the second slope at r. Return the mean of (student(x,t)−ema(x_r,r))². Do not modify x; ema represents the stop-gradient target.
import numpy as np

def consistency_loss(student, ema, teacher, x, t, r):
  pass
Shift+Enter to run
QuizDMD’s second score
Why does DMD fit an additional score model on current generator samples?
Key idea

A fast map shifts work from inference to training or changes the learned objective. A useful comparison includes integration error, diversity and the cost of producing that map.