Architectures & Paradigms

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 ▼

Attention & Transformer Variants

Scalable Diffusion Models with Transformers

William Peebles (9,078), Saining Xie (80,338)

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.

imagediffusionunread


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.

Figure 1. DiT block with adaLN-Zero (Fig. 3). The input tokens pass a layer norm, a scale and shift, self-attention and a scale, and then a residual addition. The same pattern wraps the pointwise feedforward. An MLP on the conditioning c gives γ1,β1,α1 and γ2,β2,α2.
  • Latent input (§3.1, §4). DiT works in the latent space of the Stable Diffusion VAE. A 256×256×3 image becomes z 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 p×p patch of the I×I×C input (I=32 at 256×256) becomes one token, so there are T=(I/p)2 tokens of width d with fixed sine-cosine position embeddings, for p∈{2,4,8}. Halving p at least quadruples the Gflops but keeps the parameter count.

  • adaLN-Zero block (§3.2). An MLP on c=temb+yemb regresses the shift β, scale γ and gate α: x←x+α1Attn((1+γ1)LN(x)+β1), 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 p=2, 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 p×p×2C: the noise and a learned diagonal covariance Σθ. Lsimple=‖ϵθ(xt)−ϵt‖22 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 ϵ^θ=ϵθ(xt,∅)+s(ϵθ(xt,c)−ϵθ(xt,∅)) on the first three of four latent channels only, with s=1.5 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).

Figure 2. FID against Gflops (Fig. 8). All twelve DiT models after 400K steps. Color gives the configuration from S to XL, and a darker, larger marker gives a smaller patch size. The dashed line is a linear fit with a correlation of −0.93.
  • 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)

Tokenization & Latent Spaces

High-Resolution Image Synthesis with Latent Diffusion Models

Robin Rombach (71,232), Andreas Blattmann (61,374), Dominik Lorenz (39,811), Patrick Esser (42,667), Björn Ommer (40,716)

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.

imagediffusionunread


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.

Figure 1. Latent diffusion (Fig. 3). Pixel space (red): the encoder ℰ maps x to z, and the decoder 𝒟 maps a latent back to x~. Latent space (green): the diffusion process and the denoising U-Net ϵθ. Conditioning (gray): τθ encodes y for cross-attention layers.
  • Perceptual compression (§3.1). An autoencoder maps x∈ℝH×W×3 to z=ℰ(x)∈ℝh×w×c with the factor f=H/h. An L1 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 10−6, 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 0.18215z, 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 f=4 model, with and without the rescaling.

  • Latent diffusion objective (§3.2, Eq. 2). LLDM=𝔼ℰ(x),ϵ~𝒩(0,1),t‖ϵ−ϵθ(zt,t)‖22 is the pixel objective Eq. (1) on the noised latent zt, with t uniform in {1,…,T}. 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 y to τθ(y)∈ℝM×dτ. U-Net layer i attends to it with softmax(QKT/d)V, Q=WQ(i)φi(zt), K=WK(i)τθ(y), V=WV(i)τθ(y), where φi(zt) is the flattened feature map of that layer and d is the width of Q and K.

  • Conditional objective (§3.3, Eq. 3). LLDM=𝔼ℰ(x),y,ϵ,t‖ϵ−ϵθ(zt,t,τθ(y))‖22 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 zt instead.

  • Experiments (§4). Factors f=4 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

Ali Razavi (7,212), Aaron van den Oord (48,328), Oriol Vinyals (294,027)

DeepMind

Advances in Neural Information Processing Systems (NeurIPS), 2019

Jun 02, 2019      VQ-VAE-2 (2,551)

imageautoregressiveunread


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.

Figure 1. Hierarchical VQ-VAE (Fig. 2). Left: training. The encoder maps a 256×256 image to a 64×64 bottom map and a 32×32 top map, and the decoder uses both. Right: generation. A PixelCNN samples the top codes, and a second one samples the bottom codes from them.
  • VQ-VAE objective (§2.1, Eq. 2). The encoder output E(x) becomes its nearest codebook vector e Eq. (1), and the loss is ‖x−D(e)‖22+‖sg[E(x)]−e‖22+β‖sg[e]−E(x)‖22, where D is the decoder, sg is the stop-gradient operator and β weights the last term.

  • EMA codebook (§2.1). Moving averages replace the codebook term: Ni←γNi+(1−γ)ni, mi←γmi+(1−γ)∑jE(x)i,j, ei=mi/Ni, with γ=0.99, where ni counts the batch vectors that map to ei. 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

Aaron van den Oord (48,328), Oriol Vinyals (294,027), Koray Kavukcuoglu (256,343)

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.

imageaudioautoregressiveunread


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.

Figure 1. VQ-VAE (Fig. 1, left). The encoder CNN gives ze(x), and each vector maps to the index of the nearest codebook vector. The decoder CNN reconstructs the image from zq(x). The red arrow is the gradient ∇zL, copied from the decoder input to the encoder.
  • Codebook and quantization (§3.1, Eq. 2). The codebook e∈ℝK×D holds K vectors of dimension D. Each encoder output vector becomes its nearest entry, zq(x)=ek, k=argminj‖ze(x)−ej‖2, so the posterior q(z∣x) is one-hot Eq. (1). ImageNet uses K=512 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: zq=ze+sg[zq−ze], where sg is the stop-gradient operator. It works because both vectors share one D-dimensional space.

  • Loss (§3.2, Eq. 3). L=logp(x∣zq(x))+‖sg[ze(x)]−e‖22+β‖ze(x)−sg[e]‖22 with β=0.25, and β from 0.1 to 2.0 gives the same results. Its terms (1) train the decoder and the encoder, (2) move e toward ze(x), and (3), the commitment loss, keep the encoder near its code.

  • Prior (§3.1, §3.3). Training keeps a uniform prior over the K codes, so the KL term is the constant logK 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])

Generative Modeling Paradigms

Improved Mean Flows: On the Challenges of Fastforward Generative Models

Zhengyang Geng (3,092), Yiyang Lu (474), Zongze Wu (3,031), Eli Shechtman (76,014), J. Zico Kolter (76,576), Kaiming He (893,639)

CMU · MIT · Adobe · THU

Conference on Computer Vision and Pattern Recognition (CVPR), 2026

Dec 01, 2025      iMF (142)      code (359)

✓ reviewedimageflow


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.

