Generative Models: VAE, Diffusion, and Flow Matching

Generative models (Generative Models) are a type of machine learning model that learns data distribution and can generate new samples from it.

Unlike discriminative tasks such as classification and regression, generative models usually hope to learn the statistical structure of the data so that the generated results have similar characteristics to real data.

Common applications include:

  • Image Generation: Image generation.
  • Video Generation: Video generation.
  • Audio Generation: Speech and audio generation.
  • Image Editing: Image editing.
  • Data Synthesis: synthetic data.
  • Representation Learning: Indicates learning.

There are several important technical routes in modern generative AI:

methodcore ideaMain positioning
VAELearning probabilistic latent variables and decoding processRepresentation learning, latent space modeling
GANTraining via generator versus discriminator adversarialClassic generation method, still valuable in specific scenarios
DiffusionLearning to progressively recover data from noiseImportant methods for modern image and video generation
Flow MatchingLearning a continuous velocity field that connects the noise distribution to the data distributionImportant training methods for modern generative models
Autoregressive ModelsPredict the next element step by step based on existing contentLLM、Token-based Generation

This article focuses on VAE, Diffusion, and Flow Matching. Autoregressive Transformer has already been discussed in relation to LLM, so it will not be repeated.

1. Generative Modeling: Basic concepts

Assume that the real data comes from some unknown distribution:

x∼pdata(x)x\sim p_{\text{data}}(x)

Generative models want to learn a distribution:

pθ(x)≈pdata(x)p_\theta(x)\approx p_{\text{data}}(x)

Among them:

  • xx: Sample, such as picture or audio.
  • p_datap\_{\text{data}}: Real data distribution.
  • p_θp\_\theta: Distribution learned by the model.
  • θ\theta: model parameters.

After training is completed, new data can be generated by sampling from the model.

Conditional Generation

In addition to unconditional generation, conditions can also be added:

pθ(x∣c)p_\theta(x\mid c)

where cc can be:

  • Text Prompt。
  • Class Label。
  • Reference Image。
  • Audio。
  • Spatial Information。

For example:

Text Prompt
     ↓
Generative Model
     ↓
Generated Image

Modern Text-to-Image and Text-to-Video systems are generally Conditional Generative Models.

Sampling

Sampling (sampling) is an important concept in generative models.

The training phase learns the data distribution or generation process.

The inference phase starts with random noise or latent variables and uses the learned mapping to generate samples.

The main differences between different generative models are:

How represents data distribution and how to convert random variables into real data.

2. Latent Space: latent space

Latent Space (latent space) is a very important concept in generative models.

For a picture:

x∈R3×512×512x\in\mathbb R^{3\times512\times512}

Performing complex calculations directly in pixel space may require high memory and computational costs.

Therefore, the data can be mapped via Encoder to a more compact Latent Representation:

z=Encoder(x)z=Encoder(x)

Then restore via Decoder:

x^=Decoder(z)\hat x=Decoder(z)

Pixel Space and Latent Space

Pixel Space
[3, 512, 512]
      ↓
    Encoder
      ↓
Latent Space
[4, 64, 64]
      ↓
    Decoder
      ↓
Reconstructed Image

The shape above is only used to illustrate the compression idea and does not mean that all models use the same number of channels and downsampling ratio.

The value of Latent Space includes:

  • Reduce some generation calculation costs.
  • Learn more compact data representations.
  • Separate representation compression from the generation process.
  • Allows generative models to learn complex distributions in Latent Space.

But please note:

Latent Space is a data representation, Diffusion and Flow Matching are generation methods, and the two are not concepts at the same level.

3. Autoencoder: Autoencoder

Autoencoder is the basis for understanding VAE.

Basic structure:

Input x
   ↓
Encoder
   ↓
Latent z
   ↓
Decoder
   ↓
Reconstruction x̂

The training goal is usually to minimize Reconstruction Loss:

Lrecon=d(x,x^)\mathcal L_{\text{recon}}=d(x,\hat x)

Among them, dd can be MSE and other reconstruction losses.

For example:

import torch.nn as nn

encoder = nn.Sequential(
    nn.Linear(784, 256),
    nn.ReLU(),
    nn.Linear(256, 32),
)

decoder = nn.Sequential(
    nn.Linear(32, 256),
    nn.ReLU(),
    nn.Linear(256, 784),
)

Ordinary Autoencoder can be used for representation learning, compression and reconstruction, but it may not necessarily be directly used as a reliable probability generative model.

The reason is that it does not automatically guarantee that any random sample in Latent Space will generate reasonable data.

