建议搭配 Diffusion 和 Flow Matching 博客食用,本篇只会简单介绍其数学推导。为了表述符合规范,本博客主要使用英文进行讲解,一些重要内容或存疑内容会附赠中文解释。为保证连贯性,本篇将花费较多篇幅完整记录 6.S184 课程的所有内容,故将采取分段更新的形式。

L1. Flow and Diffusion


Key ideas

Let us define what it means to generate something. In machine learning, we call a data distribution as the space of data itself, and denote it as pdatap_{\mathrm{data}}. Mathematically, one can think of pdatap_{\mathrm{data}} as a probability density, i.e. a function

pdata:Rd→R⩾0p_{\mathrm{data}}:\mathbb{R}^d \rightarrow \mathbb{R}_{\geqslant0}

A generative model is a machine learning model that allows us to generate samples from pdatap_{\mathrm{data}}. When generating a new object zz, we say that we sample it from the data distribution pdatap_{\mathrm{data}}.

A dataset consists of a finite number of samples z1,⋯ ,zN∼pdataz_1,\cdots,z_N \sim p_{\mathrm{data}}. In many cases, we want to generate an object conditioned on some data yy. We can rephrase this as sampling from a conditional distribution pdata(⋅∣y)p_{\mathrm{data}}(\cdot|y), where yy is a conditioning variable.

In the following chapters, we will talk about how to realize this sampling process.

Flow and ODEs

We start by defining ordinary differential equations (ODEs). Every ODE is defined by a vector field uu, which has both spatial feature x∈Rdx\in\mathbb{R}^d and temporal feature t∈[0,1]t\in[0,1] as follows

u:Rd×[0,1]→Rd,(x,t)↦ut(x)\begin{equation}u:\mathbb{R}^d\times[0,1]\rightarrow\mathbb{R}^d,\quad (x,t)\mapsto u_t(x)\end{equation}

An ODE imposes a condition on a trajectory: we want a trajectory X=XtX=X_t that follows along the lines of the vector field utu_t, starting at the point x0x_0. This could be described as an ODE equation

ddtXt=ut(Xt),X0=x0\begin{equation}\frac{\mathrm{d}}{\mathrm{d}t}X_t=u_t(X_t),\quad X_0=x_0\end{equation}

We may now ask: if we start at X0=x0X_0 = x_0 at t=0t = 0, where are we at time tt (what is XtX_t)? This question is answered by a function called the flow, which is a solution to the ODE

ψ:Rd×[0,1]→Rd,ψt(X0)=Xt\begin{equation}\psi:\mathbb{R}^d\times[0,1]\rightarrow\mathbb{R}^d,\quad \psi_t(X_0)=X_t\end{equation}

Therefore, vector fields, ODEs, and flows are, intuitively, three descriptions of the same object: vector fields define ODEs whose solutions are flows.

也就是说,速度场 ut(x)u_t(x) 定义了一个常微分方程 ODE,其解可以表示为流函数 ψ\psi。

If u:Rd×[0,1]→Rdu:\mathbb{R}^d\times[0,1]\rightarrow\mathbb{R}^d is continuously differentiable with a bounded derivative, then the ODE above has a unique solution given by a flow ψt\psi_t.

We can now construct a generative model via an ODE by making the vector field a neural network vector field utθu^{\theta}_t. Specifically, we choose an initial distribution pinit∼N(0,Id)p_{\mathrm{init}}\sim \mathcal{N}(0,I_d) for simplicity. A flow model is then described by the following ODE

X0∼pinit,ddtXt=utθ(Xt)X_0\sim p_{\mathrm{init}},\quad \frac{\mathrm{d}}{\mathrm{d}t}X_t=u^{\theta}_t(X_t)

Our goal is to make the endpoint X1X_1 of the trajectory have distribution pdatap_{\mathrm{data}}, i.e.

X1=ψ1θ(X0)∼pdataX_1=\psi_1^{\theta}(X_0)\sim p_{\mathrm{data}}

where ψtθ\psi^{\theta}_t describes the flow induced by utθu^{\theta}_t. In order to compute the flow, we need to simulate the ODE. One way is to use the Euler method with the iteration steps Xt+h=Xt+hut(Xt)X_{t+h}=X_t+hu_t(X_t), which hh is very small.

Diffusion and SDEs

Stochastic differential equations (SDEs) extend the deterministic trajectories from ODEs with stochastic trajectories. A stochastic trajectory is commonly called a stochastic process (Xt)0⩽t⩽1(X_t)_{0\leqslant t\leqslant 1} and is given by

X:[0,1]→Rd,t↦Xt is a random trajectory for every random XX:[0,1]\rightarrow\mathbb{R}^d,\quad t\mapsto X_t\text{ is a random trajectory for every random } X

SDEs are constructed via a Brownian motion. You can think of a Brownian motion as a continuous random walk. Specifically, A Brownian motion W=(Wt)0⩽t⩽1W = (W_t)_{0\leqslant t\leqslant 1} is a stochastic process such that W0=0W_0 = 0, the trajectories t↦Wtt \mapsto W_t are continuous, with the following 3 features

  1. Wt−Ws∼N(0,(t−s)Id)W_t-W_s\sim\mathcal{N}(0,(t-s)I_d) for all 0⩽s⩽t0\leqslant s\leqslant t.
  2. For any 0⩽t0⩽t1⩽⋯⩽tn⩽10\leqslant t_0\leqslant t_1\leqslant\cdots\leqslant t_n\leqslant 1, the increments Wti−Wti−1W_{t_i}-W_{t_{i-1}} are independent random variables.
  3. We can easily simulate a Brownian motion approximately with step size h>0h > 0 by setting W0=0W_0 = 0 and updating Wt+h=Wt+hεW_{t+h}=W_t+\sqrt{h}\varepsilon, where ε∼N(0,Id)\varepsilon\sim\mathcal{N}(0,I_d) is a random Gaussian noise.

A stochastic differential equation(SDE) is usually denoted in the following symbolic notation

X0=x0,dXt=ut(Xt)dt+σtdWt\begin{equation}X_0=x_0,\quad\mathrm{d}X_t=u_t(X_t)\mathrm{d}t+\sigma_t\mathrm{d}W_t\end{equation}

where σt⩾0\sigma_t \geqslant 0 describes the diffusion coefficient. Finally, note that every ODE is also an SDE – simply with a diffusion coefficient σt=0\sigma_t = 0. Therefore, when we speak about SDEs, we consider ODEs as a special case.

How might we simulate an SDE? The simplest such scheme is known as the Euler-Maruyama method, and is essentially to SDEs what the Euler method is to ODEs. Using the Euler-Maruyama method, we initialize X0=x0X_0 = x_0 and update iteratively via

Xt+h=Xt+hut(Xt)+σthε,ε∼N(0,Id)X_{t+h}=X_t+hu_t(X_t)+\sigma_t\sqrt{h}\varepsilon,\quad \varepsilon\sim\mathcal{N}(0,I_d)

SDE generative models

Throughout this chapter, a diffusion model consists of a neural network utθu^{\theta}_t with parameters θ\theta that parameterize a vector field and a fixed diffusion coefficient σt\sigma_t as follows

  • Neural network utθ:Rd×[0,1]→Rd,(x,t)↦utθ(x)u_t^{\theta}:\mathbb{R}^d\times[0,1]\rightarrow\mathbb{R}^d,\quad (x,t)\mapsto u^{\theta}_t(x)
  • Diffusion coefficient σt:[0,1]→[0,+∞),t↦σt\sigma_t:[0,1]\rightarrow [0,+\infty),\quad t\mapsto \sigma_t

To obtain samples from our SDE model (i.e. generate objects), the procedure is as follows

  • Initialization:X0∼pinitX_0\sim p_{\mathrm{init}}
  • Simulation:dXt=utθ(Xt)dt+σtdWt\mathrm{d}X_t=u^{\theta}_t(X_t)\mathrm{d}t+\sigma_t\mathrm{d}W_t
  • Goal:X1∼pdataX_1\sim p_{\mathrm{data}}

