17.2 Gaussian Paths: Diffusion and Flow Matching

As Section 17.1 showed, a single noise level σ\sigma cannot serve both mixing and sharp generation: at small σ\sigma Langevin chains are trapped in their initial modes, whereas at large σ\sigma they mix across modes but sample a heavily blurred density. The remedy is to connect the data distribution at t=0t = 0 to a unit Gaussian at t=1t = 1 along a continuous Gaussian path xt=αtx0+σtϵ\mathbf{x}_t = \alpha_t \mathbf{x}_0 + \sigma_t \boldsymbol\epsilon, and to walk from high noise down to zero noise.

Denoising diffusion probabilistic models (DDPM) (Ho et al., 2020), score-based models (Song and Ermon, 2019; Song et al., 2021), and flow matching (Lipman et al., 2023; Liu et al., 2023; Albergo et al., 2023) all train a single time-conditioned network across levels t∈[0,1]t \in [0, 1] by least-squares regression. Because every common training target (the clean point x0\mathbf{x}_0, the noise ϵ\boldsymbol\epsilon, the score ∇log⁡pt(xt)\nabla \log p_t(\mathbf{x}_t), the velocity α˙tx0+σ˙tϵ\dot\alpha_t \mathbf{x}_0 + \dot\sigma_t \boldsymbol\epsilon, and the angular velocity v=αtϵ−σtx0\mathbf{v} = \alpha_t \boldsymbol\epsilon - \sigma_t \mathbf{x}_0) is an affine function of xt\mathbf{x}_t and the posterior mean x^0(xt)=E[x0∣xt]\hat{\mathbf{x}}_0(\mathbf{x}_t) = \mathbb{E}[\mathbf{x}_0 \mid \mathbf{x}_t], a network trained on any one target determines all the others. In this section we define the standard Gaussian paths and their shared log signal-to-noise ratio (log-SNR) clock, verify annealed Langevin sampling on exact scores, derive conditional flow matching and the target conversion dictionary, and verify our trained networks against the exact loss floor on the three-mode mixture.

torch.set_float32_matmul_precision('high')  # tf32 matmuls on tensor cores

17.2.1 Paths from Data to Noise#

A walk through all noise levels needs the levels in a row, each labeled by a time.

17.2.1.1 Signal, Noise and the Log-SNR#

The noisy point of the previous section, x~=x0+σϵ\tilde{\mathbf{x}} = \mathbf{x}_0 + \sigma\boldsymbol\epsilon, becomes a path once σ\sigma grows with time. This path keeps the data at full size and lets the noise grow until the data are negligible. Its variance grows without bound, hence the name variance-exploding (VE) path. A network on it sees inputs whose size grows with the noise, so one set of weights has to handle inputs of size one and, in Song and Ermon's model of CIFAR-10 images, inputs fifty times larger. Most models therefore shrink the data as the noise grows, which keeps every input near unit size. A Gaussian path is a pair of functions αt\alpha_t and σt\sigma_t on t∈[0,1]t \in [0, 1] that defines the noisy point

xt=αt x0+σt ϵ,ϵ∼N(0,I),(17.2.1)\mathbf{x}_t = \alpha_t\, \mathbf{x}_0 + \sigma_t\, \boldsymbol{\epsilon}, \qquad \boldsymbol{\epsilon} \sim \mathcal{N}(\mathbf{0}, \mathbf{I}), \tag{17.2.1}

starting from (α0,σ0)=(1,0)(\alpha_0, \sigma_0) = (1, 0). Unlike the VE path, the two paths in common use end at pure noise, (α1,σ1)=(0,1)(\alpha_1, \sigma_1) = (0, 1), or nearly so.

The variance-preserving (VP) path of DDPM (Ho et al., 2020) keeps αt2+σt2=1\alpha_t^2 + \sigma_t^2 = 1, so data of unit variance keep unit variance. A rate β(t)=βmin⁡+(βmax⁡−βmin⁡) t\beta(t) = \beta_{\min} + (\beta_{\max} - \beta_{\min})\, t, growing linearly from βmin⁡=0.1\beta_{\min} = 0.1 to βmax⁡=20\beta_{\max} = 20, sets how fast it forgets the data. In each instant dtdt the signal loses the fraction β(t) dt\beta(t)\, dt of its variance, so the surviving fraction is the exponential of minus the integrated rate:

αˉt:=αt2=exp⁡(−∫0tβ(r) dr),log⁡αˉt=−(0.1 t+9.95 t2).\begin{aligned} \bar\alpha_t &:= \alpha_t^2 = \exp\Big(-\int_0^t \beta(r)\, dr\Big), \\ \log \bar\alpha_t &= -\big(0.1\, t + 9.95\, t^2\big). \end{aligned}

The numbers 0.10.1 and 2020 are not arbitrary. They are DDPM's first and last step variances, 10−410^{-4} and 0.020.02, multiplied by its 1,0001{,}000 steps, and the next subsection shows how the steps become a rate. At the end of the path αˉ1=e−10.05≈4⋅10−5\bar\alpha_1 = e^{-10.05} \approx 4 \cdot 10^{-5}, close enough to pure noise for any purpose. Followed through time, one point of the VP path performs an Ornstein--Uhlenbeck process, a random walk pulled toward the origin (Section 26.4.3), on a clock that speeds up: the pull and the variance of the noise both scale with β(t)\beta(t), which is two hundred times larger at the end than at the start.

The linear path of flow matching and rectified flow (Lipman et al., 2023; Liu et al., 2023; Albergo et al., 2023) draws a straight line from each clean point to its noise:

αt=1−t,σt=t.(17.2.2)\alpha_t = 1 - t, \qquad \sigma_t = t. \tag{17.2.2}

It is the simplest path that ends exactly at noise, and each example travels along its line at constant speed. That simplicity made it the path of the chapter's default model and of many image generators since 2024 (Esser et al., 2024).

When do two paths, at different times, tell a denoiser the same thing? What a denoiser can infer from xt\mathbf{x}_t depends only on the ratio of signal to noise, measured as the log-SNR λt=log⁡(αt2/σt2)\lambda_t = \log(\alpha_t^2 / \sigma_t^2). To see why, multiply a noisy point by c=1/(αt+σt)c = 1/(\alpha_t + \sigma_t). The coefficients of cαtx0+cσtϵc\alpha_t \mathbf{x}_0 + c\sigma_t \boldsymbol\epsilon add up to one, so the result is a point of the linear path, at the time σt/(αt+σt)\sigma_t/(\alpha_t + \sigma_t), with the same ratio of signal to noise. Multiplying by a known number loses nothing, so the rescaled point carries the same information as xt\mathbf{x}_t.

Two paths, read at times of equal λ\lambda, therefore hold the same information about the clean point, and the log-SNR is a clock that all paths share. It runs from +∞+\infty at the data down to −∞-\infty at pure noise. The linear path covers all of it, and the VP path stops near λ=−10\lambda = -10. Choosing a path thus amounts to choosing how fast this clock runs, which decides where training and sampling spend their time.

GaussianPath holds αt\alpha_t and σt\sigma_t, computes the log-SNR and draws xt\mathbf{x}_t. Its constructors build the VP path, the linear path and a third path, the cosine path, which we meet below.