VAE introduces the probabilistic latent variable model on this basis.

4. VAE:Variational Autoencoder

Variational Autoencoder (variational autoencoder) is a generation method based on latent variable probabilistic model.

VAE does not directly map the input to a fixed Latent Vector, but instead learns the probability distribution of the latent variable.

basic structure

Input x
   ↓
Encoder qφ(z|x)
   ↓
Mean μ / Variance σ²
   ↓
Sample Latent z
   ↓
Decoder pθ(x|z)
   ↓
Reconstructed x

Mainly contains two models:

  • Encoder / Inference Network: estimated q_ϕ(z∣x)q\_\phi(z\mid x).
  • Decoder / Generative Network: Define p_θ(x∣z)p\_\theta(x\mid z).

It is also common to define a simple Prior for the latent variable:

p(z)=N(0,I)p(z)=\mathcal N(0,I)

This means that when generating new samples, the latent variables can be sampled from the standard normal distribution and the data generated by Decoder.

Reparameterization Trick

VAE needs to be sampled from the probability distribution predicted by Encoder when training.

Commonly used methods:

z=μ+σ⊙ϵz=\mu+\sigma\odot\epsilon

Among them:

ϵ∼N(0,I)\epsilon\sim\mathcal N(0,I)

This way the randomness is transferred to the independently sampled ϵ\epsilon, and the model is still able to propagate gradients through μ\mu and σ\sigma.

This is Reparameterization Trick (heavy parameterization technique).

Training target of VAE: ELBO

VAE wishes to maximize the log-likelihood of the data:

log⁡pθ(x)\log p_\theta(x)

But direct calculations are often difficult.

So using Evidence Lower Bound (ELBO):

LELBO=Eqϕ(z∣x)[log⁡pθ(x∣z)]−DKL(qϕ(z∣x)∥p(z))\mathcal L_{\text{ELBO}} = \mathbb E_{q_\phi(z|x)} [\log p_\theta(x|z)] - D_{\text{KL}}(q_\phi(z|x)\|p(z))

Maximizing ELBO is equivalent to balancing two terms in a common implementation:

  1. Reconstruction Term: Enables Decoder to reconstruct the original data.
  2. KL Divergence: Make the latent variable distribution of Encoder close to Prior.

Common minimized forms:

LVAE=Lrecon+LKL\mathcal L_{\text{VAE}} = \mathcal L_{\text{recon}} + \mathcal L_{\text{KL}}

However, the specific Reconstruction Loss depends on the probability distribution assumed by Decoder, and MSE cannot be used arbitrarily for all data without considering its implications.

KL Divergence

For a diagonal Gaussian distribution:

qϕ(z∣x)=N(μ,diag⁡(σ2))q_\phi(z|x)=\mathcal N(\mu,\operatorname{diag}(\sigma^2))

KL Divergence with standard normal Prior can be written as:

DKL=−12∑j(1+log⁡σj2−μj2−σj2)D_{\text{KL}} = -\frac12\sum_j (1+\log\sigma_j^2-\mu_j^2-\sigma_j^2)

This is a common formula in VAE implementations.

5. VAE: PyTorch implementation

The following constructs a simple VAE suitable for 28×28 grayscale images such as MNIST.

import torch
import torch.nn as nn
import torch.nn.functional as F

class VAE(nn.Module):
    def __init__(self, latent_dim=16):
        super().__init__()

        self.encoder = nn.Sequential(
            nn.Linear(784, 256),
            nn.ReLU(),
        )

        self.fc_mu = nn.Linear(256, latent_dim)
        self.fc_logvar = nn.Linear(256, latent_dim)

        self.decoder = nn.Sequential(
            nn.Linear(latent_dim, 256),
            nn.ReLU(),
            nn.Linear(256, 784),
        )

    def encode(self, x):
        h = self.encoder(x)
        return self.fc_mu(h), self.fc_logvar(h)

    def reparameterize(self, mu, logvar):
        std = torch.exp(0.5 * logvar)
        eps = torch.randn_like(std)
        return mu + eps * std

    def decode(self, z):
        return self.decoder(z)

    def forward(self, x):
        x = x.flatten(1)

        mu, logvar = self.encode(x)
        z = self.reparameterize(mu, logvar)

        logits = self.decode(z)

        return logits, mu, logvar

VAE Loss

For an image normalized to 0~1 using Bernoulli Observation Model:

def vae_loss(logits, x, mu, logvar):
    x = x.flatten(1)

    reconstruction = F.binary_cross_entropy_with_logits(
        logits,
        x,
        reduction="sum",
    )

    kl = -0.5 * torch.sum(
        1 + logvar - mu.pow(2) - logvar.exp()
    )

    return (reconstruction + kl) / x.size(0)