where a diffusion model with σt=0\sigma_t=0 is call a flow model.

L2. Training Target


Key ideas

As we discussed, our goal is that X1X_1 is distributed according to the data distribution pdatap_{\mathrm{data}}, i.e. X1∼pdataX_1 \sim p_{\mathrm{data}}. But how do we optimize θ\theta such that simulating the diffusion model results in samples from the data distribution X1∼pdataX_1 \sim p_{\mathrm{data}}?

One way is to minimize the mean squard error between our neural network utθu_t^{\theta} and the target vector field uttargetu_t^{\mathrm{target}}, shown as:

L(x,θ)=∥utθ(x)−uttarget(x)∥2L(x,\theta)=\|u_t^{\theta}(x)-u_t^{\mathrm{target}}(x)\|^2

However, we don’t yet know what the target uttargetu_t^{\mathrm{target}} looks like. So in this chapter, we will introduce how to construct a training target uttargetu_t^{\mathrm{target}} with some math tricks. Before that, here are two key terminology necessary to understand

  • Conditional means per single data point
  • Marginal means across distribution of data points

Conditional and marginal probability path

The first step is to specify a probability path. Intuitively, a probability path specifies a gradual interpolation between noise pinitp_{\mathrm{init}} and data pdatap_{\mathrm{data}}. A simple distribution called Dirac distribution δz\delta_z is defined that X∼δz,X=zX\sim \delta_z,X=z i.e. the Dirac distribution always gives one single certain output zz.

A conditional probability path is a set of distribution pt(x∣z)p_t(x|z) over Rd\mathbb{R}^d such that

p0(x∣z)=pinit,∀z∈Rdp1(⋅∣z)=δzp_0(x|z)=p_{\mathrm{init}},\quad \forall z\in\mathbb{R}^d\quad p_1(\cdot|z)=\delta_z

In other words, a conditional probability path gradually converts the initial distribution pinitp_{\mathrm{init}} into a single data point. One particularly popular probability path is the Gaussian probability path. This is the probability path used by most state-of-the-art models. Let αt,βt\alpha_t,\beta_t be two noise schedulers: two continuously differentiable, monotonic functions with α0=β1=0\alpha_0 = \beta_1 = 0 and α1=β0=1\alpha_1 = \beta_0 = 1. We then define the conditional probability path (usually with αt=t\alpha_t=t and βt=1−t\beta_t=1-t)

pt(⋅∣z)∼N(αtz,βt2Id)\begin{equation}p_t(\cdot|z)\sim\mathcal{N}(\alpha_tz,\beta_t^2I_d)\end{equation}

Every conditional probability path pt(x∣z)p_t(x|z) induces a marginal probability path pt(x)p_t(x) defined as the distribution that we obtain by first sampling a data point z∼pdataz ∼ p_{\mathrm{data}} from the data distribution and then sampling from pt(⋅∣z)p_t(\cdot|z), such that

pt(x)=∫pt(x∣z)pdata(z)dz\begin{equation}p_t(x)=\int p_t(x|z)p_{\mathrm{data}}(z)\mathrm{d}z\end{equation}

The marginal probability path ptp_t satisfies that

p0(x)=pinit,p1(x)=pdatap_0(x)=p_{\mathrm{init}},\quad p_1(x)=p_{\mathrm{data}}

We can express sampling from the marginal Gaussian path ptp_t as

z∼pdata,ε∼pinit=N(0,Id)⇒x=αtz+βε∼ptz\sim p_{\mathrm{data}},\quad\varepsilon\sim p_{\mathrm{init}}=\mathcal{N}(0,I_d)\quad\Rightarrow\quad x=\alpha_tz+\beta\varepsilon\sim p_t

这两种概率路径可以这样理解

  • 条件概率路径: 已知一个具体样本 zz,如何构造从噪声到该样本的概率分布变化过程
  • 边缘概率路径: 考虑整个数据集时,整体概率分布如何从噪声分布演化到真实数据分布

Conditional and marginal vector fields

For every data point z∈Rdz \in \mathbb{R}^d, let uttarget(⋅∣z)u^{\mathrm{target}}_t(\cdot|z) denote a conditional vector field. This can be any vector field such that corresponding ODE yields the conditional probability path pt(⋅∣z)p_t(\cdot|z), i.e. such that it holds

X0∼pinit,ddtXt=uttarget(Xt∣z)⇒Xt∼pt(⋅∣z)X_0\sim p_{\mathrm{init}},\quad \frac{\mathrm{d}}{\mathrm{d}t}X_t=u^{\mathrm{target}}_t(X_t|z)\quad \Rightarrow\quad X_t\sim p_t(\cdot|z)

We can often find a conditional vector field uttarget(⋅∣z)u^{\mathrm{target}}_t(\cdot|z) analytically by hand. This means that all endpoints of the ODE X1X_1 will collaspe to X1=zX_1=z, but we can use a marginalization trick to transform the conditional vector field into the marginal vector field uttarget(x)u^{\mathrm{target}}_t(x) defined as

uttarget(x)=∫uttarget(x∣z)⋅pt(x∣z)pdata(z)pt(x)dz\begin{equation}u^{\mathrm{target}}_t(x)=\int u^{\mathrm{target}}_t(x|z)\cdot\frac{p_t(x|z)p_{\mathrm{data}}(z)}{p_t(x)}\mathrm{d}z\end{equation}

follows the margin probability path, i.e.

X0∼pinit,ddtXt=uttarget(Xt)⇒Xt∼ptX_0\sim p_{\mathrm{init}},\quad \frac{\mathrm{d}}{\mathrm{d}t}X_t=u^{\mathrm{target}}_t(X_t)\quad \Rightarrow\quad X_t\sim p_t

Let’s gain some intuition for the marginal vector field.

  1. Bayes’ rule says that pt(x∣z)pdata(z)pt(x)\dfrac{p_t(x|z)p_{\mathrm{data}}(z)}{p_t(x)} describes a posterior distribution. The marginal vector field then is simply an average: for every possible data point zz, it takes the velocity ut(x∣z)u_t(x|z) (i.e. the direction that would bring us to zz) and then weighs this velocity by how much we believe that xx comes from zz. Averaging over all data points, we obtain the marginal vector field.
  2. Mathematically, an flow model with vector field uttarget(x)u^{\mathrm{target}}_t(x) with X0∼pinitX_0\sim p_{\mathrm{init}} satisfies Xt∼ptX_t\sim p_t if and only if the continuity equation below holds. This could give out the only form of uttargetu^{\mathrm{target}}_t in (7)(7)

∀x∈Rd,t∈[0,1]∂tpt=−div(ptuttarget)(x)\begin{equation}\forall x\in\mathbb{R}^d,t\in[0,1]\quad\partial_tp_t=-\mathrm{div}(p_tu_t^{\mathrm{target}})(x)\end{equation}

As before, let pt(⋅∣z)=N(αtz,βt2Id)p_t(·|z) = \mathcal{N}(\alpha_tz,\beta^2 _tI_d) for noise schedulers αt,βt\alpha_t,\beta_t. Let α˙t=∂tαt,β˙t=∂tβt\dot{\alpha}_t = \partial_t\alpha_t,\dot{\beta}_t = \partial_t\beta_t denote respective time derivatives of αt,βt\alpha_t,\beta_t. Here, we want to show that the conditional Gaussian vector field given by

uttarget(x∣z)=(α˙t−β˙tβtαt)z+β˙tβtx\begin{equation}u^{\mathrm{target}}_t(x|z)=\left(\dot{\alpha}_t-\frac{\dot{\beta}_t}{\beta_t}\alpha_t \right)z+\frac{\dot{\beta}_t}{\beta_t}x\end{equation}

Conditional and marginal score functions