class GaussianPath:
    """x_t = alpha(t) x0 + sigma(t) eps, data at t = 0 and noise at t = 1."""
    def __init__(self, alpha, sigma):
        self.alpha, self.sigma = alpha, sigma

    @staticmethod
    def vp(beta_min=0.1, beta_max=20.0):
        """Variance preserving, Ho et al.'s linear beta in continuous time."""
        log_abar = lambda t: -(beta_min * t + (beta_max - beta_min) * t**2 / 2)
        return GaussianPath(lambda t: torch.exp(log_abar(t) / 2),
                            lambda t: torch.sqrt(-torch.expm1(log_abar(t))))

    @staticmethod
    def linear():
        """The straight line of flow matching and rectified flow."""
        return GaussianPath(lambda t: 1 - t, lambda t: t)

    @staticmethod
    def cosine(s=0.008):
        """Variance preserving, Nichol and Dhariwal's cosine schedule."""
        c = lambda t: torch.cos(math.pi / 2 * (t + s) / (1 + s))
        g = lambda t: c(t) / c(torch.zeros_like(t))   # exactly 1 at t = 0
        # and exactly 0 at t = 1 (cos(pi/2) is not), keeping the slope
        f = lambda t: torch.where(t < 1, g(t), g(t) - g(t).detach())
        return GaussianPath(f, lambda t: torch.sqrt(1 - f(t) ** 2))

    def log_snr(self, t):
        """lambda_t = log(alpha_t^2 / sigma_t^2), falling from +inf at 0."""
        return 2 * (torch.log(self.alpha(t)) - torch.log(self.sigma(t)))

    def sample(self, x0, t, eps):
        """x_t for per-example times t of shape (n,)."""
        t = t.reshape(-1, *[1] * (x0.dim() - 1))
        return self.alpha(t) * x0 + self.sigma(t) * eps

At t=0.5t = 0.5 the linear path holds signal and noise in equal parts, λ=0\lambda = 0. Where is the VP path?

vp, linear = GaussianPath.vp(), GaussianPath.linear()
t = torch.tensor([0.1, 0.5, 0.9])
r2 = lambda v: [round(u, 2) for u in v.tolist()]
for name, path in (('vp', vp), ('linear', linear)):
    print(f'{name:>6}: alpha {r2(path.alpha(t))} sigma {r2(path.sigma(t))} '
          f'log-SNR {r2(path.log_snr(t))}')
    vp: alpha [0.95, 0.28, 0.02] sigma [0.32, 0.96, 1.0] log-SNR [2.16, -2.46, -8.15]
linear: alpha [0.9, 0.5, 0.1] sigma [0.1, 0.5, 0.9] log-SNR [4.39, 0.0, -4.39]

Halfway in time the VP path is already mostly noise, with α=0.28\alpha = 0.28 and λ≈−2.5\lambda \approx -2.5, and at t=0.9t = 0.9 it keeps two percent of the signal against the linear path's ten. It crosses λ=0\lambda = 0 near t=0.26t = 0.26 and so spends three quarters of its time where noise dominates (Figure 17.2.1).

Figure 17.2.1:

Two Gaussian paths on one clock. (a) The signal coefficient αt\alpha_t (solid) and the noise coefficient σt\sigma_t (dashed) of the variance-preserving path, with β(t)\beta(t) rising from 0.10.1 to 2020, and of the linear path. (b) Their log-SNR λt\lambda_t, clipped to [−10,10][-10, 10]. The variance-preserving path reaches the noisy regime much earlier.

For small images this is wasteful. Nichol and Dhariwal (2021) observed that on images of 3232 and 6464 pixels on a side the last stretch of DDPM's schedule contributes little, because the image is gone long before t=1t = 1. Their cosine path sets αt=cos⁡πt2\alpha_t = \cos\frac{\pi t}{2}, up to a small offset near the data, and σt=sin⁡πt2\sigma_t = \sin\frac{\pi t}{2}. It is again a VP path, but its αˉt\bar\alpha_t falls almost linearly through the middle and changes slowly at both ends, so less time is spent where the image has already disappeared.

Papers on diffusion write the same quantities in several notations. Table 17.2.1 is for reference: it collects the symbols the chapter uses from here on and how papers write them. It can be skipped on a first reading and consulted when a paper's notation gets in the way.

Table 17.2.1. Notation of the diffusion chapter. Later sections add a few symbols of their own where they arise.
symbolmeaningpapers write
t∈[0,1]t \in [0, 1]time along the path: data at 00, noise at 11data at t=1t = 1 in flow matching; an integer step in DDPM
x0\mathbf{x}_0, ϵ\boldsymbol\epsilon, xt\mathbf{x}_ta clean point, standard Gaussian noise, the noisy pointx1\mathbf{x}_1 for data, x0\mathbf{x}_0 for noise in flow matching
αt\alpha_t, σt\sigma_tsignal and noise coefficients of the pathαˉt\sqrt{\bar\alpha_t}, 1−αˉt\sqrt{1 - \bar\alpha_t} in DDPM, whose αt\alpha_t is 1−βt1 - \beta_t
αˉt=αt2\bar\alpha_t = \alpha_t^2, β(t)\beta(t)squared signal coefficient of the VP path, its rate
kk, TT, βk\beta_kstep of the DDPM chain, number of steps, variance added at step kktt for kk
λt\lambda_tlog-SNR, log⁡(αt2/σt2)\log(\alpha_t^2 / \sigma_t^2)−γ(t)-\gamma(t) in VDM
σ\sigma, σ~i\tilde\sigma_ia noise level of the VE path; level ii of a ladderσi\sigma_i for σ~i\tilde\sigma_i
ptp_t, ∇log⁡pt\nabla \log p_tdensity of xt\mathbf{x}_t, its score
x^0\hat{\mathbf{x}}_0, ϵ^\hat{\boldsymbol\epsilon}posterior means of x0\mathbf{x}_0 and ϵ\boldsymbol\epsilon given xt\mathbf{x}_t; with a subscript θ\boldsymbol\theta, a network's predictions of themDθD_{\boldsymbol\theta} (a denoiser), ϵθ\boldsymbol\epsilon_{\boldsymbol\theta}
ut\mathbf{u}_t, uθ\mathbf{u}_{\boldsymbol\theta}marginal velocity of the path; a network that predicts itutu_t, vtv_t in flow matching, with the opposite sign
v\mathbf{v}αtϵ−σtx0\alpha_t \boldsymbol\epsilon - \sigma_t \mathbf{x}_0, the target of v\mathbf{v}-prediction
πk\pi_k, μk\boldsymbol\mu_k, ssweights, means and standard deviation of the mixture's components (here kk indexes components)

17.2.1.2 The DDPM Chain#

The VP path was not born as a path. Ho et al. (2020) defined a Markov chain of TT small steps, each shrinking the point a little and adding a little noise,

xk=1−βk xk−1+βk ϵk,k=1,…,T,(17.2.3)\mathbf{x}_k = \sqrt{1 - \beta_k}\, \mathbf{x}_{k-1} + \sqrt{\beta_k}\, \boldsymbol{\epsilon}_k, \qquad k = 1, \ldots, T, \tag{17.2.3}

with independent standard Gaussians ϵk\boldsymbol\epsilon_k and step variances βk∈(0,1)\beta_k \in (0, 1). Each step maps unit variance to unit variance, and because the noises are independent Gaussians, kk steps compose into a single draw,