Training:

model = VAE(latent_dim=16)
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3)

for images, _ in train_loader:
    optimizer.zero_grad()

    logits, mu, logvar = model(images)

    loss = vae_loss(logits, images, mu, logvar)

    loss.backward()
    optimizer.step()

Among them, train_loader needs to provide the image Tensor with compatible shape and value range from 0 to 1.

Generate data from latent variables

model.eval()

with torch.inference_mode():
    z = torch.randn(16, 16)

    logits = model.decode(z)

    images = torch.sigmoid(logits).reshape(
        16, 1, 28, 28
    )

Here we sample directly from the standard normal distribution and then use Decoder to generate the image.

Features of VAE

Advantages:

  • Have explicit probabilistic latent variable modeling objectives.
  • Can learn continuous Latent Representation.
  • Suitable for representation learning, reconstruction and latent space modeling.
  • Encoder and Decoder can be used as components of more complex systems.

Limitations:

  • Reconstruction quality depends on model capacity and probabilistic assumptions.
  • Latent variable regularization may lead to loss of reconstruction detail.
  • There may be a problem with Posterior Collapse, that is, Decoder ignores Latent Variable.

VAE’s modern positioning

VAE is not only a stand-alone generative model, but is also often used as the encoding and decoding component of modern Latent Generative Models.

For example, Latent Diffusion can use pre-trained Autoencoder, convert the image to Latent, and then perform diffusion generation in it.

The Autoencoder here do not necessarily strictly adopt the training objectives of the above standard VAE.

6. GAN:Generative Adversarial Network

GAN (Generative Adversarial Network) is a classic generative model.

It contains two networks:

  • Generator (G): Generate samples from random variables.
  • Discriminator (D): Distinguish between real samples and generated samples.

Training process:

Random Noise z
      ↓
Generator G
      ↓
Fake Samples ─────┐
                  ↓
Real Samples ─→ Discriminator D
                  ↓
             Real / Fake

Two networks are trained adversarially.

classic goal

min⁡Gmax⁡DEx∼pdata[log⁡D(x)]+Ez∼p(z)[log⁡(1−D(G(z)))]\min_G\max_D \mathbb E_{x\sim p_{\text{data}}}[\log D(x)] + \mathbb E_{z\sim p(z)} [\log(1-D(G(z)))]

Generator hopes to generate samples that can fool Discriminator.

Discriminator wants to correctly differentiate between real and generated samples.

Features of GAN

Advantages:

  • The build phase usually only requires executing Generator.
  • Some scenarios have lower inference latency.
  • Produces results with better visual detail.

Limitations:

  • Adversarial training can be unstable.
  • Mode Collapse (mode collapse) may occur.
  • The resulting distribution may have insufficient coverage.
  • The training process is sensitive to architecture and hyperparameters.

Current location

GAN is an important architecture for understanding the development of generative models, but there is no need to delve into all the historical variants of DCGAN, CycleGAN, StyleGAN, etc.

GAN remains valuable in research related to specific image generation, image transformation, low-latency generation, and adversarial training.

For modern high-quality, controllable general-purpose image and video generation, Diffusion and Flow Matching are generally more worthy of priority research.

7. Diffusion Models: Diffusion generative model

The core idea of Diffusion Models is:

learns how to recover information from noise-contaminated data during training; during generation, it starts with random noise and gradually generates samples.

Classic Denoising Diffusion Probabilistic Models (DDPM) usually consists of two processes.

Forward Diffusion: Noise adding process

Gradually add Gaussian noise to real data:

Clean Image
    ↓
Slightly Noisy
    ↓
More Noisy
    ↓
Very Noisy
    ↓
Gaussian Noise

Reverse Process: Generation process

Learning gradually shifts from noise to data distribution:

Gaussian Noise
    ↓
Denoising Step
    ↓
Denoising Step
    ↓
Denoising Step
    ↓
Generated Image

The forward denoising process is usually predefined and does not require neural network learning.

The model focuses on learning the information needed for the reverse generation process.

8. DDPM: Mathematical form of the noise adding process

Classic DDPM definition:

q(xt∣xt−1)=N(1−βtxt−1,βtI)q(x_t|x_{t-1}) = \mathcal N( \sqrt{1-\beta_t}x_{t-1}, \beta_tI )

Among them:

  • x0x_0: raw data.
  • xtx_t: Noise data at step tt.
  • βt\beta_t: Variance parameter in Noise Schedule.

Definition:

αt=1−βt\alpha_t=1-\beta_t αˉt=∏s=1tαs\bar\alpha_t=\prod_{s=1}^{t}\alpha_s

The noise addition result at any time step can be obtained directly from the original data:

xt=αˉtx0+1−αˉtϵ\boxed{ x_t=\sqrt{\bar\alpha_t}x_0+ \sqrt{1-\bar\alpha_t}\epsilon }

Among them:

ϵ∼N(0,I)\epsilon\sim\mathcal N(0,I)

This is very important: when training , you don't really need to gradually add noise T times.

Just randomly sample a time step tt, and you can directly construct the corresponding xtx_t.

PyTorch example

import torch

T = 1000

betas = torch.linspace(1e-4, 0.02, T)
alphas = 1.0 - betas
alpha_bars = torch.cumprod(alphas, dim=0)

x0 = torch.randn(8, 3, 64, 64)

t = torch.randint(0, T, (8,))
noise = torch.randn_like(x0)

a_bar = alpha_bars[t].view(-1, 1, 1, 1)

xt = (
    torch.sqrt(a_bar) * x0
    + torch.sqrt(1 - a_bar) * noise
)

The simple linear Beta Schedule is used here to illustrate the principle, but it does not mean that it is the best Noise Schedule for modern models.

9. Diffusion Training: Noise prediction

A common training method for classic DDPM is to have the neural network predict noise added to the data.

Model input:

ϵθ(xt,t)\epsilon_\theta(x_t,t)

Among them:

  • xtx_t: Noisy data.
  • tt:Noise Level / Timestep。
  • ϵ_θ\epsilon\_\theta: Noise prediction network.

Training goals:

Lnoise=Ex0,ϵ,t[∥ϵ−ϵθ(xt,t)∥22]\mathcal L_{\text{noise}} = \mathbb E_{x_0,\epsilon,t} \left[ \|\epsilon-\epsilon_\theta(x_t,t)\|_2^2 \right]

Training process

Clean Image x0
      ↓
Sample Timestep t
      ↓
Sample Gaussian Noise ε
      ↓
Construct Noisy Image xt
      ↓
Noise Prediction Network
      ↓
Predicted Noise εθ
      ↓
MSE(εθ, ε)
      ↓
Backpropagation

PyTorch training logic

The following assumes that model(noisy_images, timesteps) returns a noisy prediction Tensor of the same shape as the input image:

import torch.nn.functional as F

for clean_images in train_loader:
    clean_images = clean_images.to(device)

    batch_size = clean_images.size(0)

    t = torch.randint(
        0,
        T,
        (batch_size,),
        device=device,
    )

    noise = torch.randn_like(clean_images)

    a_bar = alpha_bars.to(device)[t].view(
        -1, 1, 1, 1
    )

    noisy_images = (
        a_bar.sqrt() * clean_images
        + (1 - a_bar).sqrt() * noise
    )

    predicted_noise = model(noisy_images, t)

    loss = F.mse_loss(predicted_noise, noise)

    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

This is the core logic of training, omitting the definition of noise network, data set and optimizer.

Others Prediction Targets

Modern Diffusion models do not necessarily predict noise.

Common forecasting goals include:

  • ε-prediction: prediction noise.
  • x₀-prediction: Predict clean data.
  • v-prediction: Predict some variable that is a combination of data and noise.

The specific definition of vv depends on the way the noise is parameterized, and Velocity cannot be treated as exactly the same variable in all papers.

10. Diffusion Sampling: Sampling vs. Scheduler

After training is completed, start with random noise and use model predictions to gradually generate data.

xT ~ N(0, I)
     ↓
Model Prediction
     ↓
Scheduler Step
     ↓
xT-1
     ↓
...
     ↓
x0

Model and Scheduler

Two components need to be distinguished:

Denoising Model

Responsible for predicting noise, data, or other targets based on noisy samples, time steps, and optional conditions.

Scheduler / Sampler

Responsible for calculating the next sample based on the model output and the current time step.

Common Scheduler include:

  • DDPM。
  • DDIM。
  • Euler。
  • DPM-Solver。
  • Others ODE / SDE-based Samplers.

DDPM and DDIM

The classical inverse process of DDPM can involve random sampling.

DDIM allows deterministic or random sampling paths and can reduce the number of inference steps.

But we cannot simply think that DDIM is better than DDPM on all models. The actual effect depends on the model, scheduling method and number of steps.

Hugging Face Diffusers

Installation:

pip install diffusers

Example:

from diffusers import DDPMScheduler

scheduler = DDPMScheduler(
    num_train_timesteps=1000,
)

