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:
| method | core idea | Main positioning |
|---|---|---|
| VAE | Learning probabilistic latent variables and decoding process | Representation learning, latent space modeling |
| GAN | Training via generator versus discriminator adversarial | Classic generation method, still valuable in specific scenarios |
| Diffusion | Learning to progressively recover data from noise | Important methods for modern image and video generation |
| Flow Matching | Learning a continuous velocity field that connects the noise distribution to the data distribution | Important training methods for modern generative models |
| Autoregressive Models | Predict the next element step by step based on existing content | LLM、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:
Generative models want to learn a distribution:
Among them:
- : Sample, such as picture or audio.
- : Real data distribution.
- : Distribution learned by the model.
- : 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:
where 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:
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:
Then restore via Decoder:
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:
Among them, 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 .
- Decoder / Generative Network: Define .
It is also common to define a simple Prior for the latent variable:
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:
Among them:
This way the randomness is transferred to the independently sampled , and the model is still able to propagate gradients through and .
This is Reparameterization Trick (heavy parameterization technique).
Training target of VAE: ELBO
VAE wishes to maximize the log-likelihood of the data:
But direct calculations are often difficult.
So using Evidence Lower Bound (ELBO):
Maximizing ELBO is equivalent to balancing two terms in a common implementation:
- Reconstruction Term: Enables Decoder to reconstruct the original data.
- KL Divergence: Make the latent variable distribution of Encoder close to Prior.
Common minimized forms:
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:
KL Divergence with standard normal Prior can be written as:
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
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:
Among them:
- : raw data.
- : Noise data at step .
- : Variance parameter in Noise Schedule.
Definition:
The noise addition result at any time step can be obtained directly from the original data:
Among them:
This is very important: when training , you don't really need to gradually add noise T times.
Just randomly sample a time step , and you can directly construct the corresponding .
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:
Among them:
- : Noisy data.
- :Noise Level / Timestep。
- : Noise prediction network.
Training goals:
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 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:
reduced to:
In this example, the spatial position is reduced to the original .
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:
- Autoencoder is responsible for the compression and reconstruction of image representations.
- 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:
where 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:
Among them:
- : Conditional prediction.
- : Unconditional prediction.
- :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:
The convention is used here:
- : Noise distribution.
- : Data distribution.
The goal is to learn:
where 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:
Sample from real data distribution:
Definition:
Then the speed of this sample path is:
So the model can be trained to predict:
Corresponding simplification goals:
This is a basic example for understanding Rectified Flow / Conditional Flow Matching.
Why is it possible?
When training you can:
- Randomly select a real sample.
- Randomly sample a noise sample.
- Randomly select time .
- Construct based on interpolation.
- 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 , , and optional conditions, not the unknown target endpoint 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
| Features | Classic DDPM | Flow Matching |
|---|---|---|
| core training objectives | Commonly used is noise prediction | Velocity field prediction |
| Time representation | Commonly used are discrete time steps | Usually continuous time |
| generation process | Reverse denoising process | ODE Flow |
| Sampling algorithm | DDPM, DDIM, etc. | Euler, Heun, others ODE Solver |
| Available Backbone | U-Net、Transformer | U-Net、Transformer |
| available space | Pixel / Latent | Pixel / 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:
| components | function |
|---|---|
| Text Encoder | Convert Prompt to conditional representation |
| VAE / Autoencoder | Conversion between image and Latent |
| U-Net / DiT | Predict training targets such as noise, speed, etc. |
| Diffusion / Flow Matching | Define a generative modeling approach |
| Scheduler / ODE Solver | Advance the sampling process |
| Guidance | The 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:
| components | function |
|---|---|
| Pipeline | Encapsulate the complete generation process |
| Model | Neural networks such as U-Net and Transformer |
| Scheduler | Time scheduling and sampling updates |
| Autoencoder | Convert between Latent and images |
| Text Encoder | conditional text encoding |
| LoRA / Adapters | Efficient 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?
| method | Main advantages | Main limitations | Current learning focus |
|---|---|---|---|
| VAE | Probabilistic latent variables, encoding and decoding | Trade-off between reconstruction quality and latent variable constraints | ELBO、KL、Reparameterization |
| GAN | Some scenes can be generated with low latency | Adversarial training is unstable, Mode Collapse | Learn about Generator / Discriminator |
| Diffusion | High-quality generation and flexible condition control | Multi-step builds can be costly | Forward / Reverse Process、Scheduler |
| Flow Matching | Flexible continuous generation modeling, ODE sampling | Dependency paths, solvers, and training design | Velocity Field、Probability Path、ODE |
| Autoregressive | Suitable for discrete sequence modeling | Sequence generation often has stepwise dependencies | Discussed 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 points | importance |
|---|---|
| Generative Modeling / Sampling | core |
| Conditional Generation | core |
| Latent Space | core |
| Autoencoder | important |
| VAE / ELBO / KL Divergence | core |
| Reparameterization Trick | core |
| GAN / Adversarial Training | Understand |
| Diffusion / Forward / Reverse | core |
| DDPM / Noise Schedule | core |
| Noise Prediction / Velocity Prediction | core |
| Scheduler / Sampler | core |
| Latent Diffusion | core |
| U-Net / DiT | important |
| Classifier-Free Guidance | important |
| Flow Matching / Velocity Field | core |
| Probability Path / ODE | core |
| Rectified Flow | important |
| FID / Alignment Evaluation | important |
The five most important concepts of generative models:
- Latent Variable Modeling: VAE learns a generative representation of the data using probabilistic latent variables and Encoder–Decoder.
- Diffusion: Generation is achieved by learning the process of recovering data from noise.
- Flow Matching: Train continuous-time velocity fields to convert simple noise distributions into data distributions.
- Architecture vs Generative Method: U-Net, Transformer are network architectures, and Diffusion, Flow Matching are generative modeling methods.
- 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
- Auto-Encoding Variational Bayes
- An Introduction to Variational Autoencoders
- Generative Adversarial Nets
- Denoising Diffusion Probabilistic Models
- Denoising Diffusion Implicit Models
- High-Resolution Image Synthesis with Latent Diffusion Models
- Scalable Diffusion Models with Transformers
- Flow Matching for Generative Modeling
- Flow Straight and Fast: Learning to Generate and Transfer Data with Rectified Flow
- Hugging Face Diffusers Documentation
- Diffusers:Train a Diffusion Model
- Diffusers:Schedulers