How a model is built, and the algorithms it learns by.
22 papers · 6,003 avg citations
Written by Junkun Yuan.
Click here to go back to main contents.
Table of contents ▼
LDM(CVPR 2022) VQ-VAE-2(NeurIPS 2019) VQ-VAE(NeurIPS 2017)
Scalable Diffusion Models with Transformers
UC Berkeley · New York University · Meta AI (FAIR)
International Conference on Computer Vision (ICCV), 2023
Dec 19, 2022 DiT (8,056) code (8.7K)
It made the plain transformer the standard diffusion backbone in place of the U-Net. Later image and video generators build on its adaLN-conditioned block.
A transformer on latent patches replaces the U-Net of latent diffusion, and adaLN-Zero blocks take in the timestep and the class label.
Insight. Diffusion quality follows the Gflops of a plain transformer, so later image and video generators scale up this same backbone.
Latent input (§3.1, §4). DiT works in the latent space of the Stable Diffusion VAE. A 256×256×3 image becomes of shape 32×32×4, scaled by 0.18215, and the VAE decoder maps the samples back to pixels. The VAE has 84M parameters and stays frozen during training.
Patchify (§3.2). Each patch of the input ( at 256×256) becomes one token, so there are tokens of width with fixed sine-cosine position embeddings, for . Halving at least quadruples the Gflops but keeps the parameter count.
adaLN-Zero block (§3.2). An MLP on regresses the shift , scale and gate : , and the same for the MLP. Its last layer starts at zero, so each block starts as the identity. It gets FID 19.47, against 26.14 for cross-attention.
Model sizes (§3.2, Tab. 1). S, B and L follow ViT, and XL adds 28 layers of width 1152. DiT-XL/2 is XL with , at 118.6 Gflops.
Output and loss (§3.1, §3.2). A final adaptive layer norm and a zero-initialized linear layer decode each token to : the noise and a learned diagonal covariance . trains the noise, and the full variational bound trains with the mean frozen.
Guidance on three channels (§3.1, App. A). Training drops labels with the probability 0.1, so the model learns the null class . Sampling uses on the first three of four latent channels only, with for the reported best FID.
Experiments (§5). On class-conditional ImageNet 256×256, DiT-XL/2 with guidance 1.5 gets FID 2.27 at 118.6 Gflops (LDM-4-G: 3.60).
Gflops, not parameters, set FID (Fig. 8). From XL/8 to XL/2, DiT keeps about 675M parameters and cuts FID from 106.41 to 19.47.
More steps do not replace size (Fig. 10). XL/2 with 128 steps gets FID-10K 23.7 at 15.2 Tflops, and L/2 with 1,000 steps gets 25.9.
The training and sampling code. Follow §3 and §4 of the paper.
def linear_alphas(num_steps=1000, beta_start=1e-4, beta_end=2e-2):
return torch.cumprod(1 - torch.linspace(beta_start, beta_end, num_steps), 0)
def modulate(x, shift, scale):
return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1)
def dit_block(x, c, attn, mlp, norm1, norm2, ada_ln):
shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = ada_ln(c).chunk(6, dim=1) # zero-initialized
x = x + gate_msa.unsqueeze(1) * attn(modulate(norm1(x), shift_msa, scale_msa)) # adaLN-Zero
x = x + gate_mlp.unsqueeze(1) * mlp(modulate(norm2(x), shift_mlp, scale_mlp))
return x
def dit_xl_2():
return build_dit(depth=28, hidden_size=1152, patch_size=2, num_heads=16) # Tab. 1
def dit(model, z_t, t, y, patch_size=2):
x = model.patchify(z_t, patch_size) + model.pos_embed # T = (I / p)^2 tokens with sine-cosine positions
c = model.t_embed(t) + model.y_embed(y)
for block in model.blocks:
x = dit_block(x, c, *block)
shift, scale = model.final_ada_ln(c).chunk(2, dim=1)
return model.unpatchify(model.final_linear(modulate(model.final_norm(x), shift, scale))) # noise and covariance
def train(model, vae, x, y, scale_factor=0.18215, class_dropout=0.1, num_classes=1000):
# 1. Encode the images to latents.
with no_grad():
z_0 = vae.encode(x).latent_dist.sample() * scale_factor
# 2. Drop labels for classifier-free guidance, and add noise at a random step t.
y = torch.where(rand(bs) < class_dropout, num_classes, y) # the null class
alphas = linear_alphas()
t = torch.randint(0, 1000, (bs,))
noise = torch.randn_like(z_0)
a_t = alphas[t].view(-1, 1, 1, 1)
z_t = a_t.sqrt() * z_0 + (1 - a_t).sqrt() * noise
# 3. Predict the noise and the variance. The bound trains the variance through a frozen mean.
eps, var = dit(model, z_t, t, y).chunk(2, dim=1)
loss = (eps - noise).square().mean() + vlb(cat([eps.detach(), var], 1), z_0, z_t, t) # L_simple and L_vlb
def sample(model, vae, y, num_steps=250, cfg_scale=4.0, scale_factor=0.18215, num_classes=1000):
z = torch.randn(bs, 4, 32, 32)
for t in respaced_steps(num_steps): # 250 of the 1,000 DDPM steps
out = dit(model, cat([z, z]), full((2 * bs,), t), cat([y, full((bs,), num_classes)]))
eps, var = out.chunk(2, dim=1)
eps_c, eps_u = eps.chunk(2)
guided = eps_u[:, :3] + cfg_scale * (eps_c[:, :3] - eps_u[:, :3]) # guidance on the first three channels
z = ddpm_step(z, cat([guided, eps_c[:, 3:]], 1), var[:bs], t) # learned-range variance
return vae.decode(z / scale_factor)High-Resolution Image Synthesis with Latent Diffusion Models
LMU Munich · Heidelberg University · Runway ML
Conference on Computer Vision and Pattern Recognition (CVPR), 2022
Dec 20, 2021 LDM (28,859) code (14.2K)
Its split into a reusable autoencoder and a diffusion model on the latents became the standard base design of open text-to-image and text-to-video models.
Diffusion in the latent space of an autoencoder with mild compression, and cross-attention in the U-Net to condition on text or layouts.
Insight. Spend diffusion compute on content, not on imperceptible pixel detail. Later image and video models kept this two-stage split.
Perceptual compression (§3.1). An autoencoder maps to with the factor . An and LPIPS reconstruction loss and a patch-based adversarial loss keep the decoded images sharp. It trains once for many diffusion models.
Latent regularization (§3.1). KL-reg. adds a VAE-style KL penalty toward a standard normal with the small weight , and VQ-reg. puts a vector quantization layer into the decoder, as in a VQGAN tokenizer. Both stop the variance of the latent from growing without limit.
Latent scale (§4.3.2). The diffusion model sees , the latent divided by its standard deviation. The scale sets the signal-to-noise ratio of the noised latent, and it changes the results. The paper shows the effect on a KL-regularized model, with and without the rescaling.
Latent diffusion objective (§3.2, Eq. 2). is the pixel objective Eq. (1) on the noised latent , with uniform in . The U-Net uses mostly 2D convolutions, because the latent keeps its 2D structure, and one pass of decodes a sample.
Cross-attention (§3.3). A domain encoder maps the condition to . U-Net layer attends to it with , , , , where is the flattened feature map of that layer and is the width of and .
Conditional objective (§3.3, Eq. 3). trains and together. For text, is a transformer on BERT tokens, in a 1.45B-parameter model that trains on the LAION-400M data. The model concatenates spatial conditions to instead.
Experiments (§4). Factors to 16 balance speed and quality. On ImageNet, LDM-4 with guidance gets FID 3.60 (ADM-G: 4.59).
Worse reconstruction, better samples (§4). VQ latents reconstruct slightly worse than KL latents but give better LDM samples.
The training and sampling code. Follow §3 of the paper.
def make_alphas(num_steps=1000, linear_start=0.00085, linear_end=0.012):
betas = torch.linspace(linear_start ** 0.5, linear_end ** 0.5, num_steps) ** 2
return torch.cumprod(1 - betas, 0) # cumulative product of alpha_t
def cross_attention(x, context, to_q, to_k, to_v, to_out, heads=8):
q, k, v = (t.unflatten(-1, (heads, -1)).transpose(1, 2) for t in (to_q(x), to_k(context), to_v(context)))
attn = (q @ k.transpose(-1, -2) / q.shape[-1] ** 0.5).softmax(-1) # softmax(QK^T / sqrt(d))
return to_out((attn @ v).transpose(1, 2).flatten(2))
def train_autoencoder(encoder, decoder, discriminator, x, step, kl_weight=1e-6, disc_weight=0.5, disc_start=50001):
# 1. Encode the images to a diagonal Gaussian, and decode one sample of it.
mean, logvar = encoder(x).chunk(2, dim=1)
z = mean + (0.5 * logvar).exp() * torch.randn_like(mean)
x_rec = decoder(z)
# 2. Calculate the L1 and LPIPS reconstruction loss and the small KL penalty.
rec_loss = ((x - x_rec).abs() + lpips(x, x_rec)).sum() / bs
kl = 0.5 * (mean ** 2 + logvar.exp() - 1 - logvar).sum([1, 2, 3]).mean()
loss = rec_loss + kl_weight * kl
# 3. After disc_start steps, add the patch adversarial loss, scaled to the gradient of the reconstruction loss.
if step >= disc_start:
g_loss = -discriminator(x_rec).mean()
d_weight = grad_norm(rec_loss, decoder.last_layer) / (grad_norm(g_loss, decoder.last_layer) + 1e-4)
loss = loss + disc_weight * d_weight.clamp(0, 1e4).detach() * g_loss
def train(unet, encoder, cond_encoder, x, y, scale_factor=0.18215):
# 1. Encode the images with the frozen autoencoder, and scale the latents to unit variance.
with no_grad():
mean, logvar = encoder(x).chunk(2, dim=1)
z_0 = scale_factor * (mean + (0.5 * logvar).exp() * torch.randn_like(mean))
# 2. Add noise at a random step t.
alphas = make_alphas()
t = torch.randint(0, 1000, (bs,))
noise = torch.randn_like(z_0)
a_t = alphas[t].view(-1, 1, 1, 1)
z_t = a_t.sqrt() * z_0 + (1 - a_t).sqrt() * noise
# 3. Predict the noise. The U-Net calls cross_attention to the encoded condition in its transformer blocks.
loss = (noise - unet(z_t, t, context=cond_encoder(y))).square().mean() # Eq. 3
def sample(unet, decoder, cond_encoder, y, num_steps=200, guidance_scale=5.0, scale_factor=0.18215):
alphas = make_alphas()
steps = torch.arange(0, 1000, 1000 // num_steps) + 1 # uniform DDIM steps
c, null = cond_encoder(y), cond_encoder([""] * bs)
z = torch.randn(bs, 4, 32, 32)
for i in reversed(range(num_steps)):
a_t = alphas[steps[i]]
a_prev = alphas[steps[i - 1]] if i > 0 else alphas[0]
eps_c, eps_u = unet(cat([z, z]), full((2 * bs,), steps[i]), context=cat([c, null])).chunk(2)
eps = eps_u + guidance_scale * (eps_c - eps_u) # classifier-free guidance
x_0 = (z - (1 - a_t).sqrt() * eps) / a_t.sqrt()
z = a_prev.sqrt() * x_0 + (1 - a_prev).sqrt() * eps # DDIM step with eta = 0
return decoder(z / scale_factor)Generating Diverse High-Fidelity Images with VQ-VAE-2
DeepMind
Advances in Neural Information Processing Systems (NeurIPS), 2019
Jun 02, 2019 VQ-VAE-2 (2,551)
A two-level hierarchy of VQ-VAE codes, a coarse map for global structure and a fine map for detail, with PixelCNN priors over both maps.
Insight. A likelihood model on compressed codes can match GANs and keep diversity. Later work kept the codes, not the PixelCNN prior.
VQ-VAE objective (§2.1, Eq. 2). The encoder output becomes its nearest codebook vector Eq. (1), and the loss is , where is the decoder, is the stop-gradient operator and weights the last term.
EMA codebook (§2.1). Moving averages replace the codebook term: , , , with , where counts the batch vectors that map to . So each code is the running mean of the encoder vectors that map to it.
Two-level hierarchy (§3.1). For 256×256 images, the encoder downsamples by 4 to a 64×64 bottom map and by 2 more to a 32×32 top map. The bottom map also takes the decoded top code, so the top map keeps the global structure and the bottom map keeps the local detail.
Priors (§3.2). A PixelCNN with self-attention models the top codes, conditioned on the class. A PixelCNN with large conditioning stacks models the bottom codes, conditioned on the class and the top codes, because self-attention at 64×64 resolution needs too much memory.
Classifier-based rejection (§3.3). A pretrained ImageNet classifier scores each sample by the probability of its class, and the method drops the samples with the lowest scores. This trades some diversity for quality, and the paper uses it only for metrics, not for the sample figures.
Experiments (§5). On ImageNet, a classifier trained on the model's samples gets 54.83% top-1 on real images (BigGAN-deep: 42.65%).
FID punishes the compression blur (§5.3.1). The VQ-VAE reconstructions of real images alone get an FID of about 10, not about 2.
The training and sampling code. Follow §2 and §3 of the paper.
def quantize_ema(z_e, vq, decay=0.99, eps=1e-5):
flat = z_e.reshape(-1, vq["codebook"].shape[1])
indices = torch.cdist(flat, vq["codebook"]).argmin(1) # Eq. 1
z_q = vq["codebook"][indices].reshape(z_e.shape)
# Move each code to the running mean of the encoder vectors that map to it.
one_hot = torch.eye(len(vq["codebook"]))[indices]
vq["size"].mul_(decay).add_(one_hot.sum(0), alpha=1 - decay) # N_i
vq["sum"].mul_(decay).add_(one_hot.T @ flat, alpha=1 - decay) # m_i
n = vq["size"].sum()
size = (vq["size"] + eps) / (n + len(vq["codebook"]) * eps) * n # Laplace smoothing
vq["codebook"].copy_(vq["sum"] / size[:, None]) # e_i = m_i / N_i
commitment = (z_q.detach() - z_e).square().mean()
return z_e + (z_q - z_e).detach(), commitment # straight-through estimator
def train(enc_bottom, enc_top, dec_top, decoder, vq_top, vq_bottom, x, commitment_cost=0.25):
# 1. Encode the image to the bottom features at 1/4 size and the top features at 1/8 size.
h_bottom = enc_bottom(x)
h_top = enc_top(h_bottom)
# 2. Quantize the top map, and quantize the bottom map together with the decoded top code.
z_top, commit_top = quantize_ema(h_top, vq_top)
z_bottom, commit_bottom = quantize_ema(cat([h_bottom, dec_top(z_top)], -1), vq_bottom)
# 3. Decode both maps and calculate the loss.
x_recon = decoder(cat([upsample(z_top), z_bottom], -1))
loss = (x_recon - x).square().mean() + commitment_cost * (commit_top + commit_bottom) # Eq. 2 with EMA
def rejection_sample(samples, labels, classifier, keep_ratio):
scores = classifier(samples).softmax(-1)[torch.arange(len(labels)), labels]
keep = scores.argsort(descending=True)[: int(keep_ratio * len(samples))]
return samples[keep]
def sample(prior_top, prior_bottom, decoder, vq_top, vq_bottom, labels):
top = prior_top.sample(labels) # 32 x 32 codes, PixelCNN with self-attention
bottom = prior_bottom.sample(labels, top) # 64 x 64 codes, conditioned on the top codes
z_top, z_bottom = vq_top["codebook"][top], vq_bottom["codebook"][bottom]
return decoder(cat([upsample(z_top), z_bottom], -1))Neural Discrete Representation Learning
DeepMind
Advances in Neural Information Processing Systems (NeurIPS), 2017
Nov 02, 2017 VQ-VAE (8,366) code
It made learned discrete codes the input of generative models. Image, audio and video token models still start from its nearest-code quantizer and its two-stage recipe.
A VAE with a discrete latent: each encoder output maps to the nearest codebook vector, and a separate prior generates the codes.
Insight. First compress data into discrete tokens, then model the tokens. Most later token-based image generators follow this same route.
Codebook and quantization (§3.1, Eq. 2). The codebook holds vectors of dimension . Each encoder output vector becomes its nearest entry, , , so the posterior is one-hot Eq. (1). ImageNet uses code vectors.
Straight-through gradient (§3.2). The arg min has no gradient, so the backward pass copies the gradient of the decoder input to the encoder output: , where is the stop-gradient operator. It works because both vectors share one -dimensional space.
Loss (§3.2, Eq. 3). with , and from 0.1 to 2.0 gives the same results. Its terms (1) train the decoder and the encoder, (2) move toward , and (3), the commitment loss, keep the encoder near its code.
Prior (§3.1, §3.3). Training keeps a uniform prior over the codes, so the KL term is the constant and drops out. After training, a PixelCNN for images or a WaveNet for audio fits an autoregressive prior over the code map. The paper leaves joint training for future work.
Experiments (§4). On CIFAR-10 the VQ-VAE gets 4.67 bits/dim, near a continuous VAE (4.51) and ahead of the VIMCO estimator (5.14).
Codes match phonemes (§4.3). A map from the 128 speech codes to the 41 phonemes is 49.3% accurate, against 7.2% by chance.
The training and sampling code. Follow §3 of the paper.
def quantize(z_e, codebook):
flat = z_e.reshape(-1, codebook.shape[1])
distances = (flat ** 2).sum(1, keepdim=True) - 2 * flat @ codebook.T + (codebook ** 2).sum(1)
indices = distances.argmin(1) # Eq. 1
z_q = codebook[indices].reshape(z_e.shape) # Eq. 2
return z_q, indices.reshape(z_e.shape[:-1])
def train(encoder, decoder, codebook, x, data_variance, commitment_cost=0.25):
# 1. Encode the images and quantize each latent vector.
z_e = encoder(x)
z_q, _ = quantize(z_e, codebook)
# 2. Calculate the codebook loss and the commitment loss.
codebook_loss = (z_q - z_e.detach()).square().mean()
commitment_loss = (z_q.detach() - z_e).square().mean()
# 3. Copy the decoder-input gradient to the encoder, and reconstruct the images.
z_q = z_e + (z_q - z_e).detach() # straight-through estimator
recon_loss = (decoder(z_q) - x).square().mean() / data_variance
loss = recon_loss + codebook_loss + commitment_cost * commitment_loss # Eq. 3
def sample(prior, decoder, codebook, shape):
indices = prior.sample(shape) # PixelCNN over the code map
return decoder(codebook[indices])Improved Mean Flows: On the Challenges of Fastforward Generative Models
CMU · MIT · Adobe · THU
Conference on Computer Vision and Pattern Recognition (CVPR), 2026
Dec 01, 2025 iMF (142) code (359)
Recast the self-built target of MeanFlow as plain velocity regression, and make its fixed guidance scale one more condition at test time.
Insight. MeanFlow's target leaks the true velocity through its input. A setting fixed before training, like CFG, cannot change at test time.
MeanFlow's target (§3, Eq. 6–7). With noise and data , the average velocity over , , and the instantaneous satisfy Eq. (4–5). MeanFlow fits Eq. (6) by Eq. (7) (sg: stop-gradient).
An equivalent v-loss (§4.1, Eq. 9–10). Solve the identity for , Eq. (8), to get Eq. (9), where is its stop-gradient form. The loss Eq. (10) is a v-loss re-parameterized by u-pred, equivalent to Eq. (6–7).
The illegitimate input (Eq. 11). In fact, is . It uses the conditional velocity, which no regressor of may use.
Network-predicted tangent (Eq. 12). : both arguments are now network outputs of alone.
Two sources of (§4.1). uses the free boundary condition or an 8-layer -head on a flow-matching loss.
Guidance as a condition (§4.2, Eq. 15). MeanFlow fixes the scale of the guided velocity for the class , Eq. (13), before training. iMF makes an input, Eq. (15), with on for a skew .
The guided target (App. A, Eq. 17). for the null class . is no guidance.
Guidance interval (§4.2). with and . Outside it, , and the rows span .
In-context conditioning (Eq. 16). takes conditions as tokens, 8 for the class and 4 per other, without adaLN-zero.
Experiments (§5). On ImageNet-256 from scratch, iMF-XL/2 gets FID 1.72 at 1-NFE (MeanFlow-XL/2: 3.43) and 1.54 at 2-NFE.
Size labels mislead (Tab. 2). XL/2 costs 174.6 Gflops in iMF and 119.0 in MeanFlow. At similar FLOPs, M/2 gets 2.27 and 5.01.
The training and sampling code. Follow Algorithm 2 of the paper.
def sample_time_steps(bs, time_mu=-0.4, time_sigma=1.0, ratio_r_not_equal_t=0.5):
time_samples = torch.randn(bs, 2)
time_samples = torch.sigmoid(time_samples * time_sigma + time_mu)
sorted_samples, _ = torch.sort(time_samples, dim=1) # make r < t
r, t = sorted_samples[:, 0], sorted_samples[:, 1]
# Set r to t with the probability of r = t.
fraction_equal = 1.0 - ratio_r_not_equal_t
equal_mask = torch.rand(bs) < fraction_equal
r = torch.where(equal_mask, t, r)
return r, t
def sample_cfg_scale(bs, cfg_beta=1.0, cfg_omega_max=8.0):
u = torch.rand(bs)
if cfg_beta == 1.0:
return torch.exp(u * math.log(cfg_omega_max))
power = 1.0 - cfg_beta
return (1 + u * (cfg_omega_max ** power - 1)) ** (1 / power)
def sample_cfg_interval(bs, full_mask, t_min_range=(0.0, 0.5), t_max_range=(0.5, 1.0)):
def uniform(low, high):
return low + (high - low) * torch.rand(bs)
t_min = torch.where(full_mask, 0.0, uniform(*t_min_range))
t_max = torch.where(full_mask, 1.0, uniform(*t_max_range))
return t_min, t_max
def adaptive_loss(error, adaptive_eps=0.01, adaptive_p=1.0):
loss = error.square().flatten(1).sum(dim=1)
return loss / (loss.detach() + adaptive_eps).pow(adaptive_p)
def train(z_0):
# 1. Sample the timesteps r and t.
r, t = sample_time_steps(bs)
# 2. Sample the guidance scale and interval.
omega = sample_cfg_scale(bs)
t_min, t_max = sample_cfg_interval(bs, r == t)
# 3. Build the noisy latent z_t and its velocity v_t.
noise = torch.randn_like(z_0)
z_t = (1 - t) * z_0 + t * noise # linear path
v_t = noise - z_0 # conditional velocity
# 4. Predict the average velocity u and the instantaneous velocity v with a class dropout.
dropped = rand(bs) < 0.1 # 10% class dropout
y_in = where(dropped, null, y)
u, v = model(z_t, r, t, omega, t_min, t_max, y=y_in) # Eq. 16
# 5. Predict the conditional and unconditional instantaneous velocities at t with the v-head.
omega_t = where((t >= t_min) & (t <= t_max), omega, 1)
with no_grad():
v_c, v_u = model(cat([z_t, z_t]), cat([t, t]), cat([t, t]), cat([omega_t, ones]), cat([zeros, zeros]),
cat([ones, ones]), y=cat([y, null]), predict_u=False).chunk(2) # Eq. 17
# 6. Build the guided velocity target.
v_target = v_t + (1 - 1 / omega_t) * (v_c - v_u) # Eq. 17
v_target = where(dropped, v_t, v_target)
# 7. Build the compound prediction V, with the predicted v_c as the JVP tangent.
fn = lambda z, r_, t_: model(z, r_, t_, omega, t_min, t_max, y=y_in, predict_v=False)
_, dudt = jvp(fn, (z_t, r, t), (v_c, zeros_like(r), ones_like(t)))
V = u + (t - r) * dudt # Eq. 15
# 8. Calculate the loss of the u-head and of the auxiliary v-head.
loss = adaptive_loss(V - v_target) + adaptive_loss(v - v_target)
loss = loss.mean()
def sample(num_steps, omega, t_min, t_max, y):
time_steps = linspace(1, 0, num_steps + 1)
for i in range(num_steps):
t = full((bs,), time_steps[i])
r = full((bs,), time_steps[i + 1])
u, _ = model(z, r, t, omega, t_min, t_max, y=y, predict_v=False)
z = z - (t - r) * uBack to Basics: Let Denoising Generative Models Denoise
MIT
Conference on Computer Vision and Pattern Recognition (CVPR), 2026
Nov 17, 2025 JiT (361) code (2.6K)
Predict the clean image rather than the noise, and a plain ViT on raw pixel patches becomes a strong diffusion model at any resolution.
Insight. The prediction target, not the tokenizer, blocked diffusion on raw pixels. Latent-free generation is again a serious route at scale.
The manifold assumption (§3.3). Clean data lies near a low-dimensional manifold, but the noise and the velocity do not. Thus a network that predicts needs only the manifold coordinates. A network that predicts or must keep all dimensions of a 16×16 patch.
Flow setup (§3.1, Eq. 1–2). Eq. (1) moves noise to data at , and Eq. (2), with .
-prediction under the -loss (§3.2, Eq. 5–6). Under Eq. (1–2), one output gives the others, Eq. (5). So the network predicts the image: with , where is clipped at 0.05 to prevent division by zero.
Plain ViT on pixels (§4.1–4.2). A ViT takes 16×16 tokens of pixels, and a two-layer bottleneck embeds each patch.
Sampling (§3.1, Eq. 4). Take 50 Heun steps on a linear in , with an Euler last step and guidance only on .
Experiments (§5). On ImageNet 256, JiT-H/16 gets FID 1.86 at 182 Gflops (latent DiT-XL/2: 2.27). At 512, JiT-G/32 gets 1.78.
The training and sampling code. Follow Algorithm 1 and 2 of the paper.
def sample_t(bs, p_mean=-0.8, p_std=0.8):
return torch.sigmoid(torch.randn(bs) * p_std + p_mean) # logit-normal
def to_velocity(net, z, t, y, t_eps=0.05):
return (net(z, t, y) - z) / (1 - t).clamp_min(t_eps) # Eq. 5, from the x-prediction
def guided_velocity(net, z, t, y, cfg=2.9, interval=(0.1, 1.0)):
v_c, v_u = to_velocity(net, z, t, y), to_velocity(net, z, t, null)
scale = cfg if interval[0] < t < interval[1] else 1.0 # guidance interval
return v_u + scale * (v_c - v_u)
def train(net, x, y, noise_scale=1.0, t_eps=0.05, label_drop_prob=0.1):
# 1. Sample a time, and sample noise with a scale for the resolution.
t = sample_t(bs)
e = torch.randn_like(x) * noise_scale
# 2. Interpolate, and calculate the target velocity.
z = t * x + (1 - t) * e # Eq. 1
v = (x - z) / (1 - t).clamp_min(t_eps) # Eq. 2, v = x - e
# 3. Predict the clean image with a class dropout, and convert it to a velocity.
y = where(rand(bs) < label_drop_prob, null, y)
v_pred = to_velocity(net, z, t, y)
# 4. Calculate the v-loss.
loss = (v_pred - v).square().mean() # Eq. 6
def sample(net, y, num_steps=50, noise_scale=1.0):
z = torch.randn(shape) * noise_scale
ts = linspace(0, 1, num_steps + 1)
for i in range(num_steps):
v = guided_velocity(net, z, ts[i], y)
if i == num_steps - 1:
z = z + (ts[i + 1] - ts[i]) * v # last step Euler
else:
v_next = guided_velocity(net, z + (ts[i + 1] - ts[i]) * v, ts[i + 1], y)
z = z + (ts[i + 1] - ts[i]) * (v + v_next) / 2 # Eq. 4, Heun
return zAlphaFlow: Understanding and Improving MeanFlow Models
Snap Inc. · University of Michigan
International Conference on Learning Representations (ICLR), 2026
Oct 23, 2025 AlphaFlow (54) code (131)
It shows that the MeanFlow loss has two conflicting terms, and it anneals a family of losses from trajectory flow matching to the MeanFlow loss.
Insight. Part of the one-step quality gap is in the optimization, not the objective: the final loss is MeanFlow's, but the samples are better.
MeanFlow loss (§2, Eq. 5). The network predicts the average velocity over from the latent for the data and the noise . MeanFlow fits , where , is the stop-gradient copy, and is one JVP call.
Loss decomposition (§3.1, Eq. 6). , where is trajectory flow matching and is trajectory consistency. Their gradients have a cosine below −0.4, so joint training is slow and unstable.
Two timesteps (§3.2, Tab. 3). and come from lognorm, and 50% of the pairs on XL/2 set (B/2: 25%, MeanFlow: 75%). The plain flow matching loss Eq. (7) is on the slice, where . So it lowers with less gradient conflict with .
α-Flow loss (Def. 1, Eq. 8). , where and . is the consistency step ratio, the shift velocity is , and is not an EMA copy. For , one model call at replaces the JVP call.
Unification (Thm. 1). With , gives . With , gives twice the Shortcut loss. As , : expand to first order at . Consistency training (CT) is the case with a clean-data prediction.
Curriculum (§4.2). Training has three phases: (1) trajectory flow matching at , (2) a transition that lowers from 1 to 0, (3) MeanFlow fine-tuning at with the JVP target of Eq. (5). The first phase reaches the narrow manifold before the gradient conflict starts.
Schedule (Alg. 2). At iteration , with , K, M of the 1.2M training steps on XL/2, where and are the start and the end of the transition. is 1 above and 0 below , the best fixed (Tab. 5c).
Adaptive weight (§4.2, App. H.2). As , , so the MeanFlow weight for the error becomes , , with under the stop-gradient operator. On the rows and in the MeanFlow phase, the numerator is 1 instead of .
Guidance (§4.2, App. G). As in MeanFlow, for the class and the null class , with the CFG scales , for on XL/2, with a 10% class dropout. is the model's own instantaneous velocity.
Sampling (§4.2, Alg. 3). One step is . For two steps, XL/2 uses consistency sampling: , then at . B/2 uses the ODE step . For MeanFlow-XL/2, the ODE step is better (Fig. 5).
Experiments (§5). On ImageNet-256, α-Flow-XL/2 gets one-step FID 2.95 (MeanFlow: 3.43) at 240 epochs, and XL/2+ gets 2.58.
A JVP-free α-Flow falls short (Tab. 5d). At a fixed , FID on B/2 is 45.6, against 43.3 for MeanFlow and its JVP target.
The training and sampling code. Follow Algorithm 1, 2 and 3 of the paper.
def sample_time_steps(bs, time_mu=-0.4, time_sigma=1.0, ratio_r_equal_t=0.5):
def logit_normal(n):
return torch.sigmoid(torch.randn(n) * time_sigma + time_mu)
n_equal = int(bs * ratio_r_equal_t)
t_equal = logit_normal(n_equal) # r = t
t_1, t_2 = logit_normal(bs - n_equal), logit_normal(bs - n_equal)
t = cat([t_equal, torch.maximum(t_1, t_2)])
r = cat([t_equal, torch.minimum(t_1, t_2)]) # make r < t
return r, t
def sample_alpha(k, k_s=600_000, k_e=1_000_000, gamma=25.0, eta=5e-3):
scale, offset = 1 / (k_e - k_s), -(k_s + k_e) / 2 / (k_e - k_s)
alpha = 1 - 1 / (1 + math.exp(-(scale * k + offset) * gamma)) # Alg. 2
if alpha < eta:
return 0.0
return 1.0 if alpha > 1 - eta else alpha
def train(
model, z_0, y, k,
cfg_w=0.2, cfg_kappa=0.92, cfg_min_t=0.0, cfg_max_t=0.75, cfg_prob=0.1,
clamp_target=4.0, adaptive_eps=1e-3
):
# 1. Sample the timesteps r and t, the ratio alpha and the intermediate timestep s.
r, t = sample_time_steps(bs)
alpha = sample_alpha(k)
s = alpha * r + (1 - alpha) * t
# 2. Build the noisy latent z_t and its velocity v_t.
noise = torch.randn_like(z_0)
z_t = (1 - t) * z_0 + t * noise # linear path
v_t = noise - z_0 # conditional velocity
# 3. Predict the average velocity u with a class dropout.
guided = (t > cfg_min_t) & (t < cfg_max_t)
y = torch.where(guided & (rand(bs) < cfg_prob), null, y)
u = model(z_t, r, t, y)
# 4. Calculate the guided velocity.
with no_grad():
u_c, u_u = model(cat([z_t, z_t]), cat([t, t]), cat([t, t]), y=cat([y, null])).chunk(2)
v_tilde = cfg_w * v_t + cfg_kappa * u_c + (1 - cfg_w - cfg_kappa) * u_u
v_tilde = torch.where(guided, v_tilde, v_t)
# 5. Build the target: the JVP target at alpha = 0, else the alpha-Flow target.
with no_grad():
if alpha == 0:
fn = lambda z, r_, t_: model(z, r_, t_, y)
_, dudt = jvp(fn, (z_t, r, t), (v_tilde, zeros_like(r), ones_like(t)))
u_target = v_tilde - (t - r) * dudt # Eq. 5
else:
z_s = z_t - (t - s) * v_tilde # trajectory value at s
u_target = alpha * v_tilde + (1 - alpha) * model(z_s, r, s, y) # Eq. 8
u_target = torch.where(r == t, v_tilde, u_target.clamp(-clamp_target, clamp_target))
# 6. Calculate the adaptively weighted prediction error.
loss = (u - u_target).square().flatten(1).mean(1)
row_alpha = torch.where(r == t, 1.0, alpha) if alpha > 0 else ones_like(t)
loss = (row_alpha * loss / (loss.detach() + adaptive_eps)).mean()
def sample(model, z, y, time_steps=(1.0, 0.55, 0.0), consistency=True):
for t, t_next in zip(time_steps[:-1], time_steps[1:]):
if consistency:
x_hat = z - t * model(z, 0.0, t, y=y)
z = (1 - t_next) * x_hat + t_next * torch.randn_like(z) # consistency sampling
else:
z = z - (t - t_next) * model(z, t_next, t, y=y) # ODE step
return zMean Flows for One-step Generative Modeling
CMU · MIT
Advances in Neural Information Processing Systems (NeurIPS), 2025
May 19, 2025 MeanFlow (711) code (622)
Model the average velocity over an interval, not the instantaneous one, for a one-step generator from scratch with guidance in the field.
Insight. An identity that the regressed quantity must satisfy replaces the teacher. The identity-plus-JVP template opened one-step training.
Average velocity definition (§4.1, Eq. 3). : the displacement over , a field from alone.
The MeanFlow identity (Eq. 6). Differentiate with respect to to get Eq. (6).
JVP (Eq. 8). is one Jacobian–vector product, with the tangent .
The objective (Eq. 9–11). with : stop-gradient avoids double backpropagation.
Sampling (§4.1, Eq. 12). : the integral is the prediction, so is one call. Few steps chain it.
Guidance inside the field (§4.2, Eq. 19). Define for the class , so . A mixing scale gives another form, , with and as the two CFG scales.
Adaptive loss weighting (§4.3, App. B.2, Tab. 1e). For the error , the powered loss equals the squared loss under the weight , , , as . FID is 61.06 for , 63.98 for Pseudo-Huber-like , 79.75 for plain .
Two timesteps (§4.3, Tab. 1a/c/d). come from lognorm, , and only 25% of pairs keep . The input is .
The training and sampling code. Follow Algorithm 1 and 2 of the paper.
def sample_time_steps(bs, time_mu=-0.4, time_sigma=1.0, ratio_r_not_equal_t=0.25):
time_samples = torch.randn(bs, 2)
time_samples = torch.sigmoid(time_samples * time_sigma + time_mu)
sorted_samples, _ = torch.sort(time_samples, dim=1) # make r < t
r, t = sorted_samples[:, 0], sorted_samples[:, 1]
# Set r to t with the probability of r = t.
fraction_equal = 1.0 - ratio_r_not_equal_t
equal_mask = torch.rand(bs) < fraction_equal
r = torch.where(equal_mask, t, r)
return r, t
def train(
model, z_0, y,
cfg_omega=0.2, cfg_kappa=0.92, cfg_min_t=0.0, cfg_max_t=0.8, cfg_prob=0.1,
adaptive_eps=0.01, adaptive_p=1.0
):
# 1. Sample the timesteps r and t.
r, t = sample_time_steps(bs)
# 2. Build the noisy latent z_t and its velocity v_t.
noise = torch.randn_like(z_0)
z_t = (1 - t) * z_0 + t * noise # linear path
v_t = noise - z_0 # conditional velocity
# 3. Predict the average velocity u with a class dropout.
dropped = rand(bs) < cfg_prob
y = torch.where(dropped, null, y)
u = model(z_t, r, t, y)
# 4. Calculate the guided velocity.
with no_grad():
u_c, u_u = model(cat([z_t, z_t]), cat([t, t]), cat([t, t]), y=cat([y, null])).chunk(2)
v_tilde = cfg_omega * v_t + cfg_kappa * u_c + (1 - cfg_omega - cfg_kappa) * u_u # Eq. 21
v_hat = torch.where((t >= cfg_min_t) & (t <= cfg_max_t) & ~dropped, v_tilde, v_t)
# 5. Calculate the JVP and get the target average velocity.
_, dudt = jvp(lambda z, r_, t_: model(z, r_, t_, y), (z_t, r, t), (v_hat, zeros_like(r), ones_like(t))) # Eq. 8
u_target = v_hat - (t - r) * dudt # Eq. 10
# 6. Calculate the prediction error.
loss = (u - u_target.detach()).square().flatten(1).sum(1) # Eq. 9
loss = (loss / (loss.detach() + adaptive_eps).pow(adaptive_p)).mean()
def sample(model, num_steps=1):
time_steps = linspace(1, 0, num_steps + 1)
for i in range(num_steps):
t = full((bs,), time_steps[i])
r = full((bs,), time_steps[i + 1])
z = z - (t - r) * model(z, r, t, y=y)One Step Diffusion via Shortcut Models
UC Berkeley
International Conference on Learning Representations (ICLR), 2025
Oct 16, 2024 Shortcut Models (482) code (777)
One network, conditioned on step size, jumps any distance along the flow. It trains in one run, with no teacher and no second stage.
Insight. With the jump size as an input, the step budget becomes a test-time choice. Later models that take two times as input started here.
Flow matching (Eq. 1). for noise and data , with . Eq. (2) fits : one step gives the mean.
Step-size conditioning (Eq. 3). The shortcut gives the jump . At , it equals the flow velocity.
Self-consistency (§3, Eq. 4). One step equals two half steps, , both from the EMA model.
Combined loss (Eq. 5, Alg. 1). , with a stop-gradient on one row in 8.
Binary step grid (§3.1). units give eight lengths . Each fits two of the next smaller one, and is a multiple of .
Sampling (Alg. 2). Start from noise at and apply for steps of . One step uses .
Experiments (§5). On ImageNet-256 with DiT-B, the FID is 15.5 / 40.3 at 128 / 1 steps, better than other end-to-end methods.
Bootstrapping still scales (§5.3). Unlike Q-learning, one-step FID decreases with model size, to 10.6 at DiT-XL (3.8 at 128 steps).
The training and sampling code. Follow Algorithm 1 and 2 of the paper.
def sample_bootstrap_steps(n, denoise_timesteps=128):
log2_sections = int(log2(denoise_timesteps))
dt_base = (log2_sections - 1 - torch.arange(log2_sections)).repeat_interleave(n // log2_sections)
dt_base = cat([dt_base, zeros(n - len(dt_base))]) # exponents 6, ..., 0, the remainder at d = 1
t = torch.floor(torch.rand(n) * 2 ** dt_base) / 2 ** dt_base # t on multiples of d
return t, dt_base
def train(model, model_ema, x_1, y, bootstrap_every=8, denoise_timesteps=128, class_dropout_prob=0.1):
# 1. Sample step sizes and times for the bootstrap rows.
n_b = bs // bootstrap_every
t_b, dt_base = sample_bootstrap_steps(n_b)
d = 1 / 2 ** dt_base
# 2. Build the bootstrap targets from two chained half-steps of the EMA model.
x_0 = torch.randn_like(x_1)
x_t_b = (1 - (1 - 1e-5) * t_b) * x_0[:n_b] + t_b * x_1[:n_b] # Eq. 1, a 1e-5 noise floor
with no_grad():
s_1 = model_ema(x_t_b, t_b, dt_base + 1, y[:n_b]) # dt_base + 1 is the step d/2
x_mid = clip(x_t_b + d / 2 * s_1, -4, 4) # Eq. 3
s_2 = model_ema(x_mid, t_b + d / 2, dt_base + 1, y[:n_b])
s_target = clip((s_1 + s_2) / 2, -4, 4) # Eq. 4
# 3. Build the flow-matching targets for the other rows on the finest grid, with a class dropout.
t_f = torch.randint(0, denoise_timesteps, (bs - n_b,)) / denoise_timesteps
x_t_f = (1 - (1 - 1e-5) * t_f) * x_0[n_b:] + t_f * x_1[n_b:]
v_target = x_1[n_b:] - (1 - 1e-5) * x_0[n_b:] # Eq. 1
y_f = where(rand(bs - n_b) < class_dropout_prob, null, y[n_b:])
# 4. Regress both kinds of target with one loss.
dt_flow = full((bs - n_b,), log2(denoise_timesteps)) # flow rows use the finest step
x_t, t, dt_in = cat([x_t_b, x_t_f]), cat([t_b, t_f]), cat([dt_base, dt_flow])
loss = (model(x_t, t, dt_in, cat([y[:n_b], y_f])) - cat([s_target, v_target])).square().mean() # Eq. 5
def sample(model, y, num_steps=1, cfg_scale=4.0):
x = torch.randn(shape)
dt_base = full((bs,), log2(num_steps))
for i in range(num_steps):
t = full((bs,), i / num_steps)
s_c, s_u = model(x, t, dt_base, y), model(x, t, dt_base, null)
x = x + (s_u + cfg_scale * (s_c - s_u)) / num_steps # Eq. 3
return xSimplifying, Stabilizing and Scaling Continuous-Time Consistency Models
OpenAI
International Conference on Learning Representations (ICLR), 2025
Oct 14, 2024 sCM (321)
It made continuous-time consistency training work at scale. MeanFlow, rCM and newer few-step families use its TrigFlow, tangent normalization and JVP recipe.
Simplify consistency models, stabilize their continuous-time tangent, and scale them to 1.5B: two steps come within 10% of the teacher.
Insight. Continuous-time consistency seemed too unstable to train. With a controlled tangent, it became the scalable form, also for video.
TrigFlow (§3, Eq. 3, 5). For noise and the data standard deviation , , . With the network , the PF-ODE is Eq. (3), and the CM is a DDIM step, Eq. (5).
The tangent (Eq. 6). . is Eq. (3) in sCD, in sCT.
Time conditioning (Eq. 7). , positional embeddings and adaptive double normalization keep the term stable.
Tangent normalization and warmup (§4.2). Eq. (6) becomes , . scales its term.
Adaptive weighting (§4.2, Eq. 8). Eq. (2) becomes an MSE, because for any free of . As in EDM2, a learned weight balances the loss over times, , where is the data dimension.
Time proposal (§4.2, App. G). On ImageNet 512, , . The small mean keeps training near clean data.
JVP rearrangement (§5.1). To prevent FP16 overflow near , the JVP takes at .
Sampling and guidance (App. G). One step uses , two re-noise to . The guidance scale is an input.
Experiments (§5.2). On CIFAR-10, ImageNet 64 and 512, two steps get FID 2.06 / 1.48 / 1.88, near the teachers' 2.01 / 1.33 / 1.73.
sCT is weak in latent space (Tab. 2). It is better than sCD at 64px, but at ImageNet 512-S it gets FID 10.13 and sCD gets 3.07.
FID and FD-DINOv2 disagree (Tab. 7). VSD after sCD moves the FID only 2.75 → 2.67, but it moves FD-DINOv2 83.78 → 54.81.
The training and sampling code. Follow Algorithm 1 of the paper. The sampler follows Appendix G.2.
def sample_time(bs, p_mean=-0.8, p_std=1.6, sigma_d=0.5):
tau = torch.randn(bs) * p_std + p_mean
return torch.arctan(torch.exp(tau) / sigma_d) # log-normal proposal on sigma_d tan(t)
def train(
model, weight_net, teacher, x_0, iters, consistency_training=False,
sigma_d=0.5, c=0.1, warmup_iters=10000, cfg_max=2.0
):
# 1. Sample t and build the TrigFlow sample x_t.
t = sample_time(bs)
z = torch.randn_like(x_0) * sigma_d
x_t = cos(t) * x_0 + sin(t) * z
# 2. Get the ODE direction from the pair for sCT, or from the guided teacher for sCD.
s = rand(bs) * (cfg_max - 1) + 1 # guidance scale, also a student input
if consistency_training:
dxdt = cos(t) * z - sin(t) * x_0
else:
dxdt = sigma_d * teacher(x_t / sigma_d, t, s) # Eq. 3
# 3. Run the student, and run its stop-gradient copy through the rearranged JVP.
F = model(x_t / sigma_d, t, s)
tangent = (cos(t) * sin(t) * dxdt, cos(t) * sin(t) * sigma_d)
with no_grad():
F_sg, cs_dFdt = jvp(lambda x, t_: model(x, t_, s), (x_t / sigma_d, t), tangent)
# 4. Build the warmed-up tangent and normalize it.
r = min(1.0, iters / warmup_iters)
g = -cos(t) ** 2 * (sigma_d * F_sg - dxdt) - r * (cos(t) * sin(t) * x_t + cs_dFdt) # Eq. 6 times cos(t)
g = g / (g.flatten(1).norm(dim=1) + c)
# 5. Calculate the adaptive-weighted loss.
w, D = weight_net(t), x_0[0].numel()
loss = (exp(w) / D * (F - F_sg - g).square().flatten(1).sum(1) - w).mean() # Eq. 8
def sample(model, s, num_steps=1, sigma_d=0.5, t_mid=1.1):
t_max = arctan(80 / sigma_d) # EDM's sigma_max = 80
x = torch.randn(shape) * sigma_d
x = cos(t_max) * x - sin(t_max) * sigma_d * model(x / sigma_d, t_max, s) # Eq. 5
if num_steps == 2:
x = cos(t_mid) * x + sin(t_mid) * torch.randn_like(x) * sigma_d
x = cos(t_mid) * x - sin(t_mid) * sigma_d * model(x / sigma_d, t_mid, s) # Eq. 5
return xPyramidal Flow Matching for Efficient Video Generative Modeling
Peking University · Kuaishou Technology · Beijing University of Posts and Telecommunications
International Conference on Learning Representations (ICLR), 2025
Oct 08, 2024 Pyramid Flow (420) code (3.2K)
A spatial pyramid of stages, only the last at full resolution, and a temporal pyramid of compressed history use one DiT and one loss.
Insight. Resolution can be an axis of the generative path, not a cascade. Run the early, noisy steps small, and then renoise at each jump.
Flow matching (§3.1, Eq. 2–3). from noise to data has the target , for any end distributions.
Pyramidal flow (§3.2, Eq. 6). On the window , with , where and resize. Each stage goes from a pixelated, noisier start to a finer, cleaner end, and only the last of is at full resolution.
Stage endpoints (§3.2.1, Eq. 9–10). The two endpoints are Gaussians around the resized clean latent Eq. (7–8) with one shared noise : Eq. (9) and Eq. (10). Because , the paths do not cross.
Unified loss (§3.2.1, Eq. 11). unifies generation and decompression, with stages drawn 1 : 2 : 1.
Renoising at the jumps (§3.2.2, Eq. 15). Upsampling correlates pixels, so the jump rescales and adds block-correlated noise Eq. (14) with for the most decorrelation: . Here , so time goes back a little.
Blockwise causal Transformer (§3.4). Attention is full on the short sequence and causal across frames. Images are first frames.
Sampling (Alg. 1). Euler steps go through the stages: 20 steps per stage at guidance 7 for the first frame, 10 at guidance 5 after it.
Experiments (§4). SD3-Medium's 2B MM-DiT gets VBench 81.72 on 768p text-to-video (Gen-3 Alpha: 82.32) in 20.7k A100-hours.
The training and sampling code. Follow Section 3.2–3.3 and Algorithm 1 of the paper.
def noise_pyramid(noise, stages=3):
pyramid = [noise]
for _ in range(stages - 1):
pyramid.append(2 * interpolate(pyramid[-1], scale_factor=0.5, mode="bilinear")) # 2x keeps unit variance
return pyramid[::-1] # coarse to fine
def stage_sigmas(stages=3, stage_range=(0, 1 / 3, 2 / 3, 1), gamma=1 / 3):
start, end = [], []
for k in range(stages):
s = 1 - stage_range[k] # noise level where stage k starts on the global schedule
if k > 0:
signal = 1 - s
s = 1 - signal / (sqrt(1 + 1 / gamma) * (1 - signal) + signal) # corrected so Eq. 15 holds
start.append(s)
end.append(1 - stage_range[k + 1])
dist = [s - e for s, e in zip(start, end)]
bounds = [sum(dist[:k]) / sum(dist) for k in range(stages + 1)] # each stage's share of the timestep axis
return start, end, bounds
def stage_timestep(r, k, bounds, num_train_timesteps=1000):
return num_train_timesteps * (1 - bounds[k] - (1 - r) * (bounds[k + 1] - bounds[k]))
def history_condition(latents, k, num_units, frame_per_unit=1, corrupt_ratio=1 / 3):
sigma = torch.rand(bs) * corrupt_ratio # t' ~ U[0, 1/3]
corrupt = lambda clip: sigma * torch.randn_like(clip) + (1 - sigma) * clip
hist, j, stage = [], 1, k
while j < num_units and (j == 1 or stage > 0): # j units back, one stage coarser each
hist.append(corrupt(latents[stage][:, :, -(j + 1) * frame_per_unit:-j * frame_per_unit])) # Eq. 16
j, stage = j + 1, max(stage - 1, 0)
if j < num_units:
hist.append(corrupt(latents[0][:, :, :-j * frame_per_unit])) # the rest at the coarsest stage
return hist[::-1]
def past_condition(history, k):
scales = [0.5 ** (2 - max(k - j, 0)) for j in range(len(history))]
return [interpolate(h, scale_factor=s) for h, s in zip(history[::-1], scales)][::-1] # Eq. 17
def block_noise(x, gamma=1 / 3):
cov = torch.eye(4) * (1 + gamma) - torch.ones(4, 4) * gamma # Sigma' of Eq. 14, per 2x2 block
n = MultivariateNormal(torch.zeros(4), cov).sample(x.shape[:-2] + (x.shape[-2] // 2, x.shape[-1] // 2))
return rearrange(n, "... h w (p q) -> ... (h p) (w q)", p=2, q=2)
def train(model, latents, text, num_units, sample_ratios=(1.0, 2.0, 1.0), frame_per_unit=1):
# 1. Build the noise pyramid from one Gaussian noise. The list latents holds the clip at each stage's resolution.
noise = noise_pyramid(torch.randn_like(latents[-1]))
start_sigma, end_sigma, bounds = stage_sigmas()
# 2. Pick a stage and build its endpoints from the shared noise.
k = torch.multinomial(torch.tensor(sample_ratios), 1).item()
coarse = interpolate(latents[k - 1], scale_factor=2, mode="nearest") if k > 0 else 0
start = start_sigma[k] * noise[k] + (1 - start_sigma[k]) * coarse # Eq. 10, pure noise at k = 0
end = end_sigma[k] * noise[k] + (1 - end_sigma[k]) * latents[k] # Eq. 9, the clean latent at k = 2
# 3. Interpolate inside the stage and map the position to the model's timestep.
r = torch.rand(bs) # 1 at the stage's start, 0 at its end
x_t = r * start + (1 - r) * end # Eq. 6
t = stage_timestep(r, k, bounds)
# 4. Keep the newest unit as the trained one and condition it on the corrupted history.
x_t, target = x_t[:, :, -frame_per_unit:], (start - end)[:, :, -frame_per_unit:]
hist = history_condition(latents, k, num_units)
text = where(rand(bs) < 0.1, "", text) # 10% text dropout
# 5. Regress the stage displacement on the newest unit.
v = model(cat(hist + [x_t], dim=2), t, text)[:, :, -frame_per_unit:] # blockwise causal attention
loss = (v - target).square().mean() # Eq. 11
def sample(
model, text, num_units,
steps=(20, 20, 20), video_steps=(10, 10, 10), guidance=7.0, video_guidance=5.0
):
start_sigma, _, bounds = stage_sigmas()
history = []
for unit in range(num_units):
x = torch.randn(low_res_shape) # stage 0 starts from noise at the coarsest resolution
n_steps, scale = (steps, guidance) if unit == 0 else (video_steps, video_guidance)
for k in range(3):
if k > 0:
s_k = 1 - start_sigma[k] # the stage's corrected start signal
up = interpolate(x, scale_factor=2, mode="nearest")
x = (1 + s_k) / 2 * up + sqrt(3) * (1 - s_k) / 2 * block_noise(up) # Eq. 15
rs = linspace(1, 0, n_steps[k] + 1)
for r, r_next in zip(rs[:-1], rs[1:]):
inp, t = cat(past_condition(history, k) + [x], dim=2), stage_timestep(r, k, bounds)
v_c, v_u = model(inp, t, text)[:, :, -1:], model(inp, t, "")[:, :, -1:]
x = x + (r_next - r) * (v_u + scale * (v_c - v_u)) # Euler step
history.append(x)
return cat(history, dim=2)Visual Autoregressive Modeling: Scalable Image Generation via Next-Scale Prediction
Peking University · ByteDance
Advances in Neural Information Processing Systems (NeurIPS), 2024
Apr 03, 2024 VAR (1,265) code (8.8K)
It made next-scale prediction a third route to image generation, beside diffusion and raster AR. Many later generators now predict coarse-to-fine token maps.
Generate an image coarse to fine: a GPT-style autoregressive transformer predicts the whole token map of the next scale at each step.
Insight. The raster token order, not autoregression, limited image AR. A coarse-to-fine order gives it LLM-like power-law scaling with size.
Next-scale likelihood (§3.2, Eq. 6). The unit of the autoregression is a whole token map, , where is the map at scale . The model samples the tokens of in parallel, so an map costs , not .
Multi-scale residual tokens (Alg. 1). Each scale quantizes the residual of : , , where is upsampled to . picks the nearest code Eq. (3) of one codebook with , shared by all scales.
Reconstruction (Alg. 2). The decoder gets the sum of the scales, , and gives . Each is , and 4 such convolutions are shared over the scales. Without them, the upsampled would lose detail.
Scales (§4). A 256×256 image becomes a 16×16 map at a 16× downsampling, and the 10 scales are 1, 2, 3, 4, 5, 6, 8, 10, 13, 16, so one image has 680 tokens in all. The tokenizer keeps the VQGAN architecture and its loss Eq. (5), and it trains on the OpenImages dataset.
Teacher-forced input (Fig. 4). The input for scale is after scales, downsampled to . The class embedding is the start token, and a block-wise causal mask lets attend only to . The loss is the cross-entropy, with 10% of the class labels dropped.
Transformer (§4, Eq. 7–8). It is a GPT-2-style decoder with AdaLN on the class embedding, and are normalized to unit vectors. The shape follows the depth , the number of layers: , , , where is the drop-path rate, so Eq. (8).
Sampling (§5). The guidance on the logits grows with the scale, for the logits with the class and with the null class: , . Then top-900 and top-p 0.96 filtering keeps the likely tokens, and a KV cache replaces the mask at inference.
Experiments (§5). On ImageNet 256, the 2B VAR gets FID 1.73 in 10 steps with rejection sampling (DiT-XL/2: 2.27 in 250 steps).
Power laws hold to 2B (§5.2, Eq. 11). Over 12 sizes from 18M to 2B, the test loss follows , where is the number of parameters, with a Pearson coefficient near −0.998. DiT gains little past 675M, and the law for compute holds over 6 orders of magnitude.
The training and sampling code. Follow Algorithm 1 and 2 of the paper.
def phi(k, z, convs, num_scales=10, resi_ratio=0.5):
ticks = torch.linspace(1 / 12, 11 / 12, len(convs)) # 4 shared convolutions
conv = convs[(ticks - k / (num_scales - 1)).abs().argmin()]
return (1 - resi_ratio) * z + resi_ratio * conv(z)
def upsample(e, pn, size):
return F.interpolate(e.transpose(1, 2).unflatten(2, (pn, pn)), size=(size, size), mode="bicubic")
def multi_scale_tokens(f, codebook, convs, patch_nums=(1, 2, 3, 4, 5, 6, 8, 10, 13, 16)):
tokens, size = [], patch_nums[-1]
for k, pn in enumerate(patch_nums):
rest = F.interpolate(f, size=(pn, pn), mode="area").flatten(2).transpose(1, 2)
r_k = torch.cdist(rest, codebook).argmin(-1) # Eq. 3, the nearest code
tokens.append(r_k)
f = f - phi(k, upsample(codebook[r_k], pn, size), convs) # Alg. 1 line 9
return tokens
def reconstruct(tokens, codebook, convs, decoder, patch_nums=(1, 2, 3, 4, 5, 6, 8, 10, 13, 16)):
f_hat = 0
for k, (r_k, pn) in enumerate(zip(tokens, patch_nums)):
f_hat = f_hat + phi(k, upsample(codebook[r_k], pn, patch_nums[-1]), convs) # Alg. 2 line 8
return decoder(f_hat)
def next_scale_inputs(tokens, codebook, convs, patch_nums=(1, 2, 3, 4, 5, 6, 8, 10, 13, 16)):
f_hat, inputs = 0, []
for k in range(len(patch_nums) - 1):
f_hat = f_hat + phi(k, upsample(codebook[tokens[k]], patch_nums[k], patch_nums[-1]), convs)
pn = patch_nums[k + 1]
inputs.append(F.interpolate(f_hat, size=(pn, pn), mode="area").flatten(2).transpose(1, 2))
return cat(inputs, dim=1)
def block_causal_mask(patch_nums=(1, 2, 3, 4, 5, 6, 8, 10, 13, 16)):
scale = cat([full((pn * pn,), k) for k, pn in enumerate(patch_nums)])
return scale[:, None] >= scale[None, :] # r_k attends to r_<=k
def train(model, encoder, codebook, convs, images, labels, num_classes=1000, cond_drop_rate=0.1):
# 1. Tokenize the images, and build the teacher-forced inputs.
with no_grad():
tokens = multi_scale_tokens(encoder(images), codebook, convs)
x = next_scale_inputs(tokens, codebook, convs)
# 2. Drop labels for the guidance.
labels = where(rand(bs) < cond_drop_rate, num_classes, labels) # the null class
# 3. Predict all scales at once, and calculate the cross-entropy over all 680 tokens.
logits = model(labels, x, mask=block_causal_mask()) # Eq. 6
loss = F.cross_entropy(logits.flatten(0, 1), cat(tokens, dim=1).flatten())
def sample(model, codebook, convs, decoder, labels, patch_nums=(1, 2, 3, 4, 5, 6, 8, 10, 13, 16),
cfg=1.5, top_k=900, top_p=0.96, num_classes=1000):
f_hat, x, K = 0, None, len(patch_nums)
null = full_like(labels, num_classes)
for k, pn in enumerate(patch_nums):
logits_c, logits_u = model(cat([labels, null]), x, scale=k).chunk(2) # KV cache, no mask
s = cfg * k / (K - 1) # the guidance grows with the scale, k counts from 0
r_k = sample_top_k_top_p((1 + s) * logits_c - s * logits_u, top_k, top_p)
f_hat = f_hat + phi(k, upsample(codebook[r_k], pn, patch_nums[-1]), convs)
if k < K - 1:
x = F.interpolate(f_hat, size=(patch_nums[k + 1],) * 2, mode="area").flatten(2).transpose(1, 2)
x = x.repeat(2, 1, 1) # the conditional and the null halves
return decoder(f_hat)Improved Techniques for Training Consistency Models
OpenAI
International Conference on Learning Representations (ICLR), 2024
Oct 22, 2023 iCT (528)
Improve consistency training: remove the teacher EMA, replace LPIPS with Pseudo-Huber, grow the discretization, and beat distillation.
Insight. The recipe, not the idea, kept consistency training behind distillation. A perceptual loss with the metric's features inflates the score.
Consistency training (§2, Eq. 5). For data , noise , adjacent levels of an -level grid, the model and a metric , . is a weighting function, and the teacher is an EMA of the student by Eq. (4).
No EMA on the teacher (§3.2, Eq. 6). On a Dirac example, the limit with ignores the data, so the teacher uses .
Pseudo-Huber (§3.3, Eq. 8). with for dimension replaces LPIPS, whose features leak into FID.
Discretization and noise schedule (§3.4–3.5, Eq. 9–10). doubles from to during training Eq. (9). The levels follow a discretized lognormal, with , Eq. (10). Each pair has the weight .
Latent Consistency Models: Synthesizing High-Resolution Images with Few-Step Inference
Tsinghua University
arXiv, 2023
Oct 06, 2023 LCM (1,060) code (4.6K)
Consistency distillation in Stable Diffusion's latent space, with classifier-free guidance in one stage, makes 768px images in 2–4 steps.
Insight. Acceleration became a plug-in: the distilled model is an adapter that community fine-tunes of the base model can use with no change.
Latent consistency distillation (§4.1, Eq. 9). On SD latents with a prompt , , with the schedule and , . The teacher's weights initialize . Only training uses the ODE solver , here DDIM.
One-stage guided distillation (§4.2, Eq. 12–15). The ODE of the teacher uses the guided noise Eq. (12), so its solver step has two calls Eq. (15). The student takes the guidance scale as an input through new parameters.
Skipping step (§4.3, Eq. 16). With , Eq. (16), where Eq. (17) and is an EMA. skips near-identical steps of SD.
Experiments (§5). On LAION-Aesthetics with SD2.1, the 768px FID is 34.22 / 13.53 at 1 / 4 steps. Guided-Distill gets 120.28 / 16.70.
Consistency Trajectory Models: Learning Probability Flow ODE Trajectory of Diffusion
Sony AI · Stanford · CMU
International Conference on Learning Representations (ICLR), 2024
Oct 01, 2023 CTM (517) code (326)
It learns jumps between any two times of the PF ODE in a single network that also gives the score, and trains them by soft consistency.
Insight. If all jumps end at time zero, more steps make samples worse. Two-time jumps avoid this, and later flow-map models learn them.
PF ODE (§2, Eq. 1). With Gaussian noise , the noisy data is . A pretrained denoiser defines .
Trajectory jump (§3.1). moves on the PF ODE to any , where is the denoiser. CTM writes , so as : one network gives the jumps and the denoiser, which gives the score.
Neural jump (§3.1, §5.1). with , EDM's scalings, and a time embedding for . So needs no extra constraint. The teacher's weights start near , so training is 10–20 times faster.
Soft consistency (§3.2, Eq. 3). The teacher solves from to , then the student jumps to : . is the stop-gradient EMA of with . With and , it is the distillation target of consistency models (CM).
CTM loss (§3.2). The EMA student takes both sides of Eq. (3) to time 0: and . Then , where is LPIPS, a feature distance on clean images.
Timesteps (App. D.1). lie on an EDM grid with . The teacher takes Heun steps from to , with and .
DSM loss (§3.3). trains the denoiser at , where the factor gives almost no gradient. Half of the times come from lognormal, and half come from the high noise of the grid, so the network keeps a good denoiser at large .
GAN loss (§3.3). A discriminator compares the generated and the real images by . The code uses a hinge loss on eight StyleGAN-XL heads over EfficientNet and DeiT features. The GAN loss joins after 10K warm-up steps without it.
Adaptive weights (§3.3). , and has the same form, where is the last layer. They balance the gradient scales of the losses, and the objective is . The released code clips to .
γ-sampling (§4, Alg. 2). Each step jumps from to and adds the noise . is the CM sampler: all jumps end at time 0, so their errors add up (Thm. 1). is deterministic and adds no noise, and generalizes the stochastic sampler of EDM.
Experiments (§5). On CIFAR-10 and ImageNet-64, one-step FID is 1.98 and 1.92. EDM needs 35 and 79 steps for 2.01 and 2.44.
No teacher is necessary (§5.2). With as its own teacher, one-step CIFAR-10 FID is 2.39 (consistency training: 8.70).
Recall is lower (Tab. 2). On ImageNet-64, recall is 0.57 (EDM: 0.67, CM: 0.63), but the paper says that the samples look diverse.
The training and sampling code. Follow Algorithm 2 and 4 of the paper.
def karras_t(ramp, sigma_min=0.002, sigma_max=80.0, rho=7.0):
return (sigma_max ** (1 / rho) + ramp * (sigma_min ** (1 / rho) - sigma_max ** (1 / rho))) ** rho
def sample_indices(bs, num_scales=40, max_heun_steps=20):
p = torch.arange(1, max_heun_steps + 1).float() # p(k) proportional to k
k = torch.multinomial(p / p.sum(), 1).item() + 1 # one teacher step count per batch
n_t = torch.randint(0, num_scales - k, (bs,))
n_u = n_t + k
n_s = n_u + (torch.rand(bs) * (num_scales - n_u)).long() # s uniform on the grid below u
return n_t, n_u, n_s, k
def sample_dsm_sigmas(bs, p_mean=-1.2, p_std=1.2, ramp_max=0.7):
sigma_lognormal = torch.exp(p_mean + p_std * torch.randn(bs // 2))
sigma_high = karras_t(torch.rand(bs - bs // 2) * ramp_max) # high noise of the grid
return torch.cat([sigma_lognormal, sigma_high])
def jump(net, x_t, t, s, sigma_data=0.5):
c_in = 1 / (t ** 2 + sigma_data ** 2) ** 0.5
c_skip = sigma_data ** 2 / (t ** 2 + sigma_data ** 2)
c_out = t * sigma_data / (t ** 2 + sigma_data ** 2) ** 0.5
g = c_skip * x_t + c_out * net(c_in * x_t, 250 * log(t), 250 * log(s)) # EDM scalings
return g, s / t * x_t + (1 - s / t) * g # g and the neural jump G
def heun_solve(teacher, x, n_t, k, num_scales=40):
for i in range(k):
t = karras_t((n_t + i) / (num_scales - 1))
t_next = karras_t((n_t + i + 1) / (num_scales - 1))
d = (x - teacher(x, t)) / t # Eq. 1
x_euler = x + (t_next - t) * d
d_next = (x_euler - teacher(x_euler, t_next)) / t_next # Eq. 1
x = x + (t_next - t) * (d + d_next) / 2
return x
def adaptive_weight(loss_ctm, loss_other, last_layer):
grad_ctm = torch.autograd.grad(loss_ctm, last_layer, retain_graph=True)[0]
grad_other = torch.autograd.grad(loss_other, last_layer, retain_graph=True)[0]
return (grad_ctm.norm() / (grad_other.norm() + 1e-4)).clamp(0, 1e4).detach() # lambda of §3.3
def train(
net, net_ema, teacher, disc, x_0, last_layer, step,
num_scales=40, sigma_min=0.002, sigma_data=0.5, mu=0.999, gan_start=10000
):
# 1. Sample the times t > u >= s on the grid.
n_t, n_u, n_s, k = sample_indices(bs)
t, u, s = (karras_t(n / (num_scales - 1)) for n in (n_t, n_u, n_s))
# 2. Add noise to the data at time t.
noise = torch.randn_like(x_0)
x_t = x_0 + t * noise
# 3. Jump from t to s with the student, and then to time 0 with the EMA student.
_, G_ts = jump(net, x_t, t, s)
x_est = jump(net_ema, G_ts, s, sigma_min)[1]
# 4. Solve the teacher ODE from t to u, jump to s, and then jump to time 0.
with no_grad():
x_u = heun_solve(teacher, x_t, n_t, k)
x_target = jump(net_ema, jump(net, x_u, u, s)[1], s, sigma_min)[1] # Eq. 3
loss_ctm = lpips(resize(x_est, 224), resize(x_target, 224)).mean()
# 5. Calculate the DSM loss of g at s = t.
sigma = sample_dsm_sigmas(bs)
g, _ = jump(net, x_0 + sigma * torch.randn_like(x_0), sigma, sigma)
weight = (sigma ** 2 + sigma_data ** 2) / (sigma * sigma_data) ** 2 # EDM weighting
loss_dsm = (weight * (g - x_0).square()).flatten(1).mean(1).mean()
loss = loss_ctm + adaptive_weight(loss_ctm, loss_dsm, last_layer) * loss_dsm
# 6. Add the GAN loss of a two-jump sample after the warm-up.
if step >= gan_start:
x_fake = jump(net, G_ts, s, sigma_min)[1]
loss_gan = -torch.stack([logit.mean() for logit in disc(x_fake)]).mean()
loss = loss + adaptive_weight(loss_ctm, loss_gan, last_layer).clip(0.01, 10) * loss_gan
# 7. Update the EMA student.
net_ema = mu * net_ema + (1 - mu) * net # stop-gradient EMA
def train_disc(disc, x_0, x_fake):
loss_real = torch.stack([torch.relu(1 - logit).mean() for logit in disc(x_0)]).mean() # hinge loss
loss_fake = torch.stack([torch.relu(1 + logit).mean() for logit in disc(x_fake.detach())]).mean()
loss = loss_real + loss_fake
def sample(net, num_steps=1, gamma=0.0, sigma_min=0.002, sigma_max=80.0):
ts = karras_t(linspace(0, 1, num_steps + 1))
x = torch.randn(shape) * sigma_max
for i in range(num_steps):
s = sqrt(1 - gamma ** 2) * (ts[i + 1] - sigma_min) + sigma_min # Alg. 2
x = jump(net, x, ts[i], s)[1]
if i < num_steps - 1:
x = x + sqrt(ts[i + 1] ** 2 - s ** 2) * torch.randn_like(x) # Alg. 2
return xConsistency Models
OpenAI
International Conference on Machine Learning (ICML), 2023
Mar 02, 2023 Consistency Models (2,439) code (6.5K)
It opened the consistency route to one-step generation. Self-consistency is the training signal, and the teacher is optional. A large family of few-step models followed.
Learn the map from any ODE point to its origin, from a teacher or from scratch, so one network evaluation maps noise directly to data.
Insight. Few-step generation became a map to learn along the ODE, not a sampler to shorten. Most later few-step models change its rule.
The consistency function (§3, Eq. 5). The function maps each point of a PF-ODE trajectory on to its origin, so one call at gives a sample. With the network , , and the values , make the identity.
Time grid (§4). The grid divides into intervals at , , , .
Consistency distillation (§4, Eq. 6–7). With , one teacher step Eq. (6), with a Heun step on the teacher and , gives Eq. (7). is LPIPS, better than and , and .
EMA target (Eq. 8). with , for ImageNet-64 distillation. The target stabilizes training.
Consistency training (§5, Eq. 9–10). With the score estimate , Eq. (9) (Thm. 2). Thus Eq. (10) uses one shared for both levels and needs no diffusion model.
CT schedules (App. C). Step of : , , , , .
Multistep sampling (Alg. 1). Alternate the model with re-noise steps to lower levels from a ternary search.
Experiments (§6). On CIFAR-10 / ImageNet-64, one-step CD gets FID 3.55 / 6.20, better than progressive distillation. CT gets 8.70.
The metric gives part of the lead (§6.2). With LPIPS in place of , progressive distillation also improves at every number of steps.
The training and sampling code. Follow Algorithm 1, 2 and 3 of the paper.
def karras_sigmas(n, num_scales, sigma_min=0.002, sigma_max=80.0, rho=7.0):
return (sigma_max ** (1 / rho) + n / (num_scales - 1) * (sigma_min ** (1 / rho) - sigma_max ** (1 / rho))) ** rho
def ct_schedule(step, total_steps=800000, start_ema=0.95, start_scales=2, end_scales=200):
scales = ceil(sqrt(step / total_steps * ((end_scales + 1) ** 2 - start_scales ** 2) + start_scales ** 2) - 1)
scales = max(scales, 1)
mu = exp(start_scales * log(start_ema) / scales) # EMA rate rises with N
return scales + 1, mu
def f(net, x_t, sigma, sigma_min=0.002, sigma_data=0.5):
c_skip = sigma_data ** 2 / ((sigma - sigma_min) ** 2 + sigma_data ** 2)
c_out = (sigma - sigma_min) * sigma_data / (sigma ** 2 + sigma_data ** 2) ** 0.5
c_in = 1 / (sigma ** 2 + sigma_data ** 2) ** 0.5
return c_skip * x_t + c_out * net(c_in * x_t, 250 * log(sigma)) # Eq. 5, c_skip = 1 and c_out = 0 at sigma_min
def train(theta, theta_ema, teacher, x, step, distill=True, num_scales=40, mu=0.95):
# 1. Set N and the EMA rate. Consistency training increases both on a schedule.
if not distill:
num_scales, mu = ct_schedule(step)
# 2. Pick adjacent levels t > t2 of the N-level grid, and add noise to the image at level t.
n = torch.randint(0, num_scales - 1, (bs,))
t, t2 = karras_sigmas(n, num_scales), karras_sigmas(n + 1, num_scales)
noise = torch.randn_like(x)
x_t = x + t * noise
# 3. Map x_t with the student.
pred = f(theta, x_t, t) # dropout RNG state saved here
# 4. Take one ODE step to t2 and map it with the EMA target.
with no_grad():
if distill:
d = (x_t - teacher(x_t, t)) / t
x_t2 = x_t + (t2 - t) * d
d2 = (x_t2 - teacher(x_t2, t2)) / t2
x_t2 = x_t + (t2 - t) * (d + d2) / 2 # Eq. 6, Heun on the teacher
else:
x_t2 = x + t2 * noise # Euler on the score estimate lands here
target = f(theta_ema, x_t2, t2) # rerun under the student's dropout mask
# 5. Match the two outputs, then update the EMA target.
loss = lpips(resize(pred, 224), resize(target, 224)).mean() # Eq. 7, or Eq. 10 for CT
theta_ema = mu * theta_ema + (1 - mu) * theta # Eq. 8
def sample(theta, ts=(0, 22, 39), steps=40, sigma_min=0.002):
x = torch.randn(shape) * karras_sigmas(ts[0], steps)
for i in range(len(ts) - 1):
x_0 = f(theta, x, karras_sigmas(ts[i], steps))
t_next = karras_sigmas(ts[i + 1], steps)
x = x_0 + torch.randn_like(x) * sqrt(t_next ** 2 - sigma_min ** 2) # re-noise to the next level
return xFlow Matching for Generative Modeling
Meta AI (FAIR) · Weizmann Institute of Science
International Conference on Learning Representations (ICLR), 2023
Oct 06, 2022 Flow Matching (7,550) code (4.8K)
It made the probability path a free design choice, not a consequence of a diffusion process. Large image and video generators now train on its straight-line path.
A simulation-free objective trains continuous normalizing flows, and an optimal-transport path makes the trajectories straight by design.
Insight. Choose the probability path directly, not through a diffusion. The straight path it allowed became the default of large flow models.
Throughout, is noise and is data — the reverse of the diffusion convention.
Flow (§2, Eq. 1, 3). A field defines a flow Eq. (1) from noise to Eq. (3). Likelihood fits simulate it.
Flow Matching objective (§3, Eq. 5). , where generates a target path , and both are unknown.
Conditional Flow Matching (§3.1–3.2, Eq. 9). Per-example paths mix over the data into Eq. (6), and a posterior-weighted mix of their fields generates it Eq. (8). So has the gradient of (Thm. 2).
Gaussian paths (§4, Eq. 11). Eq. (11) moves standard noise to Eq. (10), with for a small . Its unique field is Eq. (15) (Thm. 3), in closed form.
Optimal-transport path (Eq. 20). With , , Eq. (22) is straight at constant speed.
The OT loss (§4.1, Eq. 23). Eq. (22) in Eq. (9) gives , , with a constant target.
Sampling (§6, Eq. 1). Integrate Eq. (1) from noise at to data at with dopri5 at absolute and relative tolerances of 1e-5.
Experiments (§6). On CIFAR-10 and ImageNet 32–128, FM-OT gets CIFAR-10 FID 6.35 at 142 NFE, and DDPM gets 7.48 at 274.
Same path, better target (Tab. 1). On the diffusion path, FM takes CIFAR-10 FID 19.94 → 8.06, so the target gives part of the gain.
The training and sampling code. Follow Section 4.1 and Equation 1 of the paper.
def train(model, x_1, sigma_min=0.0):
# 1. Sample a time and a noise point. Here t = 0 is noise and t = 1 is data.
t = torch.rand(bs)
x_0 = torch.randn_like(x_1)
# 2. Take the point on the optimal-transport conditional path.
mu, sigma = t * x_1, 1 - (1 - sigma_min) * t # Eq. 20
x_t = sigma * x_0 + mu # Eq. 11
# 3. Regress the conditional velocity.
u = x_1 - (1 - sigma_min) * x_0 # Eq. 21 evaluated at x_t
loss = (model(x_t, t) - u).square().mean() # Eq. 23
def sample(model, atol=1e-5, rtol=1e-5):
x_0 = torch.randn(shape)
return odeint(model, x_0, t=[0.0, 1.0], method="dopri5", atol=atol, rtol=rtol) # Eq. 1Flow Straight and Fast: Learning to Generate and Transfer Data with Rectified Flow
University of Texas at Austin
International Conference on Learning Representations (ICLR), 2023
Sep 07, 2022 Rectified Flow (4,625) code (1.7K)
It named the straight-line interpolant that most large flow models now train on. Reflow on the model's own pairs is a standard first step toward a one-step generator.
Learn an ODE that follows the straight line between two samples, then reflow on its own pairs until one Euler step is nearly enough.
Insight. Training can make a flow straight. The linear interpolant became the default path of today's large image and video flow models.
The rectified flow objective (§2.1, Eq. 1–2). For noise and data , moves with , which needs . Fit Eq. (1). Its minimizer Eq. (2) is the average of the lines through .
Marginals preserved (Thm. 3.3). ODE paths cannot cross, so reconnects crossings. is a coupling with .
Reflow (§2.1, Alg. 1). for independent pairs : simulate the flow with RK45, keep its pairs, refit on them.
Straightness (Eq. 3, Thm. 3.7). is zero when one Euler step is exact, and .
Distillation (§2.2). Fit to with Eq. (1) at . It copies the coupling, so it comes last, after the reflows.
Sampling (§5). Take Euler steps, , from noise at . After reflow or distillation, use one step.
Experiments (§5). On CIFAR-10, RK45 gets FID 2.58 (diffusion ODEs: 3.16 / 3.93). One distilled step gets 4.85 (prior best: 8.91).
Reflow helps one step, not many (Tab. 1a). Over 3 rectified flows, RK45 FID rises 2.58 → 3.96, and one-step FID falls 378 → 8.15.
The training and sampling code. Follow Algorithm 1 of the paper.
def sample_time(bs, distill=False, eps=1e-3):
t = torch.zeros(bs) if distill else torch.rand(bs) # distillation fixes t at the start
return t * (1 - eps) + eps
def train(model, x_0, x_1, distill=False):
# 1. Sample a time. Here t = 0 is noise and t = 1 is data.
t = sample_time(bs, distill)
# 2. Take a point on the straight line between the pair, and regress its direction.
x_t = t * x_1 + (1 - t) * x_0
loss = (model(x_t, t * 999) - (x_1 - x_0)).square().mean() # Eq. 1
def reflow(model, new_model, n, eps=1e-3):
z_0 = torch.randn(n, *shape)
z_1 = odeint(lambda t, z: model(z, t * 999), z_0, t=[eps, 1.0], method="rk45", rtol=1e-5, atol=1e-5)
for x_0, x_1 in batches(z_0, z_1): # the k-th flow's own coupling
train(new_model, x_0, x_1) # Alg. 1, reflow step
def sample(model, z, num_steps=1, eps=1e-3):
for i in range(num_steps):
t = full((bs,), i / num_steps * (1 - eps) + eps)
z = z + model(z, t * 999) / num_steps # Euler step
return zClassifier-Free Diffusion Guidance
Google Research, Brain Team
Workshop at Advances in Neural Information Processing Systems (NeurIPSW), 2021
Jul 26, 2022 CFG (7,713)
It removed the separate classifier from guidance. Nearly every text-to-image and text-to-video diffusion model now samples with its two-pass mix of predictions.
Train one network with condition dropout, then mix its conditional and unconditional predictions: guidance with no separate classifier.
Insight. The generator holds its own guidance signal: the gap between its two predictions. It became a default of conditional sampling.
Continuous-time diffusion (§2, Eq. 5). adds the noise to the data , with and Eq. (1), where is the log signal-to-noise ratio. The network with the condition , a class label here, trains with Eq. (5).
Noise levels (§2). for , where bound to : a hyperbolic secant density.
Sampler mean (§2, Eq. 3). Ancestral steps run up , at uniform , from . From to , the mean is Eq. (3): the forward posterior mean, with the prediction in place of the data .
Sampler variance (§2, Eq. 4). With the reverse variance and the forward variance , the step variance is , a log-space interpolation, with at 128×128, where keeps the reverse variance. The last step outputs .
Classifier guidance (§3.1). A classifier gives . The samples then follow : less diverse and more faithful to . It needs this second network, which trains on noisy for guidance.
Joint training (§3.2, Alg. 1). Training replaces by a null token with , so one network also gives .
Implicit classifier (§3.2). With exact scores, has . Classifier guidance with then gives . But the network difference is no classifier gradient in general, so the step is no attack on a classifier.
Classifier-free guidance (§3.2, Eq. 6). replaces at sampling, with two forward passes per step and for the best 128×128 FID. is the plain conditional model, and any sampler, DDIM too, can use the guided prediction.
Experiments (§4). On class-conditional ImageNet 128×128 with ADM's network, gets FID 2.43 (classifier-guided ADM-G: 2.97).
A little unconditional training is enough (§4.2). and 0.2 give the same IS–FID frontier, and 0.5 is worse everywhere on it.
Equal compute loses (§4.3). Two passes per step make 128 steps cost what ADM-G's 256 do, and the best FID is 3.02 (ADM-G: 2.97).
The training and sampling code. Follow Algorithm 1 and 2 of the paper.
def sample_log_snr(u, lambda_min=-20.0, lambda_max=20.0):
b = math.atan(math.exp(-lambda_max / 2))
a = math.atan(math.exp(-lambda_min / 2)) - b
return -2 * torch.log(torch.tan(a * u + b)) # bounded hyperbolic secant
def alpha_sigma(lam):
alpha2 = torch.sigmoid(lam) # Eq. 1
return alpha2.sqrt(), (1 - alpha2).sqrt()
def train(model, x, c, p_uncond=0.1):
# 1. Drop the condition with the probability p_uncond.
c = torch.where(torch.rand(bs) < p_uncond, null, c)
# 2. Sample a log SNR and corrupt the data.
lam = sample_log_snr(torch.rand(bs))
alpha, sigma = alpha_sigma(lam)
noise = torch.randn_like(x)
z = alpha * x + sigma * noise
# 3. Predict the noise.
loss = (model(z, lam, c) - noise).square().mean() # Eq. 5
def sample(model, c, w=0.3, num_steps=256, v=0.2):
lams = sample_log_snr(torch.linspace(1, 0, num_steps)) # increasing log SNR, uniform in u
z = torch.randn(shape)
for t in range(num_steps):
alpha, sigma = alpha_sigma(lams[t])
eps = (1 + w) * model(z, lams[t], c) - w * model(z, lams[t], null) # Eq. 6
x = (z - sigma * eps) / alpha
if t == num_steps - 1:
return x
# Take one ancestral step to the next log SNR.
alpha_next, sigma_next = alpha_sigma(lams[t + 1])
r = torch.exp(lams[t] - lams[t + 1]) # e^(lambda - lambda')
mean = r * (alpha_next / alpha) * z + (1 - r) * alpha_next * x # Eq. 3
var = ((1 - r) * sigma_next ** 2) ** (1 - v) * ((1 - r) * sigma ** 2) ** v # Eq. 4
z = mean + var.sqrt() * torch.randn_like(z)Elucidating the Design Space of Diffusion-Based Generative Models
NVIDIA
Advances in Neural Information Processing Systems (NeurIPS), 2022
Jun 01, 2022 EDM (4,188) code (2K)
It made a complex theory into a table of independent choices. Papers still state their design with its noise parameterization, Heun sampler and preconditioning.
A modular design space for diffusion: sampler, schedule, preconditioning and loss weighting become choices that change one at a time.
Insight. A split into independent choices is a contribution itself. Later work states its schedule, sampler and preconditioning in these terms.
Probability-flow ODE and denoiser (§2, Eq. 1–3). The ODE Eq. (1) needs only a score. A denoiser gives it as Eq. (3) and trains with Eq. (2) on images with noise . is the rate of the noise level .
Schedule (§3, Eq. 4). For the scale , , and one Euler step to gives the denoised image.
Heun sampler (§3, Alg. 1). With slopes at and at the Euler endpoint, . The last step is Euler.
Step discretization (§3, Eq. 5). with , , : steps are shorter near .
Stochastic sampler (§4, Alg. 2). Before each step, add new noise, scaled by slightly above 1, to raise the level to with inside . Then take a Heun step. The noise corrects earlier errors, and gives Alg. 1.
Preconditioning (§5, Eq. 7–8). The denoiser is Eq. (7) with the network , so the loss Eq. (8) regresses . give unit variance, minimizes to limit the network error, and .
Weighting and noise levels (§5). gives unit initial loss. aims where loss falls.
Non-leaking augmentation (§5). Augmentation parameters condition and are zero at sampling, so augmentations do not leak.
Experiments (§3, §5). On CIFAR-10 and ImageNet-64, the sampler takes ImageNet FID 2.07 → 1.55, and retraining gets 1.36.
The training and sampling code. Follow Algorithm 1 and 2 of the paper.
def karras_sigmas(num_steps=18, sigma_min=0.002, sigma_max=80, rho=7):
i = torch.arange(num_steps)
lo, hi = sigma_min ** (1 / rho), sigma_max ** (1 / rho)
t = (hi + i / (num_steps - 1) * (lo - hi)) ** rho # Eq. 5
return cat([t, zeros(1)]) # t_N = 0
def denoise(model, x, sigma, label, aug=None, sigma_data=0.5):
c_skip = sigma_data ** 2 / (sigma ** 2 + sigma_data ** 2)
c_out = sigma * sigma_data / (sigma ** 2 + sigma_data ** 2).sqrt()
c_in = 1 / (sigma ** 2 + sigma_data ** 2).sqrt()
return c_skip * x + c_out * model(c_in * x, sigma.log() / 4, label, aug) # Eq. 7
def train(model, x, label, p_mean=-1.2, p_std=1.2, sigma_data=0.5):
# 1. Draw one noise level per image from the log-normal distribution.
sigma = (torch.randn(bs) * p_std + p_mean).exp()
# 2. Add noise to an augmented image. Its augmentation parameters condition the network.
y, aug = augment(x) # aug is zero at sampling time
x_t = y + torch.randn_like(y) * sigma
# 3. Denoise through the preconditioning and weight the error by 1 / c_out^2.
weight = (sigma ** 2 + sigma_data ** 2) / (sigma * sigma_data) ** 2
loss = (weight * (denoise(model, x_t, sigma, label, aug) - y) ** 2).mean() # Eq. 8
def sample(model, label, num_steps=18, s_churn=0, s_tmin=0, s_tmax=float("inf"), s_noise=1):
t = karras_sigmas(num_steps)
x = torch.randn(shape) * t[0]
for i in range(num_steps):
gamma = min(s_churn / num_steps, sqrt(2) - 1) if s_tmin <= t[i] <= s_tmax else 0 # Alg. 2, 0 gives Alg. 1
t_hat = t[i] * (1 + gamma)
x_hat = x + (t_hat ** 2 - t[i] ** 2).sqrt() * s_noise * torch.randn_like(x)
d = (x_hat - denoise(model, x_hat, t_hat, label)) / t_hat # Eq. 4 with sigma(t) = t
x = x_hat + (t[i + 1] - t_hat) * d # Euler step
if i < num_steps - 1:
d_next = (x - denoise(model, x, t[i + 1], label)) / t[i + 1]
x = x_hat + (t[i + 1] - t_hat) * (d + d_next) / 2 # Heun correction
return xDenoising Diffusion Implicit Models
Stanford University
International Conference on Learning Representations (ICLR), 2021
Oct 06, 2020 DDIM (14,360) code (1.9K)
Its deterministic sampler cut diffusion sampling from a thousand steps to a few tens. Its inversion of images to noise is the base of most diffusion image editing.
Non-Markovian forward processes share DDPM's loss, so a trained DDPM model gets a deterministic sampler that is 10–50× faster.
Insight. Training fixes only the marginals, so the sampler can change after training. Fast ODE samplers and inversion came from this.
DDPM's loss (§2, Eq. 5). Here is the cumulative product that DDPM writes , so Eq. (4). DDPM trains the noise predictor with Eq. (5) at , the loss . DDIM reuses these models and changes only the sampler.
Marginals only (§3). depends only on the marginals , so every process with the same marginals has the same loss.
Non-Markovian forward process (§3.1, Eq. 7). A family , indexed by , keeps the marginals (Lemma 1) with . Each then depends on both and .
Same objective (§3.2, Thm. 1). The generative process Eq. (10) puts the predicted into Eq. (7). Its variational objective Eq. (11) equals for some and a constant (Thm. 1). So, if no weights are shared across , the trained model also minimizes every .
Sampling step (§4.1, Eq. 12). has three terms: (1) the predicted Eq. (9), (2) the direction that points back to , and (3) random noise of scale , with .
Noise scale (§5, Eq. 16). sets the noise. gives DDPM, whose is the posterior variance, and gives DDIM, an implicit model: a fixed procedure maps each to its sample. Values between 0 and 1 mix the two samplers.
Shorter trajectories (§4.2, App. D.2). A forward process on an increasing sub-sequence of of length keeps the same marginals, so the trained model samples in steps. The steps are (linear) for most data, or (quadratic) for CIFAR-10, with a constant .
ODE view (§4.3, Eq. 14). With and the ratio , Eq. (12) at is an Euler step of Eq. (14). It equals the probability-flow ODE of a variance-exploding SDE (Prop. 1), and, run backward, it encodes into a latent .
Experiments (§5). On CIFAR-10, CelebA and LSUN, with the same models, DDIM gets CIFAR-10 FID 4.67 in 50 steps (DDPM: 8.01).
The training and sampling code. Follow Section 4 and Appendix D.3 of the paper.
def linear_betas(num_steps=1000, beta_start=1e-4, beta_end=0.02):
return torch.linspace(beta_start, beta_end, num_steps)
def compute_alpha(betas, t):
alphas = cat([ones(1), torch.cumprod(1 - betas, dim=0)]) # alpha_0 = 1
return alphas[t + 1].view(-1, 1, 1, 1)
def train(model, x_0):
betas = linear_betas()
# 1. Sample the timesteps in antithetic pairs t and T - 1 - t.
t = torch.randint(0, len(betas), (bs // 2 + 1,))
t = cat([t, len(betas) - t - 1])[:bs]
# 2. Add the noise to the images in one step.
noise = torch.randn_like(x_0)
a = compute_alpha(betas, t)
x_t = a.sqrt() * x_0 + (1 - a).sqrt() * noise # Eq. 4
# 3. Predict the noise and calculate the squared error.
loss = (noise - model(x_t, t)).square().sum(dim=(1, 2, 3)).mean() # Eq. 5 with gamma = 1
def sample(model, num_steps=1000, eta=0.0):
betas = linear_betas()
T = len(betas)
seq = list(range(0, T, T // num_steps)) # linear sub-sequence tau
seq_next = [-1] + seq[:-1]
x = torch.randn(shape)
for i, j in zip(reversed(seq), reversed(seq_next)):
a_t, a_next = compute_alpha(betas, full((bs,), i)), compute_alpha(betas, full((bs,), j))
eps = model(x, full((bs,), i))
x_0 = (x - (1 - a_t).sqrt() * eps) / a_t.sqrt() # Eq. 9
sigma = eta * ((1 - a_t / a_next) * (1 - a_next) / (1 - a_t)).sqrt() # Eq. 16
x = a_next.sqrt() * x_0 + (1 - a_next - sigma ** 2).sqrt() * eps + sigma * torch.randn_like(x) # Eq. 12
return xDenoising Diffusion Probabilistic Models
UC Berkeley
Advances in Neural Information Processing Systems (NeurIPS), 2020
Jun 19, 2020 DDPM (37,492) code (5.4K)
It made diffusion a strong image generator, able to match GANs. Its noise-prediction loss, linear schedule and U-Net became the base of later diffusion models.
A network that predicts the added noise reverses a fixed Gaussian diffusion, and its samples match GANs on CIFAR-10 and LSUN.
Insight. A reweighted bound can beat the true bound on samples. Loss weighting became a design choice, and noise prediction a default.
Forward process (§2, Eq. 4). A fixed Markov chain adds noise: is Gaussian with mean and variance Eq. (2). With , one jump from the data gives Eq. (4), where is the standard Gaussian noise.
Reverse process and bound (§2, Eq. 5). The model is a chain of learned Gaussians Eq. (1) from . It trains on the variational bound Eq. (3), and Eq. (5) splits it into KL terms against the posterior .
Posterior (§2, Eq. 7). The posterior of the forward process is Gaussian, with and . So each KL term compares two Gaussians in closed form, with no high-variance Monte Carlo estimate.
Noise prediction (§3.2, Eq. 11). Expand Eq. (8) with Eq. (4), and let , where predicts the noise . Up to a constant, becomes Eq. (12), a denoising score matching over many noise levels.
Simplified loss (§3.4, Eq. 14). drops the weight of Eq. (12), with uniform in . Small get less weight, so the network spends its effort on harder, noisier inputs. CIFAR-10 FID is 3.17, against 13.51 for the true bound.
Schedule (§4). , with linear from to : the reverse steps stay near Gaussian, and is nearly the pure noise .
Sampling (§3.2, Alg. 2). From , with , and at . The variances stay untrained, in the code, because learned ones train unstably. The code takes from Eq. (7) at Eq. (15), clipped to .
Experiments (§4). On CIFAR-10 and LSUN, the FID is 3.17 on CIFAR-10 (StyleGAN2 + ADA: 3.26) and 4.90 on LSUN Bedroom.
The training and sampling code. Follow Algorithm 1 and 2 of the paper.
def linear_schedule(num_steps=1000, beta_start=1e-4, beta_end=0.02):
betas = torch.linspace(beta_start, beta_end, num_steps, dtype=torch.float64)
alphas_cumprod = torch.cumprod(1 - betas, dim=0) # alpha_bar_t
alphas_cumprod_prev = cat([ones(1), alphas_cumprod[:-1]]) # alpha_bar_{t-1}
return betas, alphas_cumprod, alphas_cumprod_prev
def train(model, x_0):
betas, alphas_cumprod, _ = linear_schedule()
# 1. Sample one timestep per image and the noise.
t = torch.randint(0, len(betas), (bs,))
noise = torch.randn_like(x_0)
# 2. Add the noise to the images in one step.
a_bar = alphas_cumprod[t].view(-1, 1, 1, 1)
x_t = a_bar.sqrt() * x_0 + (1 - a_bar).sqrt() * noise # Eq. 4
# 3. Predict the noise and calculate the unweighted squared error.
loss = (noise - model(x_t, t)).square().mean() # Eq. 14
def sample(model):
betas, alphas_cumprod, alphas_cumprod_prev = linear_schedule()
coef_x0 = betas * alphas_cumprod_prev.sqrt() / (1 - alphas_cumprod) # Eq. 7
coef_xt = (1 - alphas_cumprod_prev) * (1 - betas).sqrt() / (1 - alphas_cumprod) # Eq. 7
x = torch.randn(shape)
for i in reversed(range(len(betas))):
eps = model(x, full((bs,), i))
x_0 = (x - (1 - alphas_cumprod[i]).sqrt() * eps) / alphas_cumprod[i].sqrt() # Eq. 15
mean = coef_x0[i] * x_0.clamp(-1, 1) + coef_xt[i] * x # Eq. 11 when nothing is clipped
x = mean + betas[i].sqrt() * torch.randn_like(x) if i > 0 else mean # sigma_t^2 = beta_t
return xLast updated on November 04, 2026 · Citations from Semantic Scholar & Google Scholar; stars from GitHub, November 2026