noisy_images = scheduler.add_noise(
    clean_images,
    noise,
    timesteps,
)

diffusers modularly packages Model, Scheduler and Pipeline to facilitate the combination of different generation architectures and sampling algorithms.

11. U-Net and Diffusion Transformer (DiT)

Diffusion is the generation method, U-Net and Transformer are the network architecture.

The two are on different levels.

U-Net

Classic Diffusion Models often uses U-Net to predict noise.

Noisy Image
     ↓
Downsampling Blocks
     ↓
Bottleneck
     ↓
Upsampling Blocks
     ↓
Noise Prediction

U-Net combines features of different resolutions via Skip Connections.

Its advantage is that it is suitable for processing image data with obvious spatial structure.

Diffusion Transformer(DiT)

DiT applies Transformer to the main computational part of Diffusion Model.

Typical process:

Noisy Image / Latent
        ↓
Patch Embedding
        ↓
Transformer Blocks
        ↓
Prediction Head
        ↓
Noise / Other Target

DiT combines:

  • Patch / Token Representation。
  • Self-Attention。
  • Timestep Conditioning。
  • Transformer Blocks。

Therefore, DiT is not another generation method replacing Diffusion, but a class of network architectures that can be used for Diffusion.

Modern Flow Matching models are also available as Transformer Backbone.

12. Latent Diffusion: latent space diffusion

Running multi-step Diffusion directly in high-resolution Pixel Space can be computationally expensive.

Latent Diffusion Models (LDM) shifts the generation process to compressed Latent Space.

basic structure

Training Image
      ↓
VAE / Autoencoder Encoder
      ↓
Image Latent z0
      ↓
Add Noise
      ↓
Denoising Model
      ↓
Predicted Noise

When generated:

Random Latent Noise
       ↓
Denoising Steps
       ↓
Generated Latent
       ↓
VAE / Autoencoder Decoder
       ↓
Generated Image

Why is it more efficient?

Assume that the image space is:

[3, 512, 512]

The compressed Latent Space is:

[4, 64, 64]

Then the number of spatial positions is given by:

5122=262144512^2=262144

reduced to:

642=409664^2=4096

In this example, the spatial position is reduced to the original 1/641/64.

However, the actual computing cost is also affected by the number of channels, network structure and other operations, and it cannot be directly concluded that the FLOPs of the entire model is also reduced by 64 times.

Importance of Latent Diffusion

Latent Diffusion separates the two questions:

  1. Autoencoder is responsible for the compression and reconstruction of image representations.
  2. Generative Model is responsible for learning Latent Distribution.

This is also an important reason why VAE and modern Diffusion/Flow Matching can appear together in one system.

13. Conditional Generation and CFG

Modern generative models often require controlling results based on conditions such as Text Prompt.

For example:

ϵθ(xt,t,c)\epsilon_\theta(x_t,t,c)

where cc is the text condition.

Text Encoder can first convert Prompt to Embeddings, and then affect the generative model through Cross-Attention or other condition injection mechanisms.

Classifier-Free Guidance(CFG)

CFG is a common conditional generation boot method.

In the classical noise prediction form:

ϵ^=ϵuncond+s(ϵcond−ϵuncond)\hat\epsilon = \epsilon_{\text{uncond}} + s( \epsilon_{\text{cond}} - \epsilon_{\text{uncond}} )

Among them:

  • ϵ_cond\epsilon\_{\text{cond}}: Conditional prediction.
  • ϵ_uncond\epsilon\_{\text{uncond}}: Unconditional prediction.
  • ss:Guidance Scale。

Larger Guidance Scale usually makes the generated results adhere more strongly to the condition, but may also reduce diversity or produce visual distortion.

It is important to note that CFG implementations and output parameterizations of modern models do not necessarily agree exactly with this classic formula.

CFG is also not a required mechanic for all new models.

14. Flow Matching: Stream matching

Flow Matching (FM) is a very important training method in modern generative models.

Its core idea is:

constructs a continuous probability path from a simple distribution to a real data distribution, and trains a neural network to predict the velocity field moving along this path (Velocity Field).

Different from the classical stepwise stochastic denoising representation of DDPM, Flow Matching often uses continuous-time ODE to describe the generation process.

Basic concepts

Define a continuously changing state:

xt,t∈[0,1]x_t,\qquad t\in[0,1]

The convention is used here:

  • t=0t=0: Noise distribution.
  • t=1t=1: Data distribution.

The goal is to learn:

dxtdt=vθ(xt,t)\frac{dx_t}{dt}=v_\theta(x_t,t)