Figure 1. Inputs (Fig. 1). (a) MeanFlow's v-loss takes the latent z and the velocity e−x. (b) iMF's takes only z.
Figure 2. Loss (Fig. 3). MeanFlow's loss rises and varies. iMF's drops at once and stays flat.
  • MeanFlow's target (§3, Eq. 6–7). With noise e and data x, the average velocity u over [r,t], r≤t, and the instantaneous v satisfy u=v−(t−r)JVP(u;v) Eq. (4–5). MeanFlow fits utgt=(e−x)−(t−r)JVP(uθ;e−x) Eq. (6) by 𝔼‖uθ−sg(utgt)‖2 Eq. (7) (sg: stop-gradient).

  • An equivalent v-loss (§4.1, Eq. 9–10). Solve the identity for v, v=u+(t−r)du/dt Eq. (8), to get Vθ≜uθ+(t−r)JVPsg(uθ;e−x) Eq. (9), where JVPsg is its stop-gradient form. The loss 𝔼‖Vθ−(e−x)‖2 Eq. (10) is a v-loss re-parameterized by u-pred, equivalent to Eq. (6–7).

  • The illegitimate input (Eq. 11). In fact, Vθ is Vθ(zt,e−x). It uses the conditional velocity, which no regressor of zt may use.

  • Network-predicted tangent (Eq. 12). Vθ(zt)≜uθ(zt)+(t−r)JVPsg(uθ;vθ): both arguments are now network outputs of zt alone.

  • Two sources of vθ (§4.1). vθ uses the free boundary condition vθ(zt,t)≡uθ(zt,t,t) or an 8-layer v-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 c, vcfg(zt∣c)=ωv(zt∣c)+(1−ω)v(zt) Eq. (13), before training. iMF makes ω an input, Vθ(·∣c,ω)≜uθ(zt∣c,ω)+(t−r)JVPsg Eq. (15), with ω~p(ω)∝ω−β on [1,8] for a skew β.

  • The guided target (App. A, Eq. 17). vtgt=(e−x)+(1−1/ω)(uθ(zt∣t,t,c)−uθ(zt∣t,t,∅)) for the null class ∅. ω=1 is no guidance.

  • Guidance interval (§4.2). Ω={ω,tmin,tmax} with tmin~U[0,0.5] and tmax~U[0.5,1]. Outside it, ω=1, and the r=t rows span [0,1].

  • In-context conditioning (Eq. 16). uθ(zt∣r,t,c,Ω) 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) * u

Back to Basics: Let Denoising Generative Models Denoise

Tianhong Li (1,781), Kaiming He (893,639)

MIT

Conference on Computer Vision and Pattern Recognition (CVPR), 2026

Nov 17, 2025      JiT (361)      code (2.6K)

imagediffusionflowunread


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.

Figure 1. Two dimensions inside D (Fig. 2). A fixed random orthogonal projection puts a 2-D spiral into D dimensions, and a 5-layer MLP of width 256 learns it. Columns: the ground truth and the three prediction spaces. Rows: the dimensions D=2,8,16,512.
  • The manifold assumption (§3.3). Clean data lies near a low-dimensional manifold, but the noise ϵ and the velocity v do not. Thus a network that predicts x needs only the manifold coordinates. A network that predicts ϵ or v must keep all D=768 dimensions of a 16×16 patch.

  • Flow setup (§3.1, Eq. 1–2). zt=tx+(1−t)ϵ Eq. (1) moves noise ϵ to data x at t=1, and v=x−ϵ Eq. (2), with logit(t)~𝒩(−0.8,0.82).

  • x-prediction under the v-loss (§3.2, Eq. 5–6). Under Eq. (1–2), one output gives the others, vθ=(xθ−zt)/(1−t) Eq. (5). So the network predicts the image: ℒ=𝔼‖vθ(zt,t)−v‖2 with vθ(zt,t)=(netθ(zt,t)−zt)/(1−t), where 1−t 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 p×p×3 pixels, and a two-layer bottleneck d′<768 embeds each patch.

Figure 2. Bottleneck patch embedding (Fig. 4). The FID of JiT-B/16 over the inner dimension of the two-layer embedding. Dashed: the single-layer embedding of the full raw patch.
  • Sampling (§3.1, Eq. 4). Take 50 Heun steps on a linear t in [0,1], with an Euler last step and guidance only on t∈[0.1,1].

  • 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.

Figure 3. Loss and denoised samples (Fig. 7). Top: the v-loss under v- and x-prediction at 256. Bottom: one-step denoised images from each model at five noise levels.
  • 512 beats 256 at scale (Tab. 6). JiT-G/32 at 512 gets 1.78, and JiT-G/16 at 256 gets only 1.82. The paper says it overfits less.

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 z

AlphaFlow: Understanding and Improving MeanFlow Models

Huijie Zhang (338), Aliaksandr Siarohin (6,773), Willi Menapace (2,748), Michael Vasilkovsky (480), Sergey Tulyakov (1,416), Qing Qu (338), Ivan Skorokhodov (2,626)

Snap Inc. · University of Michigan

International Conference on Learning Representations (ICLR), 2026

Oct 23, 2025      AlphaFlow (54)      code (131)

imageflowunread


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 uθ(zt,r,t) predicts the average velocity over [r,t] from the latent zt=(1−t)x+tϵ for the data x and the noise ϵ. MeanFlow fits ℒMF=𝔼‖uθ−vt+(t−r)duθ−/dt‖22, where vt=ϵ−x, θ− is the stop-gradient copy, and d/dt is one JVP call.

  • Loss decomposition (§3.1, Eq. 6). ℒMF=ℒTFM+ℒTC+C, where ℒTFM=𝔼‖uθ−vt‖22 is trajectory flow matching and ℒTC=𝔼[2(t−r)uθ⊤duθ−/dt] is trajectory consistency. Their gradients have a cosine below −0.4, so joint training is slow and unstable.

Figure 1. Gradient similarity (Fig. 3a). The cosine of ∇ℒTC with ∇ℒTFM (red) and with ∇ℒFM′ (purple), over 400K steps of MeanFlow. The bands show the 5–95% range.
  • Two timesteps (§3.2, Tab. 3). t and r<t come from lognorm(−0.4,1.0), and 50% of the pairs on XL/2 set r=t (B/2: 25%, MeanFlow: 75%). The plain flow matching loss ℒFM′ Eq. (7) is ℒTFM on the r=t slice, where ℒTC=0. So it lowers ℒTFM with less gradient conflict with ℒTC.

  • α-Flow loss (Def. 1, Eq. 8). ℒα=𝔼[α−1‖uθ(zt,r,t)−(αv~s,t+(1−α)uθ−(zs,r,s))‖22], where s=αr+(1−α)t and zs=zt−(t−s)v~s,t. α∈(0,1] is the consistency step ratio, the shift velocity is v~s,t=vt, and θ− is not an EMA copy. For α>0, one model call at s replaces the JVP call.

  • Unification (Thm. 1). With v~s,t=vt, α=1 gives ℒTFM. With v~s,t=uθ−(zt,s,t), α=1/2 gives twice the Shortcut loss. As α→0, ∇θℒα→∇θℒMF: expand uθ−(zs,r,s) to first order at s=t. Consistency training (CT) is the case r≡0 with a clean-data prediction.