xk=αˉk x0+1−αˉk ϵ,αˉk=∏j=1k(1−βj),(17.2.4)\mathbf{x}_k = \sqrt{\bar\alpha_k}\, \mathbf{x}_0 + \sqrt{1 - \bar\alpha_k}\, \boldsymbol{\epsilon}, \qquad \bar\alpha_k = \prod_{j=1}^{k} (1 - \beta_j), \tag{17.2.4}

in which the surviving signal is the product of the factors of all steps so far (Section 26.6.3.2 gives the induction). This closed form is why training never simulates the chain: any xk\mathbf{x}_k is one Gaussian draw away from x0\mathbf{x}_0.

Place the steps at the times tk=k/Tt_k = k/T and choose βk=1−αˉtk/αˉtk−1\beta_k = 1 - \bar\alpha_{t_k} / \bar\alpha_{t_{k-1}}. The product telescopes to αˉtk\bar\alpha_{t_k}, and the chain is the VP path read on a grid. On a fine grid βk≈β(tk)/T\beta_k \approx \beta(t_k)/T, so the step variances and the rate are one quantity, counted per step and per unit time. Figure 17.2.2 shows the forward chain and the reverse chain that generation runs.

Figure 17.2.2:

The graphical model of a diffusion model. The forward process (top) is a fixed Markov chain of Gaussian transitions from the data x0\mathbf{x}_0 to noise xT\mathbf{x}_T; the reverse process (bottom) is a learned chain of Gaussian transitions whose means a network predicts.

grid lists α\alpha and σ\sigma at evenly spaced times from noise to data, the default grid of the chapter's samplers.

@d2l.add_to_class(GaussianPath)
def grid(self, steps, t_start=1.0, t_end=0.0):
    """Lists of alpha and sigma at steps + 1 even times, t_start to t_end."""
    t = torch.linspace(t_start, t_end, steps + 1, dtype=torch.float64)
    return self.alpha(t).tolist(), self.sigma(t).tolist()

Which step variances does our path give for T=1000T = 1000? From βk≈β(tk)/T\beta_k \approx \beta(t_k)/T we expect about 10−410^{-4} for the first step and 0.020.02 for the last. The grid lists the times from the noise end, so its first entries belong to the last step.

a, _ = vp.grid(1000)
print(f'beta_1 = {1 - (a[-2] / a[-1]) ** 2:.1e}, '
      f'beta_T = {1 - (a[0] / a[1]) ** 2:.4f}, alpha_bar_T = {a[0] ** 2:.1e}')
beta_1 = 1.1e-04, beta_T = 0.0198, alpha_bar_T = 4.3e-05

The steps grow from 1.1⋅10−41.1 \cdot 10^{-4} to 0.01980.0198, close to the linear schedule of Ho et al., which runs from 10−410^{-4} to 0.020.02. After a thousand steps a factor αˉT≈0.007\sqrt{\bar\alpha_T} \approx 0.007 of the data survives.

17.2.1.3 Annealing through Noise Levels#

Does a walk through many noise levels do what one level could not? The scores of the blurred mixture are known exactly, so we can test this before training any network, walking down the VE path of the previous section. We run the Langevin update x←x+h2∇log⁡p(x)+h ξ\mathbf{x} \leftarrow \mathbf{x} + \tfrac{h}{2}\nabla \log p(\mathbf{x}) + \sqrt{h}\,\boldsymbol\xi of Section 17.1, with fresh Gaussian noise ξ\boldsymbol\xi, down a ladder of ten noise levels σ~i\tilde\sigma_i, evenly spaced in log scale from 33 down to 0.050.05. Each level takes 100100 steps on the exact score and starts where the previous level stopped. Its step size hi=0.1 σ~i2h_i = 0.1\, \tilde\sigma_i^2 shrinks with the square of the level, so that the noise of each step, hi≈0.3 σ~i\sqrt{h_i} \approx 0.3\, \tilde\sigma_i, stays a fixed fraction of the current blur.

The control spends the same 1,0001{,}000 steps at the finest level, with the step size h=0.05h = 0.05 of the previous section. That step is two hundred times larger than the ladder's at the same level, which gives the control every chance to cross a valley. Both start from the same 2,0002{,}000 points drawn from N(0,9I)\mathcal{N}(\mathbf{0}, 9\mathbf{I}). If the idea is right, the ladder lands near the weights 0.50.5, 0.30.3 and 0.20.2, and the control near a third each.

torch.manual_seed(0)
device = d2l.try_gpu()
mix = d2l.GaussianMixture.three_modes(device)
x_init = 3 * torch.randn(2000, 2, device=device)
x = x_init
for sig in torch.logspace(math.log10(3), math.log10(0.05), 10).tolist():
    x = d2l.langevin(lambda z: mix.score(z, 1.0, sig), x, 0.1 * sig ** 2, 100)
control = d2l.langevin(lambda z: mix.score(z, 1.0, 0.05), x_init, 0.05, 1000)
print('finest level only:', mix.summary(control))
print('ten levels:       ', mix.summary(x))
d2l.scatter_panels([control, x], ['finest level only', 'ten levels'],
                   data=mix.sample(2000));
finest level only: {'weights': [0.339, 0.331, 0.33], 'stray': 0.0145, 'spread': 0.493}
ten levels:        {'weights': [0.496, 0.297, 0.208], 'stray': 0.015, 'spread': 0.516}

The ladder lands within about 0.030.03 of the weights, with one to two percent of strays, points far from every mode, against about one percent in the data themselves. The control has the right spread around each mode but keeps the weights of its starting points, about a third each. The proportions are decided at the coarse levels, where the smoothed density has no valleys; the fine levels only sharpen each mode. A diffusion model divides the work the same way along its path. No network took part, so this experiment tests the idea alone, and whatever goes wrong later is the fault of a network.

This annealed Langevin dynamics sampled the first generator of this kind, the noise-conditional score network of Song and Ermon (2019). One network takes the noise level as an input and is trained by denoising score matching at every level of the ladder, weighted by σ~i2\tilde\sigma_i^2 (Section 26.6.3). Its levels, step sizes and step counts were set by hand, which in high dimensions is delicate (Exercise 4). A path replaces the ten levels by a continuum, and one network must learn them all.

17.2.2 Regression onto the Marginal Field#

One network is to serve every point of the path. We first decide what it should learn there, then find a regression that teaches it without knowing the answer.

17.2.2.1 Conditional Targets and Marginal Fields#

The network of the previous section learned, at one noise level, the score, and with it, through Tweedie's formula, the posterior mean of the clean point, x^0=E[x0∣xt]\hat{\mathbf{x}}_0 = \mathbb{E}[\mathbf{x}_0 \mid \mathbf{x}_t]. At every time this one object gives the score and tells a noisy point which way to move. It depends on the whole data distribution and is unknown. Condition on the clean point as well, and the problem becomes trivial: given x0\mathbf{x}_0, the best guess of x0\mathbf{x}_0 is x0\mathbf{x}_0 itself.