where v_θv\_\theta is Velocity Field learned by the neural network.

Intuitive understanding

Gaussian Noise
      ↓
Continuous Flow
      ↓
Intermediate State
      ↓
Continuous Flow
      ↓
Data Sample

Velocity Field can be understood as: at a certain time and location, in what direction and at what speed the data should move.

The model learns velocity patterns throughout space rather than memorizing an independent path for each data point.

15. Conditional Flow Matching

For ease of understanding, the simplest linear interpolation path can be used.

Sample from standard normal noise:

x0∼N(0,I)x_0\sim\mathcal N(0,I)

Sample from real data distribution:

x1∼pdatax_1\sim p_{\text{data}}

Definition:

xt=(1−t)x0+tx1\boxed{x_t=(1-t)x_0+tx_1}

Then the speed of this sample path is:

dxtdt=x1−x0\frac{dx_t}{dt}=x_1-x_0

So the model can be trained to predict:

vθ(xt,t)≈x1−x0v_\theta(x_t,t)\approx x_1-x_0

Corresponding simplification goals:

LFM=Ex0,x1,t[∥vθ(xt,t)−(x1−x0)∥2]\mathcal L_{\text{FM}} = \mathbb E_{x_0,x_1,t} \left[ \|v_\theta(x_t,t)-(x_1-x_0)\|^2 \right]

This is a basic example for understanding Rectified Flow / Conditional Flow Matching.

Why is it possible?

When training you can:

  1. Randomly select a real sample.
  2. Randomly sample a noise sample.
  3. Randomly select time tt.
  4. Construct xtx_t based on interpolation.
  5. Use the difference between the two end samples as the speed supervision target.

It is not necessary to completely solve a ODE trajectory in each training step.

Note: the neural network only receives xtx_t, tt, and optional conditions, not the unknown target endpoint x1x_1 directly. What is trained is an appropriate average representation of the conditional path velocity field.

16. Flow Matching: PyTorch example

Next, use simple MLP to learn Flow Matching for two-dimensional data.

Velocity Network

import torch
import torch.nn as nn
import torch.nn.functional as F

class VelocityMLP(nn.Module):
    def __init__(self):
        super().__init__()

        self.network = nn.Sequential(
            nn.Linear(3, 128),
            nn.SiLU(),
            nn.Linear(128, 128),
            nn.SiLU(),
            nn.Linear(128, 2),
        )

    def forward(self, x, t):
        inputs = torch.cat([x, t], dim=1)
        return self.network(inputs)

The input consists of 2D coordinates and a time variable, so the total dimension is 3.

Training

Assume real_samples is real 2D training data of shape [N, 2]:

model = VelocityMLP()

optimizer = torch.optim.AdamW(
    model.parameters(),
    lr=1e-3,
)

for step in range(5000):
    indices = torch.randint(
        len(real_samples),
        (256,),
    )

    x1 = real_samples[indices]
    x0 = torch.randn_like(x1)

    t = torch.rand(x1.size(0), 1)

    xt = (1 - t) * x0 + t * x1

    target_velocity = x1 - x0

    predicted_velocity = model(xt, t)

    loss = F.mse_loss(
        predicted_velocity,
        target_velocity,
    )

    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

This code shows the core training mechanism of Flow Matching, excluding the large-scale Backbone and complex Conditioning required for real image generation.

Sampling:ODE Integration

After training is completed, starting from random noise, ODE is solved based on the velocity field predicted by the model.

The simplest Euler Method is used below:

model.eval()

num_steps = 100
dt = 1.0 / num_steps

with torch.inference_mode():
    x = torch.randn(1000, 2)

    for i in range(num_steps):
        t = torch.full(
            (x.size(0), 1),
            i / num_steps,
        )

        velocity = model(x, t)

        x = x + dt * velocity

The final x is the generated sample.

This is a complete conceptual process of Flow Matching:

Sample Noise
     ↓
Predict Velocity
     ↓
Euler / ODE Solver
     ↓
Update Sample
     ↓
Repeat
     ↓
Generated Data

Real-world image and video generative models often use more complex velocity networks, temporal scheduling, and numerical solution methods.

17. The relationship between Flow Matching and Diffusion

This is where most confusion arises in modern generative models.

They are not completely mutually exclusive technologies.

Diffusion

Classic DDPM learns the corresponding reverse generation process by defining the noise addition process.

You can use the probabilistic form of the inverse Markov Chain, or you can sample by the related ODE / SDE representation.

Flow Matching

Flow Matching trains continuous-time generative dynamical systems by performing velocity field regression on predefined probabilistic paths.