Diffusion models take a different perspective focused on score functions. Therefore, in this section, we will rephrase what we have learned here in the language of score functions. Let q(x)q(x) be an arbitrary probability distribution. Then the score function of qq is defined as ∇log⁡q(x)\nabla \log q(x), i.e. as the gradient of the log-likelihood of qq with respect to xx.

Let us return to the setting of conditional probability paths pt(x∣z)p_t(x|z) and marginal probability paths pt(x)p_t(x). Then we can equivalently define the conditional score function as ∇xlog⁡pt(x∣z)\nabla_x \log p_t(x|z) and the marginal score function as ∇log⁡pt(x)\nabla \log p_t(x). the marginal score can be expressed via the conditional score function ∇xlog⁡pt(x∣z)\nabla_x \log p_t(x|z) via

∇log⁡pt(x)=∫∇xlog⁡pt(x∣z)⋅pt(x∣z)pdata(z)pt(x)dz\begin{equation}\nabla\log p_t(x)=\int \nabla_x \log p_t(x|z)\cdot\frac{p_t(x|z)p_{\mathrm{data}}(z)}{p_t(x)}\mathrm{d}z\end{equation}

For any diffusion coefficient σt⩾0\sigma_t\geqslant 0, we may construct an SDE by adding stochastic dynamics to the dynamics of the original ODE. By doing so, we could combine the stochastic continuity equation and get

X0∼pinit,dXt=[uttarget(Xt)+σt22∇log⁡pt(Xt)]dt+σtdWt⇒Xt∼ptX_0\sim p_{\mathrm{init}},\quad \mathrm{d}X_t=\left[u^{\mathrm{target}}_t(X_t)+\frac{\sigma_t^2}{2}\nabla\log p_t(X_t)\right]\mathrm{d}t+\sigma_t\mathrm{d}W_t\quad \Rightarrow\quad X_t\sim p_t

L3. Flow Matching


Flow matching loss

In a flow model, our goal is to set utθ(x)≈uttarget(x)u^{\theta}_t(x)\approx u_t^{\mathrm{target}}(x). If this holds, we know that the endpoints X1∼pdataX_1\sim p_{\mathrm{data}}. In the following, we denote U[0,1]U[0,1] as the uniform distribution on the interval [0,1][0,1], and E\mathbb{E} the expected value of a random variable. An intuitive way of obtaining utθ(x)≈uttarget(x)u^{\theta}_t(x)\approx u_t^{\mathrm{target}}(x) is to use a mean-squared error, i.e. to use the flow matching loss defined as

LFM=Et∼U[0,1],x∼pt[∥utθ(x)−uttarget(x)∥2]\begin{equation}\mathcal{L}_{\mathrm{FM}}=\mathbb{E}_{t\sim U[0,1],x\sim p_t}\left[\|u^{\theta}_t(x)-u_t^{\mathrm{target}}(x)\|^2\right]\end{equation}

Intuitively, this loss describes the following workflow:

  1. Draw a random time t∈[0,1]t\in[0,1]
  2. Draw a random point zz from our data set, sample from pt(⋅∣z)p_t(·|z) and compute utθ(x)u^{\theta}_t(x)
  3. Compute the loss between the output of our neural network and the marginal vector field uttarget(x)u_t^{\mathrm{target}}(x)

Conditional flow matching loss

While we do know the formula for uttarget(x)u_t^{\mathrm{target}}(x) by (7)(7), we cannot compute it efficiently as the
integral is intractable in high dimensions
. Instead, we will exploit the fact that the conditional velocity field uttarget(x)u_t^{\mathrm{target}}(x) is tractable. To do so, let us define the conditional flow matching loss as

LCFM=Et∼U[0,1],z∼pdata,x∼p(⋅∣z)[∥utθ(x)−uttarget(x∣z)∥2]\begin{equation}\mathcal{L}_{\mathrm{CFM}}=\mathbb{E}_{t\sim U[0,1],z\sim p_{\mathrm{data}},x\sim p(\cdot|z)}\left[\|u^{\theta}_t(x)-u_t^{\mathrm{target}}(x|z)\|^2\right]\end{equation}

Note the difference to (12)(12): we use the conditional vector field uttarget(x∣z)u_t^{\mathrm{target}}(x|z) instead of the marginal vector uttarget(x)u_t^{\mathrm{target}}(x). As we have an analytical formula for uttarget(x∣z)u_t^{\mathrm{target}}(x|z), we can minimize the above loss easily.

Actually, we could proof that the marginal flow matching loss equals the conditional flow matching loss up to a constant, that is

LFM(θ)=LCFM(θ)+C\mathcal{L}_{\mathrm{FM}}(\theta)=\mathcal{L}_{\mathrm{CFM}}(\theta)+C

here CC is independent of θ\theta. Therefore, their gradients coincide:

∇θLFM(θ)=∇θLCFM(θ)\begin{equation}\nabla_{\theta}\mathcal{L}_{\mathrm{FM}}(\theta)=\nabla_{\theta}\mathcal{L}_{\mathrm{CFM}}(\theta)\end{equation}

In particular, for the minimizer θ∗\theta^* of LCFM(θ)\mathcal{L}_{\mathrm{CFM}}(\theta), it will hold that utθ∗(x)=uttarget(x)u^{\theta^*}_t(x)=u_t^{\mathrm{target}}(x), i.e. the
neural network will equal the marginal vector field. This is an exploding result, which shows that we can simply minimizing LCFM(θ)\mathcal{L}_{\mathrm{CFM}}(\theta) to get the solution of flow matching ODE.

Proof of Equation (13)

The proof works by expanding the mean-squared error into three components and removing constants:

LFM=Et∼U[0,1],x∼pt[∥utθ(x)−uttarget(x)∥2]=Et∼U[0,1],x∼pt[∥utθ(x)∥2−2⟨utθ(x),uttarget(x)⟩+∥uttarget(x)∥2]=Et∼U[0,1],x∼pt[∥utθ(x)∥2]−2Et∼U[0,1],x∼pt⟨utθ(x),uttarget(x)⟩+Et∼U[0,1],x∼pt[∥uttarget(x)∥2]:=C0−2C1+C2\begin{aligned}\mathcal{L}_{\mathrm{FM}}&=\mathbb{E}_{t\sim U[0,1],x\sim p_t}\left[\|u^{\theta}_t(x)-u_t^{\mathrm{target}}(x)\|^2\right]\\&=\mathbb{E}_{t\sim U[0,1],x\sim p_t}\left[\|u^{\theta}_t(x)\|^2-2\langle u^{\theta}_t(x),u_t^{\mathrm{target}}(x)\rangle+\|u_t^{\mathrm{target}}(x)\|^2\right]\\&=\mathbb{E}_{t\sim U[0,1],x\sim p_t}\left[\|u^{\theta}_t(x)\|^2\right]-2\mathbb{E}_{t\sim U[0,1],x\sim p_t}\langle u^{\theta}_t(x),u_t^{\mathrm{target}}(x)\rangle+\mathbb{E}_{t\sim U[0,1],x\sim p_t}\left[\|u_t^{\mathrm{target}}(x)\|^2\right]\\&:=C_0-2C_1+C_2\end{aligned}

Let us reexpress the second term C1C_1 as:

C1=Et∼U[0,1],x∼pt⟨utθ(x),uttarget(x)⟩=∫01dt∫pt(x)⟨utθ(x),uttarget(x)⟩dx=∫01dt∫pt(x)⟨utθ(x),∫uttarget(x∣z)⋅pt(x∣z)pdata(z)pt(x)dz⟩dx=∫01dt∬pt(x∣z)pdata(z)⟨utθ(x),uttarget(x∣z)⟩dzdx=Et∼U[0,1],z∼pdata,x∼pt(⋅∣z)⟨utθ(x),uttarget(x∣z)⟩\begin{aligned}C_1&=\mathbb{E}_{t\sim U[0,1],x\sim p_t}\langle u^{\theta}_t(x),u_t^{\mathrm{target}}(x)\rangle\\&=\int_{0}^1\mathrm{d}t\int p_t(x)\langle u^{\theta}_t(x),u_t^{\mathrm{target}}(x)\rangle\mathrm{d}x\\&=\int_{0}^1\mathrm{d}t\int p_t(x)\left\langle u^{\theta}_t(x),\int u^{\mathrm{target}}_t(x|z)\cdot\frac{p_t(x|z)p_{\mathrm{data}}(z)}{p_t(x)}\mathrm{d}z\right\rangle\mathrm{d}x\\&=\int_{0}^1\mathrm{d}t\iint p_t(x|z)p_{\mathrm{data}}(z)\left\langle u^{\theta}_t(x),u^{\mathrm{target}}_t(x|z)\right\rangle\mathrm{d}z\mathrm{d}x\\&=\mathbb{E}_{t\sim U[0,1],z\sim p_{\mathrm{data}},x\sim p_t(\cdot|z)}\left\langle u^{\theta}_t(x),u^{\mathrm{target}}_t(x|z)\right\rangle\end{aligned}

Now, we also rewrite the first term C0C_0 as

C0=Et∼U[0,1],x∼pt[∥utθ(x)∥2]=Et∼U[0,1],z∼pdata,x∼pt(⋅∣z)[∥utθ(x)−uttarget(x∣z)∥2+2⟨utθ(x),uttarget(x∣z)⟩−∥uttarget(x∣z)∥2]=Et∼U[0,1],z∼pdata,x∼pt(⋅∣z)[∥utθ(x)−uttarget(x∣z)∥2]+2C1−Et∼U[0,1],z∼pdata,x∼pt(⋅∣z)[∥uttarget(x∣z)∥2]:=Et∼U[0,1],z∼pdata,x∼pt(⋅∣z)[∥utθ(x)−uttarget(x∣z)∥2]+2C1−C3\begin{aligned}C_0&=\mathbb{E}_{t\sim U[0,1],x\sim p_t}\left[\|u^{\theta}_t(x)\|^2\right]\\&=\mathbb{E}_{t\sim U[0,1],z\sim p_{\mathrm{data}},x\sim p_t(\cdot|z)}\left[\|u^{\theta}_t(x)-u^{\mathrm{target}}_t(x|z)\|^2+2\left\langle u^{\theta}_t(x),u^{\mathrm{target}}_t(x|z)\right\rangle-\|u^{\mathrm{target}}_t(x|z)\|^2\right]\\&=\mathbb{E}_{t\sim U[0,1],z\sim p_{\mathrm{data}},x\sim p_t(\cdot|z)}\left[\|u^{\theta}_t(x)-u^{\mathrm{target}}_t(x|z)\|^2\right]+2C_1-\mathbb{E}_{t\sim U[0,1],z\sim p_{\mathrm{data}},x\sim p_t(\cdot|z)}\left[\|u^{\mathrm{target}}_t(x|z)\|^2\right]\\&:=\mathbb{E}_{t\sim U[0,1],z\sim p_{\mathrm{data}},x\sim p_t(\cdot|z)}\left[\|u^{\theta}_t(x)-u^{\mathrm{target}}_t(x|z)\|^2\right]+2C_1-C_3\end{aligned}

In short, we gather these results to get

LFM(θ)=Et∼U[0,1],z∼pdata,x∼pt(⋅∣z)[∥utθ(x)−uttarget(x∣z)∥2]+2C1−C3−2C1+C2:=LCFM(θ)+(C2−C3)\begin{aligned}\mathcal{L}_{\mathrm{FM}}(\theta)&=\mathbb{E}_{t\sim U[0,1],z\sim p_{\mathrm{data}},x\sim p_t(\cdot|z)}\left[\|u^{\theta}_t(x)-u^{\mathrm{target}}_t(x|z)\|^2\right]+2C_1-C_3-2C_1+C_2\\&:=\mathcal{L}_{\mathrm{CFM}}(\theta)+(C_2-C_3)\end{aligned}

It’s easy to see that C=C2−C3C=C_2-C_3 is not relied on θ\theta, thus we get to the end

∇θLFM(θ)=∇θLCFM(θ)\nabla_{\theta}\mathcal{L}_{\mathrm{FM}}(\theta)=\nabla_{\theta}\mathcal{L}_{\mathrm{CFM}}(\theta)

Flow matching algorithm

Now we could discuss the algorithm of training a flow model. For a Gaussian CondOT path pt(x∣z)=N(tz,(1−t)2)p_t(x|z)=\mathcal{N}(tz,(1-t)^2) (i.e. αt=t,βt=1−t\alpha_t=t,\beta_t=1-t), suppose we have a dataset of samples z∼pdataz\sim p_{\mathrm{data}} and a untrained neural network utθu_t^{\theta}. Here’s the training algorithm below.

Algorithm 1 Flow Matching Training for CondOT path

  1. for each mini-batch of data do
  2. \quad Sample a data example zz from the dataset
  3. \quad Sample a random time t∼U[0,1]t\sim U[0,1]
  4. \quad Sample noise ε∼N(0,Id)\varepsilon\sim \mathcal{N}(0,I_d)
  5. \quad Compute x=tz+(1−t)ε∼pt(x∣z)x=tz+(1-t)\varepsilon\sim p_t(x|z)
  6. \quad Compute LCFM(θ)=∥utθ(x)−(z−ε)∥2\mathcal{L}_{\mathrm{CFM}}(\theta)=\|u_t^{\theta}(x)-(z-\varepsilon)\|^2 where (z−ε)=uttarget(x∣z)(z-\varepsilon)=u^{\mathrm{target}}_t(x|z)
  7. \quad Update θ←grad_algorithm(LCFM(θ))\theta \leftarrow \mathrm{grad\_algorithm}(\mathcal{L}_{\mathrm{CFM}}(\theta))
  8. end for

When we’ve trained a flow matching model, we could simply draw a sample X0∼pinitX_0\sim p_{\mathrm{init}} and simulate the ODE defined by our neural network utθ(x)u_t^{\theta}(x). By doing so, we could generate new data X1X_1.

L4. Score Matching


Key ideas

In previous chapters, we’ve introduced vector fields and score functions. Now let’s consider their relationships: For the Gaussian path pt(x∣z)=N(αtz,βt2Id)p_t(x|z) = \mathcal{N}(\alpha_tz,\beta^2_tI_d), we can use the form of the Gaussian probability density that

∇xlog⁡pt(x∣z)=∇xN(αtz,βt2Id)=−x−αtzβt2\begin{equation}\nabla_x \log p_t(x|z)=\nabla_x\mathcal{N}(\alpha_tz,\beta^2_tI_d)=-\frac{x-\alpha_tz}{\beta_t^2}\end{equation}

Note that the score function for a Gaussian probability path is a linear function of xx and zz. The same is true for the conditional vector field uttarget(x∣z)u^\mathrm{target}_t(x|z) in (9)(9). It is thus possible to convert between the two, shown as

uttarget(x∣z)=at∇xlog⁡pt(x∣z)+btx\begin{equation}u_t^{\mathrm{target}}(x|z)=a_t\nabla_x\log p_t(x|z)+b_tx\end{equation}

where at,bta_t,b_t are

at=(α˙tβt2αt−β˙tβt),bt=α˙tαt\begin{equation}a_t=\left(\frac{\dot{\alpha}_t\beta_t^2}{\alpha_t}-\dot{\beta}_t\beta_t\right),\quad b_t=\frac{\dot{\alpha}_t}{\alpha_t}\end{equation}

Notice that the marginal vector field uttarget(x)u_t^{\mathrm{target}}(x) and marginal score function ∇log⁡pt(x)\nabla\log p_t(x) shares the same form of intergrals, thus we could also get the following equation

uttarget(x)=at∇log⁡pt(x)+btx\begin{equation}u_t^{\mathrm{target}}(x)=a_t\nabla\log p_t(x)+b_tx\end{equation}