Figure 2. Training trajectories (Fig. 4). Discrete CT, continuous CT, Shortcut, MeanFlow and α-Flow, in this order. The red arrow is the prediction, the black arrows are the target, and the blue arrow is the shift velocity. Green labels give α, and the gray curve is the trajectory.
  • Curriculum (§4.2). Training has three phases: (1) trajectory flow matching at α=1, (2) a transition that lowers α from 1 to 0, (3) MeanFlow fine-tuning at α=0 with the JVP target of Eq. (5). The first phase reaches the narrow ℒTFM manifold before the gradient conflict starts.

  • Schedule (Alg. 2). At iteration k, α=1−sigmoid(γ(k−(ks+ke)/2)/(ke−ks)) with γ=25, ks=600K, ke=1M of the 1.2M training steps on XL/2, where ks and ke are the start and the end of the transition. α is 1 above 1−η and 0 below η=5×10−3, the best fixed α (Tab. 5c).

  • Adaptive weight (§4.2, App. H.2). As α→0, ℒα→αℒMF, so the MeanFlow weight 1/(‖Δ‖22+c) for the error Δ becomes ω=α/(‖Δ‖22+c), c=10−3, with ω under the stop-gradient operator. On the r=t rows and in the MeanFlow phase, the numerator is 1 instead of α.

  • Guidance (§4.2, App. G). As in MeanFlow, v~s,t=wvt+κuθ−(zt,t,t∣c)+(1−w−κ)uθ−(zt,t,t∣∅) for the class c and the null class ∅, with the CFG scales w=0.2, κ=0.92 for t<0.75 on XL/2, with a 10% class dropout. uθ−(zt,t,t) is the model's own instantaneous velocity.

  • Sampling (§4.2, Alg. 3). One step is z0=z1−uθ(z1,0,1). For two steps, XL/2 uses consistency sampling: x^=z−tuθ(z,0,t), then z←(1−t′)x^+t′ϵ at t′=0.55. B/2 uses the ODE step z←z−(t−t′)uθ(z,t′,t). 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 α=0.005, 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 z

Mean Flows for One-step Generative Modeling

Zhengyang Geng (3,092), Mingyang Deng (1,773), Xingjian Bai (890), J. Zico Kolter (76,576), Kaiming He (893,639)

CMU · MIT

Advances in Neural Information Processing Systems (NeurIPS), 2025

May 19, 2025      MeanFlow (711)      code (622)

✓ reviewedimageflow


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). u(zt,r,t)≜(1/(t−r))∫rtv(zτ,τ)dτ: the displacement over [r,t], a field from v alone.

  • The MeanFlow identity (Eq. 6). Differentiate (t−r)u=∫rtv with respect to t to get u(zt,r,t)=v(zt,t)−(t−r)du/dt Eq. (6).

  • JVP (Eq. 8). du/dt=(dzt/dt)∂zu+(dr/dt)∂ru+(dt/dt)∂tu=v∂zu+∂tu is one Jacobian–vector product, with the tangent (v,0,1).

  • The objective (Eq. 9–11). ℒ(θ)=𝔼‖uθ(zt,r,t)−sg(utgt)‖22 with utgt=vt−(t−r)(vt∂zuθ+∂tuθ): stop-gradient avoids double backpropagation.

  • Sampling (§4.1, Eq. 12). zr=zt−(t−r)uθ(zt,r,t): the integral is the prediction, so z0=z1−uθ(z1,0,1) is one call. Few steps chain it.

  • Guidance inside the field (§4.2, Eq. 19). Define vcfg≜ωv(zt,t∣c)+(1−ω)v(zt,t) for the class c, so vtcfg=ωuθ(zt,t,t|c)+(1−ω)uθ(zt,t,t). A mixing scale κ gives another form, v~t≜ω(ϵ−x)+κuθ(zt,t,t∣c)+(1−ω−κ)uθ(zt,t,t), with ω and κ as the two CFG scales.

  • Adaptive loss weighting (§4.3, App. B.2, Tab. 1e). For the error Δ=uθ−utgt, the powered loss ‖Δ‖22γ equals the squared L2 loss under the weight w=1/(‖Δ‖22+c)p, p=1−γ, c=10−3, as sg(w)·‖Δ‖22. FID is 61.06 for p=1, 63.98 for Pseudo-Huber-like p=0.5, 79.75 for plain L2.

  • Two timesteps (§4.3, Tab. 1a/c/d). (r,t) come from lognorm(−0.4,1.0), t>r, and only 25% of pairs keep r≠t. The input is (t,t−r).

Figure 1. Instantaneous and average. The instantaneous v is the path's tangent. The average u uses the displacement across [r,t].
  • Experiments (§5). On ImageNet-256 with DiT B/2–XL/2, one-step FID is 3.43 (Shortcut: 10.60). Two steps get 2.20, like a 250-step DiT.

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

Kevin Frans (2,087), Danijar Hafner (18,764), Sergey Levine (296,999), Pieter Abbeel (291,303)

UC Berkeley

International Conference on Learning Representations (ICLR), 2025

Oct 16, 2024      Shortcut Models (482)      code (777)

imageflow


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.

Figure 1. Two objectives, one run. At d≈0, the target is the empirical velocity, as in flow matching (top). For larger d, two chained half-size shortcuts form the target (bottom).
Figure 2. Training (Alg. 1). The first k samples use the flow-matching target x1−x0 at d=0. The rest use two chained small steps under stop-gradient.
Figure 3. Why one naive step fails (Fig. 2). Left: random noise–data pairs force flow matching to the mean direction 𝔼[vt∣xt]. Right: fewer steps drift to the mean, and one step loses all modes.
Figure 4. Sampling (Alg. 2). M Euler steps of size 1/M each.
  • Flow matching (Eq. 1). xt=(1−t)x0+tx1 for noise x0 and data x1, with vt=x1−x0. Eq. (2) fits 𝔼[vt∣xt]: one step gives the mean.

  • Step-size conditioning (Eq. 3). The shortcut s(xt,t,d) gives the jump xt+d′=xt+s(xt,t,d)d. At d→0, it equals the flow velocity.

  • Self-consistency (§3, Eq. 4). One step equals two half steps, s(xt,t,2d)=s(xt,t,d)/2+s(xt+d′,t+d,d)/2, both from the EMA model.

  • Combined loss (Eq. 5, Alg. 1). ℒS=𝔼[‖sθ(xt,t,0)−(x1−x0)‖2+‖sθ(xt,t,2d)−starget‖2], with a stop-gradient starget on one row in 8.

  • Binary step grid (§3.1). M=128 units give eight lengths d∈(1/128,…,1). Each fits two of the next smaller one, and t is a multiple of d.

  • Sampling (Alg. 2). Start from noise at t=0 and apply x←x+sθ(x,t,d)d for M steps of d=1/M. One step uses d=1.

  • 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 x

Simplifying, Stabilizing and Scaling Continuous-Time Consistency Models

