# The Core Principles of AIGC (Part 1): Generative Models Explained

> This article dives deep into the fundamental principles of generative models that power AIGC. It provides detailed explanations and mathematical derivations for four major latent variable models—VAE, GAN, Flow Models, and Diffusion Models—while focusing on key techniques such as DDPM, DDIM, classifier-guided, and classifier-free guidance. It also introduces the IS and FID metrics used to evaluate image generation quality.

- Source: https://www.waytoagi.com/en/kb/learning-path/aigc-composition-principle-part1
- Original (Feishu, Chinese): https://waytoagi.feishu.cn/wiki/KmkAwqnXPisrvfkK7RJcK9GqnAf
- Updated: 2026-10-27

---

> Author: Xiao A, aaronxic, [Zhihu Profile](https://www.zhihu.com/people/aaronxic)
>
> Publication Date: July 8, 2023
>
> Original Article: https://zhuanlan.zhihu.com/p/646149258
![](https://www.waytoagi.com/api/kb-media/Yy6ob6LvDoWxzTxIcTWcSe1FnVc)


# **Introduction**

Hello everyone, I’m aaronxic. In the previous articles, we explored how Transformers are applied in the fields of LLMs and multimodal models. Starting from this article, we will shift our focus to AIGC and examine what components are used to build AIGC systems.

AIGC (Artificial Intelligence Generated Content) emphasizes the “GC” part — that is, the decoder.

- The previous article [(4) The Path to Multimodal Unification](https://ywh1bkansf.feishu.cn/wiki/ReVzwZUr0ivgWfkaQ91cXrYUnoh) focused on the encoder side, including the encoding of Image and Video. The generation aspect of the decoder mainly centered on text generation.

- This article, *Principles of AIGC Composition (Part 1)*, introduces four major categories of generative algorithms: VAE, GAN, Flow Models, and Diffusion Models. It also covers two common evaluation metrics for generated images: IS (Inception Score) and FID (Fréchet Inception Distance).

- The next article, *Principles of AIGC Composition (Part 2)*, will cover specific algorithms for Image generation, Video generation, Audio generation, and 3D generation.

PS: Long-read alert! This article is approximately 12,000 words. Follow and save it, then read it on a computer for the best experience~ (^_^)

The outline is as follows (two main sections):

- First, we introduce the fundamental goal of generative models: modeling the distribution *p(x)*.
  - We begin with the most basic approach — maximum likelihood estimation. Although simple, it requires an explicit parametric form of the distribution, which is often unavailable in practice.
  - Next, we introduce four latent variable models: VAE, GAN, Flow Models, and Diffusion Models. In essence, they all approximate *p(x) = ∫ p(x|z) p(z) dz*.
  - **VAE**: Attempts to improve the sampling efficiency of *p(z)* by minimizing *KL(q_θ(z|x) || p(z))*, ultimately yielding a regularization term and a reconstruction error term.
  - **GAN**: Extends the MSE loss function further by introducing a discriminator *D(x', x)* to implicitly learn a metric.
  - **Flow Models**: Force the function *f* to be invertible, establishing a one-to-one mapping between *x* and *z*. We use RevNet as an example to illustrate how Flow Models are implemented in practice.
  - **Diffusion Models (DDPM)**: Extend VAE to multiple steps. Although the mathematical derivation is complex, the core idea is similar to that of VAE.
  - **Score Function in DDPM**: Viewing DDPM from another perspective, we find that a network *s_θ(x_t, t)* can be used to predict *∇_{x_t} log p(x_t)*.

  - **DDIM**: Attempts to accelerate sampling in DDPM by turning the process into a deterministic one.
  - **Classifier-Guided**: Uses classifier-guided techniques to raise the IS and FID scores of DDPM and DDIM to levels comparable with GANs for the first time. During inference, DDPM can directly compute *p(x_t | x_{t+1}, y)*; for DDIM, since it is a deterministic process, it degenerates into computing *p(x_t | y)*.

  - **Classifier-Free**: To avoid the gradient computation required by classifier-guided methods, classifier-free guidance mixes conditional and unconditional models during training. This allows inference without solving gradients, achieving high fidelity while maintaining computational efficiency.

- Then we introduce two common metrics for image generation.
  - **IS (Inception Score)**: Offers two perspectives for understanding. IS carries a strong prior assumption that only distributions conforming to ImageNet are considered “real.”
  - **FID (Fréchet Inception Distance)**: Measures the distance between two datasets and is considered a more scientifically grounded metric.

# **Starting from Generative Models**

Suppose we have a real image dataset of size N, denoted as \( S_x = \{x_1, x_2, \cdots, x_N\} \).

- If there exists a perfect distribution \( p(x) \) that can generate all elements in the set \( S_x \), it means that every sample drawn \( x' \sim p(x) \) must satisfy \( x' \in S_x \).

- When the number of elements N is relatively small, \( p(x) \) can simply memorize the entire set. However, as N becomes extremely large, obtaining this perfect distribution \( p(x) \) becomes nearly impossible.

The core task of AIGC is to approximate this perfect distribution \( p(x) \). Here, \( x \) can represent an Image, Video, Audio, or 3D model.

So how exactly do we approximate this perfect distribution \( p(x) \)? Different methods have their own ingenious approaches. Let’s examine them one by one.

![](https://www.waytoagi.com/api/kb-media/C8j0bcc77o7WVsxL2aqcuTfIn0e)

## **Maximum Likelihood Estimation**

The most direct way to estimate a distribution \( p(x) \) is through **Maximum Likelihood Estimation (MLE)**. We first assume that \( p(x) \) takes the parametric form \( p_\theta(x) \), where \( \theta \) represents the parameters to be determined. For example, we might assume that \( x \) follows a multivariate Gaussian distribution \( \mathcal{N}(\mu, \Sigma) \), i.e., \( x \sim \mathcal{N}(\mu, \Sigma) \), where the dimensionality of the Gaussian matches the number of pixels in the image. In this case, the parameters to be estimated are \( \theta = (\mu, \Sigma) \). The likelihood function is then:

\[ L_\theta(S_x) = p(S_x; \theta) = \prod_{i=1}^N p(x_i; \theta) \]

To perform maximum likelihood estimation, we use gradient descent or analytical derivation to find the optimal parameters \( \hat{\theta} \):

\[ (\hat{\mu}, \hat{\Sigma}) = \hat{\theta} = \arg\max_\theta L_\theta(S_x) = \arg\min_\theta \left( -\sum_{i=1}^N \ln p(x_i; \theta) \right) \]

This yields the estimated distribution \( p(x) = \mathcal{N}(\hat{\mu}, \hat{\Sigma}) \).

Although the above method is simple and intuitive, its drawbacks are also evident:

- The functional form of \( p(x) \) is unknown. Determining the exact form of \( p(x) \) requires extensive domain knowledge. For complex problems, only “God” would know the true parametric expression of the distribution.

- The parameter space of \( \theta \) is overwhelmingly large. The dimensionality of a multivariate Gaussian matches the number of pixels in an image. For example, ImageNet images are in \( \mathbb{R}^{3 \times 224 \times 224} \), meaning we are dealing with a 150,528-dimensional Gaussian. Estimating such a distribution accurately would require an astronomical amount of data.

**Latent Variable Estimation**

To address the two issues mentioned above, a more widely adopted approach is **latent variable estimation**. In essence, the four mainstream categories of generative models today are all latent variable models, as shown below. [Original image source](https://lilianweng.github.io/posts/2021-07-11-diffusion-models/)

![](https://www.waytoagi.com/api/kb-media/Wn4xbu23KociTpxfC8Wcs6aDnbg)

Before introducing the four methods above, let’s first develop a deeper understanding of what a latent variable model is.

A latent variable model, as the name suggests, introduces a latent variable \( z \). The goal is to start from a simple distribution \( p(z) \) and indirectly compute the complex \( p(x) \) using an integral:

$$
p(x)=\int p(x|z) p(z) \, \text{d}z
$$

It is worth noting the following points:

- **“Simple”** refers to two properties:
  - The distribution \( p(z) \) has a simple analytical form (e.g., a standard multivariate Gaussian).
  - The dimensionality of \( z \) is low. For example, in a multivariate Gaussian, the dimension \( d \) satisfies \( d \ll 3 \times 224 \times 224 \).

- \( p(x|z) \) can be a deterministic process \( p_\theta(x|z) \), i.e., \( x = f(z) \), where \( f \) is parameterized by a neural network.

- With a universal approximator \( f \), the process of generating any complex distribution \( p(x) \) from a simple prior \( p(z) \) is as follows:
  - **Step 1**: To obtain the probability \( p(x = x') \), first examine the function \( f \) and find all \( z \) such that \( x' = f(z) \).
  - **Step 2**: If the solution set is \( \{z_1, z_2, \cdots, z_M\} \), sum the probabilities of all these \( z \) values to get the probability of \( x' \), i.e., \( p(x = x') = \sum_{i=1}^M p(z = z_i) \).

However, finding the solution set in Step 2 is generally intractable. Therefore, even though \( p(z) \) is simple and \( f \) is deterministic, \( p(x) \) remains difficult to compute directly because \( f \) is typically not invertible.

What we *can* do is to generate samples \( x' \sim p(x) \) via numerical simulation. The most common technique is the **Monte Carlo method**:

- First, sample \( z \) from \( p(z) \) for \( K \) times to obtain an array \( T_z = [z_1, z_2, \cdots, z_K] \), where each \( z_i \sim p(z) \).
- Compute the corresponding \( x_i = f(z_i) \) to obtain \( T_x = [x_1, x_2, \cdots, x_K] \).
- Note that if \( p(z_i) \) is higher, \( z_i \) will appear more frequently in the samples, and consequently the corresponding \( x_i \) will appear with higher probability in \( T_x \).
- Finally, simply take the average of \( T_x \) to obtain the sampled value: \( x' = \frac{1}{K} \sum_{i=1}^K x_i \).

Although the Monte Carlo method is straightforward, it has two major directions for improvement:

- **Improve sampling efficiency.** The value of \( K \) often needs to be extremely large to produce satisfactory results, meaning generating one \( x' \) requires many samples of \( z \). One promising direction is to make sampling of \( z \) much more efficient — ideally, a single sample should suffice. **(This is the direction taken by VAE.)**

- **Replace MSE with a learned metric.** In actual network training, the Monte Carlo samples \( x' \) are typically compared to the ground-truth image \( x \) using mean squared error (MSE). There is no theoretical guarantee that MSE is the optimal metric. Another direction is to use a neural network \( D(x, x') \) to implicitly learn a suitable distance or similarity measure. **(This is the direction taken by GAN.)**

## **VAE**

Observing the integral form of the latent variable:

$$
p(x)=\int p(x|z) \, p(z) \, \text{d}z
$$

How can we improve the sampling efficiency of $z$? One idea is to use $p(z|x)$ to approximate $p(z)$, because once we have information about $x$, the value of $z$ should become more certain. Here, the variable under study is $z$, so $p(z)$ is the prior distribution, and $p(z|x)$ is the posterior distribution.

However, even so, conjuring up $p(z|x)$ out of thin air leads to a chicken-and-egg dilemma. We need a concrete, optimizable model to approximate $p(z|x)$. This leads us to introduce a new probability distribution $q_\theta(z|x)$. The approach gradually becomes clear:

- **Step 1**: First, construct a new distribution $q_\theta(z|x)$ such that $z' \sim q_\theta(z|x)$.

- **Step 2**: Then continuously optimize $q_\theta(z|x)$ to make it closer to $p(z|x)$, so that eventually $z' \approx p(z|x)$.

The introduced $q_\theta(z|x)$ represents a family of distributions. We need to perform optimization within this family to select the most suitable distribution $q_{\theta^*}(z|x)$. This process is called **variational inference**.

Next, let’s measure the difference between these two distributions using KL divergence:

$$
\begin{align}
\text{KL}(q_\theta(z|x) || p(z|x)) &= \int q_\theta(z|x) \ln \frac{q_\theta(z|x)}{p(z|x)} \, \text{d}z \\
&= \mathbb{E}_{z \sim q_\theta(z|x)}[\ln q_\theta(z|x) - \ln p(z|x)] \\
&= \mathbb{E}_{z \sim q_\theta(z|x)}[\ln q_\theta(z|x) - \ln \frac{p(x|z)p(z)}{p(x)}] \\
&= \mathbb{E}_{z \sim q_\theta(z|x)}[\ln q_\theta(z|x) - \ln p(x|z) - \ln p(z) + \ln p(x)] \\
&= \text{KL}(q_\theta(z|x) || p(z)) - \mathbb{E}_{z \sim q_\theta(z|x)}[\ln p(x|z)] + \ln p(x)
\end{align}
$$

We can see that through variational inference, we bypass the elusive $p(z|x)$. The three remaining terms are all analytically tractable.

Let’s analyze each term one by one:

- The clear objective is to make the KL divergence on the left side as small as possible. We need to focus on how $q_\theta(z|x)$ should change in order to approach $p(z|x)$.

- The first term on the right, $\text{KL}(q_\theta(z|x) || p(z))$, should be as small as possible. This means the $z'$ obtained from the newly introduced sampling process should not deviate too far from the original prior assumption $p(z)$ (typically a standard multivariate Gaussian). We want the variance of $z'$ to become smaller, rather than turning into something completely different. This is exactly what we mean by keeping the regularization term as small as possible.

- The second term on the right, $-\mathbb{E}_{z \sim q_\theta(z|x)}[\ln p(x|z)]$, should also be as small as possible. This is equivalent to making $\mathbb{E}_{z \sim q_\theta(z|x)}[\ln p(x|z)]$ as large as possible. The meaning is that the likelihood $\ln p(x|z)$ for each image should explain the observed data $x$ as well as possible across all sampled $z$. This is precisely what we mean by making the reconstruction error as small as possible.

- The third term on the right, $\ln p(x)$, is a constant that has nothing to do with $q_\theta(z|x)$. It does not change with $q_\theta(z|x)$, so we can ignore it.

The above equation is also commonly written in the following form:

```latex
\begin{align}
\ln p(x) &= \text{KL}(q_\theta(z|x) || p(z|x)) - \text{KL}(q_\theta(z|x) || p(z)) + \mathbb{E}_{z \sim q_\theta(z|x)} \ln p(x|z) \\
&\ge -\text{KL}(q_\theta(z|x) || p(z)) + \mathbb{E}_{z \sim q_\theta(z|x)} \ln p(x|z) \\
&= \text{Variational Lower Bound}
\end{align}
```

To maximize \(p(x)\), it suffices to continuously increase the VLB (Variational Lower Bound), i.e., maximize the VLB.

From the above, we can see that the first term is the regularization term and the second term is the reconstruction error. The overall VAE network structure now becomes clear. Here is a modified version of [Teacher Su’s](https://spaces.ac.cn/archives/5253) diagram:

![](https://www.waytoagi.com/api/kb-media/JpaebH5aMoaPN8xqofRc4AMEnyc)

- The \(q_\theta(z|x)\) process is a sampling process. The neural network \(g\) is a deterministic process and inherently has no randomness. To make the network parameters learnable, the reparameterization trick must be introduced. Taking the example of a multivariate Gaussian with independent components:

  - The \(g\) process directly predicts the mean \(\mu_i\) and variance \(\sigma_i\) for each dimension, then adds a random number generator \(\epsilon_i \sim \mathcal{N}(0, 1)\) to obtain the sampled result \(z'_i = \sigma_i \cdot \epsilon_i + \mu_i\).

  - After performing this operation on every dimension \(i\), we obtain \(z' = [z'_1, z'_2, \cdots, z'_d]\).

  - All \(\mu_i\) together form \(\mu\), and all \(\sigma_i\) together form \(\Sigma\). Then \(z' \sim \mathcal{N}(\mu, \Sigma)\).

- The \(p_\theta(x|z)\) process is deterministic. Once \(z'\) is sampled, simply passing it through the decoder network yields the reconstructed \(\hat{X}\).

Now that we understand the VAE network, let’s return to its loss function, which consists of two parts:

- Minimize the regularization term. Convert \(\text{KL}(q_\theta(z|x) || p(z))\) to \(\text{KL}(\mathcal{N}(\mu, \Sigma) || \mathcal{N}(0, I))\), which has a closed-form solution: minimize \(\sum_{j=1}^d \frac{1}{2} (-\ln \sigma_j^2 + \sigma_j^2 + \mu_j^2 - 1)\).

- Minimize the reconstruction error term. \(\mathbb{E}_{z \sim q_\theta(z|x)} \ln p(x|z)\) can be transformed into requiring the MSE between \(x_i\) and \(\hat{x}^i\) to be as small as possible, i.e., minimize \(\sum_{i=1}^N \|x_i - \hat{x}^i\|_2^2\).

The final loss of the VAE network is:

$$
\sum_{i=1}^N \left( \frac{1}{2} \sum_{j=1}^d (\sigma_{i,j}^2 + \ln \frac{1}{\sigma_{i,j}^2} + \mu_{i,j}^2 - 1) + \|x_i - \hat{x}^i\|_2^2 \right)
$$

After the model converges:

- Discard the encoder network.

- Each time, sample \(z\) from the standard multivariate Gaussian distribution and pass it through the decoder network to obtain \(\hat{x}\), completing one sampling operation.
```

**GAN**

Let’s return to where the dream began and revisit the latent variable model:

$$
p(x)=\int p(x|z) \, p(z) \, \text{d}z
$$

As mentioned earlier, VAE improves sampling efficiency for $p(z)$ by parameterizing the posterior distribution $q_\theta(z|x)$. After parameterization, the mean $\mu$ and covariance $\Sigma$ can be obtained directly from the data, yielding $q_\theta(z|x)=\mathcal{N}(\mu, \Sigma)$.

In contrast, the original GAN keeps $p(z)$ as a fixed standard multivariate Gaussian distribution and introduces an additional network $D(x', x)$ to classify generated samples $x'$ against real samples $x$, rather than relying on a fixed MSE loss function like VAE.

![](/api/kb-media/X4xtbpaJcovloPxOdP5cOSrFnDh)

The mathematical formulation of GAN is as follows. Although the formula looks straightforward, it contains many profound insights. Readers interested in the properties and optimization of GANs are strongly recommended to read [this article on WGAN](https://zhuanlan.zhihu.com/p/25071913).

$$
-\mathbb{E}_{x\sim P_r}[\log D(x)]-\mathbb{E}_{x\sim P_g}[\log(1- D(x))]
$$

**Flow Model**

Next, we introduce the third type of generative model: the Flow Model. We still start from the latent variable model:

$$
p(x)=\int p(x|z) \, p(z) \, \text{d}z
$$

Previously, we discussed how to use a neural network $f$ to represent $p_\theta(x|z)$ and establish the relationship between $z$ and $x$. The approach is as follows:

- **Step 1**: If we want to obtain the probability $p(x=x')$, we first study the function $f$ and find all $z$ such that $x'=f(z)$.

- **Step 2**: Suppose the solution set for $z$ is $\{z_1, z_2, \cdots, z_M\}$. Then the probability of $x'$ appearing is the sum of the probabilities of all these $z$ values, i.e., $p(x=x')=\sum_{i=1}^M p(z=z_i)$.

However, we know that finding the solution set for $z$ in Step 2 is extremely difficult. Therefore, even though $p(z)$ is simple and $f$ is a deterministic process, $p(x)$ is still hard to compute directly because $f$ is not necessarily invertible. As a compromise, instead of deriving an explicit expression for $p(x)$, we settle for being able to sample $x' \sim p(x)$ via Monte Carlo methods.

But what if we insist on deriving an explicit expression? It is possible, provided the following conditions are met:

- The function $f$ must be invertible — that is, given $x=f(z)$, it should be easy to derive $z = f^{-1}(x)$.

- Therefore, $f$ must be a bijective mapping, and $x$ and $z$ must have the same dimensionality. If $x \in \mathbb{R}^{D}$, then $z \in \mathbb{R}^{D}$.

- Since $f$ is bijective, we no longer need integration. We can directly perform a change of variables with $z = f^{-1}(x) \sim \mathcal{N}(0, I)$.

After the change of variables, the probability density becomes:

$$
p(x)=\frac{1}{(2\pi)^{D/2}}\exp\left(-\frac{1}{2}||f^{-1}(x)||^2\right)\bigg|\det\left[\frac{\partial f^{-1}}{\partial x}\right]\bigg|
$$

As we can see, in addition to requiring $f$ to be invertible, the determinant of the Jacobian of the inverse function $f^{-1}(x)$ must also be computationally efficient.

A representative work that fully embodies the Flow Model philosophy is RevNet (Reversible Network), shown below:

![](/api/kb-media/NyFSbnv8NoCJWQxQ0IycaIQxnrZ)

- Input is $x$, output is $y$

- $x$ is split into two parts $x_1$ and $x_2$; $y$ is also split into $y_1$ and $y_2$

- $\mathcal{F}$ and $\mathcal{G}$ are functions that preserve the tensor shape between input and output

The forward and backward passes can then be computed as:

![](/api/kb-media/XDsUbEIrOoBbDBxTUmZcQdXFnaf)

Note that this is fundamentally different from the memory-saving technique known as checkpointing:

- Checkpointing recomputes the current layer’s input using inputs from shallower layers.

- RevNet directly computes the current layer’s input from its output.

Once the input to the current layer is recovered, gradients can be computed normally. The complete gradient backpropagation formula is as follows:

![](/api/kb-media/YDgUbZ4b4ocUcqxPG8CcG1bqn5b)

## **Diffusion Model (DDPM)**

Finally, let’s take a look at the Diffusion Model, represented by DDPM, which has exploded in popularity in recent years. We return once again to the latent variable model:

$$
p(x)=\int p(x|z) \, p(z) \, \text{d}z
$$

Recall that VAE improves sampling efficiency for $p(z)$ through two components:

- **Encoder**: A parameterized posterior model $q_\theta(z|x)$ that directly predicts the mean $\mu$ and covariance $\Sigma$, so that $q_\theta(z|x)=\mathcal{N}(\mu, \Sigma)$.

- **Decoder**: After sampling $z$, it uses a parameterized distribution $p_\theta(x|z)$ to generate the final $\hat{x}$.

What if $q_\theta(z|x)$ is not generated in a single step, but instead requires $T$ steps? In that case, the encoder becomes:

$$
q_\theta(z|x)=q_\theta(z|x_{T-1})\cdot q_\theta(x_{T-1}|x_{T-2})\cdots q_\theta(x_{t}|x_{t-1}) \cdots q_\theta(x_2|x_1) \cdot q_\theta(x_1|x)
$$

Similarly, the decoder can be rewritten as:

$$
p_\theta(x|z)=p_\theta(x|x_1)\cdot p_\theta(x_1|x_2)\cdots p_\theta(x_{t-1}|x_t) \cdots p_\theta(x_{T-2}|x_{T-1})\cdot p_\theta(x_{T-1}|z)
$$

As shown below, this is the core idea of the diffusion model. However, it differs significantly from VAE.

(PS: We slightly change the notation — $x$ becomes $x_0$, and $z$ becomes $x_T$.)

![](/api/kb-media/ITtNb5jiqoU3tYxRJHfcHVSTnof)

- The encoder (right to left) is a **parameter-free** process $q(x_t|x_{t-1})$. Unlike VAE, which uses learnable parameters, this is a predefined process. Starting from the original clean image $x_0$, Gaussian noise is gradually added at each step until it becomes a standard multivariate Gaussian $x_T$.

- The decoder (left to right) is a **parameterized** model $p_\theta(x_{t-1}|x_t)$. Instead of directly predicting $\hat{x}$ like VAE, it predicts the Gaussian noise, which is then subtracted to recover a clearer image.

- Additionally, the intermediate latent variable $x_T$ now has the same dimensionality as the original image $x_0$.

**Encoder Process**

First, we define an increasing sequence of constants $\beta_t$ satisfying $0 < \beta_1 < \beta_2 < \cdots < \beta_T < 1$.

Let the observed original image be the random variable $x_0$. The transition from $x_{t-1}$ to $x_t$ is defined as:

$$
\begin{align}
q(x_t|x_{t-1})=\mathcal{N}(x_t;\sqrt{1-\beta_t}x_{t-1}, \beta_t )
\end{align}
$$

That is, $x_t$ follows a Gaussian distribution with mean $\sqrt{1-\beta_t}x_{t-1}$ and variance $\beta_t$. Using a reparameterization trick similar to VAE, we obtain:

$$
\begin{align}
x_t = \sqrt{1-\beta_t}x_{t-1} + \sqrt{\beta_t} \epsilon_{t-1}, \quad \epsilon_i \sim \mathcal{N}(0, 1)
\end{align}
$$

Equation (2) can be interpreted as follows:

- The squared coefficients in front of $x_{t-1}$ and $\epsilon_{t-1}$ sum to 1.
- Since $\beta_t$ increases monotonically and $\beta_t \in (0, 1)$, the variance is nearly 0 when $t=0$ and approaches 1 when $t=T$.

For convenience, we further define:

- $\alpha_t = 1 - \beta_t$
- $\bar{\alpha}_t = \prod_{i=1}^t \alpha_i$
- $\bar{\epsilon}_k \sim \mathcal{N}(0, 1)$, representing the merged Gaussian after combining $k$ independent Gaussians.

By recursively expanding the formula, we can derive:

```latex
\begin{align}
x_t &= \sqrt{\alpha_t} x_{t-1} + \sqrt{1-\alpha_t} \epsilon_{t-1} \\
    &= \sqrt{\alpha_t \alpha_{t-1}} x_{t-2} + \sqrt{1-\alpha_t \alpha_{t-1}} \bar{\epsilon}_2 \\
    &= \cdots \\
    &= \sqrt{\bar{\alpha}_t} x_0 + \sqrt{1-\bar{\alpha}_t} \bar{\epsilon}_t
\end{align}
```

**Notes**

- Here we use the property of variance: the sum of two Gaussian distributions is still a Gaussian, and the new variance equals the sum of the variances of the two Gaussians.
- $\bar{\epsilon}_k$ is the new Gaussian obtained after merging $k$ Gaussian distributions.
- The sum of the squares of the two coefficients in front of $x_0$ and $\bar{\epsilon}_t$ remains 1.

By observing $x_t$ in Equation (6), we can see that:

- As $t \rightarrow T$, $\sqrt{\bar{\alpha}_t} \rightarrow 0$ and $\sqrt{1-\bar{\alpha}_t} \rightarrow 1$, so $x_t \rightarrow \mathcal{N}(0, 1)$. It gradually becomes a standard Gaussian distribution. In the extreme case, $x_T = \mathcal{N}(0, 1)$.

- Not only can $q(x_t|x_{t-1}) = \mathcal{N}(\sqrt{1-\beta_t}x_{t-1}, \beta_t)$ be computed directly, but $q(x_t|x_0) = \mathcal{N}(\sqrt{\bar{\alpha}_t}x_0, 1-\bar{\alpha}_t)$ can also be computed directly.

- The entire encoder process is completely transparent, allowing us to efficiently compute any intermediate distribution $q(x_t|x_0)$.

**Optimization Objective**

After obtaining the encoder process, we next look for the optimization objective. There are [two derivation approaches](https://lilianweng.github.io/posts/2021-07-11-diffusion-models/):

- Method 1: Minimize $D_{\text{KL}}(q(x_{1:T}|x_0) || p_\theta(x_{1:T}|x_0))$ (same as in the VAE case).

- Method 2: Minimize the cross-entropy loss $-\mathbb{E}_{q(x_0)}\log p_\theta(x_0)$.

Both approaches lead to the same conclusion: we need to minimize $L_{t-1}$:

$$
L_{t-1} = \text{KL}(q(x_{t-1}|x_t, x_0) || p_\theta(x_{t-1}|x_t))
$$

- $q(x_{t-1}|x_t, x_0)$ can be obtained using Bayes’ rule.
- $p_\theta(x_{t-1}|x_t)$ is a parameterized model of $q(x_{t-1}|x_t)$. We assume it also follows a Gaussian distribution, so we only need to focus on its mean and variance.

**Analysis of $\mathbf{q(x_{t-1}|x_t, x_0)}$**

Using Bayes’ rule:

\begin{align}
q(x_{t-1}|x_t, x_0) &= q(x_t|x_{t-1},x_0) \frac{q(x_{t-1}|x_0)}{q(x_t|x_0)} \\
&= q(x_t|x_{t-1}) \frac{q(x_{t-1}|x_0)}{q(x_t|x_0)}
\end{align}
```

Surprisingly, we find that each \( q(\cdot) \) represents the probability density function of a Gaussian distribution. Therefore, we can substitute it in to obtain the density function of \( q(x_{t-1}|x_t, x_0) \), which is also a Gaussian distribution. At this point, we can use the method of undetermined coefficients to [derive](https://www.notion.so/classifier-guidance-5c758f6bf4fb477d8fd7528b1ba70ca1?pvs=21) the mean \( \mu_t(x_t, x_0) \) and variance \( \sigma_t^2(x_t, x_0) \) of \( q(x_{t-1}|x_t, x_0) \), as shown below:

\begin{align}
\mu_t(x_t,x_0)&=\frac{\sqrt{\alpha_t}(1-\bar{\alpha}_{t-1})}{1-\bar{\alpha}_t}x_t+\frac{\sqrt{\bar{\alpha}_{t-1}}(1-\alpha_t)}{1-\bar{\alpha}_t}x_0\\
\sigma_t^2(x_t, x_0)&=\frac{1-\bar{\alpha}_{t-1}}{1-\bar{\alpha}_t} \cdot \beta_t
\end{align}

By substituting \( x_0 \) in the above equation, we obtain:

\begin{align}
\mu_t(x_t,x_0)&=\frac{1}{\sqrt{\alpha_t}} \left(x_t-\frac{1-\alpha_t}{\sqrt{1-\bar{\alpha}_t}} \bar{\epsilon}_t\right)\\
\sigma_t^2(x_t, x_0)&=\frac{1-\bar{\alpha}_{t-1}}{1-\bar{\alpha}_t} \cdot \beta_t
\end{align}

Upon closer examination of the variance formula \( \sigma_t^2(x_t, x_0) \), we see that there are actually several possible choices:

- **Choice 1**: \( \bar{\alpha}_{t-1} \) and \( \bar{\alpha}_t \) are directly computed from the pre-defined \( \beta_t \), so the result is a constant.

- **Choice 2**: DDPM further shows that it can be simplified to \( \sigma_t^2(x_t, x_0)=\beta_t \).

- **Choice 3**: Improved DDPM shows that it can also be set as a learnable parameter.

Here we adopt the second choice, i.e., \( \sigma_t^2(x_t, x_0)=\beta_t \). Therefore:

\begin{align}
q(x_{t-1}|x_t, x_0)=\mathcal{N}(x_{t-1};\mu_t(x_t, x_0), \beta_t)
\end{align}

**Analysis of** \( \mathbf{p_\theta(x_{t-1}|x_t)} \)

Since we have already assumed that \( p_\theta(x_{t-1}|x_t) \) is a Gaussian distribution satisfying

\begin{align}
p_\theta(x_{t-1}|x_t)=\mathcal{N}(x_{t-1}; \mu_\theta(x_t, t), \beta_t)
\end{align}

when we compute the KL divergence between these two Gaussian distributions, we can use the known closed-form result to obtain:

\begin{align}
L_{t-1}&=\text{KL}(\mathcal{N}(x_{t-1};\mu_t(x_t, x_0), \beta_t)||\mathcal{N}(x_{t-1}; \mu_\theta(x_t, t), \beta_t))\\
&\propto||\mu_t(x_t, x_0)-\mu_\theta(x_t, t)||^2
\end{align}

One of the key contributions of DDPM is the discovery that instead of having the network directly predict \( \mu_\theta(x_t, t) \) to approximate \( \mu_t(x_t, x_0) \), it is better to have the network predict \( \epsilon_\theta(x_t,t) \) to approximate \( \bar{\epsilon}_t \). The relationship between \( \mu_\theta(x_t, t) \) and \( \epsilon_\theta(x_t,t) \) is as follows:

\begin{align}\mu_\theta(x_t, t)= \frac{1}{\sqrt{\alpha_t}} (x_t-\frac{1-\alpha_t}{\sqrt{1-\bar{\alpha}_t}} \epsilon_\theta(x_t,t))\end{align}

We have finally arrived at the final Loss expression:

\begin{align}L_{t-1} &\propto ||\bar{\epsilon}_t-\epsilon_\theta(x_t,t)||^2 \\&= ||\bar{\epsilon}_t-\epsilon_\theta(\sqrt{\bar{\alpha_t}}x_0 +\sqrt{1-\bar{\alpha_t}}\bar{\epsilon}_t,t)||^2\end{align}

Here, $\epsilon_\theta(\sqrt{\bar{\alpha_t}}x_0 +\sqrt{1-\bar{\alpha_t}}\bar{\epsilon}_t,t)$ is a U-Net network, and the timestep $t$ must be embedded (via timestep embedding) into the network.

**Training & Inference Process**

The training method now becomes clear. We refer to the pseudocode from the original DDPM paper:

![](/api/kb-media/Nlx4bWs1EojgHvxcT6lcaEfNnKP)

- During training, we only randomly sample one timestep from the entire $T$ steps. This is possible thanks to the nice property that $x_t$ can be computed directly from $x_0$.

- Lines 2–3: Randomly sample an image $x_0$ from the dataset and randomly select a timestep $t$.

- Line 4: Sample a value from the standard Gaussian distribution; this serves as the sample for $\bar{\epsilon}_t$, the combined noise from $t$ Gaussian distributions in the expression for $x_t$.

- Line 5: Compute the gradient according to the MSE loss derived above and perform a gradient update.

The corresponding inference process is shown below:

![](/api/kb-media/ZtmjbgNmmoEkrUxvNb7cWg1fnpb)

- Just like in a VAE, once training is complete, the encoder is discarded. We begin sampling from a standard Gaussian distribution and iteratively generate $x_0$ over $T$ steps.

- Line 1: Start from $x_T$ by sampling from a standard Gaussian.

- Lines 2–5: Let $t$ decrease from $T$ down to $t=1$.
  - At each step, the decoder takes $t$ and $x_t$ as input. The neural network first predicts the noise $\epsilon_\theta(x_t, t)$.
  - The mean of $x_{t-1}$ is computed using the formula for $\mu_\theta(x_t, t)$.
  - The variance $\sigma_t$ of $x_{t-1}$ can be calculated using the earlier formula for $\sigma_t(x_t, x_0)$. Using $\sigma_t^2 = \beta_t$ directly also works well, so there is no need for the neural network to predict the variance.
  - Finally, a sample is drawn from the Gaussian $\mathcal{N}(\mu_\theta(x_t, t), \sigma_t^2)$ to obtain $x_{t-1}$.

- A point that often causes confusion is why we still need to sample $z$ at each step of the generation process. Why not just use the mean of the Gaussian? The personal understanding is that this is similar to top-$p$ (nucleus) sampling during inference in ChatGPT (for those who forgot, refer to [(3) How is a ChatBot Built?](https://ywh1bkansf.feishu.cn/wiki/HRnLw588DiTDLPkSTXCcKit8nbD)). Introducing a certain amount of randomness ultimately leads to better results.

The DDPM derivation contains many details. Let’s summarize the core logic.

- First, model the encoder process as the forward diffusion process that gradually converts a clean image \( x_0 \) into standard Gaussian noise \( x_T \). The corresponding decoder process is the reverse sampling process that generates a clean image \( x_0 \) from standard Gaussian noise \( x_T \). What we ultimately need is the decoder process.

- Define a monotonically increasing sequence \( \beta_t \), and define the recursive expression for \( q(x_t | x_{t-1}) \).

- Using the recursive formula, we can derive the distribution of each step \( x_t \) in the encoder: \( q(x_t | x_0) \).

- Using Bayes' theorem, we can obtain the posterior distribution \( q(x_{t-1} | x_t, x_0) \), which follows \( \mathcal{N}(x_{t-1}; \mu_t(x_t, x_0), \sigma_t^2(x_t, x_0)) \).

- Variational analysis shows that the final optimization objective is  
  \( L_{t-1} = \text{KL}(q(x_{t-1}|x_t, x_0) || p_\theta(x_{t-1}|x_t)) \).

- Set the model’s reverse transition \( p_\theta(x_{t-1}|x_t) \) as a Gaussian distribution:  
  \( \mathcal{N}(x_{t-1}; \mu_\theta(x_t, t), \beta_t) \).

- Substitute into \( L_{t-1} \), solve and simplify the expression. It is ultimately discovered that the network only needs to predict the noise \( \epsilon_\theta(x_t, t) \) to approximate \( \bar{\epsilon}_t \).

**Understanding DDPM through the Score Function**

**Energy Function**

For any distribution \( p(\textbf{x}): \mathbb{R}^{D} \rightarrow \mathbb{R} \), it is impossible to directly fit it with a neural network that takes a \( D \)-dimensional input and produces a 1-dimensional output. This is because the distribution must satisfy

\[ \int p(\textbf{x}) \, dx = 1 \]

However, after the following transformation, we find that \( f_\theta(\textbf{x}) \) has almost no constraints:

\[ p(\textbf{x}) = \frac{1}{Z_\theta} e^{-f_\theta(\textbf{x})} \]

Although this introduces a normalization constant \( Z_\theta \) in the denominator, if we take the logarithm and differentiate with respect to \( \textbf{x} \), we get:

\begin{align}
\nabla_\textbf{x}\log p(\textbf{x}) &= \nabla_\textbf{x}\log \left( \frac{1}{Z_\theta} e^{-f_\theta(\textbf{x})} \right) \\
&= \nabla_\textbf{x}\log \frac{1}{Z_\theta} + \nabla_\textbf{x}\log \left( e^{-f_\theta(\textbf{x})} \right) \\
&= -\nabla_\textbf{x} f_\theta(\textbf{x})
\end{align}

Surprisingly, the \( Z_\theta \) term disappears. Here, \( f_\theta(\textbf{x}) \) is the **energy function**, which is a free function with no restrictions.

**Score Function**

Taking a closer look, we see that \( \nabla_\textbf{x}\log p(\textbf{x}) \) represents the direction of steepest ascent that maximizes the probability \( p(\textbf{x}) \). It is a vector field, where the vectors point toward the direction of increasing probability.

![](/api/kb-media/Ekylbd7DioOq6jxjCZxczwi0nKb)

If we now define a function \( \mathbf{s}_\theta(\textbf{x}) \in \mathbb{R}^{D} \rightarrow \mathbb{R}^{D} \) and train it to directly approximate \( \nabla_\textbf{x}\log p(\textbf{x}) \) by minimizing the following objective:

\[ \mathbb{E}_{p(\textbf{x})} \left[ \| \mathbf{s}_\theta(\mathbf{x}) - \nabla_\textbf{x}\log p(\textbf{x}) \|_2^2 \right] \]

When the model converges, the vector field formed by \( \mathbf{s}_\theta(\textbf{x}) \) will point toward the modes of \( p(\textbf{x}) \). Walking along the direction of \( \mathbf{s}_\theta(\textbf{x}) \) allows us to find the maxima of \( p(\textbf{x}) \). This \( \mathbf{s}_\theta(\textbf{x}) \) is called the **score function** of \( p(\textbf{x}) \).

**An Alternative View of DDPM**

What does DDPM have to do with the score function?

Consider a Gaussian random variable \( z \sim \mathcal{N}(\mu, \sigma^2) \). Given an observation of \( z \), the expected value of the mean \( \mu \) satisfies **Tweedie’s Formula**:

\[ \mathbb{E}(\mu|z) = z + \sigma^2 \nabla_z \log p(z) \]

Recall that in DDPM, the forward process is defined as \( q(x_t|x_0) = \mathcal{N}(x_t; \sqrt{\bar{\alpha}_t} x_0, 1 - \bar{\alpha}_t) \). Therefore,

\[ \mathbb{E}(\mu_t | x_t) = x_t + (1 - \bar{\alpha}_t) \nabla_{x_t} \log p(x_t) \]

Additionally, the optimal estimate of \( \mu_t \) is the mean of this Gaussian, i.e.,

\[ \sqrt{\bar{\alpha}_t} x_0 = \mathbb{E}(\mu_t | x_t) = x_t + (1 - \bar{\alpha}_t) \nabla_{x_t} \log p(x_t) \]

Therefore, \( x_0 \) can be expressed using \( \nabla_{x_t} \log p(x_t) \):

$$
x_0 = \frac{x_t + (1 - \bar{\alpha}_t) \nabla_{x_t} \log p(x_t)}{\sqrt{\bar{\alpha}_t}}
$$

Substituting \( x_0 \) into the formula for \( \mu_t(x_t, x_0) \) (Equation 7), we obtain:

$$
\mu_t(x_t, x_0) = \frac{1}{\sqrt{\alpha_t}} x_t + \frac{1 - \alpha_t}{\sqrt{\alpha_t}} \nabla_{x_t} \log p(x_t)
$$

At this point, it is similar to the \( \epsilon_\theta(x_t, t) \) and \( \bar{\epsilon}_t \) in the earlier DDPM. Here, we can use \( s_\theta(x_t, t) \) to approximate \( \nabla_{x_t} \log p(x_t) \), i.e.:

$$
\begin{align}
L_{t-1} &\propto \| s_\theta(x_t, t) - \nabla_{x_t} \log p(x_t) \|_2^2
\end{align}
$$

After training is complete, during inference sampling, we first obtain \( s_\theta(x_t, t) \) and then compute:

$$
\mu_\theta(x_t, x_0) = \frac{1}{\sqrt{\alpha_t}} x_t + \frac{1 - \alpha_t}{\sqrt{\alpha_t}} s_\theta(x_t, t)
$$

We then sample to obtain \( x_{t-1} \):

$$
x_{t-1} = \mathcal{N}(x_{t-1}; \mu_\theta(x_t, x_0), \beta_t)
$$

Thus, we have gained another perspective for understanding DDPM: using the network \( s_\theta(x_t, t) \) to predict \( \nabla_{x_t} \log p(x_t) \).

## DDIM

The motivation behind DDIM is to reduce the number of sampling steps. Observing the recursive formula in DDPM:

$$
x_{t-1} = q(x_{t-1} | x_0) = \sqrt{\bar{\alpha}_{t-1}} x_0 + \sqrt{1 - \bar{\alpha}_{t-1}} \bar{\epsilon}_{t-1}
$$

DDIM introduces two key insights:

- Insight 1: Decompose the Gaussian noise \( \bar{\epsilon}_{t-1} \) into the sum of two Gaussian terms \( \bar{\epsilon}_t \) and \( \epsilon \).
- Insight 2: “Create” \( x_0 \) out of nothing by estimating it from \( x_t \) and \( \bar{\epsilon}_t \), and then use it in the computation of \( x_{t-1} \).

$$
\begin{align}
x_{t-1} &\approx \sqrt{\bar{\alpha}_{t-1}} x_0 + \sqrt{1 - \bar{\alpha}_{t-1} - \sigma_t^2} \bar{\epsilon}_t + \sigma_t \epsilon \\
&\approx \sqrt{\bar{\alpha}_{t-1}} \left( \frac{x_t - \sqrt{1 - \bar{\alpha}_t} \bar{\epsilon}_t}{\sqrt{\bar{\alpha}_t}} \right) + \sqrt{1 - \bar{\alpha}_{t-1} - \sigma_t^2} \bar{\epsilon}_t + \sigma_t \epsilon
\end{align}
$$

If we let the U-Net learn \( \bar{\epsilon}_t \), i.e., \( \epsilon_\theta^t(x_t) \), we arrive at the final expression:

$$
x_{t-1} = \sqrt{\bar{\alpha}_{t-1}} \left( \frac{x_t - \sqrt{1 - \bar{\alpha}_t} \cdot \epsilon_\theta^t(x_t)}{\sqrt{\bar{\alpha}_t}} \right) + \sqrt{1 - \bar{\alpha}_{t-1} - \sigma_t^2} \cdot \epsilon_\theta^t(x_t) + \sigma_t \epsilon
$$

As we can see, at each recursive step, we first estimate \( x_0 \) from the current \( x_t \) and the predicted noise \( \epsilon_\theta^t(x_t) \), and then use it to compute \( x_{t-1} \). Note that the variance here is \( \sigma_t \). Recall that the variance in the original DDPM was

\sigma_t^2(x_t, x_0)=\frac{1-\bar{\alpha}_{t-1}}{1-\bar{\alpha}_t} \cdot \beta_t

Therefore, for the variance to be comparable, we require

\sigma_t^2=\frac{1-\bar{\alpha}_{t-1}}{1-\bar{\alpha}_t} \cdot \beta_t=\eta \cdot \beta_t

It is clear that \eta must be non-negative. When \eta=0, the process becomes deterministic. This is exactly DDIM:

x_{t-1}=\sqrt{\bar{\alpha}_{t-1}}\left(\frac{x_t-\sqrt{1-\bar{\alpha}_t} \cdot \epsilon_\theta^t(x_t)}{\sqrt{\bar{\alpha}_t}}\right)+\sqrt{1-\bar{\alpha}_{t-1}} \cdot\epsilon_\theta^t(x_t)

Thus, DDIM primarily turns the reverse process into a deterministic one and significantly reduces the number of sampling steps.

## Classifier-Guided Diffusion

Although the images generated by DDPM and DDIM look visually decent, they have consistently lagged behind GANs on metrics such as FID. This changed with the emergence of the Classifier-Guided method, which essentially trades off some diversity for improved fidelity.

**DDPM Process**

We want to understand how adding a label \( y \) in DDPM affects the generation of \( x_t \). Note that the model’s encoder (forward process) remains unchanged. Starting from the original definition of \( p(x_t|x_{t+1}, y) \), we apply Bayes’ rule and eventually obtain the following formula:

\begin{align}
p(x_t|x_{t+1},y) &= \frac{p(x_t|x_{t+1})p(y|x_t, x_{t+1})p(x_{t+1})}{p(y|x_{t+1})p(x_{t+1})}\\
&= \frac{p(x_t|x_{t+1})p(y|x_t)}{p(y|x_{t+1})}\\
&= Z \cdot p_\theta(x_t|x_{t+1}) \cdot p_\phi(y|x_t)
\end{align}

**Derivation Hints:**

- \( y \) is independent of \( x_{t+1} \), so \( p(x_{t+1}|x_t, y)=p(x_{t+1}|x_t) \)
- For a given image, the value of \( y \) is fixed, therefore \( p(y|x_{t+1})=p(y)=\text{const} \)

Taking the logarithm on both sides and introducing a scaling factor \( s \) to \( \log p_\phi(y|x_t) \), we get:

\log p(x_t|x_{t+1}, y) = \log p_\theta(x_t|x_{t+1}) + s \cdot \log p_\phi(y|x_t)

Further analysis (full derivation available in [this article](https://sunlin-ai.github.io/2022/05/30/guided-diffusion.html)) shows:

- The \( \log p_\theta(x_t|x_{t+1}) \) term is a Gaussian distribution in DDPM. Its mean \( \mu_\theta(x_t, t) \) can be computed from \( \epsilon_\theta(x_t, t) \), so the log-probability can be written using the Gaussian density function.
- For the \( \log p_\phi(y|x_t) \) term, performing a Taylor expansion around \( x_t=\mu_\theta(x_t, t) \) yields the final expression:

\begin{align}
\log p(x_t|x_{t+1}, y) &= \log p(z) + C,\ \ z \sim \mathcal{N}(\mu_\theta(x_t, t)+\sigma\cdot s \cdot\nabla_{x_t}\log p_\phi(y|x_t), \sigma^2)
\end{align}

The final sampling procedure is shown below. In essence, it applies a correction to the mean:

![](/api/kb-media/SlDXb6uX3onUaDxhUEccR2m3n8e)

**DDIM Process**

Since DDIM is a deterministic process, \( p(x_t | x_{t+1}) \) is a deterministic mapping rather than a distribution. The target object therefore degenerates from \( p(x_t | x_{t+1}, y) \) to \( p(x_t | y) \).

According to Bayes’ theorem:

$$
p(x_t | y) = \frac{p(y | x_t) \cdot p(x_t)}{p(y)}
$$

Take the logarithm on both sides and differentiate with respect to \( x_t \) (note that \( y \) cannot be expressed by \( x_t \), so \( \nabla_{x_t} \log p(y) = 0 \)):

$$
\begin{align}
\nabla_{x_t} \log p(x_t | y) 
&= \nabla_{x_t} \log p(y | x_t) + \nabla_{x_t} \log p(x_t) - \nabla_{x_t} \log p(y) \\
&= \nabla_{x_t} \log p(y | x_t) + \nabla_{x_t} \log p(x_t)
\end{align}
$$

Add a scaling factor to \( \nabla_{x_t} \log p(y | x_t) \) to facilitate label strength adjustment:

$$
\begin{align}
\nabla_{x_t} \log p(x_t | y) 
= \nabla_{x_t} \log p(x_t) + \gamma \cdot \nabla_{x_t} \log p(y | x_t)
\end{align}
$$

From the paper’s conclusion (https://arxiv.org/abs/2105.05233), using the property of the score function:

$$
\nabla_{x_t} \log p(x_t) = -\frac{1}{\sqrt{1 - \bar{\alpha}_t}} \epsilon(x_t)
$$

Substituting and rearranging, and parameterizing the probability (where \( p_\phi(y | x_t) \) is the classifier), we obtain:

$$
-\frac{1}{\sqrt{1 - \bar{\alpha}_t}} \epsilon_\theta^t(x_t | y) 
= -\frac{1}{\sqrt{1 - \bar{\alpha}_t}} \epsilon_\theta^t(x_t) 
+ \gamma \cdot \nabla_{x_t} \log p_\phi(y | x_t)
$$

Rearranging gives:

$$
\epsilon_\theta^t(x_t | y) = \epsilon_\theta^t(x_t) - \sqrt{1 - \bar{\alpha}_t} \cdot \gamma \cdot \nabla_{x_t} \log p_\phi(y | x_t)
$$

After computing \( \epsilon_\theta^t(x_t) \), correct it using the classifier’s gradient to obtain \( \epsilon_\theta^t(x_t | y) \), then replace the original \( \epsilon_\theta^t(x_t) \). Finally, substitute into the DDIM recurrence formula.

The complete **Classifier-Guided DDIM** algorithm is as follows:

![](/api/kb-media/KwYubf8gnoNqm0x61iIcK9tinIe)

## Classifier-Free Guidance

Although training can improve fidelity, it comes with many issues. Whether using DDPM or DDIM during inference, every step requires computing gradients, which is computationally expensive. The classifier itself is a specialized version designed to handle noisy inputs and must be retrained (e.g., a noisy-CLIP model). Is it possible to achieve both high-fidelity results and eliminate gradient computation during inference? Classifier-free guidance was developed to address this. Its core idea is to enhance the model’s capability during the training phase, thereby removing the need for gradient calculations at inference time.

The network first ingests the condition. Note that this condition must be related to the data. For example:
- In classification tasks, it is the class of the image to be generated.
- In text-to-image tasks, it is the text embedding.

During training, the input condition is randomly set to null with a certain probability, i.e.:

$$
\epsilon_\theta(x_t|y) \rightarrow \epsilon_\theta(x_t|\varnothing)
$$

In the inference sampling stage, the following formula is used:

$$
\hat{\epsilon}_\theta(x_t|y)=(1+w)\cdot \epsilon_\theta(x_t|y)-w\cdot\epsilon_\theta(x_t|\varnothing)
$$

where $w$ is the guidance strength. It is generally believed that when $w>0$, the generation process is steered toward directions where the difference between the conditioned and unconditioned outputs is larger. The stronger the guidance, the more diversity is sacrificed in exchange for higher fidelity. Here, $y$ can be replaced with other types of conditions.

## Summary

Generative models are underpinned by a large amount of mathematical theory. At their core, they aim to solve the problem of how to generate $p(X)$. A summary of various methods is shown below:

![](/api/kb-media/IkbXbeuXMoSKu7xZKwEcFQ6TnJb)

# AIGC Evaluation Metrics

Multimodal content generated by AIGC often carries strong subjective characteristics, making evaluation relatively difficult. In this section, we introduce two commonly used metrics for assessing image generation quality: IS (Inception Score) and FID (Fréchet Inception Distance).

## IS Score (Inception Score)

Inception Score (IS) is a highly intuitive metric. It is designed based on the property that **the Inception network has strong discriminative power on real images**. There are two perspectives to understand this metric: the mutual information perspective and the KL divergence perspective.

Symbol definitions are as follows:

- \( x \) is a random variable generated by the image generation network \( G \). Let the set of images generated by \( G \) be \( X_G \), and the distribution of images generated by \( G \) be \( P_G \). Then \( x \in X_G \) and \( x \sim P_G \).

- \( y \) is a random variable whose value lies in the discrete set \( L_Y = \{1, 2, \cdots, 1000\} \). Let the 1000-class probability vector output by the Inception network after softmax be \( \mathbf{p} \). Then \( y \in L_Y \) and \( p(y=i) = \mathbf{p}_i \).

We can understand this metric from two perspectives: mutual information and KL divergence.

**Mutual Information**

First, from the mutual information perspective, we examine \( I(y;x) \), which measures the degree of dependence between the two random variables \( y \) and \( x \).

- Case 1: If \( x \) is a random noise image, the information in \( x \) provides no help in determining \( y \). \( x \) and \( y \) are completely independent, so \( I(y;x) = 0 \).

- Case 2: If \( x \) constitutes the entire ImageNet dataset, then \( x \) alone can completely determine the distribution of \( y \). The two are fully correlated, and \( I(y;x) \) should reach its maximum value.

From this we can see that \( I(y;x) \) has a positive correlation with how realistic \( x \) is. If we further analyze \( I(y;x) \) and want to know what conditions the maximum value should satisfy, we can derive it from the mutual information formula:

$$
I(y;x) = H(y) - H(y|x)
$$

To maximize this metric, we need:

- **Diversity**: Maximize the first term \( H(y) \). The more uniform the distribution of \( y \), the greater the diversity and the less mode collapse occurs. \( H(y) \) reaches its maximum when \( y \) follows a uniform distribution.

- **Clarity**: Minimize the second term \( H(y|X) \), which represents the entropy of the label \( y \) given the image \( x \). The sharper the distribution (closer to one-hot), the smaller \( H(y|X) \) becomes.

Therefore, the maximum value of \( I(y;x) \) is:

$$
\begin{align}
I_\text{max}(y; x) &= H(y) - 0 \\
&= -\sum_{i=1}^{1000}\frac{1}{1000}\ln\left(\frac{1}{1000}\right) \\
&= \ln(1000)
\end{align}
$$

**KL Divergence**

From another perspective, we examine the KL divergence, which gives the standard definition of IS:

$$
\text{IS}(G)=\exp\left(\mathbb{E}_{x\sim {P_G}}[\text{KL}(p(y|x)||p(y))]\right)
$$

Although this expression looks complex, mathematical derivation shows that it is equivalent to the mutual information \( I(y;x) \) above. The complete derivation is as follows:

$$
\begin{align}
\ln(\text{IS}(G)) &= \mathbb{E}_{x\sim {P_G}}[\text{KL}(p(y|x)||p(y))] \\
&= \sum_{x\in X_G} p(x)\sum_{y\in L_Y}p(y=i|x)\cdot \ln\frac{p(y=i|x)}{p(y=i)} \\
&= \sum_{x\in X_G} \sum_{y\in L_Y} p(y=i, x)\cdot \ln p(y=i|x) - \sum_{x\in X_G} \sum_{y\in L_Y} p(y=i, x)\cdot \ln p(y=i)\\
&= -H(y;x) + \left(-\sum_{y\in L_Y} \ln p(y=i)\sum_{x\in X_G}p(y=i, x)\right) \\
&= -H(y;x) + \left(-\sum_{y\in L_Y} \ln p(y=i) \cdot p(y=i)\right) \\
&= -H(y;x) + H(y) \\
&= I(y;x)
\end{align}
$$

Therefore, we obtain:

$$
\text{IS}(G)=e^{I(y;x)}
$$

**Implementation Code**

Assumptions:

- Suppose we select \( N \) images, denoted as \( \{x_1, x_2, \cdots, x_N\} \).

- Feed these \( N \) images into the Inception network to obtain the output softmax probability tensor \( Z \in \mathbb{R}^{N \times 1000} \).

- \( Z(i, j) \) corresponds to \( p(y=j|x=x_i) \), i.e., the probability of the \( j \)-th label for the \( i \)-th image.

- \( p(x=x_i)=1/N \), treated as a uniform distribution.

- The marginal distribution is rewritten in the form of a sum over conditional probabilities.

```latex
\begin{align}p(y=j)&=\sum_{i=1}^Np(y=j, x=x_i)\\&=\sum_{i=1}^N p(x=x_i) \cdot p(y=j|x=x_i) \\&=\frac{1}{N}\sum_{i=1}^N p(y=j|x=x_i)\end{align}

Therefore, we can obtain a computable expression for IS as follows:

\begin{align}\text{IS}(G)&=\exp(\sum_{x\in X_G} p(x)\sum_{y\in L_Y}p(y=i|x)\cdot \ln\frac{p(y=i|x)}{p(y=i)}) \\&=\exp(\sum_{i=1}^N \frac{1}{N}\sum_{j=1}^{1000} p(y=j|x=x_i)\cdot \ln\frac{p(y=j|x=x_i)}{\frac{1}{N}\sum_{k=1}^Np(y=j|x=x_k)}) \\\end{align}

At this point, we can finally replace all $p(y=j|x=x_i)$ with $Z$, which gives:

\begin{align}\text{IS}(G)&=\exp(\frac{1}{N} \sum_{i=1}^N \sum_{j=1}^{1000} Z(i,j)\cdot \ln\frac{Z(i,j)}{\frac{1}{N}\sum_{k=1}^NZ(k,j)}) \\\end{align}

The final code is as follows (typically split into multiple splits for computation, then calculate the mean and variance):

```python
def calculate_inception_score(z_preds, splits=10):
    # z_preds: (N, 1000)
    scores = []
    for i in range(splits):
        slice_start = i * z_preds.shape[0] // splits
        slice_end = (i + 1) * z_preds.shape[0] // splits
        part = z_preds[slice_start:slice_end, :]
        kl = part * (np.log(part) - np.log(np.mean(part, 0, keepdims=True)))
        kl = np.mean(np.sum(kl, 1))
        kl = np.exp(kl)
        scores.append(kl)
    return np.mean(scores), np.std(scores)
```
```

## **FID Score**

The term “Fréchet” comes from the name of a French mathematician who proposed the concept of Fréchet Distance.

The calculation process of the Fréchet Inception Distance (FID) metric is as follows:

- Given a set of generated images \( X_G \) and a set of real images \( X_R \), with sizes \( N \) and \( M \) respectively.

- Both \( X_G \) and \( X_R \) are passed through an Inception v3 network to obtain the corresponding feature sets \( F_G \in \mathbb{R}^{N \times D} \) and \( F_R \in \mathbb{R}^{M \times D} \).

- Treat \( F_G \) and \( F_R \) as samples drawn from two distributions \( P_G \) and \( P_R \), where \( \mu_G \) and \( \Sigma_G \) are the mean and covariance of \( P_G \), and \( \mu_R \) and \( \Sigma_R \) are the mean and covariance of \( P_R \).

- Under the assumption that both \( P_G \) and \( P_R \) are multivariate Gaussian distributions, the FID can be computed according to the definition of Fréchet Distance (FD):

$$
\text{FID}(X_G, X_R)=\text{FD}(P_G, P_R)=||\mu_G-\mu_R||^2_2+\text{Tr}(\Sigma_G+\Sigma_R-2(\Sigma_G \Sigma_R)^{\frac{1}{2}})
$$

Here is some intuitive personal understanding:

- FID measures the distance between generated images and real images. The smaller the value, the better.

- The mathematical definition of the FD metric is quite complex. It is also known as the 2-Wasserstein distance and is closely related to optimal transport theory.

- The FD metric itself is a lower bound. It can be understood as the minimum expected transport cost of projecting the probability distribution \( P_G \) onto \( P_R \). For the detailed mathematical definition, see the [Wikipedia page](https://en.wikipedia.org/wiki/Wasserstein_metric).

The code for calculating the FD metric is as follows:

```python
import numpy as np
from scipy import linalg

def calculate_frechet_distance(feat_G, feat_R, eps=1e-6):
    # feat_G: (N, D)
    # feat_R: (M, D)
    mu1, sigma1 = np.mean(feat_G, axis=0), np.cov(feat_G.T)
    mu2, sigma2 = np.mean(feat_R, axis=0), np.cov(feat_R.T)
    diff = mu1 - mu2

    # product might be almost singular
    covmean, _ = linalg.sqrtm(sigma1.dot(sigma2), disp=False)
    if not np.isfinite(covmean).all():
        offset = np.eye(sigma1.shape[0]) * eps
        covmean = linalg.sqrtm((sigma1 + offset).dot(sigma2 + offset))

    # numerical error might give slight imaginary component
    if np.iscomplexobj(covmean):
        if not np.allclose(np.diagonal(covmean).imag, 0, atol=1e-3):
            m = np.max(np.abs(covmean.imag))
            raise ValueError("Imaginary component {}".format(m))
        covmean = covmean.real

    tr_covmean = np.trace(covmean)

    return diff.dot(diff) + np.trace(sigma1) + np.trace(sigma2) - 2 * tr_covmean
```

## **Summary**

- The IS metric relies on a strong prior assumption that only distributions matching ImageNet are considered “real.”

- The FID metric measures the distance between two datasets and is generally regarded as more scientifically sound.

**Final Note**

This article is divided into two main sections.

- The first section introduces the fundamental goal of generative models: to model the distribution *p(x)*.
  - It begins with the most basic approach — maximum likelihood estimation. While simple, it requires an explicit parametric form of the distribution, which is often unavailable in practice.
  - It then introduces four types of latent variable models: VAE, GAN, Flow Models, and Diffusion Models. At their core, they all approximate *p(x) = ∫ p(x|z) p(z) dz*.
  - **VAE**: Attempts to improve the sampling efficiency of *p(z)* by minimizing *KL(q_θ(z|x) || p(z))*, ultimately resulting in a regularization term and a reconstruction error term.
  - **GAN**: Extends the MSE loss function further by introducing a discriminator *D(x', x)* to implicitly learn a distance metric.
  - **Flow Models**: Force the function *f* to be invertible, establishing a one-to-one mapping between *x* and *z*. The article uses RevNet as an example to illustrate how Flow Models are implemented in practice.
  - **Diffusion Models (DDPM)**: Extend VAE to multiple steps. Although the mathematical derivation is complex, the core idea remains similar to that of VAE.
  - **Score Function in DDPM**: Offers an alternative perspective on DDPM, showing that a network *s_θ(x_t, t)* can be used to predict *∇_{x_t} log p(x_t)*.
  - **DDIM**: Attempts to accelerate sampling in DDPM by turning the process into a deterministic one.
  - **Classifier-Guided**: Uses classifier-guided techniques to raise the IS and FID scores of both DDPM and DDIM to levels comparable with GANs for the first time. During inference, DDPM can directly compute *p(x_t | x_{t+1}, y)*; for DDIM, since it is a deterministic process, it degenerates into computing *p(x_t | y)*.
  - **Classifier-Free**: Eliminates the need for gradient computation required by classifier-guided methods. It jointly trains both conditional and unconditional models during training, allowing gradient-free inference. This approach improves fidelity while maintaining high computational efficiency.

- The second section introduces two common evaluation metrics for image generation.
  - **Inception Score (IS)**: Provides two perspectives for understanding. IS carries a strong prior assumption that distributions aligned with ImageNet represent the “real” distribution.
  - **Fréchet Inception Distance (FID)**: Measures the distance between two datasets and is considered a more scientifically grounded metric.

**Preview**: The next article, *Principles of AIGC (Part 2)*, will cover specific algorithms for Image generation, Video generation, Audio generation, and 3D generation. Stay tuned.

**PS**: Since the author, Xiao A, has not personally implemented every detail mentioned above, most of the content was synthesized in a bottom-up manner through studying code and carefully reading excellent papers. In essence, this is a compilation of others’ insights — the work of a knowledge porter. It remains theoretical on paper. Therefore, I sincerely welcome experts with hands-on experience to critique and refine it. Only through the collision of ideas can sparks fly and truth emerge through debate.

**If you want to learn about Transformer algorithms in NLP, multimodal learning, and AIGC, knowledge of distributed training, as well as how to perform PTQ quantization and deployment on TVM, feel free to follow me — aaronxic~**

---

**Series Article Navigation**

- [(1) What Exactly Is the Perplexity Metric?](https://ywh1bkansf.feishu.cn/wiki/E1pjwy9OMirKTdkFQDEcDDlfnTh)

- [(2) A First Look at LLM Foundation Models](https://ywh1bkansf.feishu.cn/wiki/UU9pwtOFtiKIqAkQiSVc3Zdun7e)

- [(3) How Is a ChatBot Built?](https://ywh1bkansf.feishu.cn/wiki/HRnLw588DiTDLPkSTXCcKit8nbD)

- [(4) The Road to Multimodal Unification](https://ywh1bkansf.feishu.cn/wiki/ReVzwZUr0ivgWfkaQ91cXrYUnoh)

**References**

- [Some Notes on AIGC](https://zhuanlan.zhihu.com/p/615522634)

- [Deriving Variational Autoencoders (VAE) from Scratch](https://zhuanlan.zhihu.com/p/249296925)

- [Variational Autoencoders (Part 1): So That’s How It Works - Scientific Spaces](https://spaces.ac.cn/archives/5253)

- [NICE: Basic Concepts and Implementation of Flow Models - Scientific Spaces](https://spaces.ac.cn/archives/5776)

- [A Casual Tour of Generative Diffusion Models (Part 1): DDPM = Demolition + Reconstruction - Scientific Spaces](https://spaces.ac.cn/archives/9119/comment-page-1)

- [What are Diffusion Models?](https://lilianweng.github.io/posts/2021-07-11-diffusion-models/)

- [DDPM: Diffusion Models](https://zhuanlan.zhihu.com/p/563661713)

- [PyTorch 32. Gumbel-Softmax Trick](https://zhuanlan.zhihu.com/p/166632315)

- [Paper Notes: Diffusion Models Beat GANs on Image Synthesis](https://sunlin-ai.github.io/2022/05/30/guided-diffusion.html)

- [Understanding the Loss Function of Diffusion Models](https://zhuanlan.zhihu.com/p/629334231)

- [Can Anyone Explain the Inception Score? - Zhihu](https://www.zhihu.com/question/297551781)

- [GAN Evaluation Metrics: IS and FID - CSDN Blog](https://blog.csdn.net/jackzhang11/article/details/104995524)

- [Mutual Information - Wikipedia](https://zh.wikipedia.org/zh-cn/%E4%BA%92%E4%BF%A1%E6%81%AF)

- [IS, FID, PPL: Evaluation Metrics for GANs](https://zhuanlan.zhihu.com/p/432965561)

- [Fréchet Inception Distance](https://en.wikipedia.org/wiki/Fr%C3%A9chet_inception_distance)

- [The Amazing Wasserstein GAN](https://zhuanlan.zhihu.com/p/25071913)
