Making training and inference fit the compute you actually have.
15 papers · 590 avg citations
Written by Junkun Yuan.
Click here to go back to main contents.
Table of contents ▼
AnyFlow: Any-Step Video Diffusion Model with On-Policy Flow Map Distillation
NVIDIA · National University of Singapore · MIT
European Conference on Computer Vision (ECCV), 2026
May 13, 2026 AnyFlow (34) code (450)
It distills a video diffusion model into a flow map between any two times and then refines it on-policy by flow map backward simulation.
Insight. A student on the teacher's ODE keeps test-time scaling. Judge few-step students at all budgets, and train them as they sample.
Flow map (§3.1, Eq. 2). A network learns the exact transport of the PF-ODE, for , and .
Central-difference MeanFlow target (§3.1, Eq. 3–4). With , the loss is and Eq. (3). FSDP lacks a JVP, so two forward passes give Eq. (4), with and .
Time sampler and weight (§4.2.1). come from with shift 5, half the batch at , a quarter at , and .
Fused guidance (Eq. 6). with the teacher's scale and the null-text prediction . Sampling has no CFG.
Adaptive reweighting (Eq. 7). for and 1 at , where is the error and is the mean boundary loss.
Flow map backward simulation (Eq. 8). Because , a rollout is three calls with gradient, .
DMD loss (Eq. 5). on the noised . The CFG-3 teacher gives , and a LoRA copy gives .
The training and sampling code. Follow Algorithm 1 and 2 of the paper.
def shift_t(t, shift=5.0):
return shift * t / (1 + (shift - 1) * t) # the teacher's timestep shift
def sample_time_steps(bs, diffusion_ratio=0.5, consistency_ratio=0.25):
u1, u2 = torch.rand(bs), torch.rand(bs)
t, r = torch.maximum(u1, u2), torch.minimum(u1, u2) # make r <= t
idx = torch.arange(bs)
is_diffusion = idx < round(diffusion_ratio * bs) # boundary rows, r = t
r = torch.where(is_diffusion, t, r)
r = torch.where(~is_diffusion & (idx < round((diffusion_ratio + consistency_ratio) * bs)), 0.0, r) # r = 0
return shift_t(t), shift_t(r), is_diffusion
def train_weight(t, n=1000):
grid = shift_t(torch.linspace(1, 0, n + 1)[:-1])
w = grid * (1 - grid) ** 0.5 # Beta(2, 1.5) shape
w = w * n / w.sum()
return w[(grid[:, None] - t.flatten()[None]).abs().argmin(0)] # nearest grid timestep
def central_difference(model, z_t, v, c, t, r, guidance=3.0, epsilon=5, num_train_timesteps=1000):
d = epsilon / num_train_timesteps
with no_grad():
return (model(z_t + d * v, c, t + d, r) - model(z_t - d * v, c, t - d, r)) / (2 * d * guidance) # Eq. 4
def train(model, x, c, null, guidance=3.0, drop_text_ratio=0.1, adaptive_eps=1e-5):
# 1. Sample the pair r <= t.
t, r, is_diffusion = sample_time_steps(x.shape[0])
# 2. Build the noisy latent z_t and its velocity v.
noise = torch.randn_like(x)
z_t = (1 - t) * x + t * noise # linear path
v = noise - x # conditional velocity
# 3. Predict the average velocity with a text dropout, and fuse the guidance into the prediction.
c = where(rand(x.shape[0]) < drop_text_ratio, null, c)
u_c = model(z_t, c, t, r)
with no_grad():
u_n = model(z_t, null, t, r)
u = (u_c - (1 - guidance) * u_n) / guidance # Eq. 6
# 4. Build the target from a central difference along v.
dudt = central_difference(model, z_t, v, c, t, r, guidance)
u_tgt = v - (t - r) * dudt # Eq. 3
# 5. Calculate the weighted loss, and rescale the transitions to the boundary loss.
loss = (u - u_tgt).square().flatten(1).mean(1) * train_weight(t)
mu = loss[is_diffusion].mean().detach()
loss = where(is_diffusion, loss, loss * mu / (loss.detach() + adaptive_eps)) # Eq. 7
return loss.mean()
def rollout(model, noise, c, num_steps_list=(2, 4, 8, 16, 50)):
n = choice(num_steps_list)
j = randint(0, n) # the step that carries the target transition
ts = cat([shift_t(linspace(1, 0, n + 1)[:-1]), [0.0]])
z = noise
for a, b in ((ts[0], ts[j]), (ts[j], ts[j + 1]), (ts[j + 1], ts[-1])): # Eq. 8
if a != b:
z = z - (a - b) * model(z, c, a, b)
return z
def dmd_grad(teacher, fake, z0, c, null, real_guidance_scale=3.0):
with no_grad():
t = shift_t(rand(z0.shape[0]))
z_t = (1 - t) * z0 + t * torch.randn_like(z0)
x_fake = z_t - t * fake(z_t, c, t, t)
x_c, x_n = z_t - t * teacher(z_t, c, t, t), z_t - t * teacher(z_t, null, t, t)
x_real = x_c + real_guidance_scale * (x_c - x_n)
grad = (x_fake - x_real) / (z0 - x_real).abs().mean(dim=(1, 2, 3, 4), keepdim=True) # Eq. 5
return torch.nan_to_num(grad)
def distill(model, teacher, fake, x, c, null, dmd_weight=1.0):
# 1. Roll out the student by flow map backward simulation, with the gradient through all three calls.
z0 = rollout(model, torch.randn_like(x), c)
# 2. Calculate the DMD loss on the re-noised rollout.
grad = dmd_grad(teacher, fake, z0, c, null)
loss = dmd_weight * (z0 - (z0 - grad).detach()).square().mean()
# 3. Add the forward loss.
loss = loss + train(model, x, c, null)
# 4. Refit the fake score to fresh rollouts by flow matching.
with no_grad():
z0 = rollout(model, torch.randn_like(x), c)
t = shift_t(torch.sigmoid(torch.randn(x.shape[0]))) # logit-normal(0, 1)
noise = torch.randn_like(z0)
loss_fake = (fake((1 - t) * z0 + t * noise, c, t, t) - (noise - z0)).square().mean()
def sample(model, c, shape, num_steps=4):
ts = cat([shift_t(linspace(1, 0, num_steps + 1)[:-1]), [0.0]])
z = torch.randn(shape)
for t, r in zip(ts[:-1], ts[1:]):
z = z - (t - r) * model(z, c, t, r) # Euler on the flow map, no CFG
return zTransition Matching Distillation for Fast Video Generation
NVIDIA · New York University
Conference on Computer Vision and Pattern Recognition (CVPR), 2026
Jan 14, 2026 TMD (30)
A main backbone runs once per transition and a recurrent flow head makes cheap inner steps, with MeanFlow pretraining and DMD2.
Insight. A step can be less than a full network call. Split semantics from refinement, and let distillation gradients reach the inner steps.
Transition matching (§2, Eq. 1–5). On Eq. (1), with data and noise , flow matching needs many small steps. TM jumps Eq. (4) with a latent Eq. (3), which an inner flow Eq. (5) in a light head samples.
MeanFlow objective (§2, Eq. 7–10). A flow map Eq. (7) uses an average velocity . Differentiation gives Eq. (8), so the loss is Eq. (9–10), where is the conditional inner velocity.
Decoupled student (Eq. 12). The first blocks are the backbone , and the last are the head .
Stage 1, TM-MF (§3.1, Eq. 13–14). Eq. (13) and Eq. (14). A central difference with and replaces the JVP, one-sided at the ends, as FSDP and flash attention lack forward-mode AD.
Inner times, guidance (App. A.2). is uniform with shift 3, is the grid point below, and 75% of batches have . uses CFG 3.
DMD2-v (Eq. 11). The loss is , where is the DMD weighting, is the stop-gradient, is the noised student sample , and is the fake score minus the teacher score (CFG 5). A Conv3D GAN head on teacher features adds a GAN loss with .
Timestep shifting (§3.2). on uniform , with for DMD noise and 10 for student grids, against mode collapse.
Flow head rollout (§3.2, Eq. 15). unrolls the head into a generator. The VSD gradient goes through all inner steps, which is backward simulation of the inner flow. This costs under 17% more compute at with 5 of 30 blocks.
Effective NFE (§4.1, Eq. 16). for transitions, each with one full pass and passes of the -block head.
Experiments (§4). VBench: Wan2.1 1.3B N2H5 gets 84.68 at 2.33 NFE (rCM 84.43 at 4), and 14B gets 84.24 at 1.38 (rCM 83.02).
The training and sampling code. Follow Algorithm 1 and 2 of the paper.
def shift(t, gamma):
return gamma * t / ((gamma - 1) * t + 1) # timestep shifting
def student_grid(n, gamma=10):
return shift(linspace(1, 0, n + 1), gamma).clamp(max=0.999) # t_M = s_N = 0.999 as in Wan
def sample_inner_times(bs, grid, shift_mf=3, ratio_r_equal_s=0.75):
s = shift(torch.rand(bs).clamp(0.001, 0.999), shift_mf)
r = grid[torch.searchsorted(-grid, -s)] # the grid point just below s
r = torch.where(torch.rand(bs) < ratio_r_equal_s, s, r)
return s, r
def inner_flow(head, m, grid):
y_1 = torch.randn(shape)
y = y_1
for s, r in zip(grid[:-1], grid[1:]):
y = y - (s - r) * (y_1 - head(y, s, r, m)) # Eq. 13 with Eq. 7's sign, Eq. 14
return y
def adaptive_loss(error, c_per_dim=1.0):
loss = error.square().flatten(1).sum(dim=1)
return loss / (loss.detach() + c_per_dim * error[0].numel()) # c = d (1.3B) or 1e-5 d (14B)
def pretrain(backbone, head, x, c, num_outer=2, num_inner=4, cfg_scale=3.0, cond_dropout=0.1, delta=0.005):
# 1. Add noise to the video at an outer grid time and run the backbone once.
t_i = student_grid(num_outer)[torch.randint(num_outer, (bs,))]
x_1 = torch.randn_like(x)
x_t = (1 - t_i) * x + t_i * x_1 # Eq. 1
dropped = rand(bs) < cond_dropout
m = backbone(x_t, t_i, where(dropped, null, c)) # never detached
# 2. Build the inner target y and its noisy state at inner times s and r.
y = x_1 - x # Eq. 3
y_1 = torch.randn_like(y)
s, r = sample_inner_times(bs, student_grid(num_inner))
y_s = (1 - s) * y + s * y_1 # Eq. 5
# 3. Guide the conditional inner velocity with the head's unconditional prediction.
with no_grad():
u_null = y_1 - head(y_s, s, s, backbone(x_t, t_i, null))
v = where(dropped, y_1 - y, cfg_scale * (y_1 - y) + (1 - cfg_scale) * u_null)
# 4. Predict the average velocity and its target, with a central difference for the JVP.
u = y_1 - head(y_s, s, r, m) # Eq. 14
with no_grad():
u_fn = lambda y_, s_: y_1 - head(y_, s_, r, m)
dudt = (u_fn(y_s + delta * v, s + delta) - u_fn(y_s - delta * v, s - delta)) / (2 * delta)
u_tgt = v - (s - r) * dudt # Eq. 10
# 5. Calculate the normalized loss.
loss = adaptive_loss(u - u_tgt).mean() # Eq. 9
def distill(
backbone, head, teacher, fake_score, disc, x, c,
num_outer=2, num_inner=4, cfg_scale=5.0, gan_weight=0.03
):
# 1. Add noise to the video at an outer grid time and run the backbone once.
t_i = student_grid(num_outer)[torch.randint(num_outer, (bs,))]
x_1 = torch.randn_like(x)
m = backbone((1 - t_i) * x + t_i * x_1, t_i, c)
# 2. Unroll the flow head into a generator, with the gradient through every inner step.
x_hat = x_1 - inner_flow(head, m, student_grid(num_inner)) # Eq. 15
# 3. Add noise to the sample and take the direction from the teacher's score to the fake one.
t = shift(rand(bs).clamp(0.001, 0.999), 5)
x_hat_t = (1 - t) * x_hat + t * torch.randn_like(x_hat)
with no_grad():
x_fake = x_hat_t - t * fake_score(x_hat_t, t, c) # Eq. 17
v_c, v_u = teacher(x_hat_t, t, c), teacher(x_hat_t, t, null)
x_real = x_hat_t - t * (v_u + cfg_scale * (v_c - v_u)) # Eq. 17
grad = (x_fake - x_real) / abs(x_hat - x_real).mean() # DMD weighting w(t)
# 4. Calculate the VSD loss plus the GAN loss on teacher features.
loss = (x_hat * grad).mean() + gan_weight * softplus(-disc(teacher.features(x_hat_t, t, c))).mean() # Eq. 11
def critic_step(fake_score, disc, teacher, x_hat, x, c):
# 1. Refit the fake score on the student's samples by flow matching.
t = shift(rand(bs).clamp(0.001, 0.999), 5)
noise = torch.randn_like(x)
x_hat_t = (1 - t) * x_hat.detach() + t * noise
loss_fake = (fake_score(x_hat_t, t, c) - (noise - x_hat.detach())).square().mean()
# 2. Train the Conv3D discriminator on teacher features of real videos and samples.
x_t = (1 - t) * x + t * noise
loss_disc = softplus(disc(teacher.features(x_hat_t, t, c))).mean()
loss_disc = loss_disc + softplus(-disc(teacher.features(x_t, t, c))).mean()
def sample(backbone, head, c, num_outer=2, num_inner=4):
x = torch.randn(shape)
ts = student_grid(num_outer)
for t_i, t_prev in zip(ts[:-1], ts[1:]):
m = backbone(x, t_i, c) # one full pass, then N head passes: Eq. 16
x = x - (t_i - t_prev) * inner_flow(head, m, student_grid(num_inner)) # Eq. 4pi-Flow: Policy-Based Few-Step Generation via Imitation Distillation
Stanford University · Adobe Research
International Conference on Learning Representations (ICLR), 2026
Oct 16, 2025 pi-Flow (33) code (477)
Between its few network calls, the student integrates the ODE with a network-free policy and learns by on-policy imitation of the teacher.
Insight. Network calls and integration steps can differ. A closed-form policy between the calls turns distillation into plain velocity imitation.
Policy-based flow (§2–3, Eq. 2). A teacher predicts on with one call for each velocity. The student gives a network-free policy once per step, and uses Euler substeps of 1/128 at negligible cost.
GMFlow policy (§3.2). The velocity is a Gaussian mixture that adapts to the current .
Closed-form velocity (App. F, Eq. 21–28). Let , Eq. (21), and , be the SNR-weighted gaps between and : Eq. (25), Eq. (27) gives logits , and with their softmax , Eq. (28).
π-ID, on-policy imitation (§4, Alg. 1). The detached policy rolls out to , , and the loss is . The teacher corrects states that the student itself visits, so the error grows linearly, not quadratically.
Starting states (Alg. 2, App. B). Data gets noise at a grid time shifted by , , with the last step halved.
GM dropout and temperature (§5.1, App. B.1). Training drops components of at (0.1 at 1 MP) to explore new modes. Inference sharpens the mixture to weights and variance Eq. (4) with at 4 NFE, but not on the last step, to keep fine textures.
Micro-window matching (Eq. 6). The target is the window-mean policy velocity, , with .
Scheduled trajectory mixing (App. B.2). On FLUX.1, rollouts start as teacher paths, whose share falls linearly to zero in 2K steps.
Experiments (§5). 1-NFE FID is 2.85 on ImageNet-256 (MeanFlow 3.43), and 4-NFE FID is 14.3 on FLUX.1 (SenseFlow 23.3).
Fewer teacher steps, sharper images (Fig. 9). FLUX.1 dev is blurrier at 128 NFE than at 43, so the window also sets sharpness.
The training and sampling code. Follow Algorithm 2 of the paper, with the GMFlow policy of Appendix F.
def warp(tau, shift=3.2):
return shift * tau / (1 + (shift - 1) * tau) # time shifting
def sample_segment(bs, nfe=4, final_step_scale=0.5):
base = 1 / (nfe - 1 + final_step_scale)
idx = torch.ceil(torch.rand(bs).clamp(min=1e-4) / base + 1 - final_step_scale).clamp(1, nfe)
tau_src = ((idx - 1 + final_step_scale) * base).clamp(max=1)
return tau_src, tau_src - torch.where(idx == 1, final_step_scale * base, base) # last step halved
def gm_policy(means, logstds, logweights, x_src, t_src):
return x_src - t_src * means, (2 * logstds).exp() * t_src ** 2, logweights, x_src, t_src # Eq. 21
def gm_dropout(gm, p=0.1):
mu_x, var_x, logweights, x_src, t_src = gm
drop = torch.rand(logweights.shape[:2] + (1, 1, 1)) < p # whole components
drop &= ~drop.all(dim=1, keepdim=True) # never all of them
return mu_x, var_x, logweights.masked_fill(drop, float('-inf')), x_src, t_src
def gm_temperature(gm, temperature=0.3):
mu_x, var_x, logweights, x_src, t_src = gm
return mu_x, var_x * temperature, torch.log_softmax(logweights / temperature, dim=1), x_src, t_src # Eq. 4
def gm_velocity(gm, x_t, t):
mu_x, var_x, logweights, x_src, t_src = gm
nu = (1 - t) * x_t / t ** 2 - (1 - t_src) * x_src / t_src ** 2 # below Eq. 22
zeta = ((1 - t) / t) ** 2 - ((1 - t_src) / t_src) ** 2
mu = (var_x * nu + mu_x) / (var_x * zeta + 1) # Eq. 25
logits = logweights + (mu_x * (nu - 0.5 * zeta * mu_x)).sum(dim=2, keepdim=True) / (var_x * zeta + 1) # Eq. 27
x_0 = (torch.softmax(logits, dim=1) * mu).sum(dim=1) # Eq. 26
return (x_t - x_0) / t # Eq. 28
def integrate(gm, x, tau_start, tau_end, total_substeps=128):
n = ((tau_start - tau_end) * total_substeps).ceil().clamp(min=1)
dtau, tau, t = (tau_start - tau_end) / n, tau_start, warp(tau_start)
for i in range(int(n.max())): # Euler substeps, no network
t_next = warp((tau - dtau).clamp(min=0))
x_next = x + gm_velocity(gm, x, t) * (t_next - t)
active = n > i
x, t, tau = where(active, x_next, x), where(active, t_next, t), where(active, tau - dtau, tau)
return x, t
def train(
model, teacher, x_0, c, iteration,
policy_dropout=0.1, num_states=4, window=3 / 128, teacher_cfg=3.5, num_decay_iters=2000
):
# 1. Pick a segment of the student grid and add noise to the data at its shifted start.
tau_src, tau_dst = sample_segment(bs)
t_src = warp(tau_src)
x_src = (1 - t_src) * x_0 + t_src * torch.randn_like(x_0)
# 2. Get the policy with one student call, and a detached copy with dropout for the rollout.
gm = gm_policy(*model(x_src, t_src, c), x_src, t_src)
gm_d = gm_dropout(tuple(g.detach() for g in gm), policy_dropout)
# 3. Split the segment into policy and teacher stretches, and decay the teacher share to zero.
teacher_ratio = 1 - min(iteration, num_decay_iters) / num_decay_iters
span = tau_src - tau_dst - window
cuts = torch.sort(torch.rand(bs, num_states)).values * ((1 - teacher_ratio) * span)[:, None]
gaps_pi = torch.diff(cuts, prepend=torch.zeros(bs, 1))
cuts = torch.sort(torch.rand(bs, num_states - 1)).values
gaps_teacher = torch.diff(cuts, prepend=torch.zeros(bs, 1), append=torch.ones(bs, 1))
gaps_teacher = gaps_teacher * (teacher_ratio * span)[:, None]
# 4. At each visited state, match the policy's window velocity to the teacher's.
loss, x, tau = 0, x_src, tau_src
for k in range(num_states):
tau_a = (tau - gaps_pi[:, k]).clamp(min=0)
tau_b = (tau_a - gaps_teacher[:, k]).clamp(min=0)
with no_grad():
x_a, t_a = integrate(gm_d, x, tau, tau_a) # rollout of the detached policy
u_teacher = teacher(x_a, t_a, c, guidance=teacher_cfg)
x_w, t_w = integrate(gm, x_a, tau_a, tau_b - window)
u_policy = (x_a - x_w) / (t_a - t_w) # Eq. 6
loss = loss + 0.5 * (u_teacher - u_policy).square().mean() / num_states
x, tau = x_a + u_teacher * (warp(tau_b) - t_a), tau_b # teacher stretch
def sample(model, c, nfe=4, final_step_scale=0.5, temperature=0.3):
base = 1 / (nfe - 1 + final_step_scale)
taus = torch.tensor([1 - i * base for i in range(nfe)] + [0.0])
x = torch.randn(shape)
for i in range(nfe):
t_src = warp(taus[i])
gm = gm_policy(*model(x, t_src, c), x, t_src) # one network call per segment
if i < nfe - 1:
gm = gm_temperature(gm, temperature) # off on the last step
x, _ = integrate(gm, x, taus[i], taus[i + 1])Large Scale Diffusion Distillation via Score-Regularized Continuous-Time Consistency
Tsinghua University · NVIDIA
International Conference on Learning Representations (ICLR), 2026
Oct 09, 2025 rCM (94) code (827)
It scales continuous-time consistency distillation to 14B video models and fixes its fine-detail failures with a score distillation regularizer.
Insight. At scale, consistency alone blurs and distribution matching alone collapses. Pair the two divergences, and also measure diversity.
TrigFlow wrapping (§3.1, Eq. 3). On , the consistency map to a trajectory's start is , where and are the two velocities. A rectified-flow teacher needs no retraining: a time map solves .
sCM loss (§3.1, Eq. 4). , with and the stop-gradient tangent .
The tangent (§3.3, Eq. 5). . At large , the fragile BF16 JVP term is the largest.
JVP (§4.2). , with in the tangent . The time embeddings use FP32.
Score regularization (§4.1, Eq. 6). A regression loss on student samples , re-noised to , gives the reverse-KL gradient of DMD: . is a teacher copy that flow matching refits on them, and .
rCM objective (§4.1). with . DMD starts at step , and the student trains in one of steps.
Time distributions (App. D, Tab. 4). : , and : , , .
Rollout (§4.1, Alg. 1). Rollouts denoise and re-noise times on , with and .
Experiments (§5). At 4 steps, Cosmos-Predict2 gets GenEval 0.83 (teacher 0.84), and Wan2.1 gets VBench 84.92 (teacher 83.58).
The quality metric does not show the collapse (Fig. 7). For from 0.001 to 1, VBench stays in 82.68–84.57, but diversity falls.
The training and sampling code. Follow Algorithm 1 of the paper.
def time_G(bs, p_mean=0.7, p_std=1.6):
return atan(torch.exp(torch.randn(bs, 1, 1, 1, 1) * p_std + p_mean)) # lognormal sigma, in TrigFlow time
def time_D(bs, shift=5.0):
u = torch.rand(bs, 1, 1, 1, 1)
rf_t = shift * u / (1 + (shift - 1) * u) # the teacher's timestep shift
return atan(rf_t / (1 - rf_t))
def guided(teacher, x_t, t, c, null, teacher_guidance=5.0):
(x0_c, F_c), (x0_u, F_u) = teacher(x_t, t, c), teacher(x_t, t, null) # each net returns (x0, F)
return x0_u + teacher_guidance * (x0_c - x0_u), F_u + teacher_guidance * (F_c - F_u)
def rollout(student, shape, c, n_steps, with_grad):
ts = [full((shape[0], 1, 1, 1, 1), pi / 2)]
for _ in range(n_steps - 1):
ts.append(torch.minimum(time_D(shape[0]), ts[-1]))
ts.append(0 * ts[-1])
x = torch.randn(shape)
for i, (t_cur, t_next) in enumerate(zip(ts[:-1], ts[1:])):
with (enable_grad if with_grad and i == n_steps - 1 else no_grad)():
x, _ = student(x, t_cur, c) # gradient through the last denoise only
x = cos(t_next) * x + sin(t_next) * torch.randn_like(x) # re-noise, and t_next = 0 keeps x
return x
def scm_loss(student, teacher, x0, c, null, it, tangent_warmup=1000, loss_scale=100.0):
t = time_G(x0.shape[0])
x_t = cos(t) * x0 + sin(t) * torch.randn_like(x0)
with no_grad():
_, F_teacher = guided(teacher, x_t, t, c, null)
tangents = (cos(t) * sin(t) * F_teacher, cos(t) * sin(t)) # JVP rearrangement
_, dF = jvp(lambda x, t_: student(x, t_, c)[1], (x_t, t), tangents)
_, F_s = student(x_t, t, c)
F_sg = F_s.detach()
r = min(1.0, it / tangent_warmup) # tangent warmup
g = -cos(t) * sqrt(1 - r ** 2 * sin(t) ** 2) * (F_sg - F_teacher) - (r * cos(t) * sin(t) * x_t + dF) # Eq. 5
g = torch.nan_to_num(g) # a BF16 overflow zeroes its entries
g = g / (g.norm(dim=(1, 2, 3, 4), keepdim=True) + 0.1)
return loss_scale * (F_s - F_sg - g).square().sum(dim=(1, 2, 3, 4)) # Eq. 4
def dmd_loss(student, teacher, fake, x0, c, null, n_steps, loss_scale_dmd=1.0):
x0_s = rollout(student, x0.shape, c, n_steps, with_grad=True)
t = time_D(x0.shape[0])
x_t = cos(t) * x0_s + sin(t) * torch.randn_like(x0_s)
with no_grad():
x0_fake, _ = fake(x_t, t, c)
x0_teacher, _ = guided(teacher, x_t, t, c, null)
weight = (x0_s - x0_teacher).abs().mean(dim=(1, 2, 3, 4), keepdim=True).clip(min=1e-5)
grad = (x0_fake - x0_teacher) / weight
return loss_scale_dmd * (x0_s - (x0_s - grad).detach()).square().sum(dim=(1, 2, 3, 4)) # Eq. 6
def critic_loss(student, fake, x0, c, n_steps):
x0_s = rollout(student, x0.shape, c, n_steps, with_grad=False)
t = time_D(x0.shape[0])
x_t = cos(t) * x0_s + sin(t) * torch.randn_like(x0_s)
x0_fake, _ = fake(x_t, t, c)
return ((x0_s - x0_fake).square() / sin(t) ** 2).sum(dim=(1, 2, 3, 4)) # flow matching on student samples
def train(student, teacher, fake, x0, c, null, it, tangent_warmup=1000, student_update_freq=5, max_steps=4):
# 1. Pick the phase. All warmup iterations are student steps, and after the warmup, one in student_update_freq.
student_phase = it < tangent_warmup or (it - tangent_warmup) % student_update_freq == 0
it_s = it if it < tangent_warmup else tangent_warmup + (it - tangent_warmup) // student_update_freq
# 2. Update the student with the sCM loss, and add the DMD loss after the warmup.
if student_phase:
loss = scm_loss(student, teacher, x0, c, null, it, tangent_warmup)
if it >= tangent_warmup:
loss = loss + dmd_loss(student, teacher, fake, x0, c, null, it_s % max_steps + 1) # lambda = 1 / 100
# 3. Otherwise, update the fake score on fresh student samples.
else:
loss = critic_loss(student, fake, x0, c, (it - it_s - 1) % max_steps + 1)
def sample(student, c, shape, num_steps=4, mid_t=(1.5, 1.4, 1.0), sigma_max=80.0):
ts = [atan(sigma_max), *mid_t[:num_steps - 1], 0.0]
x = torch.randn(shape)
for t_cur, t_next in zip(ts[:-1], ts[1:]):
x0, _ = student(x, full((shape[0], 1, 1, 1, 1), t_cur), c)
x = cos(t_next) * x0 + sin(t_next) * torch.randn_like(x0)
return xAdversarial Distribution Matching for Diffusion Distillation Towards Efficient Image and Video Synthesis
Sun Yat-sen University · ByteDance Seed
International Conference on Computer Vision (ICCV), 2025
Jul 24, 2025 ADM (46)
A discriminator on a PF-ODE step of both scores replaces DMD's reverse KL, and adversarial pre-training initializes one-step students.
Insight. In one-step distillation, the start decides stability. A learned divergence from an overlapping start needs no TTUR or regularizer.
DMD loss (§3.2, Eq. 4). DMD trains a few-step generator by . Here is a noised sample of , and and are the scores of the teacher and of the generator. DMD's reverse KL is zero-forcing, so it can drop some modes.
Fake score (Alg. 1, Eq. 3). A fake score estimator , a copy of the teacher , fits the generator's samples by , where is the target velocity. SDXL uses the noise loss Eq. (2) instead. It has no CFG, and its two time-scale update rule (TTUR) is 1.
Rollout (Alg. 1). The generator runs without gradient from to a random step , then jumps with gradient to .
One PF-ODE step (§4.1). ADM noises to Eq. (1) at . Each score, or , solves the PF-ODE from to , with , and gives or . DMD's Eq. (5) uses the predicted end points at , which lose the noise level of the input .
Real score guidance (App. B.5). The teacher uses CFG, with a scale drawn uniformly from [6, 8] on SDXL and on SD3-Medium.
ADM loss (§4.1, Eq. 7–8). is a frozen teacher copy with trainable heads on several blocks. The hinge loss trains the generator with , and with . This loss replaces the DMD loss.
ODE pairs (§4.2). For one step, ADM needs a start that overlaps the teacher, so DMDX runs adversarial distillation pre-training (ADP) first. ADP collects teacher ODE pairs offline. The generator reads and predicts the end point by a velocity.
Cubic timesteps (§4.2.1). The generator's is with , so most are near , which helps it find new modes.
Hybrid discriminators (§4.2, Eq. 9). is a teacher copy on noised at a uniform , and is SAM's vision encoder on the decoded image. The generator loss is with , . Eq. (10) is the hinge loss of both discriminators.
Experiments (§5). On COCO, one SDXL step of DMDX gets HPSv2 27.70 (DMD2: 27.45, teacher: 27.37) in 58% of DMD2's GPU time.
TTUR adds little (Tab. 5). Eight fake updates per generator step lift HPSv2 from 27.70 to 27.76, but training is 2.53 times longer.
DMDX varies more than its teacher (Tab. 6). Pairwise LPIPS is 0.7156 for DMDX, 0.6936 for the teacher and 0.6715 for DMD2.
The training and sampling code. Follow Algorithm 1 and Section 4.2 of the paper.
def sample_cfg_scale(bs, cfg_min=6.0, cfg_max=8.0):
return cfg_min + (cfg_max - cfg_min) * torch.rand(bs)
def sample_cubic_time_steps(bs):
return 1 - torch.rand(bs) ** 3 # t = (1 - (u / T)^3) T with T = 1
def ode_step(model, x_t, t, dt, c, cfg_scale=None):
v = model(x_t, t, c)
if cfg_scale is not None:
v_u = model(x_t, t, null)
v = v_u + cfg_scale * (v - v_u)
return x_t - dt * v # one Euler step of the PF-ODE
def rollout(generator, z, c, num_steps=4):
time_steps = linspace(1, 0, num_steps + 1)
n = torch.randint(num_steps, ()).item() # the steps without gradient before t_n
x = z
with no_grad():
for i in range(n):
x = x - (time_steps[i] - time_steps[i + 1]) * generator(x, time_steps[i], c)
return x - time_steps[n] * generator(x, time_steps[n], c) # jump to t_0 with gradient
def train(generator, teacher, fake_score, disc, c, num_steps=4, dt=1 / 64, cfg_min=6.0, cfg_max=8.0):
# 1. Refit the fake score on the generator's samples.
with no_grad():
x_0 = sample(generator, c, num_steps)
t_f = torch.rand(bs)
noise = torch.randn_like(x_0)
x_t = (1 - t_f) * x_0 + t_f * noise # Eq. 1
loss_fake = (fake_score(x_t, t_f, c) - (noise - x_0)).square().mean() # Eq. 3
# 2. Generate a sample with the gradient through the last step.
x_hat_0 = rollout(generator, torch.randn_like(x_0), c, num_steps)
# 3. Add noise to the sample and take one PF-ODE step with each score.
t = torch.rand(bs)
x_t = (1 - t) * x_hat_0 + t * torch.randn_like(x_hat_0) # Eq. 1
x_fake = ode_step(fake_score, x_t, t, dt, c)
with no_grad():
x_real = ode_step(teacher, x_t, t, dt, c, cfg_scale=sample_cfg_scale(bs, cfg_min, cfg_max))
# 4. Calculate the generator loss on the step of the fake score.
loss_gen = -disc(x_fake, t - dt, c).mean() # Eq. 7
# 5. Calculate the discriminator loss on both steps.
logits_fake, logits_real = disc(x_fake.detach(), t - dt, c), disc(x_real, t - dt, c)
loss_disc = relu(1 + logits_fake).mean() + relu(1 - logits_real).mean() # Eq. 8
def pretrain(generator, disc_latent, disc_pixel, vae, x_T, x_0, c, lambda_latent=0.85, lambda_pixel=0.15):
# 1. Interpolate a teacher ODE pair at a cubic timestep and predict its end point.
t = sample_cubic_time_steps(bs)
x_t = (1 - t) * x_0 + t * x_T # linear path between the pair
x_tilde_0 = x_t - t * generator(x_t, t, c) # end point from the predicted velocity
# 2. Add the same noise to the prediction and the teacher sample at a uniform timestep.
t_d = torch.rand(bs)
noise = torch.randn_like(x_0)
x_tilde_t = (1 - t_d) * x_tilde_0 + t_d * noise # Eq. 1
x_real_t = (1 - t_d) * x_0 + t_d * noise
image = vae.decode(x_tilde_0)
# 3. Calculate the generator loss with the latent and the pixel discriminator.
loss_gen = -(lambda_latent * disc_latent(x_tilde_t, t_d, c).mean()
+ lambda_pixel * disc_pixel(image).mean()) # Eq. 9
# 4. Calculate the hinge loss of both discriminators.
logits_fake, logits_real = disc_latent(x_tilde_t.detach(), t_d, c), disc_latent(x_real_t, t_d, c)
loss_latent = relu(1 + logits_fake).mean() + relu(1 - logits_real).mean()
logits_fake, logits_real = disc_pixel(image.detach()), disc_pixel(vae.decode(x_0))
loss_pixel = relu(1 + logits_fake).mean() + relu(1 - logits_real).mean()
loss_disc = lambda_latent * loss_latent + lambda_pixel * loss_pixel # Eq. 10
def sample(generator, c, num_steps=4):
time_steps = linspace(1, 0, num_steps + 1)
x = torch.randn(shape)
for i in range(num_steps):
x = x - (time_steps[i] - time_steps[i + 1]) * generator(x, time_steps[i], c)
return xAlign Your Flow: Scaling Continuous-Time Flow Map Distillation
NVIDIA · University of Toronto · Vector Institute
Advances in Neural Information Processing Systems (NeurIPS), 2025
It distills a pretrained flow model into a flow map between any two noise levels with a continuous-time loss and an autoguided teacher.
Insight. A model that jumps to clean data and adds noise back gets worse with more steps. A two-time map stays good at every step count.
Multistep consistency sampling (§3.1, Thm. 3.1). In multistep sampling, a consistency model (CM) maps to clean data and then adds noise for the next step. On data , some CM within of the optimal CM gets a larger distance when it uses more than steps.
Flow map (§3.2, Eq. 25). On , with data and noise , a pretrained velocity gives the PF-ODE . The flow map moves to in one step. The network predicts the average velocity over .
AYF-EMD (§3.2, Thm. 3.2). The Eulerian map distillation (EMD) loss matches to its stop-gradient copy , where one Euler step of the PF-ODE gives at . As , the gradient is Eq. (19), where is a weight.
Autoguided teacher (§3.3, Eq. 3). The teacher velocity is , where is a smaller and less trained model (EDM2-XS for the EDM2-S teacher). The student also takes as an input, so one student learns every guidance scale in this range.
Tangent (§3.4, Eq. 4). Then . A JVP with tangent on gives .
Tangent warmup (§3.4, Eq. 5). Alg. 1 uses , the negative tangent with a weight . At , the loss is a straightness term Eq. (5). So at iteration , with , keeps a part of the straightness term.
Loss (Alg. 1). with . Its gradient is the EMD gradient with and a normalized .
Interval schedule (App. F.1). The interval length is , on ImageNet-512, and then , .
Sampling (§5, App. F.1). The steps use a uniform grid from 1 to 0 and . The -sampling of CTM sets the noise: is one flow map jump, and jumps to 0 and adds noise back. The best values on ImageNet are –, so a little new noise at each step helps.
Experiments (§5). On ImageNet-512 with an EDM2-S teacher, 2-step FID is 1.87 (1.5B sCD: 1.88). FLUX.1 [dev] gets a 4-step LoRA.
The 2D winner fails on images (Tab. 5). AYF-LMD holds consistency at the end . Its 1-step FID is 12.45 against 3.32 for EMD.
The training and sampling code. Follow Algorithm 1 of the paper.
def sample_time_steps(bs, p_mean=-0.8, p_std=1.0):
d = torch.sigmoid(torch.randn(bs, 1, 1, 1) * p_std + p_mean) # interval length t - s
s = torch.rand(bs, 1, 1, 1) * (1 - d)
return s + d, s
def guided_velocity(teacher, weak_teacher, x_t, t, y, lam):
return lam * teacher(x_t, t, y) + (1 - lam) * weak_teacher(x_t, t, y) # Eq. 3
def train(
model, teacher, weak_teacher, x_0, y, it,
sigma_data=0.5, lam_min=1.0, lam_max=3.0, tangent_warmup=10000, r_max=0.99, tangent_c=0.1
):
# 1. Sample the interval (t, s) and the guidance scale.
bs = x_0.shape[0]
t, s = sample_time_steps(bs)
lam = lam_min + (lam_max - lam_min) * torch.rand(bs, 1, 1, 1)
# 2. Build the noisy sample x_t and get the guided teacher velocity.
noise = torch.randn_like(x_0) * sigma_data
x_t = (1 - t) * x_0 + t * noise # linear path
with no_grad():
v = guided_velocity(teacher, weak_teacher, x_t, t, y, lam) # dx_t/dt
# 3. Calculate the JVP of the student along the teacher's PF-ODE.
with no_grad():
F_sg, dFdt = jvp(lambda x, t_, s_: model(x, t_, s_, y, lam), (x_t, t, s), (v, ones_like(t), zeros_like(s)))
# 4. Build the tangent with the warmup weight and normalize it.
r = min(r_max, it / tangent_warmup)
g = (F_sg - v) + r * (t - s) * dFdt # Eq. 4
g = g / (g.norm(dim=(1, 2, 3), keepdim=True) + tangent_c)
# 5. Calculate the loss.
F = model(x_t, t, s, y, lam)
loss = (F - F.detach() + g).square().sum(dim=(1, 2, 3)).mean() # Eq. 19
def sample(model, y, shape, num_steps=4, lam=2.0, sigma_data=0.5, renoise=False):
time_steps = linspace(1, 0, num_steps + 1)
x = torch.randn(shape) * sigma_data
for i in range(num_steps):
t, s = full((shape[0], 1, 1, 1), time_steps[i]), full((shape[0], 1, 1, 1), time_steps[i + 1])
if renoise: # gamma = 1: jump to 0, then add new noise up to s
x_0 = x - t * model(x, t, zeros_like(s), y, lam)
x = (1 - s) * x_0 + s * torch.randn_like(x_0) * sigma_data
else: # gamma = 0: one flow map jump
x = x + (s - t) * model(x, t, s, y, lam) # Eq. 25
return xFrom Slow Bidirectional to Fast Autoregressive Video Diffusion Models
MIT · Adobe
Conference on Computer Vision and Pattern Recognition (CVPR), 2025
Dec 10, 2024 CausVid (519) code (1.5K)
DMD distills a bidirectional teacher into a block-causal four-step video student that starts from ODE pairs and streams with a KV cache.
Insight. Only the student needs to be causal. A bidirectional teacher can train it, and this opened the way to real-time streaming video.
DMD (§3, Eq. 1–4). On Eq. (1), DMD minimizes the reverse KL of the noised generator and data distributions, Eq. (4), where is the forward diffusion and trains online on generator outputs.
Block-causal DiT (§4.1, Eq. 5). A 3D VAE turns 16 frames into a chunk of 5 latents. Attention is bidirectional in a chunk and causal across chunks, iff with latents per chunk, because the VAE decodes whole chunks. The mask fits the pretrained DiT.
Asymmetric distillation (§4.2). Only the student is causal. stays the bidirectional teacher, because DMD matches distributions.
The loop (Alg. 1). Each chunk gets its own from the four-step set , and the causal student predicts from the noisy chunks . DMD re-noises at one for Eq. (4), with teacher guidance 3.5, and the fake score refits on the re-noised .
ODE initialization (Eq. 6). DMD alone is unstable, so the student first fits teacher ODE solutions, .
KV-cached streaming (§4.4, Alg. 2). For each chunk, reads the cache, and re-noises with fresh over the steps . A pass at writes the keys and values of the chunk, so all later chunks attend to it without a mask.
Experiments (§5). On MovieGen prompts, frame quality is 64.4 (MovieGen 61.1), and the video stream starts after 1.3 s at 9.4 fps.
The training and sampling code. Follow Algorithm 1 and 2 of the paper.
def add_noise(x_0, noise, t):
return (1 - t / 1000) * x_0 + (t / 1000) * noise # Eq. 1 with alpha = 1 - sigma
def shift(t, timestep_shift=8.0, min_step=20, max_step=980):
t = timestep_shift * (t / 1000) / (1 + (timestep_shift - 1) * (t / 1000)) * 1000
return t.clamp(min_step, max_step)
def block_causal_mask(num_frames, frames_per_block=3):
i = torch.arange(num_frames)
return (i[None, :] // frames_per_block) <= (i[:, None] // frames_per_block) # Eq. 5
def sample_block_indices(bs, num_frames, num_steps, frames_per_block=3):
idx = torch.randint(num_steps, (bs, num_frames // frames_per_block)) # one step per chunk
return idx.repeat_interleave(frames_per_block, dim=1)
def init(student, ode_latents, c, steps=(1000, 757, 522, 0)):
# 1. Read the teacher's ODE trajectory at one student step per chunk.
idx = sample_block_indices(bs, num_frames, len(steps))
t = torch.tensor(steps)[idx]
x_t = ode_latents[torch.arange(bs)[:, None], idx, torch.arange(num_frames)[None]]
x_0 = ode_latents[:, -1] # the trajectory's clean end
# 2. Regress the clean frames from the noisy ones.
x_hat = student(x_t, t, c, mask=block_causal_mask(num_frames))
loss = (x_hat - x_0)[t != 0].square().mean() # Eq. 6
def train(student, teacher, fake_score, x_0, c, steps=(1000, 757, 522, 0), guidance_scale=3.5):
# 1. Add noise to each chunk of a real video at its own step, and predict the clean frames.
t_b = torch.tensor(steps)[sample_block_indices(bs, num_frames, len(steps))]
x_t = add_noise(x_0, torch.randn_like(x_0), t_b)
x_hat = student(x_t, t_b, c, mask=block_causal_mask(num_frames))
# 2. Add noise to the prediction at one shifted step, and score it with the fake and guided teacher scores.
with no_grad():
t = shift(torch.randint(1000, (bs, 1))) # one step for the whole video
x_hat_t = add_noise(x_hat, torch.randn_like(x_hat), t)
x_fake = fake_score(x_hat_t, t, c)
x_c, x_u = teacher(x_hat_t, t, c), teacher(x_hat_t, t, null) # bidirectional, frozen
x_real = x_c + guidance_scale * (x_c - x_u)
grad = (x_fake - x_real) / abs(x_hat - x_real).mean(dim=(1, 2, 3, 4), keepdim=True) # Eq. 4
# 3. Calculate a loss whose gradient on the prediction is the DMD gradient.
loss = 0.5 * (x_hat.double() - (x_hat - grad).double().detach()).square().mean()
def critic_step(student, fake_score, x_0, c, steps=(1000, 757, 522, 0)):
# 1. Regenerate the student's clean frames without gradient.
with no_grad():
t_b = torch.tensor(steps)[sample_block_indices(bs, num_frames, len(steps))]
x_gen = student(add_noise(x_0, torch.randn_like(x_0), t_b), t_b, c, mask=block_causal_mask(num_frames))
# 2. Fit the fake score to them by flow matching on fresh noise.
t = shift(torch.randint(1000, (bs, 1)))
noise = torch.randn_like(x_gen)
x_gen_t = add_noise(x_gen, noise, t)
flow_pred = (x_gen_t - fake_score(x_gen_t, t, c)) / (t / 1000) # x_0 prediction read as a velocity
loss = (flow_pred - (noise - x_gen)).square().mean() # Eq. 2 in flow-matching form
def sample(student, c, num_blocks, steps=(1000, 757, 522, 0)):
cache, out = [], []
for i in range(num_blocks):
x = torch.randn(block_shape)
for j, t in enumerate(steps):
x_hat = student(x, t, c, kv_cache=cache) # attends to every cached chunk, no mask
if j < len(steps) - 1:
x = add_noise(x_hat, torch.randn_like(x_hat), steps[j + 1]) # re-noise with fresh noise
student(x_hat, 0, c, kv_cache=cache, write=True) # one pass at t = 0 caches the chunk
out.append(x_hat)
return cat(out, dim=1)Improved Distribution Matching Distillation for Fast Image Synthesis
MIT · Adobe Research
Advances in Neural Information Processing Systems (NeurIPS), 2024
May 23, 2024 DMD2 (813) code (1.5K)
It frees DMD from its regression loss, adds a GAN head that trains on real images, and lets a few-step student beat its own teacher.
Insight. A student that sees real data can surpass its teacher. A GAN on the student's own outputs became a core part of later distillation.
DMD (Eq. 2). , where adds noise, is the frozen teacher, and is a copy.
No regression loss (Eq. 3). DMD2 drops . Its teacher pairs cost 700 A100-days for SDXL and limit the student.
Two time-scale update rule (§4.2). The fake score and the discriminator update five times per step of the generator to follow it.
GAN head (Eq. 4). , with on 's bottleneck and real images . minimizes it.
Multi-step generator (§4.4). Training and inference use timesteps 999/749/499/249: , then .
Backward simulation (§4.5). In training, the inputs of later steps come from the student's own rollout, not from noised real images.
Experiments (§5). One EDM step gets FID 1.51 on ImageNet-64 (teacher 2.22), and four SDXL steps equal 100 teacher steps.
A pure GAN has the best FID and the worst CLIP (Tab. 4). Without distribution matching, SDXL gets FID 13.77 and CLIP 0.307.
Fast High-Resolution Image Synthesis with Latent Adversarial Diffusion Distillation
Stability AI
SIGGRAPH Asia, 2024
Mar 18, 2024 LADD (348)
Distillation is fully latent: the teacher generates the training data, its features tell real from fake, and the distillation loss is not necessary.
Insight. If the teacher generates and judges in its own latent space, adversarial distillation needs no pixels and scales to large models.
Latent space only (§3). ADD decodes to pixels for both losses, which costs memory and limits resolution. LADD stays latent.
Teacher as discriminator (§3). The frozen teacher sees latents re-noised at a logit-normal . Heads on its attention blocks judge.
No distillation loss (§4.2). On teacher images at a fixed CFG scale, distillation adds nothing, so the adversarial loss trains alone.
Experiments (§4–5). Human raters: four SD3-Turbo (8B) steps equal 50-step SD3 on quality and beat Midjourney v6 on alignment.
One-step Diffusion with Distribution Matching Distillation
MIT · Adobe Research
Conference on Computer Vision and Pattern Recognition (CVPR), 2024
Nov 30, 2023 DMD (1,241)
It first brought score-difference distribution matching into the diffusion distillation pipeline, and the fast generators of the industry now widely use this design.
It distills a diffusion model into a one-step generator by matching distributions, not trajectories. The signal is a difference of two scores.
Insight. A student free of the teacher's path made one-step generators competitive. Distribution matching became an industry standard.
One-step generator (§3.1). starts as the teacher , a clean-image predictor, at its noisiest step.
Distribution matching (Eq. 2). The gradient of the reverse KL, with the scores , is .
Diffused distributions (Eq. 3). Neither score exists off the other's support. Thus re-noises at .
Real and fake scores (Eq. 4–6). The frozen teacher gives Eq. (4). is the same expression on a copy Eq. (5), and Eq. (6) refits it to the outputs of the generator. There is no discriminator and no minimax game.
Gradient (Eq. 7–8). Eq. (7), Eq. (8) for channels and pixels.
Regression loss (Eq. 9). LPIPS on teacher ODE pairs, , stops mode dropping. minimizes .
Experiments (§4). One-step FID is 2.62 on ImageNet-64, 0.3 above the teacher, and 11.49 on COCO-30K, against SD's 8.78.
weighting_factor "diverges slightly" from Eq. 8 and reads , because the network predicts the mean, not the noise.The training and sampling code. Follow Algorithm 1 and 2 of the paper.
def karras_sigmas(n=1000, sigma_min=0.002, sigma_max=80.0, rho=7.0):
ramp = torch.linspace(0, 1, n)
sigmas = (sigma_max ** (1 / rho) + ramp * (sigma_min ** (1 / rho) - sigma_max ** (1 / rho))) ** rho
return sigmas.flip(0) # small sigma first
def dm_loss(x, labels, real_unet, fake_unet, sigmas, min_step=20, max_step=980):
with no_grad():
sigma = sigmas[torch.randint(min_step, max_step + 1, (x.shape[0], 1, 1, 1))] # t in [0.02T, 0.98T]
noisy = x + sigma * torch.randn_like(x) # Eq. 3
p_real = x - real_unet(noisy, sigma, labels) # Eq. 4, the frozen teacher
p_fake = x - fake_unet(noisy, sigma, labels) # Eq. 5
weight = p_real.abs().mean([1, 2, 3], keepdim=True) # Eq. 8
grad = torch.nan_to_num((p_real - p_fake) / weight) # Eq. 7
return 0.5 * (x - (x - grad).detach()).square().mean() # a surrogate loss whose gradient is grad
def fake_loss(x, labels, fake_unet, sigmas, sigma_data=0.5):
x = x.detach() # no gradient to the generator
sigma = sigmas[torch.randint(0, len(sigmas), (x.shape[0], 1, 1, 1))]
pred = fake_unet(x + sigma * torch.randn_like(x), sigma, labels)
weight = sigma ** -2 + 1 / sigma_data ** 2 # Karras weighting
return (weight * (pred - x) ** 2).mean() # Eq. 6
def train(generator, real_unet, fake_unet, labels, z_ref, y_ref, lambda_reg=0.25, conditioning_sigma=80.0):
# 1. Generate images in one step, from fresh noise and from the paired noise.
sigmas = karras_sigmas()
G = lambda z: generator(z * conditioning_sigma, conditioning_sigma, labels)
x, x_ref = G(torch.randn_like(z_ref)), G(z_ref)
# 2. Calculate the generator loss: distribution matching plus regression.
loss_g = dm_loss(x, labels, real_unet, fake_unet, sigmas) + lambda_reg * lpips(x_ref, y_ref) # Eq. 9
# 3. Calculate the fake-score loss on the generator's own samples.
loss_fake = fake_loss(x, labels, fake_unet, sigmas)
return loss_g, loss_fake # one update of each per step
def sample(generator, labels, shape, conditioning_sigma=80.0):
return generator(torch.randn(shape) * conditioning_sigma, conditioning_sigma, labels)Adversarial Diffusion Distillation
Stability AI
European Conference on Computer Vision (ECCV), 2024
Nov 28, 2023 ADD (960) code (27.3K)
It first brought the adversarial loss into diffusion distillation, released as SDXL-Turbo, and started the GAN-assisted route that turbo-class generators still follow.
An adversarial loss keeps one-step samples sharp, and score distillation keeps them true to the teacher. SDXL-Turbo runs in real time.
Insight. Adversarial sharpness, distillation fidelity and a frozen network as the critic became the template of real-time one-step generators.
Student (§3.1). A pretrained UNet denoises at 4 timesteps, with the top at zero terminal SNR for pure noise.
Adversarial loss (Eq. 2–3). Eq. (2), where is the student output for the noisy input at timestep , and the heads act on the features of a frozen DINOv2 network. The heads train with a hinge loss and the R1 penalty Eq. (3).
Distillation loss (§3.3, Eq. 4). . The frozen teacher denoises the re-noised student output , and the stop-gradient makes the teacher output a fixed target. The distance is , with the weight .
Objective (§3.1, Eq. 1). with . Inference uses no classifier-free guidance, so a step is one network call.
Experiments (§4). One-step ADD-M gets FID 19.7 on COCO against InstaFlow's 22.4, and four ADD-XL steps beat SDXL in ELO.
The distillation loss adds little (Tab. 1d). alone gets 20.8 FID and 0.315 CLIP, and distillation adds only 0.2 and 0.004.
InstaFlow: One Step is Enough for High-Quality Diffusion-Based Text-to-Image Generation
University of Texas at Austin · Helixon Research
International Conference on Learning Representations (ICLR), 2024
Sep 12, 2023 InstaFlow (468) code (1.4K)
It reflows Stable Diffusion on its own noise–image pairs until the flow is nearly straight, then distills the straight flow into a single step.
Insight. First change the teacher, then distill it. When the teacher's coupling is straight, plain regression gives a single-step generator.
Rectified flow (§2.2, Eq. 1–4). In Eq. (1), least squares fits to Eq. (2) along Eq. (3), where is noise and is an image. Forward Euler Eq. (4) is exact at only for a straight flow, .
Reflow (Eq. 5). , . is SD 1.5 at 25 DPM-Solver steps, CFG 5.0.
Text-conditioned distillation (Eq. 6, Alg. 2). is one Euler step. is , then LPIPS.
Guidance as a velocity mix (Eq. 7). with on the reflowed teacher during distillation.
The training and sampling code. Follow Algorithm 1 and 2 of the paper.
def cfg_velocity(v, z, t, prompt, alpha=1.5):
return alpha * v(z, t, prompt) + (1 - alpha) * v(z, t, null) # Eq. 7
def reflow(v, v_k, prompt, teacher_steps=25, teacher_cfg=5.0):
# 1. Draw a noise and the image that the current flow makes from it.
x_0 = torch.randn(shape)
with no_grad():
x_1 = ode_solve(v_k, x_0, prompt, steps=teacher_steps, cfg=teacher_cfg) # DPM-Solver on SD 1.5 at k = 1
# 2. Regress the straight direction at a point on the line between them.
t = torch.rand(bs)
x_t = t * x_1 + (1 - t) * x_0 # Eq. 3
loss = (v(x_t, t, prompt) - (x_1 - x_0)).square().mean() # Eq. 5
def distill(v_tilde, v_2, prompt, teacher_steps=25, alpha=1.5, use_lpips=False):
# 1. Draw a noise and the image that the guided 2-rectified flow makes from it.
x_0 = torch.randn(shape)
with no_grad():
x_1 = ode_solve(lambda z, t: cfg_velocity(v_2, z, t, prompt, alpha), x_0, steps=teacher_steps) # Euler
# 2. Take one Euler step from the noise at time 0, and match the teacher's image.
x_hat = x_0 + v_tilde(x_0, 0, prompt) # Eq. 6
loss = lpips(x_hat, x_1) if use_lpips else (x_hat - x_1).square().mean() # L2 first, then LPIPS
def sample(v, prompt, num_steps=1):
x = torch.randn(shape)
for t in linspace(0, 1, num_steps + 1)[:-1]:
x = x + v(x, t, prompt) / num_steps # Eq. 4On Distillation of Guided Diffusion Models
Stanford · Stability AI · Google Research, Brain Team
Conference on Computer Vision and Pattern Recognition (CVPR), 2023
Oct 06, 2022 CFG Distill (902)
It first made classifier-free guidance distillable with a student that takes the guidance scale as input. This -embedding is now standard in few-step generators.
It makes classifier-free guidance distillable: a guidance-conditioned student replaces the two models before progressive distillation.
Insight. Guidance needs no second pass. A scale-conditioned student made guidance distillation a standard step of deployed pipelines.
Guided teacher (§2, Eq. 2). Each DDIM step calls two models, , and the student must handle any scale .
Stage 1, guided student (§3.1, Eq. 3). , where is Fourier-embedded and is the log-SNR.
Stage 2, halving (§3.2). One student step matches two teacher DDIM steps, . halves, and is kept.
Stochastic sampler (§3.3, Eq. 5). It steps twice as far without noise, then one step back with new noise: Eq. (5).
Experiments (§4). Pixel and latent ImageNet and LAION: at 4 steps, ImageNet-64 FID is 2.17 against the teacher's 2.36 at 1024×2.
Metrics miss the blur (§4.2.2). At 8 steps, distilled SD equals DDIM on FID and CLIP, but DDIM blurs more than 4 student steps.
Progressive Distillation for Fast Sampling of Diffusion Models
Google Research, Brain Team
International Conference on Learning Representations (ICLR), 2022
Feb 01, 2022 PD (2,833) code
It started the progressive route to few-step diffusion sampling. Its velocity parameterization became a standard for training diffusion models, not only for distillation.
It halves the steps of a sampler by distillation many times, from 8192 to 4, and adds velocity prediction to keep few-step models stable.
Insight. The parameterization lasted longer than the halving: velocity prediction became a standard training target, also outside distillation.
DDIM step (§2, Eq. 7). is the deterministic sampler on Eq. (1), with .
Target (§3, Alg. 2). The teacher takes two DDIM steps , and the target inverts one student step. Unlike , fully determines , so the student predicts it sharply.
Repeated halving (§3). A converged student is the next teacher, and halves, 8192 to 1 on CIFAR-10, 50K updates per round.
Why ε-prediction fails (§4, Eq. 9). At zero SNR, divides by , and the -loss weight Eq. (9) is zero.
Velocity prediction (§4). There are three fixes: (1) predict , (2) predict and together, or (3) predict , with . All three work with distillation, and is the most stable, but the experiments use (1) on CIFAR-10 and (2) on the other three datasets.
Truncated-SNR weighting (§4). , which is not zero at zero SNR.
Experiments (§5.2). On CIFAR-10, 4 steps beat 50 DDIM steps, 3.00 to 4.67. ImageNet-64 and LSUN are near-optimal at 4–8 steps.
Stability over parameterization (Tab. 1). From scratch, -prediction beats , 2.51 against 2.75, and with truncated SNR diverges.
The training and sampling code. Follow Algorithm 2 of the paper.
def cosine_logsnr(u, logsnr_min=-20.0, logsnr_max=20.0):
b = atan(exp(-0.5 * logsnr_max))
a = atan(exp(-0.5 * logsnr_min)) - b
return -2 * torch.log(torch.tan(a * u + b)) # alpha_t = cos(pi t / 2), clipped at |logsnr| = 20
def alpha_sigma(logsnr):
return torch.sigmoid(logsnr).sqrt(), torch.sigmoid(-logsnr).sqrt()
def predict(model, z, logsnr, mean_type="x"):
alpha, sigma = alpha_sigma(logsnr)
out = model(z, logsnr)
x = out if mean_type == "x" else alpha * z - sigma * out # "v": x = alpha z - sigma v
return x, (z - alpha * x) / sigma
def ddim_step(model, z_t, logsnr_t, logsnr_s):
x, eps = predict(model, z_t, logsnr_t)
alpha_s, sigma_s = alpha_sigma(logsnr_s)
return alpha_s * x + sigma_s * eps, x # Eq. 7
def train(student, teacher, x, num_steps):
# 1. Sample a discrete time and add noise to the data.
i = torch.randint(0, num_steps, (x.shape[0],))
logsnr_t = cosine_logsnr((i + 1) / num_steps)
alpha_t, sigma_t = alpha_sigma(logsnr_t)
z_t = alpha_t * x + sigma_t * torch.randn_like(x) # Eq. 1
# 2. Run two teacher DDIM steps.
logsnr_mid, logsnr_s = cosine_logsnr((i + 0.5) / num_steps), cosine_logsnr(i / num_steps)
with no_grad():
z_mid, _ = ddim_step(teacher, z_t, logsnr_t, logsnr_mid)
z_s, x_mid = ddim_step(teacher, z_mid, logsnr_mid, logsnr_s)
# 3. Invert one student DDIM step to get the target.
alpha_s, sigma_s = alpha_sigma(logsnr_s)
frac = sigma_s / sigma_t
x_target = (z_s - frac * z_t) / (alpha_s - frac * alpha_t) # never clipped
x_target = where(i == 0, x_mid, x_target) # final step: the teacher's own prediction
eps_target = (z_t - alpha_t * x_target) / sigma_t
# 4. Calculate the loss with truncated-SNR weighting.
x_pred, eps_pred = predict(student, z_t, logsnr_t)
x_mse = (x_pred - x_target).square().flatten(1).mean(1)
eps_mse = (eps_pred - eps_target).square().flatten(1).mean(1) # Eq. 9: SNR times x_mse
loss = torch.maximum(x_mse, eps_mse).mean() # max(1, SNR) weighting
def distill(model, data, start_num_steps=8192, end_num_steps=1, steps_per_iter=50000):
teacher, num_steps = model, start_num_steps
while num_steps > end_num_steps:
num_steps //= 2
student = copy(teacher) # the student starts as the teacher
for _ in range(steps_per_iter):
train(student, teacher, next(data), num_steps)
teacher = student
return teacher
def sample(model, num_steps, shape):
z = torch.randn(shape)
for i in reversed(range(num_steps)):
z, x = ddim_step(model, z, cosine_logsnr((i + 1) / num_steps), cosine_logsnr(i / num_steps))
return xKnowledge Distillation in Iterative Generative Models for Improved Sampling Speed
arXiv, 2021
Jan 07, 2021 Denoising Student (424) code (30)
It distills a 100-step DDIM into a single forward pass by plain regression on the teacher's outputs, with no adversarial training anywhere.
Insight. A deterministic sampler is a function that a network can regress in one pass, and distribution matching later removed the blur.
Deterministic teacher (§2.2, Eq. 8). has no noise: the output is a map of .
KL as MSE (Eq. 10–11). Unit-variance Gaussians at teacher and student maps , give + const.
Synthesized training data (§3.1). The teacher runs 100 DDIM steps (50 for LSUN) from prior to make 1.024M pairs for reuse.
The student is the teacher (§3.2). It keeps the weights and still predicts the noise to subtract from , at the fixed top timestep .
Experiments (§4). On CIFAR-10, the student gets FID 9.36 against StyleGAN2-ADA's 2.92, and 50K samples take 51.5s, not 4,960s.
Pixel-level replication blurs (§4.1). Unresolved detail averages out, LSUN is soft, and CIFAR-10 is 9.36 against the teacher's 4.16.
The training and sampling code. Follow §3 of the paper.
def ddim_timesteps(num_steps=100, quadratic=True):
if quadratic:
return [int(s) for s in linspace(0, sqrt(800), num_steps) ** 2] # CIFAR-10, CelebA
return list(range(0, 1000, 1000 // num_steps)) # LSUN: 50 linear steps
def make_pair(teacher, bs, res, num_steps=100, quadratic=True, beta_min=1e-4, beta_max=0.02):
alphas = torch.cumprod(1 - torch.linspace(beta_min, beta_max, 1000), dim=0)
seq = ddim_timesteps(num_steps, quadratic)
x_T = x = torch.randn(bs, res, res, 3)
for i, j in zip(reversed(seq), reversed([-1] + seq[:-1])):
a, a_next = alphas[i], (alphas[j] if j >= 0 else 1.0)
eps = teacher(x, i)
x = sqrt(a_next / a) * (x - sqrt(1 - a) * eps) + sqrt(1 - a_next) * eps # Eq. 8
return x_T, x.clamp(-1, 1) # 1.024M pairs, made once and reused
def student(model, x_T, t_top=999):
return x_T - model(x_T, t_top) # the teacher's net and weights, fixed at the top timestep
def train(model, x_T, x_0, use_l2=True):
# 1. Predict the image in one step.
x_pred = student(model, x_T)
# 2. Calculate the regression loss on the synthesized pair.
err = x_0 - x_pred
loss = (err.square() if use_l2 else err.abs()).flatten(1).sum(1).mean() # Eq. 11 (CIFAR-10 uses L1)
def sample(model, bs, res):
return student(model, torch.randn(bs, res, res, 3))Last updated on November 04, 2026 · Citations from Semantic Scholar & Google Scholar; stars from GitHub, November 2026