A sampler will need to know which way to move a noisy point, so let us ask the network for that directly. One clean point and one draw of noise move with the conditional velocity x˙t=α˙tx0+σ˙tϵ\dot{\mathbf{x}}_t = \dot\alpha_t \mathbf{x}_0 + \dot\sigma_t \boldsymbol\epsilon, which on the linear path is the constant ϵ−x0\boldsymbol\epsilon - \mathbf{x}_0. Many such points pass through a given x\mathbf{x} at time tt, each heading its own way, and the cloud as a whole moves there with their average velocity,

ut(x)=E[α˙t x0+σ˙t ϵ ∣ xt=x],(17.2.5)\mathbf{u}_t(\mathbf{x}) = \mathbb{E}\big[\dot\alpha_t\, \mathbf{x}_0 + \dot\sigma_t\, \boldsymbol\epsilon \,\big|\, \mathbf{x}_t = \mathbf{x}\big], \tag{17.2.5}

the marginal velocity. Where only one clean point can have produced x\mathbf{x}, it is that point's velocity; where several can, it is their average, weighted by how likely each is.

For the mixture this field is exact. Given the mode, x0\mathbf{x}_0 and ϵ\boldsymbol\epsilon are jointly Gaussian with xt\mathbf{x}_t, so their conditional means are linear in xt\mathbf{x}_t, and velocity averages them over the modes with the modes' posterior probabilities.

@d2l.add_to_class(d2l.GaussianMixture)
def velocity(self, x, t):
    """E[eps - x0 | x_t] on the linear path x_t = (1 - t) x0 + t eps."""
    log_p, r, var, a = self._modes(x, 1 - t, t)
    eps = (1 - a) * r / var                        # E[eps | x_t, mode k]
    x0 = self.means + a * self.std ** 2 / var * r  # E[x0 | x_t, mode k]
    return (torch.softmax(log_p, 1)[..., None] * (eps - x0)).sum(1)

For real data we cannot compute this field, yet we can learn it. Least squares recovers a conditional mean, so a conditional expectation is learned by regressing on the quantity inside it. This is how denoising score matching recovered the score. For the velocity the regression gives the conditional flow matching loss, which differs from the regression onto the unknown marginal field only by a constant CC that does not depend on the network:

Et, x0, ϵ ∥uθ(xt,t)−(α˙tx0+σ˙tϵ)∥2=Et, xt ∥uθ(xt,t)−ut(xt)∥2+C.(17.2.6)\begin{aligned} &\mathbb{E}_{t,\, \mathbf{x}_0,\, \boldsymbol\epsilon}\, \big\| \mathbf{u}_{\boldsymbol\theta}(\mathbf{x}_t, t) - (\dot\alpha_t \mathbf{x}_0 + \dot\sigma_t \boldsymbol\epsilon) \big\|^2 \\ &\qquad = \mathbb{E}_{t,\, \mathbf{x}_t}\, \big\| \mathbf{u}_{\boldsymbol\theta}(\mathbf{x}_t, t) - \mathbf{u}_t(\mathbf{x}_t) \big\|^2 + C. \end{aligned} \tag{17.2.6}

The two sides have the same minimizer, so a network trained on per-example velocities learns the marginal one (Section 26.7.1 gives the proof). We never need ut\mathbf{u}_t to learn it, just as the denoiser never needed the score. Figure 17.2.3 shows both views on the mixture. With xt=x\mathbf{x}_t = \mathbf{x} fixed, the conditional velocity ϵ−x0\boldsymbol\epsilon - \mathbf{x}_0 of the linear path equals (x−x0)/t(\mathbf{x} - \mathbf{x}_0)/t, and the figure draws its negative, the direction in which a sampler moves.

Figure 17.2.3:

The conditional and the marginal views of the linear path on the mixture, computed exactly. (a) The conditional path of one clean point x0\mathbf{x}_0 from the heaviest mode: circles of radius 2σt2\sigma_t around αtx0\alpha_t\mathbf{x}_0 at five times from 00 to 11. (b) The marginal path: contours of ptp_t at the same times. (c) The conditional field −(x−x0)/t-(\mathbf{x} - \mathbf{x}_0)/t at t=0.5t = 0.5, pointing toward that one point. (d) The marginal field −u0.5(x)-\mathbf{u}_{0.5}(\mathbf{x}), the posterior average of the conditional fields.

target computes the per-example target on any path, and the training below asks it for the velocity. rates supplies α˙t\dot\alpha_t and σ˙t\dot\sigma_t for it by forward-mode differentiation, so no path needs its derivatives written by hand. The other kinds, and x0_eps, which turns a prediction back into (x^0,ϵ^)(\hat{\mathbf{x}}_0, \hat{\boldsymbol\epsilon}), wait for the next subsection.

@d2l.add_to_class(GaussianPath)
def rates(self, t):
    """The time derivatives (alpha'(t), sigma'(t)), by forward-mode AD."""
    ones = torch.ones_like(t)
    return (torch.func.jvp(self.alpha, (t,), (ones,))[1],
            torch.func.jvp(self.sigma, (t,), (ones,))[1])

@d2l.add_to_class(GaussianPath)
def target(self, kind, x0, eps, t):
    """The regression target of a kind: eps, x0, v, score or velocity."""
    t = t.reshape(-1, *[1] * (x0.dim() - 1))
    a, s = self.alpha(t), self.sigma(t)
    if kind == 'eps': return eps
    if kind == 'x0': return x0
    if kind == 'v': return a * eps - s * x0
    if kind == 'score': return -eps / s
    if kind != 'velocity': raise ValueError(f'unknown kind {kind!r}')
    da, ds = self.rates(t)                      # velocity = d x_t / dt
    return da * x0 + ds * eps

@d2l.add_to_class(GaussianPath)
def x0_eps(self, kind, out, x, t):
    """The (x0, eps) that a prediction `out` of a kind implies at (x, t)."""
    t = t.reshape(-1, *[1] * (x.dim() - 1))
    a, s = self.alpha(t), self.sigma(t)
    if kind == 'eps': return (x - s * out) / a, out
    if kind == 'x0': return out, (x - a * out) / s
    if kind == 'v': return ((a * x - s * out) / (a**2 + s**2),
                            (s * x + a * out) / (a**2 + s**2))
    if kind == 'score': return (x + s ** 2 * out) / a, -s * out
    if kind != 'velocity': raise ValueError(f'unknown kind {kind!r}')
    da, ds = self.rates(t)
    det = a * ds - s * da
    return (ds * x - s * out) / det, (a * out - da * x) / det

The method now fits in one cell. Each step draws 512512 fresh points from the mixture, with a time and a noise for each, and regresses TimeMLP, the small network of the previous section that reads the point and sinusoidal features of the time, onto the conditional velocity of the linear path. Training runs 40,00040{,}000 Adam steps with a cosine-decayed learning rate and keeps a moving average of the weights, with a half-life of 700700 steps. The averaged weights smooth out the noise of the last steps, and they are the ones we evaluate below. Since every batch is new, there is no training set to memorize, unlike the fixed 2,0002{,}000 points of the previous section (Exercise 5 asks what happens when there is). Each network trains in a minute or two on one GPU.

def regression_loss(path, kind):
    """Squared error of net(x_t, t) against the target of a kind, t ~ U(0, 1)."""
    def loss_fn(net, x0):
        t = torch.rand(len(x0), device=x0.device)
        eps = torch.randn_like(x0)
        error = net(path.sample(x0, t, eps), t) - path.target(kind, x0, eps, t)
        return (error ** 2).flatten(1).sum(1).mean()  # ||error||^2 per example
    return loss_fn