Different Probability Path can produce different training methods.

Flow Matching can use Diffusion-related Probability Paths, or Linear / Optimal-Transport-inspired Paths.

Therefore, we cannot simply think:

  • Diffusion must be random.
  • Flow Matching must be deterministic.
  • Diffusion must require many steps.
  • Flow Matching must only require one step.

Contrast

FeaturesClassic DDPMFlow Matching
core training objectivesCommonly used is noise predictionVelocity field prediction
Time representationCommonly used are discrete time stepsUsually continuous time
generation processReverse denoising processODE Flow
Sampling algorithmDDPM, DDIM, etc.Euler, Heun, others ODE Solver
Available BackboneU-Net、TransformerU-Net、Transformer
available spacePixel / LatentPixel / Latent

The importance of Flow Matching is that it provides a direct and flexible training method for continuous generative models, rather than just replacing a certain sampler of Diffusion.

18. Rectified Flow and modern generative models

Rectified Flow is a technical route closely related to the modern Flow Matching.

It emphasizes learning to generate flows through paths connecting noise and data, and studies how to obtain trajectories that are more suitable for efficient numerical integration.

core intuition

If the generated trajectories are straight and easily approximated numerically, then under certain conditions good results can be obtained using fewer solution steps.

But it needs to be distinguished:

  • Training Objective: Which target the model learns.
  • Probability Path: What kind of intermediate distribution path to choose.
  • Numerical Solver: How to integrate during inference.
  • Distillation: Whether to further train the few-step generative model.

These factors jointly determine the generation effect and speed.

Few-step sampling in modern generative models cannot all be attributed to Flow Matching itself.

19. Architectural components of modern generation systems

Several concepts can now be combined.

For example, a typical Latent Text-to-Image system:

Text Prompt
     ↓
Text Encoder
     ↓
Text Embeddings
     │
     ▼
Random Latent Noise
     ↓
Generative Backbone
(U-Net / Transformer)
     ↓
Diffusion / Flow Sampling
     ↓
Generated Latent
     ↓
VAE / Autoencoder Decoder
     ↓
Generated Image

Different components have different responsibilities:

componentsfunction
Text EncoderConvert Prompt to conditional representation
VAE / AutoencoderConversion between image and Latent
U-Net / DiTPredict training targets such as noise, speed, etc.
Diffusion / Flow MatchingDefine a generative modeling approach
Scheduler / ODE SolverAdvance the sampling process
GuidanceThe impact of adjusting conditions on generated results

This is the most important conceptual diagram for understanding modern image and video generation architecture.

For example a model can be both:

  • Latent-space Model。
  • Transformer Backbone。
  • Flow Matching Training。
  • ODE-based Sampling。

These descriptions correspond to different levels and are not contradictory.

20. Diffusers: Modern generative model development

Hugging Face Diffusers is a commonly used generative model development library that supports multiple diffusion and Flow Matching model families.

Installation:

pip install diffusers transformers accelerate

Common components:

componentsfunction
PipelineEncapsulate the complete generation process
ModelNeural networks such as U-Net and Transformer
SchedulerTime scheduling and sampling updates
AutoencoderConvert between Latent and images
Text Encoderconditional text encoding
LoRA / AdaptersEfficient fine-tuning of parameters

Basic inference example

import torch
from diffusers import DiffusionPipeline

pipe = DiffusionPipeline.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0",
    torch_dtype=torch.float16,
)

pipe = pipe.to("cuda")

image = pipe(
    prompt="A mountain landscape at sunrise",
    num_inference_steps=30,
).images[0]

image.save("generated.png")

This example requires compatible CUDA GPU, corresponding dependencies and model weights.

In actual use, the appropriate accuracy and loading method should be selected based on the video memory, hardware and model documentation.

Scheduler selection

For example, common ones:

  • DDPMScheduler。
  • DDIMScheduler。
  • DPMSolverMultistepScheduler。
  • FlowMatchEulerDiscreteScheduler。

Different Scheduler are related to different prediction goals, training parameterizations and model configurations.

cannot be assumed to be directly interchangeable between any model for all Scheduler.

For existing pre-trained models, Scheduler recommended by Checkpoint should be used first.

21. Generative Model Evaluation: Generative model evaluation

Unlike classification and regression, generative models cannot be evaluated solely with Accuracy or RMSE.

Because under the same input condition, there may be multiple reasonable outputs.

Common evaluation dimensions:

  • Sample Quality: Build quality.
  • Diversity: Diversity.
  • Distribution Alignment: How close the generated distribution is to the real data.
  • Condition Alignment: Matches Prompt or the condition.
  • Consistency: Timing and content consistency.
  • Inference Cost: Generation latency and computational cost.