Cheng Lu (17,164), Yang Song (77,289)

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.

imagediffusiondistillationunread


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.

  • Continuous-time consistency (§2.2, Eq. 2). A consistency model fθ(xt,t) maps each trajectory point to its start, fθ(x,0)≡x. In continuous time, the gradient ∇θ𝔼[w(t)fθ⊤dfθ−/dt] has no solver error, for a weight w and a stop-gradient copy θ− of θ. But training is unstable.
Figure 1. Alg. 1. The recipe has TrigFlow noise, a rearranged, normalized tangent with warmup r, and the adaptive weight wϕ. Training (sCT) and distillation (sCD) differ only in the term dxt/dt.
  • TrigFlow (§3, Eq. 3, 5). For noise z~𝒩(0,σd2I) and the data standard deviation σd, xt=cos(t)x0+sin(t)z, t∈[0,π/2]. With the network Fθ, the PF-ODE is dxt/dt=σdFθ(xt/σd,cnoise(t)) Eq. (3), and the CM is a DDIM step, fθ(xt,t)=cos(t)xt−sin(t)σdFθ(xt/σd,cnoise(t)) Eq. (5).

  • The tangent (Eq. 6). dfθ−/dt=−cos(t)(σdFθ−−dxt/dt)−sin(t)(xt+σddFθ−/dt). dxt/dt is Eq. (3) in sCD, cos(t)z−sin(t)x0 in sCT.

  • Time conditioning (Eq. 7). cnoise(t)=t, positional embeddings and adaptive double normalization keep the term sin(t)∂tFθ− stable.

  • Tangent normalization and warmup (§4.2). g=cos(t)· Eq. (6) becomes g/(‖g‖+c), c=0.1. r=min(1,iters/10k) scales its sin(t) term.

  • Adaptive weighting (§4.2, Eq. 8). Eq. (2) becomes an MSE, because ∇θ𝔼[Fθ⊤y]=(1/2)∇θ𝔼‖Fθ−Fθ−+y‖2 for any y free of θ. As in EDM2, a learned weight wϕ balances the loss over times, ℒsCM=𝔼[ewϕ(t)/D‖Fθ−Fθ−−cos(t)dfθ−/dt‖22−wϕ(t)], where D is the data dimension.

  • Time proposal (§4.2, App. G). On ImageNet 512, t=arctan(eτ/σd), τ~𝒩(−0.8,1.62). The small mean keeps training near clean data.

  • JVP rearrangement (§5.1). To prevent FP16 overflow near t=0,π/2, the JVP takes (cos(t)sin(t)dxt/dt, cos(t)sin(t)σd) at (xt/σd,t).

  • Sampling and guidance (App. G). One step uses tmax=arctan(80/σd), two re-noise to t=1.1. The guidance scale s~𝒰[1,2] is an input.

Figure 2. Discrete and continuous time (Fig. 5c). 1-step FID of distilled CMs on ImageNet 512 over training, with N up to 4096 steps and with continuous time.
Figure 3. Recall and guidance (Fig. 7b). EDM2-M on ImageNet 512: the recall of VSD, of 2-step sCD and of the teacher model as the guidance scale increases.
  • 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 x

Pyramidal Flow Matching for Efficient Video Generative Modeling

Yang Jin (831), Zhicheng Sun (553), Ningyuan Li (423), Kun Xu (934), Kun Xu (934), Hao Jiang (574), Nan Zhuang (464), Quzhe Huang (1,309), Yang Song (564), Yadong Mu (842), Zhouchen Lin (782)

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)

videoflowautoregressiveunread


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). xt=tx1+(1−t)x0 from noise x0 to data x1 has the target u=x1−x0, for any end distributions.

  • Pyramidal flow (§3.2, Eq. 6). On the window [sk,ek], x^t=t′Down(xek,2k)+(1−t′)Up(Down(xsk,2k+1)) with t′=(t−sk)/(ek−sk), where Down and Up resize. Each stage goes from a pixelated, noisier start to a finer, cleaner end, and only the last of K=3 is at full resolution.

  • Stage endpoints (§3.2.1, Eq. 9–10). The two endpoints are Gaussians around the resized clean latent x1 Eq. (7–8) with one shared noise n: x^ek=ekDown(x1,2k)+(1−ek)n Eq. (9) and x^sk=skUp(Down(x1,2k+1))+(1−sk)n Eq. (10). Because sk<ek, the paths do not cross.

  • Unified loss (§3.2.1, Eq. 11). 𝔼k,t‖vt(x^t)−(x^ek−x^sk)‖2 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 n′~𝒩(0,Σ′) Eq. (14) with γ=−1/3 for the most decorrelation: x^sk=1+sk2Up(x^ek+1)+3(1−sk)2n′. Here ek+1=2sk/(1+sk), so time goes back a little.

Figure 1. Spatial pyramid (Fig. 2). Left: the stages of one trajectory, each from a pixelated, noisier x^sk to a cleaner, finer x^ek. Right: the jump, which upsamples and renoises with n′.
  • Temporal pyramid (§3.3, Eq. 16–17). Older frames enter at lower resolution, …→Down(xt′i−2,2k+1)→Down(xt′i−1,2k)→x^ti Eq. (16), where xi is the latent of frame i. They have noise t′~U[0,1/3] in training and none at inference Eq. (17), and tokens fall by up to 1/4K.
Figure 2. Temporal pyramid (Fig. 3). Left: each row is one pyramid stage of frame i, with its history i−1,i−2,… at resolutions that decrease with distance. Right: the position encoding, which extrapolates through the spatial pyramid and interpolates across the temporal pyramid.
  • 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.

Figure 3. Pyramid and full resolution (Fig. 7, right). COCO FID on 3K prompts over image training steps, for standard flow matching (dashed) and pyramidal flow matching (solid), all else equal.
  • Semantics are weak (Tab. 1–2). The semantic score, 69.62, beats only Open-Sora Plan v1.3. The paper blames coarse captions.

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

Keyu Tian (1,269), Yi Jiang (3,572), Zehuan Yuan (14,161), Bingyue Peng (3,250), Liwei Wang (1,269)

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.

imageautoregressiveunread


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.