This is striking because it says that once we’ve learned uttarget(x)u_t^{\mathrm{target}}(x) we’ve also learned the score function ∇log⁡pt(x)\nabla \log p_t(x), and vice versa. We can illustrate with the following equation:

vector(x,z)=at⋅score(x,z)+btx\mathrm{vector}(x,z)=a_t\cdot\mathrm{score}(x,z)+b_tx

Score matching loss

Before, we’ve introduced how to train and use a flow model. Now we consider a diffusion model corresponding to a certain SDE. A quick recap is that

X0∼pinit,dXt=[uttarget(Xt)+σt22∇log⁡pt(Xt)]dt+σtdWt⇒Xt∼ptX_0\sim p_{\mathrm{init}},\quad \mathrm{d}X_t=\left[u^{\mathrm{target}}_t(X_t)+\frac{\sigma_t^2}{2}\nabla\log p_t(X_t)\right]\mathrm{d}t+\sigma_t\mathrm{d}W_t\quad \Rightarrow\quad X_t\sim p_t

where ∇log⁡pt(Xt)\nabla\log p_t(X_t) is the marginal score function. In flow matching algorithm, we train the neural network utθ(x)u_t^{\theta}(x) to get close to marginal vector field uttarget(x)u_t^{\mathrm{target}}(x). What if we train the score function stθ(x)s^{\theta}_t(x) to approximate the marginial score ∇log⁡pt(x)\nabla \log p_t(x)? In the same way as before, we can design a score
matching loss
and a denoising score matching loss:

LSM=Et∼U[0,1],x∼pt[∥stθ(x)−∇log⁡pt(x)∥2]\begin{equation}\mathcal{L}_{\mathrm{SM}}=\mathbb{E}_{t\sim U[0,1],x\sim p_t}\left[\|s^{\theta}_t(x)-\nabla \log p_t(x)\|^2\right]\end{equation}

LCSM=Et∼U[0,1],z∼pdata,x∼pt(⋅∣z)[∥stθ(x)−∇xlog⁡pt(x∣z)∥2]\begin{equation}\mathcal{L}_{\mathrm{CSM}}=\mathbb{E}_{t\sim U[0,1],z\sim p_{\mathrm{data}},x\sim p_t(\cdot|z)}\left[\|s^{\theta}_t(x)-\nabla_x\log p_t(x|z)\|^2\right]\end{equation}

As before, we ideally would want to minimize the score matching loss but can’t because we don’t know ∇log⁡pt(x)\nabla \log p_t(x). But similarly as before, the denoising score matching loss is a tractable alternative, i.e. holds

∇θLSM(θ)=∇θLCSM(θ)\begin{equation}\nabla_{\theta}\mathcal{L}_{\mathrm{SM}}(\theta)=\nabla_{\theta}\mathcal{L}_{\mathrm{CSM}}(\theta)\end{equation}

This is easy to proof promised by (13),(17)(13),(17).

Denoising diffusion model

Denoising Diffusion Probabilitic Models, known as DDPM or General Diffusion Model is designed based on score matching algorithm. When referring to the original paper, you could learn a different way of approching using Markov chain. In this section, we proof it using score matching theory.

原论文的推导过程可参考我的博客。

Let us instantiate the denoising score matching loss for the case of pt(x∣z)=N(αtz,βt2Id)p_t(x|z) = \mathcal{N}(\alpha_tz,\beta^2_tI_d)

∇xlog⁡pt(x∣z)=−x−αtzβt2\nabla_x \log p_t(x|z)=-\frac{x-\alpha_tz}{\beta_t^2}

Plugging in formula (19)(19), we could get

LCSM=Et∼U[0,1],z∼pdata,x∼pt(⋅∣z)[∥stθ(x)−x−αtzβt2∥2]\mathcal{L}_{\mathrm{CSM}}=\mathbb{E}_{t\sim U[0,1],z\sim p_{\mathrm{data}},x\sim p_t(\cdot|z)}\left[\left\|s^{\theta}_t(x)-\frac{x-\alpha_tz}{\beta_t^2}\right\|^2\right]

Notice that x=αtz+βtεx=\alpha_tz+\beta_t\varepsilon where ε∼N(0,Id)\varepsilon\sim\mathcal{N}(0,I_d):

LCSM=Et∼U[0,1],z∼pdata,ε∼N(0,Id)[∥stθ(αtz+βtε)+εβt∥2]=Et∼U[0,1],z∼pdata,ε∼N(0,Id)[1βt2∥βtstθ(αtz+βtε)+ε∥2]\begin{aligned}\mathcal{L}_{\mathrm{CSM}}&=\mathbb{E}_{t\sim U[0,1],z\sim p_{\mathrm{data}},\varepsilon\sim\mathcal{N}(0,I_d)}\left[\left\|s^{\theta}_t(\alpha_tz+\beta_t\varepsilon)+\frac{\varepsilon}{\beta_t}\right\|^2\right]\\&=\mathbb{E}_{t\sim U[0,1],z\sim p_{\mathrm{data}},\varepsilon\sim\mathcal{N}(0,I_d)}\left[\frac{1}{\beta_t^2}\left\|\beta_ts^{\theta}_t(\alpha_tz+\beta_t\varepsilon)+\varepsilon\right\|^2\right]\end{aligned}

Note that the network stθs^{\theta}_t essentially learns to predict the noise that was used to corrupt a data sample zz. This explains why the above training loss is called denoising score matching. Now we construct a neural network εtθ\varepsilon_t^{\theta} to predict noise ε\varepsilon instead of stθs_t^{\theta}, i.e. using reparameterization trick:

−βtstθ(x)=εtθ(x)\begin{equation}-\beta_ts_t^{\theta}(x)=\varepsilon_t^{\theta}(x)\end{equation}

If βt≈0\beta_t \approx 0, the loss is numerically unstable, thus we drop the constant term 1/βt21/\beta_t^2 that

LDDPM(θ)=Et∼U[0,1],z∼pdata,ε∼N(0,Id)[∥εtθ(αtz+βtε)−ε∥2]\begin{equation}\mathcal{L}_{\mathrm{DDPM}}(\theta)=\mathbb{E}_{t\sim U[0,1],z\sim p_{\mathrm{data}},\varepsilon\sim\mathcal{N}(0,I_d)}\left[\left\|\varepsilon^{\theta}_t(\alpha_tz+\beta_t\varepsilon)-\varepsilon\right\|^2\right]\end{equation}

Algorithm 2 Score Matching Training for Gaussian path

  1. for each mini-batch of data do
  2. \quad Sample a data example zz from the dataset
  3. \quad Sample a random time t∼U[0,1]t\sim U[0,1]
  4. \quad Sample noise ε∼N(0,Id)\varepsilon\sim \mathcal{N}(0,I_d)
  5. \quad Compute x=αtz+βtε∼pt(x∣z)x=\alpha_tz+\beta_t\varepsilon\sim p_t(x|z)
  6. \quad Compute L(θ)=∥εtθ(x)−ε∥2\mathcal{L}(\theta)=\|\varepsilon_t^{\theta}(x)-\varepsilon\|^2
  7. \quad Update θ←grad_algorithm(L(θ))\theta \leftarrow \mathrm{grad\_algorithm}(\mathcal{L}(\theta))
  8. end for

After training, we can simulate the SDE, pluggin in (17)(17) into SDE and get

X0∼pinit,dXt=[(at+σt22)stθ(Xt)+btXt]dt+σtdWt⇒Xt∼ptX_0\sim p_{\mathrm{init}},\quad \mathrm{d}X_t=\left[\left(a_t+\frac{\sigma_t^2}{2}\right)s_t^{\theta}(X_t)+b_tX_t\right]\mathrm{d}t+\sigma_t\mathrm{d}W_t\quad \Rightarrow\quad X_t\sim p_t

L5. Guidance


Key ideas