FID:Fréchet Inception Distance

FID uses a pre-trained vision network to extract image features and compare the feature distribution of real data and generated data.

Usually the lower the number the better.

But FID also has limitations:

  • Affected by the feature extraction model.
  • Sensitive to sample size and preprocessing.
  • Does not directly measure Prompt Alignment.
  • It cannot fully reflect the artificial subjective quality.

CLIP-based Metrics

A certain degree of semantic consistency can be measured using images and text Embeddings.

But such metrics do not guarantee that image details, authenticity, or physical relationships are correct.

Video generation evaluation

Video generation also needs to consider:

  • Temporal Consistency。
  • Motion Quality。
  • Subject Consistency。
  • Frame Quality。
  • Text-video Alignment。

Real systems often require a combination of automated metrics and manual evaluation.

22. How to choose the generation method?

methodMain advantagesMain limitationsCurrent learning focus
VAEProbabilistic latent variables, encoding and decodingTrade-off between reconstruction quality and latent variable constraintsELBO、KL、Reparameterization
GANSome scenes can be generated with low latencyAdversarial training is unstable, Mode CollapseLearn about Generator / Discriminator
DiffusionHigh-quality generation and flexible condition controlMulti-step builds can be costlyForward / Reverse Process、Scheduler
Flow MatchingFlexible continuous generation modeling, ODE samplingDependency paths, solvers, and training designVelocity Field、Probability Path、ODE
AutoregressiveSuitable for discrete sequence modelingSequence generation often has stepwise dependenciesDiscussed in LLM / Transformer

actual learning sequence

Suggestions:

Latent Space
    ↓
VAE / Autoencoder
    ↓
Diffusion / DDPM
    ↓
Scheduler / Sampling
    ↓
Latent Diffusion
    ↓
Flow Matching
    ↓
DiT / Modern Generative Systems

GAN Only needs to learn the basic mechanisms when understanding the classification of generation methods.

23. FAQ

Are VAE and Diffusion competing?

Not exactly.

VAE can be used independently for generation and representation learning, or as a compression encoding component of Latent Diffusion / Flow Model.

Diffusion Can only U-Net be used?

no.

U-Net is the classic choice, Transformer also works as Diffusion Backbone.

Is DiT the same as Flow Matching?

no.

DiT describes the network architecture, and Flow Matching describes the method of training to generate streams.

DiT can be used with different build targets.

Does Flow Matching completely replace Diffusion?

You can't judge like this.

The two are related in probabilistic paths, continuous time modeling and sampling methods, and there are different hybrid and unified representations in modern systems.

The choice of actual model depends on training goals, data type, quality, speed, and engineering complexity.

Is Flow Matching necessarily faster than Diffusion?

uncertain.

Actual speed depends on:

  • Network structure.
  • solver.
  • Number of inference steps.
  • Model size.
  • Hardware implementation.
  • Whether it goes through Distillation.

Reducing the number of sampling steps may also result in a loss of quality.

The higher the ELBO of VAE, the better the generation quality?

uncertain.

ELBO reflects optimization under specific probabilistic models and approximate inference objectives, and does not equal human perceptual quality or downstream task performance.


Summary

Knowledge pointsimportance
Generative Modeling / Samplingcore
Conditional Generationcore
Latent Spacecore
Autoencoderimportant
VAE / ELBO / KL Divergencecore
Reparameterization Trickcore
GAN / Adversarial TrainingUnderstand
Diffusion / Forward / Reversecore
DDPM / Noise Schedulecore
Noise Prediction / Velocity Predictioncore
Scheduler / Samplercore
Latent Diffusioncore
U-Net / DiTimportant
Classifier-Free Guidanceimportant
Flow Matching / Velocity Fieldcore
Probability Path / ODEcore
Rectified Flowimportant
FID / Alignment Evaluationimportant

The five most important concepts of generative models:

  1. Latent Variable Modeling: VAE learns a generative representation of the data using probabilistic latent variables and Encoder–Decoder.
  2. Diffusion: Generation is achieved by learning the process of recovering data from noise.
  3. Flow Matching: Train continuous-time velocity fields to convert simple noise distributions into data distributions.
  4. Architecture vs Generative Method: U-Net, Transformer are network architectures, and Diffusion, Flow Matching are generative modeling methods.
  5. Sampling: The quality and efficiency of the generation process not only rely on neural networks, but also on mechanisms such as Scheduler, ODE Solver, Guidance.

Reference documentation

Back to top