Figure 1. Two training stages (Fig. 4). Left: a multi-scale VQ autoencoder turns an image into the token maps r1,…,rK. Right: the transformer predicts each map from the earlier maps, under a block-wise causal mask. The start token [S] carries the class.
  • Next-scale likelihood (§3.2, Eq. 6). The unit of the autoregression is a whole token map, p(r1,…,rK)=∏k=1Kp(rk∣r1,…,rk−1), where rk∈[V]hk×wk is the map at scale k. The model samples the hkwk tokens of rk in parallel, so an n×n map costs O(n4), not O(n6).

  • Multi-scale residual tokens (Alg. 1). Each scale quantizes the residual of f=E(im): rk=Q(interpolate(f,hk,wk)), f←f−ϕk(zk), where zk is lookup(Z,rk) upsampled to hK×wK. Q picks the nearest code Eq. (3) of one codebook Z with V=4096, shared by all scales.

  • Reconstruction (Alg. 2). The decoder D gets the sum of the scales, f^=∑kϕk(zk), and gives im^=D(f^). Each ϕk is ϕ(z)=0.5z+0.5conv3×3(z), and 4 such convolutions are shared over the scales. Without them, the upsampled zk 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 k+1 is f^ after k scales, downsampled to hk+1×wk+1. The class embedding is the start token, and a block-wise causal mask lets rk attend only to r≤k. 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 q,k are normalized to unit vectors. The shape follows the depth d, the number of layers: w=64d, h=d, dr=0.1·d/24, where dr is the drop-path rate, so N(d)=73728d3 Eq. (8).

  • Sampling (§5). The guidance on the logits grows with the scale, for the logits ℓc with the class and ℓu with the null class: ℓ=(1+s)ℓc−sℓu, s=1.5(k−1)/(K−1). Then top-900 and top-p 0.96 filtering keeps the likely tokens, and a KV cache replaces the mask at inference.

Figure 2. FID and speed (Fig. 3). FID on ImageNet 256 against the time for one image. The dashed line marks the 1.78 FID of the ImageNet validation set.
  • 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 L=(2.0·N)−0.23, where N 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

Yang Song (77,289), Prafulla Dhariwal (216,849)

OpenAI

International Conference on Learning Representations (ICLR), 2024

Oct 22, 2023      iCT (528)

imagediffusion


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 x, noise z~𝒩(0,I), adjacent levels of an N-level grid, the model fθ and a metric d, ℒCT=𝔼[λ(σi)d(fθ(x+σi+1z,σi+1),fθ−(x+σiz,σi))]. λ 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 N→∞ limit with θ−≠θ ignores the data, so the teacher uses μ=0.

  • Pseudo-Huber (§3.3, Eq. 8). d(x,y)=‖x−y‖22+c2−c with c=0.00054d for dimension d replaces LPIPS, whose features leak into FID.

  • Discretization and noise schedule (§3.4–3.5, Eq. 9–10). N(k)=min(s02⌊k/K′⌋,s1)+1 doubles from s0=10 to s1=1280 during training Eq. (9). The levels σi follow a discretized lognormal, with Pmean=−1.1, Pstd=2 Eq. (10). Each pair has the weight λ=1/(σi+1−σi).

Figure 1. Original and improved CT. Each design change, with the original CT on the left and its replacement on the right.
  • Experiments (§4). On CIFAR-10 / ImageNet-64, one step gets FID 2.83 / 4.02, and iCT-deep gets 2.51 / 3.25, better than distillation.

Latent Consistency Models: Synthesizing High-Resolution Images with Few-Step Inference

Simian Luo (1,967), Yiqin Tan (1,340), Longbo Huang (8,725), Jian Li (13,326), Hang Zhao (43,269)

Tsinghua University

arXiv, 2023

Oct 06, 2023      LCM (1,060)      code (4.6K)

imagediffusiondistillation


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 z with a prompt c, fθ(z,c,t)=cskip(t)z+cout(t)(z−σtϵ^θ(z,c,t))/αt, with the schedule αt,σt and cskip(0)=1, cout(0)=0. 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 ϵ~=(1+ω)ϵθ(zt,c,t)−ωϵθ(zt,∅,t) Eq. (12), so its solver step has two calls Eq. (15). The student takes the guidance scale ω~U[2,14] as an input through new parameters.

  • Skipping step (§4.3, Eq. 16). With zn=ztn, ℒCD=𝔼[d(fθ(zn+k,ω,c,tn+k),fθ−(z^n,ω,c,tn))] Eq. (16), where z^n=zn+k+(1+ω)Ψ(zn+k,tn+k,tn,c)−ωΨ(zn+k,tn+k,tn,∅) Eq. (17) and θ− is an EMA. k=20 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

Dongjun Kim (1,249), Chieh-Hsin Lai (2,052), Wei-Hsiang Liao (1,292), Naoki Murata (1,698), Yuhta Takida (1,694), Toshimitsu Uesaka (1,313), Yutong He (846), Yuki Mitsufuji (2,353), Stefano Ermon (154,775)

Sony AI · Stanford · CMU

International Conference on Learning Representations (ICLR), 2024

Oct 01, 2023      CTM (517)      code (326)

imagediffusiondistillationganunread


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.

Figure 1. Learning targets (Fig. 2). Score-based models learn the line s=t, and distillation learns the line s=0. CTM learns all the pairs s≤t.
Figure 2. Soft consistency (Fig. 3). From xt, the student jumps to s. For the target, the teacher ODE solver goes to u, and then the EMA student jumps to s.
  • PF ODE (§2, Eq. 1). With Gaussian noise ϵ, the noisy data is xt=x0+tϵ. A pretrained denoiser Dϕ defines dxt/dt=(xt−Dϕ(xt,t))/t.

  • Trajectory jump (§3.1). G(xt,t,s):=xt+∫ts(xu−𝔼[x|xu])/udu moves xt on the PF ODE to any s≤t, where 𝔼[x|xu] is the denoiser. CTM writes G=(s/t)xt+(1−s/t)g(xt,t,s), so g→𝔼[x|xt] as s→t: one network gives the jumps and the denoiser, which gives the score.

  • Neural jump (§3.1, §5.1). Gθ=(s/t)xt+(1−s/t)gθ with gθ(xt,t,s)=cskip(t)xt+cout(t)NNθ(xt,t,s), EDM's scalings, and a time embedding for s. So Gθ(xt,t,t)=xt needs no extra constraint. The teacher's weights start gθ(xt,t,t) near Dϕ, so training is 10–20 times faster.

  • Soft consistency (§3.2, Eq. 3). The teacher solves from t to u∈[s,t), then the student jumps to s: Gθ(xt,t,s)≈Gsg(θ)(Solver(xt,t,u;ϕ),u,s). sg(θ) is the stop-gradient EMA of θ with μ=0.999. With u=t−Δt and s=0, 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: xest=Gsg(θ)(Gθ(xt,t,s),s,0) and xtarget=Gsg(θ)(Gsg(θ)(Solver(xt,t,u;ϕ),u,s),s,0). Then ℒCTM=𝔼[d(xtarget,xest)], where d is LPIPS, a feature distance on clean images.

  • Timesteps (App. D.1). t>u≥s lie on an EDM grid with N=40. The teacher takes k Heun steps from t to u, with k≤20 and p(k)∝k.

  • DSM loss (§3.3). ℒDSM=𝔼‖x0−gθ(xt,t,t)‖22 trains the denoiser at s=t, where the factor 1−s/t gives gθ almost no gradient. Half of the times come from lognormal(−1.2,1.2), and half come from the high noise of the grid, so the network keeps a good denoiser at large t.

  • GAN loss (§3.3). A discriminator dη compares the generated and the real images by ℒGAN=𝔼[logdη(x0)]+𝔼[log(1−dη(xest))]. 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). λDSM=‖∇θLℒCTM‖/‖∇θLℒDSM‖, and λGAN has the same form, where θL is the last layer. They balance the gradient scales of the losses, and the objective is minθmaxηℒCTM+λDSMℒDSM+λGANℒGAN. The released code clips λGAN to [0.01,10].

  • γ-sampling (§4, Alg. 2). Each step jumps from tn to t~n+1=1−γ2tn+1 and adds the noise γtn+1ϵ. γ=1 is the CM sampler: all jumps end at time 0, so their errors add up (Thm. 1). γ=0 is deterministic and adds no noise, and 0<γ<1 generalizes the stochastic sampler of EDM.