torch.manual_seed(1)
num_steps = 40_000
net_v, ema_v, losses_v = d2l.train_regression(
    d2l.TimeMLP(256, 3).to(device), regression_loss(linear, 'velocity'),
    lambda: mix.sample(512), num_steps, cosine=True, ema_half_life=700)
d2l.plot(torch.arange(100) * num_steps // 100,
         losses_v.reshape(100, -1).mean(1).cpu(), 'step', 'loss')

Each point of the curve averages 400400 steps. The loss levels off near 55 within a few thousand steps, far above zero. Is the network stuck? We will see that no network can do much better.

17.2.2.2 Equivalent Targets#

DDPM's network predicts the noise, and others predict the clean point. Does the choice change what the network learns? At a fixed xt\mathbf{x}_t these are not different quantities. Taking the posterior mean of both sides of (17.2.1) gives xt=αtx^0+σtϵ^\mathbf{x}_t = \alpha_t \hat{\mathbf{x}}_0 + \sigma_t \hat{\boldsymbol\epsilon} with ϵ^=E[ϵ∣xt]\hat{\boldsymbol\epsilon} = \mathbb{E}[\boldsymbol\epsilon \mid \mathbf{x}_t], so each determines the other.

The score is a third view of the same object. Tweedie's formula of the previous section says that E[x0∣x~]=x~+σ2∇log⁡pσ(x~)\mathbb{E}[\mathbf{x}_0 \mid \tilde{\mathbf{x}}] = \tilde{\mathbf{x}} + \sigma^2 \nabla \log p_\sigma(\tilde{\mathbf{x}}) for x~=x0+σϵ\tilde{\mathbf{x}} = \mathbf{x}_0 + \sigma\boldsymbol\epsilon. We apply it with αtx0\alpha_t \mathbf{x}_0 in the role of the clean point and σt\sigma_t as the noise level. Then αtx^0=xt+σt2∇log⁡pt(xt)\alpha_t \hat{\mathbf{x}}_0 = \mathbf{x}_t + \sigma_t^2 \nabla \log p_t(\mathbf{x}_t), and the score is

∇log⁡pt(xt)=αtx^0−xtσt2=−ϵ^σt.(17.2.7)\nabla \log p_t(\mathbf{x}_t) = \frac{\alpha_t \hat{\mathbf{x}}_0 - \mathbf{x}_t}{\sigma_t^2} = -\frac{\hat{\boldsymbol\epsilon}}{\sigma_t}. \tag{17.2.7}

The score points from xt\mathbf{x}_t toward the scaled posterior mean, and it is the noise prediction divided by −σt-\sigma_t.

The marginal velocity (17.2.5) is α˙tx^0+σ˙tϵ^\dot\alpha_t \hat{\mathbf{x}}_0 + \dot\sigma_t \hat{\boldsymbol\epsilon}, and eliminating x^0\hat{\mathbf{x}}_0 between it and the score gives the score–velocity identity

ut(x)=α˙tαt x−(σtσ˙t−σt2α˙tαt)∇log⁡pt(x).(17.2.8)\mathbf{u}_t(\mathbf{x}) = \frac{\dot\alpha_t}{\alpha_t}\, \mathbf{x} - \Big(\sigma_t \dot\sigma_t - \sigma_t^2 \frac{\dot\alpha_t}{\alpha_t}\Big) \nabla \log p_t(\mathbf{x}). \tag{17.2.8}

On the linear path, where α˙t=−1\dot\alpha_t = -1 and σ˙t=1\dot\sigma_t = 1, it reads

ut(x)=ϵ^−x^0=−x+t ∇log⁡pt(x)1−t.(17.2.9)\mathbf{u}_t(\mathbf{x}) = \hat{\boldsymbol\epsilon} - \hat{\mathbf{x}}_0 = -\frac{\mathbf{x} + t\, \nabla \log p_t(\mathbf{x})}{1 - t}. \tag{17.2.9}

The velocity is a known multiple of the point plus a known multiple of the score, both fixed by the path. A velocity model is a score model in disguise.

Many image models use a fifth target, v\mathbf{v}-prediction (Salimans and Ho, 2022), with v=αtϵ−σtx0\mathbf{v} = \alpha_t \boldsymbol\epsilon - \sigma_t \mathbf{x}_0. On a VP path we may write αt=cos⁡ϕt\alpha_t = \cos\phi_t and σt=sin⁡ϕt\sigma_t = \sin\phi_t, and then v=dxt/dϕt\mathbf{v} = d\mathbf{x}_t/d\phi_t is the velocity per unit of angle instead of per unit of time. On the cosine path without its small offset, ϕt=πt/2\phi_t = \pi t/2, and v\mathbf{v} is 2/π2/\pi times the velocity (Exercise 1). Salimans and Ho introduced it for samplers with very few steps, which query the network mostly at low signal-to-noise ratio. There a noise prediction yields the clean point only after division by a small αt\alpha_t, while v\mathbf{v} yields it without any division.

All five targets are affine functions of xt\mathbf{x}_t and one posterior mean, with coefficients that depend only on the path and the time. We call the exact posterior mean the oracle, the predictor a perfect network would learn whatever its target, and the conversions between targets the dictionary. Table 26.7.1 lists the dictionary in full. target reads it in one direction, from (x0,ϵ)(\mathbf{x}_0, \boldsymbol\epsilon) to a target of any kind, and x0_eps, defined beside it above, reads it back, from a prediction of any kind to (x^0,ϵ^)(\hat{\mathbf{x}}_0, \hat{\boldsymbol\epsilon}). A network trained on one target therefore defines all of them, and so does a network trained on another path, read at the time of equal log-SNR.

Let us watch the dictionary at one point. For the mixture, oracle returns the exact x^0\hat{\mathbf{x}}_0 and ϵ^\hat{\boldsymbol\epsilon}, so any loss or sampler can use it in place of a network. At the point (0.5,−0.5)(0.5, -0.5) of the VP path at t=0.5t = 0.5, where α=0.28\alpha = 0.28 and σ=0.96\sigma = 0.96, we print every target. The last line rescales the point by 1/(α+σ)1/(\alpha + \sigma) onto the linear path at equal log-SNR, t=0.773t = 0.773, and evaluates the exact field velocity there, a different formula at a different point. It should return ϵ^−x^0\hat{\boldsymbol\epsilon} - \hat{\mathbf{x}}_0, which the first two lines let us compute in advance.

def oracle(x, alpha, sigma):
    """The exact posterior means (x0_hat, eps_hat) of the mixture at x."""
    x0_hat = mix.posterior_mean(x, alpha, sigma)
    a, s = (torch.as_tensor(v, device=x.device).reshape(-1, 1)
            for v in (alpha, sigma))
    return x0_hat, (x - a * x0_hat) / s

x = torch.tensor([[0.5, -0.5]], device=device)   # one noisy point
t = torch.tensor([0.5], device=device)           # VP: alpha 0.28, sigma 0.96
x0_hat, eps_hat = oracle(x, vp.alpha(t), vp.sigma(t))
for kind in ('x0', 'eps', 'score', 'v', 'velocity'):
    print(f'{kind:>8} on vp:', r2(vp.target(kind, x0_hat, eps_hat, t)[0]))