So far, the generative models we considered were unguided, e.g. an image model would simply generate some image. Mathematically speaking, this meant that our model returned samples from an unconditional data distribution pdata(z)p_{\mathrm{data}}(z). However, in most cases, our goal is not to merely generate an arbitrary object, but to generate an object conditioned on some additional information.

In other words, we want to guide the model to generate objects of a certain kind. For example, one might imagine a generative model for images which takes in a text prompt yy, and then generates an image xx that fits to the text prompt yy.

  • Unconditional prompt: Generate an image.
  • Conditional prompt: Generate an image of a cat baking a cake.

In the following chapters, we will use yy for conditional information.

Vanilla guidance

Let’s consider a common way for conditional generation. Think of a conditioning variable or prompt yy to live in a space Y\mathcal{Y}. We define a guided diffusion model to consist of a guided vector field utθ(⋅∣y)u^{\theta}_t(·|y), parameterized by a neural network, and a time-dependent diffusion coefficient σt⩾0\sigma_t\geqslant 0, together given by

  • Neural network utθ:Rd×Y×[0,1]→Rd,(x,y,t)↦utθ(x∣y)u_t^{\theta}:\mathbb{R}^d\times\mathcal{Y}\times[0,1]\rightarrow\mathbb{R}^d,\quad (x,y,t)\mapsto u^{\theta}_t(x|y)
  • Diffusion coefficient σt:[0,1]→[0,+∞),t↦σt\sigma_t:[0,1]\rightarrow [0,+\infty),\quad t\mapsto \sigma_t

To obtain samples from our SDE model (i.e. generate objects), the procedure is as follows

  • Initialization:X0∼pinitX_0\sim p_{\mathrm{init}}
  • Simulation:dXt=utθ(Xt∣y)dt+σtdWt\mathrm{d}X_t=u^{\theta}_t(X_t|y)\mathrm{d}t+\sigma_t\mathrm{d}W_t
  • Goal:X1∼pdata(⋅∣y)X_1\sim p_{\mathrm{data}}(\cdot|y)

For a fixed yy, we obtain an unguided problem, adapt an unguided objectives to get

LCFMguided(θ;y)=Et∼U[0,1],z∼pdata(z∣y),x∼p(⋅∣z)[∥utθ(x∣y)−uttarget(x∣z)∥2]\mathcal{L}^{\mathrm{guided}}_{\mathrm{CFM}}(\theta;y)=\mathbb{E}_{t\sim U[0,1],z\sim p_{\mathrm{data}}(z|y),x\sim p(\cdot|z)}\left[\|u^{\theta}_t(x|y)-u_t^{\mathrm{target}}(x|z)\|^2\right]

By varying yy, the above yields a guided objective for yy:

LCFMguided(θ)=Et∼U[0,1],z∼pdata(z,y),x∼p(⋅∣z)[∥utθ(x∣y)−uttarget(x∣z)∥2]\mathcal{L}^{\mathrm{guided}}_{\mathrm{CFM}}(\theta)=\mathbb{E}_{t\sim U[0,1],z\sim p_{\mathrm{data}}(z,y),x\sim p(\cdot|z)}\left[\|u^{\theta}_t(x|y)-u_t^{\mathrm{target}}(x|z)\|^2\right]

Essentially, we are sampling (z,y)∼pdata(z,y)\sim p_{\mathrm{data}} rather than just z∼pdataz\sim p_{\mathrm{data}}.

Classifier guidance

In theory, vanilla guidance should lead to a faithful generation procedure of pdata(⋅∣y)p_{\mathrm{data}}(\cdot|y). However, it was soon empirically realized that images samples with this procedure did not fit well enough to the desired label yy. This can have a diversity of reasons:

  • The model might underfit (i.e. we do not actually learn the true marginal vector field)
  • Our data might be imperfect (e.g. text-image pairs from the world wide web have a lot of errors).

Therefore, to truly generate samples that fit better to a prompt, we have to find a way to artificially reinforce the prompt variable yy. The main technique for doing so is called classifier-free guidance(CFG) that is widely used in the context of state-of-the-art diffusion models, and which we discuss next. Before that, we introduce the classifier guidance method.

Recap that the vector field uttargetu_t^{\mathrm{target}} and ∇log⁡pt\nabla \log p_t are connected by the following

uttarget(x)=at∇log⁡pt(x)+btxu_t^{\mathrm{target}}(x)=a_t\nabla\log p_t(x)+b_tx

Now, rewrite the above equation using conditional variable yy

uttarget(x∣y)=at∇xlog⁡pt(x∣y)+btx\begin{equation}u_t^{\mathrm{target}}(x|y)=a_t\nabla_x\log p_t(x|y)+b_tx\end{equation}

Using Bayes’ rule on the term ∇log⁡pt(x∣y)\nabla\log p_t(x|y), we get

∇xlog⁡pt(x∣y)=∇xlog⁡(pt(x)pt(y∣x)pt(y))=∇log⁡pt(x)+∇xlog⁡pt(y∣x)\nabla_x\log p_t(x|y)=\nabla_x\log\left(\frac{p_t(x)p_t(y|x)}{p_t(y)}\right)=\nabla\log p_t(x)+\nabla_x\log p_t(y|x)

We may thus rewrite

uttarget(x∣y)=at(∇log⁡pt(x)+∇xlog⁡pt(y∣x))+btx=uttarget(x)+at∇xlog⁡pt(y∣x)u_t^{\mathrm{target}}(x|y)=a_t(\nabla\log p_t(x)+\nabla_x\log p_t(y|x))+b_tx=u_t^{\mathrm{target}}(x)+a_t\nabla_x\log p_t(y|x)

Notice the shape of the above equation: The guided vector field uttarget(x∣y)u_t^{\mathrm{target}}(x|y) is a sum of the unguided vector field uttarget(x)u_t^{\mathrm{target}}(x) plus a gradient of the likelihood pt(y∣x)p_t(y|x) of the guidance variable yy.

As people observed that their image xx did not fit their prompt yy well enough, it was a natural idea to scale up the contribution of the ∇xlog⁡pt(y∣x)\nabla_x \log p_t(y|x) term, yielding

u~(x∣y)=uttarget(x)+wat∇xlog⁡pt(y∣x)\begin{equation}\tilde{u}(x|y)=u_t^{\mathrm{target}}(x)+wa_t\nabla_x\log p_t(y|x)\end{equation}

where w>1w > 1 is known as the guidance scale. How can we learn the term log⁡pt(y∣x)\log p_t(y|x)? Note that this can be considered as a sort of classifier of noised data (i.e. it gives the log-likelihoods of yy given xx). So we can simply learn it via supervised learning. This is called classifier guidance method.

Classifier-free guidance

While classifier guidance is possible in principle, it comes with difficulties

  • We need to train a classifier alongside a flow/diffusion model- so we have 22 networks instead of 11. This increases the cost for training and generating process.
  • If the yy is high-dimensional, e.g. a text prompt and not just a class, then pt(y∣x)p_t(y|x) might be very hard to learn and the gradient ∇log⁡pt(y∣x)\nabla \log p_t(y|x) hard to obtain.

For this reason, classifier-free guidance was introduced. Classifier-free guidance results in the theoretically equivalent effect as classifier guidance but without having to train a separate classifier. We could do some algebra appling the equality ∇xlog⁡pt(x∣y)=∇log⁡pt(x)+∇xlog⁡pt(y∣x)\nabla_x \log p_t(x|y)=\nabla \log p_t(x)+\nabla_x \log p_t(y|x) into (23),(24)(23),(24):