Figure 3. FID against steps on CIFAR-10 (Fig. 7a). With γ=1, the FID rises as the number of steps grows. With γ=0, it falls toward the FID of a Heun solver that uses the CTM score.
  • 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 gθ(xt,t,t) 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 x

Consistency Models

Yang Song (77,289), Prafulla Dhariwal (216,849), Mark Chen (152,235), Ilya Sutskever (861,285)

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.

imagediffusiondistillation


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.

Figure 1. The object to learn. Each point of a probability-flow ODE trajectory maps to the origin xϵ of the trajectory. One output per trajectory is the training signal and the source of the name.
  • The consistency function (§3, Eq. 5). The function f(xt,t)↦xϵ maps each point of a PF-ODE trajectory on [ϵ,T] to its origin, so one call at xT gives a sample. With the network Fθ, fθ(x,t)=cskip(t)x+cout(t)Fθ(x,t), and the values cskip(ϵ)=1, cout(ϵ)=0 make f(·,ϵ) the identity.

  • Time grid (§4). The grid divides [ϵ,T] into N−1 intervals at ti=(ϵ1/ρ+(i−1)/(N−1)·(T1/ρ−ϵ1/ρ))ρ, ρ=7, ϵ=0.002, T=80.

  • Consistency distillation (§4, Eq. 6–7). With xn=xtn, one teacher step x^n=xn+1+(tn−tn+1)Φ(xn+1,tn+1;ϕ) Eq. (6), with a Heun step Φ on the teacher ϕ and n~U[1,N−1], gives ℒCD=𝔼[λ(tn)d(fθ(xn+1,tn+1),fθ−(x^n,tn))] Eq. (7). d is LPIPS, better than ℓ1 and ℓ2, and λ≡1.

  • EMA target (Eq. 8). θ−←stopgrad(μθ−+(1−μ)θ) with μ=0.95, N=40 for ImageNet-64 distillation. The target fθ− stabilizes training.

  • Consistency training (§5, Eq. 9–10). With the score estimate −(xt−x)/t2, ℒCD=ℒCT+o(Δt) Eq. (9) (Thm. 2). Thus ℒCT=𝔼[λ(tn)d(fθ(x+tn+1z,tn+1),fθ−(x+tnz,tn))] Eq. (10) uses one shared z~𝒩(0,I) for both levels and needs no diffusion model.

  • CT schedules (App. C). Step k of K: N(k)=⌈k/K·((s1+1)2−s02)+s02−1⌉+1, μ(k)=exp(s0logμ0/N(k)), s0=2, s1=200, μ0=0.95.

  • Multistep sampling (Alg. 1). Alternate the model with re-noise steps x^τn=x+τn2−ϵ2z to lower levels τn from a ternary search.

Figure 2. Sampling as alternation (Alg. 1). One evaluation at x^T is already a sample. Each pass adds noise to a lower τn and maps again.
Figure 3. The two algorithms (Alg. 2, 3). Left: distillation gets its pairs from one teacher ODE step. Right: training makes its pairs from one data and noise sample, without a teacher.
Figure 4. The two algorithms, redrawn. Gray is shared. Yellow differs: a teacher ODE step Φ (top) or x,z noised to tn (bottom).
  • 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 ℓ2, 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 x

Flow Matching for Generative Modeling

Yaron Lipman (27,809), Ricky T. Q. Chen (13,300), Heli Ben-Hamu (10,375), Maximilian Nickel (19,706), Matt Le (544)

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.

imageflowunread


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, t=0 is noise and t=1 is data — the reverse of the diffusion convention.

  • Flow (§2, Eq. 1, 3). A field vt defines a flow ddtϕt(x)=vt(ϕt(x)) Eq. (1) from noise p0 to pt=[ϕt]*p0 Eq. (3). Likelihood fits simulate it.

  • Flow Matching objective (§3, Eq. 5). ℒFM(θ)=𝔼t,pt(x)‖vt(x)−ut(x)‖2, where ut generates a target path pt, and both are unknown.

  • Conditional Flow Matching (§3.1–3.2, Eq. 9). Per-example paths pt(x|x1) mix over the data x1~q into pt Eq. (6), and a posterior-weighted mix of their fields ut(x|x1) generates it Eq. (8). So ℒCFM(θ)=𝔼t,q(x1),pt(x|x1)‖vt(x)−ut(x|x1)‖2 has the gradient of ℒFM (Thm. 2).

  • Gaussian paths (§4, Eq. 11). ψt(x)=σt(x1)x+μt(x1) Eq. (11) moves standard noise to pt(x|x1)=𝒩(μt(x1),σt(x1)2I) Eq. (10), with μ0=0,σ0=1,μ1=x1,σ1=σmin for a small σmin. Its unique field is ut(x|x1)=(σt′/σt)(x−μt)+μt′ Eq. (15) (Thm. 3), in closed form.

  • Optimal-transport path (Eq. 20). With μt=tx1, σt=1−(1−σmin)t, ψt(x)=(1−(1−σmin)t)x+tx1 Eq. (22) is straight at constant speed.

  • The OT loss (§4.1, Eq. 23). Eq. (22) in Eq. (9) gives 𝔼t,q(x1),p(x0)‖vt(ψt(x0))−(x1−(1−σmin)x0)‖2, t~U[0,1], with a constant target.

  • Sampling (§6, Eq. 1). Integrate Eq. (1) from noise at t=0 to data at t=1 with dopri5 at absolute and relative tolerances of 1e-5.

Figure 1. Conditional field and conditional score (Fig. 2). The arrows show direction, and the color shows magnitude: blue is large, red is small. Left: the prior p0 and one data point x1. Next four: the score of the diffusion path as t increases. Last four: the velocity of the OT path.
Figure 2. Sampling paths (Fig. 3). Six trajectories from the same six start points, with the diffusion field (left) and the OT field (right).
  • 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. 1

Flow Straight and Fast: Learning to Generate and Transfer Data with Rectified Flow