c = 1 / (vp.alpha(t) + vp.sigma(t))     # linear path, same alpha / sigma
print(f'velocity on linear at t = {(c * vp.sigma(t)).item():.3f}:',
      r2(mix.velocity(c * x, c * vp.sigma(t))[0]),
      ' eps_hat - x0_hat:', r2((eps_hat - x0_hat)[0]))
      x0 on vp: [0.29, -0.98]
     eps on vp: [0.44, -0.23]
   score on vp: [-0.46, 0.24]
       v on vp: [-0.15, 0.88]
velocity on vp: [-0.22, 1.29]
velocity on linear at t = 0.773: [0.15, 0.75]  eps_hat - x0_hat: [0.15, 0.75]

The clean point is predicted at (0.29,−0.98)(0.29, -0.98), inside the triangle of the three means (−2.5,−1.5)(-2.5, -1.5), (2.5,−1.5)(2.5, -1.5) and (0,2.5)(0, 2.5) and near none of them, because at α=0.28\alpha = 0.28 the posterior still spreads over all three modes. The score is the noise prediction divided by −0.96-0.96, and the field of the linear path returns (0.15,0.75)=ϵ^−x^0(0.15, 0.75) = \hat{\boldsymbol\epsilon} - \hat{\mathbf{x}}_0. Five targets on two paths come from one posterior mean.

Which target should we train, then? A network that reached the oracle would not care. A real network does not reach it, and two practical facts decide. First, a noise predictor says nothing about the clean point at pure noise, where x^0=(xt−σtϵ^)/αt\hat{\mathbf{x}}_0 = (\mathbf{x}_t - \sigma_t \hat{\boldsymbol\epsilon})/\alpha_t divides by zero, so it belongs on a path whose αt\alpha_t stays positive, such as VP. Second, the targets weigh the times differently. On the linear path the velocity loss is the noise loss weighted by 1/(1−t)21/(1 - t)^2 and the clean-point loss weighted by 1/t21/t^2 (Exercise 2), so equal squared errors in the velocity mean small errors of the noise near the noise end and small errors of the clean point near the data. In practice three pairs dominate: the velocity on the linear path, v\mathbf{v} on a cosine path and the noise on a VP path. None of the three is wrong, and the dictionary converts between them.

DDPM's simple loss (Ho et al., 2020) regresses onto the noise,

Lsimple(θ)=Et, x0, ϵ ∥ϵ−ϵθ(αtx0+σtϵ, t)∥2.(17.2.10)\begin{aligned} L_{\textrm{simple}}(\boldsymbol\theta) &= \mathbb{E}_{t,\, \mathbf{x}_0,\, \boldsymbol\epsilon}\, \big\| \boldsymbol\epsilon - \boldsymbol\epsilon_{\boldsymbol\theta}(\alpha_t \mathbf{x}_0 + \sigma_t \boldsymbol\epsilon,\, t) \big\|^2 . \end{aligned} \tag{17.2.10}

The per-example score, that of the conditional density N(αtx0,σt2I)\mathcal{N}(\alpha_t \mathbf{x}_0, \sigma_t^2 \mathbf{I}) of xt\mathbf{x}_t given x0\mathbf{x}_0, is −ϵ/σt-\boldsymbol\epsilon/\sigma_t, so the simple loss is denoising score matching at every level, weighted by σt2\sigma_t^2 (Section 26.6.3.2). Ho et al. derived it from a variational bound on the likelihood and then dropped the bound's weights over tt, because the samples looked better without them. Our second model makes DDPM's choice, the noise target on the VP path, and changes nothing else.

torch.manual_seed(2)
net_eps, ema_eps, losses_eps = d2l.train_regression(
    d2l.TimeMLP(256, 3).to(device), regression_loss(vp, 'eps'),
    lambda: mix.sample(512), num_steps, cosine=True, ema_half_life=700)

If both networks trained well, the dictionary says that they hold the same posterior mean despite their different paths and targets. The loss floor lets us check.

17.2.2.3 The Loss Floor#

Why did the velocity loss level off near 55? A target contains the noise of its own example, which no network can predict from xt\mathbf{x}_t. Even the oracle keeps the conditional variance of the target, averaged over the path. This loss floor, which the previous section met at one noise level, is the constant CC of (17.2.6). Once xt\mathbf{x}_t is fixed, the noise is (xt−αtx0)/σt(\mathbf{x}_t - \alpha_t \mathbf{x}_0)/\sigma_t, so every target is ctx0c_t \mathbf{x}_0 plus a function of xt\mathbf{x}_t, and its floor at time tt is

ct2  E tr Cov[x0∣xt].c_t^2\; \mathbb{E}\, \textrm{tr}\, \textrm{Cov}[\mathbf{x}_0 \mid \mathbf{x}_t].

The clean point has ct=1c_t = 1, the noise ct=−αt/σtc_t = -\alpha_t/\sigma_t, the velocity of the linear path ct=−1/tc_t = -1/t. The targets differ only in how much they magnify one posterior variance.

Near the data we can predict the number. At t=0.1t = 0.1 the modes are still far apart compared with the noise, so the posterior is that of a single Gaussian mode, with variance s2σt2/(αt2s2+σt2)s^2 \sigma_t^2 / (\alpha_t^2 s^2 + \sigma_t^2) per coordinate. Multiplied by ct2c_t^2 and summed over the two coordinates, it gives the noise floor 2αt2s2/(αt2s2+σt2)2\alpha_t^2 s^2/(\alpha_t^2 s^2 + \sigma_t^2) and the velocity floor 2s2/(αt2s2+σt2)2 s^2/(\alpha_t^2 s^2 + \sigma_t^2) of the linear path, where σt=t\sigma_t = t. With s=0.5s = 0.5, the VP path (α=0.95\alpha = 0.95, σ=0.32\sigma = 0.32) has a noise floor of about 1.371.37, and the linear path (α=0.9\alpha = 0.9, σ=0.1\sigma = 0.1) a velocity floor of 2.352.35.

The cell measures each floor on a million draws, at three times and averaged over tt, with its standard error. Any network's loss splits into the floor plus the mean squared distance between its prediction and the oracle's, because the oracle's error is uncorrelated with every function of xt\mathbf{x}_t. The cell therefore measures the excess of the averaged network over the floor directly, as that distance (column excess), and prints the training loss of the last 1,0001{,}000 steps beside it (column train loss). The last line reads the velocity network as a noise predictor on the VP path: eps_from_velocity moves each point to the linear path at equal log-SNR, asks the velocity network there, and converts its answer to ϵ^\hat{\boldsymbol\epsilon} with x0_eps.

@torch.no_grad()
def floor_and_excess(path, kind, net, x0, eps, t):
    """The floor E||target - E[target | x_t]||^2 with its standard error, and
    the network's loss minus the floor, E||net(x_t, t) - E[target | x_t]||^2."""
    x = path.sample(x0, t, eps)
    best = path.target(kind, *oracle(x, path.alpha(t), path.sigma(t)), t)
    err = ((path.target(kind, x0, eps, t) - best) ** 2).sum(1)
    out = torch.cat([net(x[i:i + 100_000], t[i:i + 100_000])  # in chunks
                     for i in range(0, len(x), 100_000)])
    return (err.mean().item(), err.std().item() / math.sqrt(len(err)),
            ((out - best) ** 2).sum(1).mean().item())