u~t(x∣y)=uttarget(x)+wat∇xlog⁡pt(y∣x)=uttarget(x)+wat(∇log⁡pt(x∣y)−∇xlog⁡pt(x))=uttarget(x)+w(at∇log⁡pt(x∣y)−at∇xlog⁡pt(x))=uttarget(x)+w[(uttarget(x∣y)−btx)−(uttarget(x)−btx)]=uttarget(x)+w(uttarget(x∣y)−uttarget(x))=(1−w)uttarget(x)+wuttarget(x∣y)\begin{aligned}\tilde{u}_t(x|y)&=u_t^{\mathrm{target}}(x)+wa_t\nabla_x\log p_t(y|x)\\&=u_t^{\mathrm{target}}(x)+wa_t(\nabla \log p_t(x|y)-\nabla_x \log p_t(x))\\&=u_t^{\mathrm{target}}(x)+w(a_t\nabla \log p_t(x|y)-a_t\nabla_x \log p_t(x))\\&=u_t^{\mathrm{target}}(x)+w\left[(u_t^{\mathrm{target}}(x|y)-b_tx)-(u_t^{\mathrm{target}}(x)-b_tx)\right]\\&=u_t^{\mathrm{target}}(x)+w(u_t^{\mathrm{target}}(x|y)-u_t^{\mathrm{target}}(x))\\&=(1-w)u_t^{\mathrm{target}}(x)+wu_t^{\mathrm{target}}(x|y)\end{aligned}

We may therefore express the scaled guided vector field u~t(x∣y)\tilde{u}_t(x|y) as the linear combination of the unguided vector field uttarget(x)u_t^{\mathrm{target}}(x) with the guided vector field uttarget(x∣y)u_t^{\mathrm{target}}(x|y). It seems that we need to train both uttarget(x)u_t^{\mathrm{target}}(x) and uttarget(x∣y)u_t^{\mathrm{target}}(x|y), but we can use the additional label ∅\varnothing that denotes the absence of conditioning, i.e.

uttarget(x)=uttarget(x∣∅)u_t^{\mathrm{target}}(x)=u_t^{\mathrm{target}}(x|\varnothing)

This approach of training a conditional and unconditional model in one is known as classifier-free guidance(CFG). In short, we’ve create a new way to train both uttarget(x)u_t^{\mathrm{target}}(x) and uttarget(x∣y)u_t^{\mathrm{target}}(x|y) in one single network uttarget(x∣⋅)u_t^{\mathrm{target}}(x|\cdot):

u~t(x∣y)=(1−w)uttarget(x∣∅)+wuttarget(x∣y)\begin{equation}\tilde{u}_t(x|y)=(1-w)u_t^{\mathrm{target}}(x|\varnothing)+wu_t^{\mathrm{target}}(x|y)\end{equation}

When w=1w=1, it’s easy to get u~t(x∣y)=uttarget(x∣y)\tilde{u}_t(x|y)=u_t^{\mathrm{target}}(x|y).

Training with CFG

We must now amend the guided conditional flow matching objective to account for the possibility of y=∅y = \varnothing. The challenge is that when sampling (z,y)∼pdata(z,y)\sim p_{\mathrm{data}}, we will never obtain y=∅y = \varnothing. It follows that we must introduce the possibility of y=∅y = \varnothing artificially. To do so, we will define a hyperparameter η\eta to be the probability that we discard the original label yy, and replace it with ∅\varnothing.

We thus arrive at our CFG conditional flow matching training objective as

LCFMguided(θ)=E□[∥utθ(x∣y)−uttarget(x∣z)∥2]\begin{equation}\mathcal{L}^{\mathrm{guided}}_{\mathrm{CFM}}(\theta)=\mathbb{E}_{\square}\left[\|u^{\theta}_t(x|y)-u_t^{\mathrm{target}}(x|z)\|^2\right]\end{equation}

□=(z,y)∼pdata(z,y),t∼U[0,1],replace y=∅ with prob. η\begin{equation}\square=(z,y)\sim p_{\mathrm{data}}(z,y),t\sim U[0,1],\text{replace }y=\varnothing\text{ with prob. }\eta\end{equation}

Algorithm 3 Flow Matching Training for Gaussian path

  1. for each mini-batch of data do
  2. \quad Sample a data example (z,y)(z,y) from the dataset
  3. \quad Sample a random time t∼U[0,1]t\sim U[0,1]
  4. \quad Sample noise ε∼N(0,Id)\varepsilon\sim \mathcal{N}(0,I_d)
  5. \quad Compute x=αtz+βtεx=\alpha_tz+\beta_t\varepsilon
  6. \quad With probability η\eta drop label: y←∅y\leftarrow \varnothing
  7. \quad Compute LCFMguided(θ)=∥utθ(x∣y)−uttarget(x∣z)∥2\mathcal{L}^{\mathrm{guided}}_{\mathrm{CFM}}(\theta)=\|u^{\theta}_t(x|y)-u_t^{\mathrm{target}}(x|z)\|^2
  8. \quad Update θ←grad_algorithm(LCFMguided(θ))\theta \leftarrow \mathrm{grad\_algorithm}(\mathcal{L}^{\mathrm{guided}}_{\mathrm{CFM}}(\theta))
  9. end for

For diffusion model with CFG, we simply do the same thing for simulating SDEs. Actually, almost any image or video that you see that is AI-generated relied heavily on classifier-free guidance w⩾4w \geqslant 4.

L6. Architectures


Key ideas

In the previous sections, we learned how to train a flow matching or diffusion model to sample from a distribution pdata(x∣y)p_{\mathrm{data}}(x|y). This recipe is general and can be applied to a variety of different data types and applications. Some well-known models such as FLUX 2.0, Stable Diffusion 3, Nano Banana and VEO-3 or Meta Movie Gen Video are designed with awesome model architectures, which we’ll introduce in this chapter.

To handle with image information, an image with RGB channels is simply described as a vector x∈R3×H×Wx\in\mathbb{R}^{3\times H\times W}. In the remain part of this chapter, we will explore ways of realizing the neural network θ\theta with some tricks, bringing out a workable model for image generations.

Embedding informations

First, we’ll consider how the raw conditioning information (the time tt and the conditioning variable yy) are embedded into a vector-valued form digestible by the actual model.

Embedding time

In practice, the scalar time tt is often embedded in a higher dimensional space using Fourier features, allowing the model to more faithfully capture high-frequency time dependence. The embedding trick of Fourier features is first used in the famous paper Attention is all you need, usually described as

TimeEmb(t)=2d[cos⁡(2πw1t)⋮cos⁡(2πwd/2t)sin⁡(2πw1t)⋮sin⁡(2πwd/2t)],wi=wmin(wmaxwmin)i−1d/2−1\mathrm{TimeEmb}(t)=\sqrt{\frac{2}{d}}\begin{bmatrix}\cos(2\pi w_1t)\\\vdots\\\cos(2\pi w_{d/2}t)\\\sin(2\pi w_1t)\\\vdots\\\sin(2\pi w_{d/2}t)\end{bmatrix},\quad w_i=w_{\mathrm{min}}\left(\frac{w_{\mathrm{max}}}{w_{\mathrm{min}}}\right)^{\frac{i-1}{d/2-1}}

Where wmax,wminw_{\mathrm{max}},w_{\mathrm{min}} are manually set. This choice of TimeEmb\mathrm{TimeEmb} is a standard choice but this exact form is not strictly necessary. Rather, the above is simply a convenient way of obtaining a normed embedding of dimension d, i.e.

∥TimeEmb(t)∥=1\|\mathrm{TimeEmb}(t)\| = 1

Embedding class labels

When yraw∈Y={0,...,N}y_{\mathrm{raw}} \in \mathcal{Y}=\{0,...,N\} is just a class label, then it is often easiest to simply
learn a separate embedding vector for each of the N+1N +1 possible values of yraw, and set yy to this embedding vector. One would consider the parameters of these embeddings to be included in the parameters of utθ(x∣y)u^{\theta}_t(x|y), and would therefore learn these during training.

类别标签通常采用可学习式嵌入法。

Embedding textual input

When yrawy_{\mathrm{raw}} is a text-prompt, the situation is more complex, and approaches largely rely on frozen, pre-trained models. One such model is known as CLIP (Contrastive Language-Image Pre
training)
.