Xingchao Liu (22,177), Chengyue Gong (7,146), Qiang Liu (6,577)

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.

imageflowdistillationunread


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.

Figure 1. Rectification of a crossing coupling (Fig. 2). (1) Linear interpolations of independent pairs cross. (2) The rectified flow keeps the marginals but reconnects the paths at the crossing (inset). (3) Straight lines join the rectified endpoints. (4) They induce a new flow.
  • The rectified flow objective (§2.1, Eq. 1–2). For noise X0 and data X1, Xt=tX1+(1−t)X0 moves with X1−X0, which needs X1. Fit minv∫01𝔼‖(X1−X0)−v(Xt,t)‖2dt Eq. (1). Its minimizer vX(x,t)=𝔼[X1−X0∣Xt=x] Eq. (2) is the average of the lines through x.

  • Marginals preserved (Thm. 3.3). ODE paths cannot cross, so Z reconnects crossings. (Z0,Z1) is a coupling with Law(Zt)=Law(Xt).

  • Reflow (§2.1, Alg. 1). Zk+1=RectFlow((Z0k,Z1k)) for independent pairs Z0: simulate the flow with RK45, keep its pairs, refit on them.

  • Straightness (Eq. 3, Thm. 3.7). S(Z)=∫01𝔼‖(Z1−Z0)−Z˙t‖2dt is zero when one Euler step is exact, and mink≤KS(Zk)≤𝔼‖X1−X0‖2/K.

  • Distillation (§2.2). Fit T^(z0)=z0+v(z0,0) to (Z0k,Z1k) with Eq. (1) at t=0. It copies the coupling, so it comes last, after the reflows.

  • Sampling (§5). Take N Euler steps, Z^t+1/N=Z^t+v(Z^t,t)/N, from noise at t=0. 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 z

Classifier-Free Diffusion Guidance

Jonathan Ho (108,336), Tim Salimans (133,463)

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.

imagediffusionunread


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). zλ=αλx+σλϵ adds the noise ϵ~𝒩(0,I) to the data x, with αλ2=1/(1+e−λ) and σλ2=1−αλ2 Eq. (1), where λ is the log signal-to-noise ratio. The network ϵθ(zλ,c) with the condition c, a class label here, trains with 𝔼‖ϵθ(zλ,c)−ϵ‖2 Eq. (5).

  • Noise levels (§2). λ=−2logtan(au+b) for u~U[0,1], where a,b bound λ to [λmin,λmax]=[−20,20]: a hyperbolic secant density.

  • Sampler mean (§2, Eq. 3). Ancestral steps run up λmin=λ1<…<λT=λmax, at uniform u, from zλ1~𝒩(0,I). From zλ to λ′, the mean is eλ−λ′(αλ′/αλ)zλ+(1−eλ−λ′)αλ′xθ Eq. (3): the forward posterior mean, with the prediction xθ=(zλ−σλϵθ)/αλ in place of the data x.

  • Sampler variance (§2, Eq. 4). With the reverse variance s~=(1−eλ−λ′)σλ′2 and the forward variance s=(1−eλ−λ′)σλ2, the step variance is s~1−vsv, a log-space interpolation, with v=0.2 at 128×128, where v=0 keeps the reverse variance. The last step outputs xθ(zλmax).

  • Classifier guidance (§3.1). A classifier pθ(c∣zλ) gives ϵ~θ=ϵθ(zλ,c)−wσλ∇zλlogpθ(c∣zλ). The samples then follow p~θ(zλ∣c)∝pθ(zλ∣c)pθ(c∣zλ)w: less diverse and more faithful to c. It needs this second network, which trains on noisy zλ for guidance.

Figure 1. Guidance on three Gaussians (Fig. 2). One Gaussian per class. Left: the unguided marginal. Right: three normalized, guided class densities, with more guidance to the right.
  • Joint training (§3.2, Alg. 1). Training replaces c by a null token ∅ with puncond=0.1, so one network also gives ϵθ(zλ)=ϵθ(zλ,∅).

  • Implicit classifier (§3.2). With exact scores, pi(c∣zλ)∝p(zλ∣c)/p(zλ) has ∇zλlogpi=−(ϵ*(zλ,c)−ϵ*(zλ))/σλ. Classifier guidance with pi then gives (1+w)ϵ*(zλ,c)−wϵ*(zλ). 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). ϵ~θ(zλ,c)=(1+w)ϵθ(zλ,c)−wϵθ(zλ) replaces ϵθ at sampling, with two forward passes per step and w=0.3 for the best 128×128 FID. w=0 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, w=0.3 gets FID 2.43 (classifier-guided ADM-G: 2.97).

  • A little unconditional training is enough (§4.2). puncond=0.1 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

Tero Karras (53,938), Miika Aittala (30,617), Timo Aila (78,397), Samuli Laine (72,836)

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.

imagediffusionunread


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.

Figure 1. ODE curvature in 1D (Fig. 3). Trajectories for data of two Dirac peaks at x=±1: (a) the variance-preserving ODE, (b) the variance-exploding ODE, (c) σ(t)=t. Insets show the data area, and black arrows show local gradients. Each panel has its own range of t.
  • Probability-flow ODE and denoiser (§2, Eq. 1–3). The ODE dx=−σ˙σ∇xlogp(x;σ)dt Eq. (1) needs only a score. A denoiser D gives it as (D−x)/σ2 Eq. (3) and trains with 𝔼‖D(y+n;σ)−y‖2 Eq. (2) on images y with noise n~𝒩(0,σ2I). σ˙ is the rate of the noise level σ(t).

  • Schedule σ(t)=t (§3, Eq. 4). For the scale s(t)=1, dx/dt=(x−D(x;t))/t, and one Euler step to t=0 gives the denoised image.

  • Heun sampler (§3, Alg. 1). With slopes di at ti and di′ at the Euler endpoint, xi+1=xi+(ti+1−ti)(di+di′)/2. The last step is Euler.

  • Step discretization (§3, Eq. 5). σi<N=(σmax1/ρ+iN−1(σmin1/ρ−σmax1/ρ))ρ with σmin=0.002, σmax=80, ρ=7: steps are shorter near σmin.

  • Stochastic sampler (§4, Alg. 2). Before each step, add new noise, scaled by Snoise slightly above 1, to raise the level to t^i=ti+γiti with γi=min(Schurn/N,2−1) inside [Stmin,Stmax]. Then take a Heun step. The noise corrects earlier errors, and Schurn=0 gives Alg. 1.

  • Preconditioning (§5, Eq. 7–8). The denoiser is Dθ(x;σ)=cskipx+coutFθ(cinx;cnoise) Eq. (7) with the network Fθ, so the loss Eq. (8) regresses (y−cskipx)/cout. cin,cout give unit variance, cskip=σdata2/(σ2+σdata2) minimizes cout to limit the network error, and cnoise=ln(σ)/4.