def eps_from_velocity(x, t):
    """ema_v as a noise predictor on the VP path, read at the linear-path
    time with the same alpha / sigma (the same posterior mean)."""
    c = 1 / (vp.alpha(t) + vp.sigma(t))
    t_lin, x_lin = c * vp.sigma(t), c[:, None] * x
    return linear.x0_eps('velocity', ema_v(x_lin, t_lin), x_lin, t_lin)[1]

n = 1_000_000
x0, eps = mix.sample(n), torch.randn(n, 2, device=device)
times = [torch.full((n,), t, device=device) for t in (0.1, 0.5, 0.9)]
times.append(torch.rand(n, device=device))             # t ~ U(0, 1)
print('target, path      t=0.1  t=0.5  t=0.9  t~U(0,1)    s.e.'
      '  train loss   excess')
for name, path, kind, net, losses in (
        ('noise, vp', vp, 'eps', ema_eps, losses_eps),
        ('velocity, linear', linear, 'velocity', ema_v, losses_v)):
    rows = [floor_and_excess(path, kind, net, x0, eps, t) for t in times]
    print(f'{name:16}' + ''.join(f'{r[0]:7.3f}' for r in rows[:3])
          + f'{rows[3][0]:10.3f}{rows[3][1]:8.4f}'
          + f'{losses[-1000:].mean().item():12.3f}{rows[3][2]:9.4f}')
floor, _, gap = floor_and_excess(vp, 'eps', eps_from_velocity, x0, eps,
                                 times[3])
print(f'velocity net read as a noise model on vp: loss {floor + gap:.3f},'
      f' excess {gap:.4f}')
target, path      t=0.1  t=0.5  t=0.9  t~U(0,1)    s.e.  train loss   excess
noise, vp         1.368  0.477  0.002     0.540  0.0011       0.542   0.0002
velocity, linear  2.351  2.796  9.157     4.906  0.0070       4.899   0.0010
velocity net read as a noise model on vp: loss 0.540, excess 0.0002

The floors at t=0.1t = 0.1 match our single-mode analytical estimate within 0.010.01. Along the path the two floors move in opposite directions: the noise floor is largest near t=0t = 0 (where small noise is indistinguishable from within-mode variance) and falls to 0.0020.002 at t=0.9t = 0.9, whereas the velocity floor rises to ≈9\approx 9 at t=0.9t = 0.9 before settling to tr⁡Cov[x0]\operatorname{tr}\textrm{Cov}[\mathbf{x}_0] at t=1t = 1 (Exercise 3). Averaged over t∼U(0,1)t \sim U(0, 1), the floors differ by an order of magnitude (0.540.54 for noise vs. 4.94.9 for velocity) because of the target scaling ct2c_t^2 and the different clocks of the two paths.

Both trained networks reach their theoretical floors: the mean squared error against the exact oracle (excess) is 0.00020.0002 for the noise network and 0.0010.001 for the velocity network, well below the Monte Carlo standard error of the floor itself. Moreover, when the linear-path velocity network is queried as a VP noise predictor via eps_from_velocity, it achieves the exact same loss (0.5400.540) and excess (0.00020.0002) as the network trained directly on the VP noise target. Both networks have learned the same underlying posterior mean. (A raw score target −ϵ/σt-\boldsymbol\epsilon/\sigma_t divides the noise floor by σt2\sigma_t^2 and diverges as t→0t \to 0, which is why score networks weight the DSM objective by σt2\sigma_t^2, reducing it to noise prediction.) Turning these learned fields into samples is the subject of Section 17.3.

17.2.3 Summary#

A Gaussian path xt=αtx0+σtϵ\mathbf{x}_t = \alpha_t \mathbf{x}_0 + \sigma_t \boldsymbol\epsilon interpolates between clean data at t=0t = 0 and Gaussian noise at t=1t = 1, and all such paths share a canonical clock given by the log signal-to-noise ratio λt=log⁡(αt2/σt2)\lambda_t = \log(\alpha_t^2 / \sigma_t^2). Annealing across noise levels resolves the single-level dilemma because high-noise levels establish global mode weights across smoothed valleys while low-noise levels sharpen each mode. Regressing onto per-example conditional targets (x0\mathbf{x}_0, ϵ\boldsymbol\epsilon, −ϵ/σt-\boldsymbol\epsilon/\sigma_t, v\mathbf{v}, or α˙tx0+σ˙tϵ\dot\alpha_t \mathbf{x}_0 + \dot\sigma_t \boldsymbol\epsilon) trains a network to output the corresponding conditional expectation given xt\mathbf{x}_t; since all five targets are affine functions of xt\mathbf{x}_t and x^0=E[x0∣xt]\hat{\mathbf{x}}_0 = \mathbb{E}[\mathbf{x}_0 \mid \mathbf{x}_t], a single trained predictor determines all five across any Gaussian path. Finally, every per-example regression objective has a positive loss floor ct2 Etr⁡Cov[x0∣xt]c_t^2\, \mathbb{E}\operatorname{tr}\textrm{Cov}[\mathbf{x}_0 \mid \mathbf{x}_t] arising from the unobserved noise realization, so predictor accuracy is measured by the excess loss above this floor rather than by the raw training loss.