CLIP is trained to learn a shared embedding space for both images and text-prompts, using a training loss designed to encourage image embeddings to be close to their corresponding prompts, while being farther from the embeddings of other images and prompts.

Therefore, one usually take y=CLIP(yraw)y=\mathrm{CLIP}(y_{\mathrm{raw}}) as the embedding vector produced by a frozen, pre-trained CLIP model. In certain cases, it may be undesirable to compress the entire sequence into a single representation. In this case, one might additionally consider embedding the prompt using a pre-trained transformer so as to obtain a sequence of embeddings.

Diffusion transformers

One particularly prominent architectural class are so-called diffusion transformers (DiTs), and their variants, which use the attention mechanism to construct the network. For query QQ, key KK and value VV, their scaled dot product attention is usually calculated by

Attention(Q,K,V)=softamx(QKTd/h)V\begin{equation}\mathrm{Attention}(Q,K,V)=\mathrm{softamx}\left(\frac{QK^T}{\sqrt{d/h}}\right)V\end{equation}

Where dd is the hidden dimension, and hh denotes the number of attention heads. We do patchify similar to ViT and get NN patches Patchify(X)∈RN×C′\mathrm{Patchify}(X)\in\mathbb{R}^{N\times C'} of the image input X∈RC×H×WX\in\mathbb{R}^{C\times H\times W}, then we apply a linear transformation to get the patch embedding

PatchEmb(X)=Patchify(X)⋅WP∈RN×d\mathrm{PatchEmb}(X)=\mathrm{Patchify}(X)\cdot W_P\in\mathbb{R}^{N\times d}

DiT has several units, so-called DiT blocks. The inputs to the diffusion transformer are then the time embedding, the prompt embedding, and the patchified image tensor given by

t~=TimeEmb(t)∈Rd,y~=PromptEmb(y)∈RS×d,x~0=PatchEmb(X)∈RN×d\tilde{t}=\mathrm{TimeEmb}(t)\in\mathbb{R}^d,\quad \tilde{y}=\mathrm{PromptEmb}(y)\in\mathbb{R}^{S\times d},\quad\tilde{x}_0=\mathrm{PatchEmb}(X)\in\mathbb{R}^{N\times d}

x~t+1=DiTBlockt(t~,y~,x~t)∈RN×d\tilde{x}_{t+1}=\mathrm{DiTBlock}_t(\tilde{t},\tilde{y},\tilde{x}_t)\in\mathbb{R}^{N\times d}

After these DiT blocks, we depatchify the output to get the image representation of the output. Now consider a certain DiT block: the query, key and value matrix are projections of given inputs, that is

Q(h)=xWQ(h),K(h)=zWK(h),V(h)=zWV(h)Q^{(h)}=xW_Q^{(h)},\quad K^{(h)}=zW_K^{(h)},\quad V^{(h)}=zW_V^{(h)}

where z=xz=x do self-attention and z=yz=y do cross-attention to the prompt. The headh\mathrm{head}_h do attention operations by (28)(28), then we concatenate heads and apply an output projection as

MultiHeadAttention=Concat(headi)i=1h⋅WO∈RN×d\mathrm{MultiHeadAttention}=\mathrm{Concat}(\mathrm{head}_i)_{i=1}^h\cdot W_O\in\mathbb{R}^{N\times d}

We also consider the adaptive normalization layer, that gives scale/shift parameters by MLPs

(γ,β)=MLP(t~)∈R2×d,AdaLNt~(x)=(1+γ)∘Norm(x)+β(\gamma,\beta)=\mathrm{MLP}(\tilde{t})\in\mathbb{R}^{2\times d},\quad \mathrm{AdaLN}_{\tilde{t}}(x)=(1+\gamma)\circ\mathrm{Norm}(x)+\beta

Here’s the image illustration of DiT.

U-net

The U-net architecture is an alternative architecture to the DiT architecture and is a specific type of convolutional neural network. A U-net consists of a series of encoders Ei\mathcal{E}_i, and a corresponding sequence of decoders Di\mathcal{D}_i, along with a latent processing block in between, which we shall refer to as a midcoder M\mathcal{M}.

The U-Net derives its name from the U-like shape formed by its encoders and decoders (see the figure below). Both the encoder and the decoder usually consist of a series of convolutional layers (with activation functions, pooling operations, etc. in between).

Latent space

The cost of modeling directly within such an image space Rd\mathbb{R}^d quickly becomes prohibitively expensive as one scales to increasingly higher resolution images. For example, a 1024×10241024\times 1024
image with three RGB color channels corresponds to a total dimension of d=3HW≈3×106d = 3HW ≈ 3\times 10^6. The important question thus becomes: How can we model high-dimensional images within a reasonable memory and computation budget?

A variational autoencoder (VAE) is obtained from a standard autoencoder formulation by relaxing the constraint that the encoder and decoder are deterministic functions. It’s basic ideas is that we compress our high-dimension input xx into a latent space variable zz (with low-dimension), then we decode it into high dimension space.

The encoder and decoder are parameterized by

z∼qϕ(⋅∣x),x∼pθ(⋅∣z)z\sim q_{\phi}(\cdot|x),\quad x\sim p_{\theta}(\cdot|z)

More details about VAE are omitted here, but it gives us an inspiration: what if we use a VAE-encoder to get x~=E(z)\tilde{x}=\mathcal{E}(z), then we do flow or diffusion operations on x~\tilde{x}, and decode it to get the generation of x=D(x~)x=\mathcal{D}(\tilde{x}). Using this architecture to do diffusion process is called a latent diffusion.

L7. Case Study


Stable diffusion 3

Stable Diffusion is a series of state-of-the-art image generation models. These models were among the first to use large-scale latent diffusion models for image generation.

Stable Diffusion 3 uses the same conditional flow matching model that we study in this work. It follows the approach by training within the latent space of a pre-trained autoencoder. Training a good autoencoder was a big contribution of the first stable diffusion papers.

To enhance text conditioning, Stable Diffusion 3 makes use of both 3 different types of text embeddings (including CLIP embeddings as well as the sequential outputs produced by a pretrained instance of the encoder of Google’s T5-XXL). They modified DiT referred to as a multi-modal DiT (MM-DiT), shown in the figure below.

The final, largest model has 88 billion parameters. For sampling, they use 5050 steps (i.e. they have to evaluate the network 5050 times) using a Euler simulation scheme and a classifier-free guidance weight between 2.0−5.02.0-5.0

MovieGen

Next, we discuss Meta’s video generator, Movie Gen Video. As the data are not images but videos, the data xx lie in the space RT×C×H×W\mathbb{R}^{T×C×H×W} where TT represents the new temporal dimension (i.e. the number of frames).

Movie Gen Video utilizes the conditional flow matching objective with the same straight line schedulers αt=t,βt=1−t\alpha_t =t, \beta_t = 1 − t. Like Stable Diffusion 3, Movie Gen Video also operates in the latent space of frozen, pretrained autoencoder.

Specifically, the authors propose to handle the added time dimension by introducing a temporal autoencoder
(TAE)
which maps a raw video xt′∈RT′×3×H′×W′x_t'\in\mathbb{R}^{T'\times 3\times H'\times W'} to a latent xt∈RT×C×H×Wx_t\in\mathbb{R}^{T\times C\times H\times W} with

T′T=H′H=W′W=8\frac{T'}{T}=\frac{H'}{H}=\frac{W'}{W}=8

To accomodate long videos, a temporal tiling procedure is proposed by which the video is chopped up into pieces, each piece is encoder separately, and the latents are sticthed together.

For text conditioning, Movie Gen Video employs three types of text embeddings:

  1. UL2 embeddings: for granular, text-based reasoning
  2. ByT5 embeddings: for attending to character-level details (for e.g., prompts explicitly requesting specific text tobe present)
  3. MetaCLIP embeddings: trained in a shared text-image embedding space.

Their final, largest model has 3030 billion parameters.

目前先主要更新到此处。