Figure 2. Loss per noise level (Fig. 5a). Green: right after initialization, flat at 1. Blue and orange: the trained 32×32 and 64×64 models. Dashed red: the log-normal training distribution ptrain, mean −1.2, std 1.2.
  • Weighting and noise levels (§5). λ(σ)=1/cout2=(σ2+σdata2)/(σσdata)2 gives unit initial loss. lnσ~𝒩(−1.2,1.22) aims where loss falls.

  • Non-leaking augmentation (§5). Augmentation parameters condition Fθ 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.

Figure 3. Churn and FID (Fig. 5b–c). FID over stochasticity at 256 steps, original and retrained: CIFAR-10 (left), ImageNet-64 (right).
  • Better models need less churn (Fig. 5). On CIFAR-10, churn helps old models and hurts retrained ones. ImageNet-64 still needs it.

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 x

Denoising Diffusion Implicit Models

Jiaming Song (24,375), Chenlin Meng (31,029), Stefano Ermon (154,775)

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.

imagediffusionunread


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 αt is the cumulative product that DDPM writes α¯t, so xt=αtx0+1−αtϵ Eq. (4). DDPM trains the noise predictor ϵθ with Lγ=∑tγt𝔼‖ϵθ(t)(xt)−ϵt‖2 Eq. (5) at γ=1, the loss L1. DDIM reuses these models and changes only the sampler.

  • Marginals only (§3). Lγ depends only on the marginals q(xt∣x0), so every process with the same marginals has the same loss.

  • Non-Markovian forward process (§3.1, Eq. 7). A family qσ, indexed by σ∈ℝ≥0T, keeps the marginals (Lemma 1) with qσ(xt−1∣xt,x0)=𝒩(αt−1x0+1−αt−1−σt2(xt−αtx0)/1−αt,σt2I). Each xt then depends on both xt−1 and x0.

  • Same objective (§3.2, Thm. 1). The generative process Eq. (10) puts the predicted x0 into Eq. (7). Its variational objective Jσ Eq. (11) equals Lγ+C for some γ and a constant C (Thm. 1). So, if no weights are shared across t, the trained L1 model also minimizes every Jσ.

  • Sampling step (§4.1, Eq. 12). xt−1=αt−1x^0+1−αt−1−σt2ϵθ(t)(xt)+σtϵt has three terms: (1) the predicted x^0=(xt−1−αtϵθ(t)(xt))/αt Eq. (9), (2) the direction that points back to xt, and (3) random noise of scale σt, with ϵt~𝒩(0,I).

  • Noise scale (§5, Eq. 16). σt(η)=η(1−αt−1)(1−αt/αt−1)/(1−αt) sets the noise. η=1 gives DDPM, whose σt2 is the posterior variance, and η=0 gives DDIM, an implicit model: a fixed procedure maps each xT 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 [1,…,T] of length S keeps the same marginals, so the trained model samples in S steps. The steps are τi=⌊ci⌋ (linear) for most data, or ⌊ci2⌋ (quadratic) for CIFAR-10, with a constant c.

  • ODE view (§4.3, Eq. 14). With x¯=x/α and the ratio σ=(1−α)/α, Eq. (12) at σt=0 is an Euler step of dx¯(t)=ϵθ(t)(x¯/σ2+1)dσ(t) Eq. (14). It equals the probability-flow ODE of a variance-exploding SDE (Prop. 1), and, run backward, it encodes x0 into a latent xT.

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

Figure 1. FID over steps and noise (Tab. 1). Rows: η=0 (DDIM) to 1 (DDPM), and DDPM's larger variance σ^. Columns: the steps S.
  • At 1000 steps, DDPM still wins (Tab. 1). With σ^, DDPM gets CIFAR-10 FID 3.17, and DDIM gets 4.04. But σ^ fails on short trajectories.

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 x

Denoising Diffusion Probabilistic Models

Jonathan Ho (108,336), Ajay Jain (39,673), Pieter Abbeel (291,303)

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.

imagediffusionunread


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: q(xt∣xt−1) is Gaussian with mean αtxt−1 and variance βt=1−αt Eq. (2). With α¯t=α1⋯αt, one jump from the data gives xt=α¯tx0+1−α¯tϵ Eq. (4), where ϵ~𝒩(0,I) is the standard Gaussian noise.

  • Reverse process and bound (§2, Eq. 5). The model is a chain of learned Gaussians pθ(xt−1∣xt)=𝒩(μθ(xt,t),Σθ(xt,t)) Eq. (1) from p(xT)=𝒩(0,I). It trains on the variational bound Eq. (3), and Eq. (5) splits it into KL terms Lt−1 against the posterior q(xt−1∣xt,x0).

  • Posterior (§2, Eq. 7). The posterior of the forward process is Gaussian, 𝒩(μ~t,β~tI) with μ~t=α¯t−1βtx0/(1−α¯t)+αt(1−α¯t−1)xt/(1−α¯t) and β~t=(1−α¯t−1)βt/(1−α¯t). So each KL term compares two Gaussians in closed form, with no high-variance Monte Carlo estimate.

  • Noise prediction (§3.2, Eq. 11). Expand Lt−1 Eq. (8) with Eq. (4), and let μθ(xt,t)=(xt−βtϵθ(xt,t)/1−α¯t)/αt, where ϵθ predicts the noise ϵ. Up to a constant, Lt−1 becomes 𝔼βt2‖ϵ−ϵθ‖2/(2σt2αt(1−α¯t)) Eq. (12), a denoising score matching over many noise levels.

  • Simplified loss (§3.4, Eq. 14). Lsimple=𝔼t,x0,ϵ‖ϵ−ϵθ(α¯tx0+1−α¯tϵ,t)‖2 drops the weight of Eq. (12), with t uniform in {1,…,T}. Small t 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). T=1000, with βt linear from 10−4 to 0.02: the reverse steps stay near Gaussian, and xT is nearly the pure noise 𝒩(0,I).

  • Sampling (§3.2, Alg. 2). From xT~𝒩(0,I), xt−1=μθ(xt,t)+σtz with z~𝒩(0,I), and z=0 at t=1. The variances stay untrained, σt2=βt in the code, because learned ones train unstably. The code takes μθ from Eq. (7) at x^0=(xt−1−α¯tϵθ)/α¯t Eq. (15), clipped to [−1,1].

  • 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.

Figure 1. Rate and distortion on CIFAR-10 (Fig. 5, right). The RMSE of the estimate x^0 on a 0–255 scale, over the bits that the reverse steps send. Each point is one step.
  • Most bits code invisible detail (§4.3). Of the 3.75 bits per dimension, 1.97 code distortions of only RMSE 0.95 on a 0–255 scale.

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 x

Last updated on November 04, 2026  ·  Citations from Semantic Scholar & Google Scholar; stars from GitHub, November 2026