17.2.4 Exercises#

  1. From v\mathbf{v} to the velocity. At the point x=(0.5,−0.5)\mathbf{x} = (0.5, -0.5) of the VP path at t=0.5t = 0.5, where αt=0.28\alpha_t = 0.28 and σt=0.96\sigma_t = 0.96, the text printed the exact prediction v^=(−0.15,0.88)\hat{\mathbf{v}} = (-0.15, 0.88).

    1. On a VP path αt2+σt2=1\alpha_t^2 + \sigma_t^2 = 1. Show that x^0=αtx−σtv^\hat{\mathbf{x}}_0 = \alpha_t \mathbf{x} - \sigma_t \hat{\mathbf{v}} and ϵ^=σtx+αtv^\hat{\boldsymbol\epsilon} = \sigma_t \mathbf{x} + \alpha_t \hat{\mathbf{v}}, and recover the printed x^0\hat{\mathbf{x}}_0 and ϵ^\hat{\boldsymbol\epsilon} by hand. Rounding the inputs to two digits costs about 0.010.01.
    2. Write αt=cos⁡ϕt\alpha_t = \cos\phi_t and σt=sin⁡ϕt\sigma_t = \sin\phi_t. Show that the velocity is ut=ϕ˙t v\mathbf{u}_t = \dot\phi_t\, \mathbf{v}, so that v\mathbf{v} is the velocity per unit of angle, and deduce the factor 2/π2/\pi of the cosine path.
    3. For the VP path of this section show that ϕ˙t=β(t) αt/(2σt)\dot\phi_t = \beta(t)\, \alpha_t / (2 \sigma_t). Evaluate it at t=0.5t = 0.5 and recover the printed velocity (−0.22,1.29)(-0.22, 1.29) from v^\hat{\mathbf{v}}, to within the rounding of the first part.
  2. Velocity, noise and clean-point targets. On the linear path, take the posterior mean of xt=(1−t)x0+tϵ\mathbf{x}_t = (1 - t)\mathbf{x}_0 + t\boldsymbol\epsilon.

    1. Show that the marginal velocity equals both (x−x^0)/t(\mathbf{x} - \hat{\mathbf{x}}_0)/t and (ϵ^−x)/(1−t)(\hat{\boldsymbol\epsilon} - \mathbf{x})/(1 - t).
    2. By the first part, an error in x^0\hat{\mathbf{x}}_0 reaches the velocity divided by tt, and an error in ϵ^\hat{\boldsymbol\epsilon} divided by 1−t1 - t. Near which end of the path is each prediction a poor source of the velocity, and how does this explain why a noise model is never queried at α=0\alpha = 0? (Exercise 6 of Section 26.7 works out the propagation of errors between all targets on the cosine path.)
    3. Show that the velocity loss of uθ=(x−x^0,θ)/t\mathbf{u}_{\boldsymbol\theta} = (\mathbf{x} - \hat{\mathbf{x}}_{0,\boldsymbol\theta})/t equals the clean-point loss E∥x^0,θ−x0∥2\mathbb{E}\|\hat{\mathbf{x}}_{0,\boldsymbol\theta} - \mathbf{x}_0\|^2 weighted by 1/t21/t^2, and the velocity loss of uθ=(ϵ^θ−x)/(1−t)\mathbf{u}_{\boldsymbol\theta} = (\hat{\boldsymbol\epsilon}_{\boldsymbol\theta} - \mathbf{x})/(1 - t) equals the noise loss weighted by 1/(1−t)21/(1 - t)^2. Which times does flow matching emphasize relative to each of the two unweighted losses?
  3. [code] The loss floor. Use oracle and floor_and_excess.

    1. Plot the floor of the velocity target on the linear path and of the noise target on the VP path against tt on a grid in (0,1)(0, 1). Where is each largest? The printed training loss is a mean over 1,0001{,}000 minibatches of 512512 points; estimate its standard error from losses_v, and compare it with the gap between the printed training loss and the floor.
    2. Let Σ\boldsymbol\Sigma be the covariance matrix of the mixture, with eigenvalues κ1,κ2\kappa_1, \kappa_2. For Gaussian data with this covariance, show that the velocity floor on the linear path at time tt is ∑iκi/((1−t)2κi+t2)\sum_i \kappa_i / \big((1 - t)^2 \kappa_i + t^2\big). Add this curve to the plot, and explain why it cannot lie below the floor of the mixture. Why do the two floors agree at both ends of the path?
    3. The score target −ϵ/σt-\boldsymbol\epsilon/\sigma_t has the floor of the noise target divided by σt2\sigma_t^2. Evaluate it on the VP path at t=0.01t = 0.01, 0.10.1 and 0.50.5, and explain why no network is trained on this target with tt uniform on (0,1)(0, 1).
    4. The noise model's training loss is about a tenth of the velocity model's. Is it the better model? At the VP times t∈{0.1,0.5,0.9}t \in \{0.1, 0.5, 0.9\} measure each network's error against the oracle in a common unit, E∥x^0−x^0⋆∥2\mathbb{E}\|\hat{\mathbf{x}}_0 - \hat{\mathbf{x}}_0^\star\|^2, where x^0⋆\hat{\mathbf{x}}_0^\star comes from oracle. Convert ema_eps with vp.x0_eps, and ema_v with eps_from_velocity followed by x^0=(xt−σtϵ^)/αt\hat{\mathbf{x}}_0 = (\mathbf{x}_t - \sigma_t \hat{\boldsymbol\epsilon})/\alpha_t. Use the factors ctc_t of the text to explain why the raw losses differ so much. Which comparison ranks the two models: the raw losses, their excesses over the floors, or the errors in a common unit?

    Part (d) is adapted from CMU 10-799, Homework 2 (Spring 2026), Question 3(a).

  4. Ladder spacing in high dimensions. ● Let the data be a single point at the origin of Rd\mathbb{R}^d, so that pσ~=N(0,σ~2I)p_{\tilde\sigma} = \mathcal{N}(\mathbf{0}, \tilde\sigma^2 \mathbf{I}), and let the ladder be geometric with ratio q=σ~i−1/σ~i>1q = \tilde\sigma_{i-1}/\tilde\sigma_i > 1.

    1. Show that r=∥x∥r = \|\mathbf{x}\| for x∼pσ~\mathbf{x} \sim p_{\tilde\sigma} satisfies E[r2]=dσ~2\mathbb{E}[r^2] = d\tilde\sigma^2 and Var[r2]=2dσ~4\textrm{Var}[r^2] = 2d\tilde\sigma^4, and conclude that rr is approximately N(σ~d,σ~2/2)\mathcal{N}(\tilde\sigma\sqrt d, \tilde\sigma^2/2) for large dd.
    2. A chain that leaves level i−1i - 1 with a sample of pσ~i−1p_{\tilde\sigma_{i-1}} enters level ii at a radius that lies, with high probability, in σ~i−1(d±3/2)\tilde\sigma_{i-1}(\sqrt d \pm 3/\sqrt 2). Show that pσ~ip_{\tilde\sigma_i} puts the mass Φ(2d(q−1)+3q)−Φ(2d(q−1)−3q)\Phi\big(\sqrt{2d}(q - 1) + 3q\big) - \Phi\big(\sqrt{2d}(q - 1) - 3q\big) on this interval, where Φ\Phi is the standard normal distribution function. Why does a mass near zero mean that the chain starts the level where the network has seen almost no training inputs?
    3. Song and Ermon (2020) choose qq so that this mass is about one half. Solve for qq at d=3072d = 3072, the dimension of CIFAR-10 images, and count the levels from σ~=50\tilde\sigma = 50 down to 0.010.01. Compare with the 232232 levels of their CIFAR-10 model.
    4. The top level must also be coarse enough to merge the modes. Two equal Gaussian components at ±μ\pm\mu with variance vv have a single mode exactly when μ2≤v\mu^2 \le v (Exercise 4 of Section 26.5). Use this criterion on the two lower modes of the mixture to estimate the noise level at which they merge, and compare it with the ladder's top level of 33.
  1. [code] The exact optimum memorizes. A finite training set is itself a distribution, a mixture of point masses, and its exact velocity field is known. Bertrand et al. (2025) take as their starting point that following this field from noise reproduces the training points, and ask why trained networks generalize instead.
    1. Draw 6464 points from the mixture and train TimeMLP(256, 3) with regression_loss(linear, 'velocity') on batches drawn from these points only.
    2. d2l.GaussianMixture(points.tolist(), [1/64] * 64, 0.0) is the empirical distribution (also pass the device), and its velocity method is the exact field for t>0t > 0. Follow it and the trained network from the same 2,0002{,}000 standard Gaussian starts, with 100100 straight steps x←x−ut(x)/100\mathbf{x} \leftarrow \mathbf{x} - \mathbf{u}_t(\mathbf{x})/100 at t=1,0.99,…,0.01t = 1, 0.99, \ldots, 0.01. For both sets of samples, plot the histogram of the distance to the nearest training point.
    3. Which field reproduces the training set, and which produces new points? Bertrand et al. argue that the noise in the regression targets is not what makes the network generalize. Repeat the first two parts with 1,0241{,}024 training points, and describe how the two histograms change.

Discussions