17.5  采样器、反演与编辑

扩散采样器每走一步都要评估一次分数或速度网络,因此生成一张图像的计算成本随步数线性增长。在 17.4 节 中,概率流 ODE 的 50 步 Euler 更新以二十分之一的开销逼近了千步祖先链的 Fréchet 距离(FD)。由于 17.2 节 的训练回归仅依赖单个时刻 \(t\) 处 \(\mathbf{x}_t\) 的边缘分布而非多步联合分布,单个训练好的网络能够支撑一整族连续的随机与确定性逆向过程 (J. Song 等 2021年)。

本节推导去噪扩散隐式模型(DDIM)家族,证明其确定性成员(\(\eta = 0\))与 \((\bar{\mathbf{x}}, \bar\sigma)\) 坐标下概率流 ODE 的 Euler 法完全重合,并跨步数预算与时间网格比较一阶(Euler/DDIM)、二阶(Heun)与多步(Adams–Bashforth / DPM-Solver++)求解器。最后,我们利用确定性 ODE 的可逆性,无需重新训练即可实现图像到噪声的反演、潜空间插值、部分加噪编辑与零样本图像修复。

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

17.5.1 确定性与随机采样器

17.3 节 中的两种采样器——祖先链与 Euler 法——尽管一个每步加入新噪声而另一个不加,但读取网络的方式完全相同。在高斯路径的点 \(\mathbf{x}_t = \alpha_t \mathbf{x}_0 + \sigma_t \boldsymbol\epsilon\) 处,网络给出干净点的估计 \(\hat{\mathbf{x}}_0\) 与噪声的估计 \(\hat{\boldsymbol\epsilon}\),二者互相决定:

\[\hat{\mathbf{x}}_0 = \frac{\mathbf{x}_t - \sigma_t \hat{\boldsymbol\epsilon}}{\alpha_t}. \tag{17.5.1}\]

无论网络训练时预测的是哪种目标,17.3 节 的 d2l.make_pred 都会将其封装为在任意噪声水平返回该数对的函数 pred(x, alpha, sigma),本节的所有采样器只读取这一接口。

17.5.1.1 DDIM 家族与 Euler 法

取时刻 \(t\) 与更早的时刻 \(s < t\)。从 \(t\) 到 \(s\) 的一步采样只需把服从 \(\mathbf{x}_t\) 分布的点变成服从 \(\mathbf{x}_s\) 分布的点;回归目标除此之外不施加任何约束。写出 \(\mathbf{x}_t = \alpha_t \mathbf{x}_0 + \sigma_t \boldsymbol\epsilon\),在 \(0\) 与 \(\sigma_s\) 之间任选一个噪声尺度 \(\tilde\sigma\),并令

\[\mathbf{x}_s = \alpha_s \mathbf{x}_0 + \sqrt{\sigma_s^2 - \tilde\sigma^2}\, \boldsymbol\epsilon + \tilde\sigma\, \boldsymbol\xi, \qquad \boldsymbol\xi \sim \mathcal{N}(\mathbf{0}, \mathbf{I}), \tag{17.5.2}\]

其中 \(\boldsymbol\xi\) 与 \(\boldsymbol\epsilon\) 独立。两项噪声方差之和恰好为 \(\sigma_s^2\),因此给定 \(\mathbf{x}_0\) 时对任意 \(\tilde\sigma\) 均有正确的 \(\mathbf{x}_s\) 分布;又因 \(\boldsymbol\epsilon = (\mathbf{x}_t - \alpha_t \mathbf{x}_0) / \sigma_t\),每个 \(\tilde\sigma\) 都定义了从 \(\mathbf{x}_t\) 到 \(\mathbf{x}_s\) 的一步转移。采样器用网络估计取代 \(\mathbf{x}_0\) 与 \(\boldsymbol\epsilon\):

\[\mathbf{x}_s = \alpha_s \hat{\mathbf{x}}_0 + \sqrt{\sigma_s^2 - \tilde\sigma^2}\, \hat{\boldsymbol\epsilon} + \tilde\sigma\, \boldsymbol\xi. \tag{17.5.3}\]

该步将预测的干净点连同预测噪声移至水平 \(s\),并把其中一部分噪声替换为新鲜噪声。J. Song 等 (2021年) 用强度参数 \(\eta \geq 0\) 度量新鲜噪声占比:

\[\tilde\sigma = \eta\, \sigma_s \sqrt{1 - \kappa^2}, \qquad \kappa = \frac{\sigma_s \alpha_t}{\alpha_s \sigma_t}. \tag{17.5.4}\]

其中 \(\kappa^2 = \mathrm{SNR}_t / \mathrm{SNR}_s < 1\),\(\mathrm{SNR} = \alpha^2 / \sigma^2\)。当 \(\eta = 1\) 时,\(\tilde\sigma^2\) 正是 17.2 节 加噪链下给定 \(\mathbf{x}_t\) 与 \(\mathbf{x}_0\) 时 \(\mathbf{x}_s\) 的方差(练习 1),此时该步以估计值代替真值从该链的后验采样。当 \(\eta = 0\) 时不加入任何新鲜噪声,步骤完全确定。这就是去噪扩散隐式模型(DDIM)——称为“隐式”,是因为它通过噪声到数据的映射而非密度链定义样本。

ddim_sample 在 path.grid 网格上搭配任意预测器 pred(x, alpha, sigma) -> (x0, eps) 运行 DDIM 家族,并可在 t_end(默认为数据端)处暂停,以便外层循环在各噪声水平之间对样本施加操作。

@torch.no_grad()
def ddim_sample(pred, x, path, steps, eta=0.0, *, t_start=1.0, t_end=0.0):
    """DDIM from x at t_start (1 is noise) to t_end; eta = 0 is deterministic.
    eta = 1 draws the posterior variance: not the ancestral sampler's."""
    a, s = path.grid(steps, t_start, t_end)
    for i in range(steps):
        x0, eps = pred(x, a[i], s[i])
        ratio = s[i + 1] * a[i] / (a[i + 1] * s[i])     # kappa of the text
        var = (eta * s[i + 1]) ** 2 * (1 - ratio ** 2)   # fresh noise
        x = a[i + 1] * x0 + math.sqrt(s[i + 1] ** 2 - var) * eps
        if var > 0:
            x = x + math.sqrt(var) * torch.randn_like(x)
    return x
def ddim_sample(pred, x, path, steps, eta=0.0, key=None, *,
                t_start=1.0, t_end=0.0):
    """DDIM from x at t_start (1 is noise) to t_end; eta > 0 needs a key.
    eta = 1 draws the posterior variance: not the ancestral sampler's."""
    if eta > 0 and key is None:
        raise ValueError('ddim_sample with eta > 0 draws noise: pass a key')
    a, s = path.grid(steps, t_start, t_end)
    a_t, s_t, a_s, s_s = a[:-1], s[:-1], a[1:], s[1:]
    ratio = s_s * a_t / (a_s * s_t)                     # kappa of the text
    var = (eta * s_s) ** 2 * (1 - ratio ** 2)           # fresh noise
    def step(x, inputs):
        a_t, s_t, a_s, c_eps, c_noise, key = inputs
        x0, eps = pred(x, a_t, s_t)
        x = a_s * x0 + c_eps * eps
        if eta > 0:
            x = x + c_noise * jax.random.normal(key, x.shape)
        return x, None
    keys = (jax.random.split(key, steps) if eta > 0
            else jnp.zeros(steps))                      # unused at eta = 0
    return jax.lax.scan(step, x, (a_t, s_t, a_s, jnp.sqrt(s_s ** 2 - var),
                                  jnp.sqrt(var), keys))[0]

迈一大步确定性步长会带来多大误差?考虑本身就是标准高斯分布的数据,沿保方差路径运行。此时 \(\mathbf{x}_t\) 在每个时刻都是标准高斯分布,精确采样器不应移动任何点。精确估计为 \(\hat{\mathbf{x}}_0 = \alpha_t \mathbf{x}_t\) 与 \(\hat{\boldsymbol\epsilon} = \sigma_t \mathbf{x}_t\),而从 \(t = 1\) 到 \(t = 0\) 的一步确定性大步返回 \(\hat{\mathbf{x}}_0 = \alpha_1 \mathbf{x}_1\):由于 \(\alpha_1 \approx 0.0066\),整个点云几乎坍缩到了均值上。原因在于单步在整个跨度内把噪声估计固定为常数,而沿精确轨迹它在不断变化。

当 \(\eta = 0\) 时,该步写作 \(\mathbf{x}_s = \alpha_s \hat{\mathbf{x}}_0 + \sigma_s \hat{\boldsymbol\epsilon}\),正是 17.3 节 中 ode_sample 执行的更新。在那里推导的坐标 \(\bar{\mathbf{x}} = \mathbf{x} / \alpha_t\) 与 \(\bar\sigma_t = \sigma_t / \alpha_t\) 下,它写作

\[\bar{\mathbf{x}}_s = \bar{\mathbf{x}}_t + (\bar\sigma_s - \bar\sigma_t)\, \hat{\boldsymbol\epsilon}, \tag{17.5.5}\]

这正是概率流 ODE \(d\bar{\mathbf{x}} / d\bar\sigma = \hat{\boldsymbol\epsilon}\) 的一步 Euler 更新,而上文的比值 \(\kappa\) 恰好就是 \(\bar\sigma_s / \bar\sigma_t\)。因此,在每条高斯路径上 DDIM 都是 Euler 法;在相同噪声水平上,\(\eta = 0\) 时的 ddim_sample 与 ode_sample 是在两套坐标系下计算同一个函数。38.6.4 节 证明了这一等价性及两个极端情形:单点数据在任意步长下均无误差积分(因为 \(\hat{\boldsymbol\epsilon}\) 沿每条轨迹恒定),而高斯数据每迈一步都会收缩(图 38.6.3)。

17.5.1.2 新鲜噪声与大步长

既然同一个网络支持任意 \(\eta\),究竟该选多大的噪声强度?令 \(f = \tilde\sigma^2 / \sigma_s^2\),则更新式 式 17.5.3 写作

\[\mathbf{x}_s = \alpha_s \hat{\mathbf{x}}_0 + \sigma_s \Big(\sqrt{1 - f}\, \hat{\boldsymbol\epsilon} + \sqrt{f}\, \boldsymbol\xi\Big), \qquad f = \eta^2 \Big(1 - \frac{\mathrm{SNR}_t}{\mathrm{SNR}_s}\Big). \tag{17.5.6}\]

家族中每个成员将干净估计放置到水平 \(s\) 的方式完全相同,只是随行噪声方差中有比例 \(f\) 换成了新鲜噪声。在细网格上,即便 \(\eta = 1\),\(f\) 也很小;在十步粗网格上,\(\eta = 1\) 采样器每步都会换掉大部分噪声。

支持引入新鲜噪声的理由很充分。17.3 节 的祖先步在一阶上拆为一步保持当前分布 \(p_t\) 不变并将离群点拉回的 Langevin 步,加上一步概率流 ODE 的 Euler 步;任何注入噪声且保持边缘分布的逆过程皆可如此拆分(38.5.5 节)。因此随机采样器不断把状态拉向模型分布,前一步的误差可能在下一步被部分遗忘;而确定性采样器会把每一步的误差一路带到终点。

反对它的理由同样充分。Langevin 拉回效应仅针对小步长成立。跨大步长时,精确逆向转移远非高斯分布(17.3 节 的练习 3),大步长随机更新自身会引入新的误差。因此确定性采样器理应在小预算下胜出;一旦步长足够小,随机采样器能否反超,我们将在 17.5.2.4 节 的图像实验中实测。图 17.5.1 在混合分布上展示了该家族的两端。

图 17.5.1: 精确预测器在三峰混合分布上保方差路径 200 步的 DDIM 家族两端,从 \(t = 1\) 的三个起点(圆圈)走到 \(t = 0\)(叉号);灰色为训练数据。(a)\(\eta = 0\) 时每个起点沿光滑曲线落入某个模式。(b)\(\eta = 1\) 时路径呈锯齿状,且此处三个起点中有两个落入了与(a)不同的模式;噪声主导的前半段路径以浅色绘制。两者在 \(t = 0\) 处产出相同的分布。

有两种随机采样器必须区分开。祖先链加入的是前向步方差 \(\sigma_t^2 - (\alpha_t / \alpha_s)^2 \sigma_s^2\),而 \(\eta = 1\) 加入的是后验方差,比前者小一个因子 \(\sigma_s^2 / \sigma_t^2\);两者移动到相同的均值。因此祖先链并非 DDIM 家族成员:它保留的噪声与新增的噪声方差之和超过了 \(\sigma_s^2\)。究竟哪个方差正确?一般而言两者皆非。当数据是单点时后验方差精确(此时 \(\mathbf{x}_t\) 对 \(\mathbf{x}_0\) 不留任何疑义),当数据是保方差路径上的标准高斯时前向步方差精确。对每坐标方差小于 1(比噪声窄)的数据,最优高斯方差介于两者之间;对更宽的数据,它甚至可超过前向步方差(练习 4)。在千步网格上,除最后几步(此时两个方差都极小)外,该因子接近 1,因此选择无关紧要;但在五十步上差异显著。

17.5.2 更少的步数

一阶方法的误差与步长成正比,因此跳过步数会以可预测的方式损失精度。我们先在能够精确计算误差的问题上度量这一损失,再考察更高阶方法与更合理的步长排布能挽回多少。预先提醒一句:我们在图像上测得的具体数值属于这个小型模型,不会照搬到下一个模型;但找到它们的实验流程是通用的。

17.5.2.1 在贯穿示例上跳步

回到 17.1 节 的三峰混合分布 mix,我们在每个噪声水平都能精确计算其后验均值以及精确数对 \((\hat{\mathbf{x}}_0, \hat{\boldsymbol\epsilon})\);pred_exact 将该数对封装为采样器接口。我们抽取 20,000 个起点与同等数量的数据点,并打印数据的散布度(点到最近模式中心的平均平方距离,17.1 节)。每个模式每坐标方差为 \(0.25\),因此散布度略低于 \(0.5\)。

mix = d2l.GaussianMixture.three_modes()
vp, lin = d2l.GaussianPath.vp(), d2l.GaussianPath.linear()

def pred_exact(x, alpha, sigma):
    """The mixture's exact (x0, eps) at x = alpha x0 + sigma eps."""
    x0 = mix.posterior_mean(x, alpha, sigma)
    return x0, (x - alpha * x0) / sigma

torch.manual_seed(0)
z, data = torch.randn(20_000, 2), mix.sample(20_000)
print(f'data: spread {mix.summary(data)["spread"]:.3f}')
data: spread 0.477
mix = d2l.GaussianMixture.three_modes()
vp, lin = d2l.GaussianPath.vp(), d2l.GaussianPath.linear()

def pred_exact(x, alpha, sigma):
    """The mixture's exact (x0, eps) at x = alpha x0 + sigma eps."""
    x0 = mix.posterior_mean(x, alpha, sigma)
    return x0, (x - alpha * x0) / sigma

k_z, k_data, k_eta = jax.random.split(jax.random.key(0), 3)  # k_eta: per n
z, data = jax.random.normal(k_z, (20_000, 2)), mix.sample(k_data, 20_000)
print(f'data: spread {mix.summary(data)["spread"]:.3f}')
data: spread 0.473

使用精确预测器时,同一出发点的十步样本与千步样本之间的任何差异都是步长离散化误差,对一阶方法而言步数翻倍则误差应减半。我们在保方差网格上以 5 至 1,000 步运行 DDIM,打印到千步样本的平均距离与散布度;在 \(\eta = 0\) 的散布度旁并列打印相同起点下 \(\eta = 1\) 与祖先链的散布度。

samples = {n: d2l.ddim_sample(pred_exact, z, vp, n)
           for n in (5, 10, 20, 50, 200, 1000)}
spread = lambda pts: f'{mix.summary(pts)["spread"]:.3f}'
for n, x in samples.items():
    gap = (x - samples[1000]).norm(dim=1).mean()
    eta1 = d2l.ddim_sample(pred_exact, z, vp, n, eta=1.0)
    chain = d2l.ancestral_sample(pred_exact, z, vp, n)
    print(f'{n:4d} steps: distance to 1,000 steps {gap:.3f}, spread '
          f'{spread(x)} (eta = 1: {spread(eta1)}, ancestral: {spread(chain)})')
d2l.scatter_panels([samples[10][:2000], samples[200][:2000]],
                   ['10 steps', '200 steps'], data=data[:2000]);
   5 steps: distance to 1,000 steps 0.411, spread 0.309 (eta = 1: 0.321, ancestral: 0.386)
  10 steps: distance to 1,000 steps 0.210, spread 0.380 (eta = 1: 0.320, ancestral: 0.528)
  20 steps: distance to 1,000 steps 0.107, spread 0.420 (eta = 1: 0.342, ancestral: 0.520)
  50 steps: distance to 1,000 steps 0.043, spread 0.451 (eta = 1: 0.397, ancestral: 0.502)
 200 steps: distance to 1,000 steps 0.009, spread 0.469 (eta = 1: 0.452, ancestral: 0.480)
1000 steps: distance to 1,000 steps 0.000, spread 0.474 (eta = 1: 0.475, ancestral: 0.479)

samples = {n: d2l.ddim_sample(pred_exact, z, vp, n)
           for n in (5, 10, 20, 50, 200, 1000)}
spread = lambda pts: f'{mix.summary(pts)["spread"]:.3f}'
for n, x in samples.items():
    gap = jnp.linalg.norm(x - samples[1000], axis=1).mean()
    k1, k2 = jax.random.split(jax.random.fold_in(k_eta, n))
    eta1 = d2l.ddim_sample(pred_exact, z, vp, n, 1.0, k1)
    chain = d2l.ancestral_sample(pred_exact, z, vp, n, k2)
    print(f'{n:4d} steps: distance to 1,000 steps {gap:.3f}, spread '
          f'{spread(x)} (eta = 1: {spread(eta1)}, ancestral: {spread(chain)})')
d2l.scatter_panels([samples[10][:2000], samples[200][:2000]],
                   ['10 steps', '200 steps'], data=data[:2000]);
   5 steps: distance to 1,000 steps 0.412, spread 0.312 (eta = 1: 0.329, ancestral: 0.386)
  10 steps: distance to 1,000 steps 0.212, spread 0.383 (eta = 1: 0.318, ancestral: 0.523)
  20 steps: distance to 1,000 steps 0.109, spread 0.421 (eta = 1: 0.338, ancestral: 0.519)
  50 steps: distance to 1,000 steps 0.043, spread 0.456 (eta = 1: 0.395, ancestral: 0.498)
 200 steps: distance to 1,000 steps 0.009, spread 0.474 (eta = 1: 0.452, ancestral: 0.481)
1000 steps: distance to 1,000 steps 0.000, spread 0.478 (eta = 1: 0.475, ancestral: 0.474)

正如预测,步数每翻一倍,距离就减半:在模式间距约 5 个单位的尺度上,5 步时约 0.4,10 步时 0.2,50 步时 0.04。误差还带有方向性:10 步时确定性样本的散布度约 0.38(真实数据为 0.47 至 0.48),左图中的点云肉眼可见地比背景真实数据更紧凑。单步在跨度内将噪声估计固定为起点值,这对高斯数据总是过度去噪(练习 2);而一旦噪声小到足以分辨各模式,混合分布的每个模式都表现得像每坐标方差 \(0.25\) 的高斯数据。

随机采样器则在两个方向上偏离。在 10 步时,\(\eta = 1\) 将模式进一步收窄至散布度约 0.32,而祖先链则将其撑宽至约 0.52(超过真实数据)。初看令人意外:加入噪声的 \(\eta = 1\) 反而比不加噪声的 \(\eta = 0\) 更窄。家族中每个成员都将相同的总方差预算 \(\sigma_s^2\) 分配给保留噪声与新鲜噪声。对高斯数据,干净估计与噪声估计均为 \(\mathbf{x}_t\) 的正倍数,因此保留噪声与干净估计同向对齐,通过交叉项增大散布;新鲜噪声与两者独立,只贡献自身方差。在粗网格上像 \(\eta = 1\) 那样把预算从保留噪声挪给新鲜噪声,反而会收窄样本(练习 2 给出了证明)。祖先链保留的噪声与 \(\eta = 1\) 相同,却加入了超出预算的新鲜噪声,多出的方差适合与噪声等宽的数据,而非比噪声窄的模式。在细网格上,三种采样器均收敛至真实数据的散布度。能朝两个方向偏离的统计量无法按大小给采样器排序,因此在图像上我们采用对双向误差均有惩罚的分数。

17.5.2.2 二阶方法与步长网格

Euler 法在一步之内保持斜率恒定,因此全程误差仅与步长成正比。Heun 法(38.2 节)先以 Euler 步作为试探步,在试探点再次求斜率,再用首尾两斜率的平均值推进:

\[ \begin{aligned} \bar{\mathbf{x}}' &= \bar{\mathbf{x}}_t + (\bar\sigma_s - \bar\sigma_t)\, \hat{\boldsymbol\epsilon}(\bar{\mathbf{x}}_t, \bar\sigma_t), \\ \bar{\mathbf{x}}_s &= \bar{\mathbf{x}}_t + (\bar\sigma_s - \bar\sigma_t)\, \frac{\hat{\boldsymbol\epsilon}(\bar{\mathbf{x}}_t, \bar\sigma_t) + \hat{\boldsymbol\epsilon}(\bar{\mathbf{x}}', \bar\sigma_s)}{2}. \end{aligned} \]

其误差随步长平方下降,代价是每步两次求值。对标准高斯数据,噪声估计为 \(\hat{\boldsymbol\epsilon} = \bar\sigma \bar{\mathbf{x}} / (1 + \bar\sigma^2)\),精确概率流将 \(\bar{\mathbf{x}}\) 乘以 \(\sqrt{(1 + \bar\sigma_s^2) / (1 + \bar\sigma_t^2)}\)。从 \(\bar\sigma_t = 1\) 到 \(\bar\sigma_s = 0.5\),精确因子为 \(0.791\),Euler 步给出 \(0.75\),Heun 步给出 \(0.80\)——误差分别为 \(0.041\) 与 \(0.009\),两倍求值换来约四分之一的误差。有两个特殊步骤无法求第二斜率:在 \(\bar\sigma = 0\) 处已无噪声可估,而从 \(\bar\sigma = \infty\) 出发的步长无限长、只能写成 \(\hat{\mathbf{x}}_0 + \bar\sigma_s \hat{\boldsymbol\epsilon}\) 的形式。因此到达 \(\bar\sigma = 0\) 的最后一步与从 \(\bar\sigma = \infty\) 出发的第一步均采用 Euler 步,heun_sample 在 \(n\) 步上花费 \(2n - 1\) 次求值(在线性路径纯噪声起点下为 \(2n - 2\) 次)。

第二次求值是否划算取决于步长排布。在带精确场的一维混合分布上,均匀网格的 Heun 法在约四十次求值以下输给 Euler 法;但在向数据端加密的网格上它在所有预算下都胜出,而同样的加密却令 Euler 法的误差翻倍以上(38.7.4 节)。Karras 等 (2022年) 将早期采样器捆绑在一起的两个选择——方法阶数与步长排布——解耦开来,并通过令 \(\bar\sigma^{1/\rho}\) 均匀分布来向数据端加密步长:

\[\bar\sigma_i = \Big(\bar\sigma_{\max}^{1/\rho} + \tfrac{i}{n - 1}\big(\bar\sigma_{\min}^{1/\rho} - \bar\sigma_{\max}^{1/\rho}\big)\Big)^{\rho}, \qquad i = 0, \ldots, n - 1, \tag{17.5.7}\]

随后再走最后一步抵达 \(\bar\sigma = 0\);对 \([-1, 1]\) 中的图像,取 \(\bar\sigma_{\max} = 80\)、\(\bar\sigma_{\min} = 0.002\) 与 \(\rho = 7\)。网格是采样器自身的选择,独立于训练路径,因为 make_pred 会把任意噪声水平换算到网络自身的时间。edm_grid 返回这些水平,heun_sample 可沿任意水平列表运行 Heun 步。下面我们打印三种选择的十步网格:保方差路径的时间均匀网格、线性路径的时间均匀网格,以及 Karras 等人的网格——按其论文 Elucidating the Design Space of Diffusion-Based Generative Models 称为 EDM 网格。

def edm_grid(steps, sigma_max=80.0, sigma_min=0.002, rho=7):
    """Karras et al.'s levels sigma_bar: even in sigma_bar^(1/rho), then 0."""
    hi, lo = sigma_max ** (1 / rho), sigma_min ** (1 / rho)
    return [(hi + i / (steps - 1) * (lo - hi)) ** rho
            for i in range(steps)] + [0.0]

@torch.no_grad()
def heun_sample(pred, x, sigma_bars):
    """Heun on d x_bar / d sigma_bar = eps: an Euler trial, then the average
    of the two slopes; from x at the first level to data, as ode_sample."""
    r0 = sigma_bars[0]
    xb = x if math.isinf(r0) else x * math.sqrt(1 + r0 ** 2)  # x / alpha
    for r_t, r_s in zip(sigma_bars[:-1], sigma_bars[1:]):
        x0, eps = d2l.pred_bar(pred, xb, r_t)
        x_next = x0 + r_s * eps                       # the Euler step
        if r_s > 0 and not math.isinf(r_t):           # no slope at 0 or inf
            x_next = xb + (r_s - r_t) * (
                eps + d2l.pred_bar(pred, x_next, r_s)[1]) / 2
        xb = x_next
    return xb

for name, levels in (('VP', vp.sigma_bars(10)), ('linear', lin.sigma_bars(10)),
                     ('EDM', d2l.edm_grid(10))):
    print(f'{name:7s}', ' '.join(f'{r:7.3g}' for r in levels))
VP          152    58.8    25.1    11.8     6.1    3.41    2.03    1.23    0.72    0.34       0
linear      inf       9       4    2.33     1.5       1   0.667   0.429    0.25   0.111       0
EDM          80    42.4    21.1    9.72    4.07     1.5    0.47   0.117  0.0204   0.002       0
def edm_grid(steps, sigma_max=80.0, sigma_min=0.002, rho=7):
    """Karras et al.'s levels sigma_bar: even in sigma_bar^(1/rho), then 0."""
    hi, lo = sigma_max ** (1 / rho), sigma_min ** (1 / rho)
    return [(hi + i / (steps - 1) * (lo - hi)) ** rho
            for i in range(steps)] + [0.0]

def heun_sample(pred, x, sigma_bars):
    """Heun on d x_bar / d sigma_bar = eps: an Euler trial, then the average
    of the two slopes; from x at the first level to data, as ode_sample."""
    with jax.ensure_compile_time_eval():          # the grid is a constant
        r = jnp.asarray(sigma_bars)
        from_inf = bool(jnp.isinf(r[0]))
    def step(xb, r):
        r_t, r_s = r
        x0, eps = d2l.pred_bar(pred, xb, r_t)
        x_next = x0 + r_s * eps                   # the Euler step
        correct = lambda _: xb + (r_s - r_t) * (
            eps + d2l.pred_bar(pred, x_next, r_s)[1]) / 2
        heun = jnp.isfinite(r_t) & (r_s > 0)      # no slope at inf or 0
        return jax.lax.cond(heun, correct, lambda _: x_next, None), None
    xb = x if from_inf else x * jnp.sqrt(1 + r[0] ** 2)  # x / alpha
    return jax.lax.scan(step, xb, (r[:-1], r[1:]))[0]

for name, levels in (('VP', vp.sigma_bars(10)), ('linear', lin.sigma_bars(10)),
                     ('EDM', d2l.edm_grid(10))):
    print(f'{name:7s}', ' '.join(f'{float(r):7.3g}' for r in levels))
VP          152    58.8    25.1    11.8     6.1    3.41    2.03    1.23    0.72    0.34       0
linear      inf       9       4    2.33     1.5       1   0.667   0.429    0.25   0.111       0
EDM          80    42.4    21.1    9.72    4.07     1.5    0.47   0.117  0.0204   0.002       0

按时间均匀的网格在 \(\bar\sigma\) 上截然不同。保方差网格把十步中的四步花在 \(152\) 到 \(6.1\) 之间,最后从 \(0.34\) 一步抵达数据;线性网格从无穷大一步跨越 \(9\) 以上的所有区间,并在 \(4\) 到 \(0.11\) 之间安排了七步;EDM 网格从 \(80\) 起步,同样在 \(4\) 以上花掉四步,并把最后三级密布在 \(0.12\) 以下。哪种分配最适合某个模型无法单凭水平表看出,下文将在图像上实测。

17.5.2.3 指数积分器与多步求解器

Heun 法为达到二阶精度每步需要两次求值。一条更省算力的路线正是我们一直在走的坐标系。在 \(\mathbf{x}\) 坐标中,概率流 ODE 包含一项关于 \(\mathbf{x}\) 线性、与网络无关的部分:例如在保方差路径上,无论分数为何,漂移项都会以速率 \(\tfrac12\beta(t)\)(\(\beta(t)\) 为噪声调度速率)收缩 \(\mathbf{x}\)。该线性部分的精确解是指数衰减(此处即因子 \(\alpha_t\)),除以 \(\alpha_t\) 便将其消去;剩下的 \(d\bar{\mathbf{x}} / d\bar\sigma = \hat{\boldsymbol\epsilon}\) 只包含网络。精确积分线性部分、仅近似网络项,这正是指数积分器的核心思想 (Zhang 和 Chen 2023年; Lu 等 2022年)。在步内保持 \(\hat{\boldsymbol\epsilon}\) 恒定的 DDIM 是它的一阶成员,因此让 DDIM 看起来像 Euler 法的坐标变换本身就是这类求解器的精髓。高阶成员的区别仅在于如何让 \(\hat{\boldsymbol\epsilon}\) 在步内变化:DPM-Solver (Lu 等 2022年) 在 \(\log \bar\sigma\) 的步中点处做第二次求值(练习 3)。

这第二次求值其实可以省去。上一步已经在刚离开的噪声水平处算过 \(\hat{\boldsymbol\epsilon}\),多步方法直接复用它:由最近两次估计将 \(\hat{\boldsymbol\epsilon}\) 线性外推至当前步的中点。记当前步长为 \(\Delta = \bar\sigma_s - \bar\sigma_t\)、上一步长为 \(\Delta'\),起点估计分别为 \(\hat{\boldsymbol\epsilon}_t\) 与 \(\hat{\boldsymbol\epsilon}'\),则二阶 Adams–Bashforth 步写作

\[\bar{\mathbf{x}}_s = \bar{\mathbf{x}}_t + \Delta \Big(\hat{\boldsymbol\epsilon}_t + \frac{\Delta}{2\Delta'}\big(\hat{\boldsymbol\epsilon}_t - \hat{\boldsymbol\epsilon}'\big)\Big). \tag{17.5.8}\]

当噪声估计在相邻两步间不变时,该式退化为 DDIM;否则校正项以每步单次求值的开销追踪其变化。第一步没有前序估计,因此采用 Euler 步;从 \(\bar\sigma = \infty\) 出发后的下一步因 \(\Delta'\) 无穷大同样采用 Euler 步。DPM-Solver++(2M) (Lu 等 2025年) 将同一思想用于干净图像估计并在 \(\log \bar\sigma\) 中外推,它及其近亲是十至二十五次求值预算下的常规首选。multistep_sample 沿任意水平列表执行上述步骤。

@torch.no_grad()
def multistep_sample(pred, x, sigma_bars):
    """Second-order Adams-Bashforth on d x_bar / d sigma_bar = eps: one
    evaluation per step, the slope extrapolated from the last two."""
    r = sigma_bars
    xb = x if math.isinf(r[0]) else x * math.sqrt(1 + r[0] ** 2)  # x / alpha
    eps_prev = 0
    for k in range(len(r) - 1):
        x0, eps = d2l.pred_bar(pred, xb, r[k])
        c = ((r[k + 1] - r[k]) ** 2 / (2 * (r[k] - r[k - 1]))
             if k > 0 and math.isfinite(r[k - 1]) else 0.0)  # 0: Euler
        xb = x0 + r[k + 1] * eps + c * (eps - eps_prev)
        eps_prev = eps
    return xb
def multistep_sample(pred, x, sigma_bars):
    """Second-order Adams-Bashforth on d x_bar / d sigma_bar = eps: one
    evaluation per step, the slope extrapolated from the last two."""
    with jax.ensure_compile_time_eval():          # the grid is a constant
        r = [float(v) for v in sigma_bars]
    c = [0.0] + [(r[k + 1] - r[k]) ** 2 / (2 * (r[k] - r[k - 1]))
                 if math.isfinite(r[k - 1]) else 0.0     # 0: Euler
                 for k in range(1, len(r) - 1)]
    def step(carry, inputs):
        xb, eps_prev = carry
        r_t, r_s, c = inputs
        x0, eps = d2l.pred_bar(pred, xb, r_t)
        return (x0 + r_s * eps + c * (eps - eps_prev), eps), None
    xb = x if math.isinf(r[0]) else x * math.sqrt(1 + r[0] ** 2)  # x / alpha
    return jax.lax.scan(step, (xb, jnp.zeros_like(xb)),
                        (jnp.array(r[:-1]), jnp.array(r[1:]),
                         jnp.array(c)))[0][0]

17.5.2.4 图像上质量与求值次数的权衡

在图像上,向量场是学习得到的。我们用线性路径的速度目标训练 17.4 节 的类别条件 U-Net(约 120 万参数)共一万次更新,在单张 GPU 上只需几分钟。十分之一的标签替换为空标签,采样使用权重的滑动平均。本节其余实验共用这一网络。无引导采样器(下文 \(\gamma = 1\))以均等频率请求每个类别(第 \(i\) 个样本请求类别 \(i\) mod 10),带引导采样器(\(\gamma > 1\))同时评估空标签,反演与编辑则各自使用图像真实标签。

X, y, X_test, y_test = d2l.load_fashion_mnist_pm1()
loss = d2l.regression_loss(lin, 'velocity')

def batch_fn():
    i = torch.randint(0, len(X), (128,), device=X.device)
    drop = torch.rand(128, device=X.device) < 0.1   # label dropout
    return X[i], torch.where(drop, 10, y[i])        # 10 is the null label

def loss_fn(net, batch):  # the regression loss of the labeled field
    x0, c = batch
    return loss(d2l.conditional(net, c), x0)

torch.manual_seed(0)
net = d2l.UNet(ch=64, num_classes=10).to(X.device)
net, ema, _ = d2l.train_regression(net, loss_fn, batch_fn, 10_000)
X, y, X_test, y_test = d2l.load_fashion_mnist_pm1()
loss = d2l.regression_loss(lin, 'velocity')

def batch_fn(key):
    k1, k2 = jax.random.split(key)
    i = jax.random.randint(k1, (128,), 0, len(X))
    drop = jax.random.uniform(k2, (128,)) < 0.1     # label dropout
    return X[i], jnp.where(drop, 10, y[i])          # 10 is the null label

def loss_fn(net, batch, key):  # the regression loss of the labeled field
    x0, c = batch
    return loss(d2l.conditional(net, c), x0, key)

net = d2l.UNet(ch=64, num_classes=10, rngs=nnx.Rngs(0))
net, ema, _ = d2l.train_regression(net, loss_fn, batch_fn, 10_000,
                                   jax.random.key(0))

我们在 d2l.FeatureCNN 特征空间中用 1,000 张样本相对 1,000 张测试图像的 Fréchet 距离(FD)打分(17.4 节)。在此样本量下,两组真实图像互相比对已得分略低于 1,且每次重新抽样波动 0.15 至 0.2(17.4.3.2 节)。因此每项测量均在三组 1,000 张噪声图像上重复(所有采样器共享同一批噪声以实现配对比较),并报告均值加减半极差;下限行将测试图像与另三组真实图像对比。落在半极差以内的差异不视为显著差异。fd_runs 还接受引导尺度 \(\gamma\)(下一小节使用,\(\gamma = 1\) 表示普通条件场)。

cnn = d2l.fashion_feature_cnn(X, y)
features = lambda imgs: d2l.fd_features(cnn, imgs)
f_test = features(X_test[:1000])
floors = [d2l.fid_score(features(X_test[k:k + 1000]), f_test)
          for k in (1000, 2000, 3000)]
labels = torch.arange(1000, device=X.device) % 10   # sample i has class i % 10
gen = torch.Generator(X.device).manual_seed(1)
noises = [torch.randn(1000, 1, 28, 28, device=X.device, generator=gen)
          for _ in range(3)]                        # shared by every sampler

def fd_runs(sampler, n, gamma=1.0):
    """FD of sampler(pred, noise, n) on each noise draw, field cfg(gamma)."""
    pred = d2l.make_pred(d2l.cfg(ema, labels, gamma), lin, 'velocity')
    return [d2l.fid_score(features(sampler(pred, z, n).clamp(-1, 1)), f_test)
            for z in noises]

def mean_range(fds):  # the mean, plus or minus half the range of the draws
    return f'{np.mean(fds):5.2f}±{(max(fds) - min(fds)) / 2:.2f}'

print('floor, 1,000 real images against 1,000 others: FD', mean_range(floors))
floor, 1,000 real images against 1,000 others: FD  0.86±0.15
cnn = d2l.fashion_feature_cnn(X, y)
features = lambda imgs: d2l.fd_features(cnn, imgs)
f_test = features(X_test[:1000])
floors = [d2l.fid_score(features(X_test[k:k + 1000]), f_test)
          for k in (1000, 2000, 3000)]
labels = jnp.arange(1000) % 10                      # sample i has class i % 10
k_noise, k_run = jax.random.split(jax.random.key(1))
noises = [jax.random.normal(k, (1000, 28, 28, 1))   # shared by every sampler
          for k in jax.random.split(k_noise, 3)]
run_keys = iter(jax.random.split(k_run, 1000))      # fresh noise of the samplers

@nnx.jit(static_argnums=(0, 1, 2))  # one trace per sampler, step count, gamma
def sample(sampler, n, gamma, model, c, z, key):
    pred = d2l.make_pred(d2l.cfg(model, c, gamma), lin, 'velocity')
    return sampler(pred, z, n, key).clip(-1, 1)

def fd_runs(sampler, n, gamma=1.0):
    """FD of sampler(pred, noise, n, key) on each noise draw, field cfg(gamma)."""
    keys = jax.random.split(next(run_keys), len(noises))
    return [d2l.fid_score(features(sample(sampler, n, gamma, ema, labels, z, k)),
                          f_test) for z, k in zip(noises, keys)]

def mean_range(fds):  # the mean, plus or minus half the range of the draws
    return f'{np.mean(fds):5.2f}±{(max(fds) - min(fds)) / 2:.2f}'

print('floor, 1,000 real images against 1,000 others: FD', mean_range(floors))
floor, 1,000 real images against 1,000 others: FD  0.88±0.20

参考下限约 0.9。第一张表在时间均匀的保方差路径上回答了前文遗留的问题,此时 \(\eta = 0\) 的 DDIM 即上方打印的第一张网格上的 Euler 法。若新鲜噪声真能纠正确定性采样器一路累积的误差,随着步长缩短,\(\eta = 1\) 与祖先链应逐步追近并在千步之前反超 \(\eta = 0\)。

vp_samplers = {  # the DDIM family and the ancestral chain, even steps on VP
    'DDIM, eta = 0': lambda p, z, n: d2l.ddim_sample(p, z, vp, n),
    'DDIM, eta = 1': lambda p, z, n: d2l.ddim_sample(p, z, vp, n, eta=1.0),
    'ancestral': lambda p, z, n: d2l.ancestral_sample(p, z, vp, n)}
steps = (10, 20, 50, 100, 200, 1000)
torch.manual_seed(2)  # the fresh noise of the stochastic samplers
fd_vp = {name: [fd_runs(f, n) for n in steps]
         for name, f in vp_samplers.items()}
print('steps        ', ''.join(f'{n:>11d}' for n in steps))
for name, row in fd_vp.items():
    print(f'{name:13s}', ''.join(f'{mean_range(v):>11s}' for v in row))
steps                  10         20         50        100        200       1000
DDIM, eta = 0   5.41±0.32  2.95±0.19  1.76±0.12  1.45±0.11  1.33±0.10  1.32±0.10
DDIM, eta = 1   7.81±0.23  4.90±0.16  3.06±0.09  2.32±0.06  1.98±0.08  1.52±0.05
ancestral      28.66±0.26 19.22±0.63  7.85±0.10  3.45±0.14  1.78±0.13  1.34±0.03
vp_samplers = {  # the DDIM family and the ancestral chain, even steps on VP
    'DDIM, eta = 0': lambda p, z, n, k: d2l.ddim_sample(p, z, vp, n),
    'DDIM, eta = 1': lambda p, z, n, k: d2l.ddim_sample(p, z, vp, n, 1.0, k),
    'ancestral': lambda p, z, n, k: d2l.ancestral_sample(p, z, vp, n, k)}
steps = (10, 20, 50, 100, 200, 1000)
fd_vp = {name: [fd_runs(f, n) for n in steps]
         for name, f in vp_samplers.items()}
print('steps        ', ''.join(f'{n:>11d}' for n in steps))
for name, row in fd_vp.items():
    print(f'{name:13s}', ''.join(f'{mean_range(v):>11s}' for v in row))
steps                  10         20         50        100        200       1000
DDIM, eta = 0   5.46±0.14  2.93±0.11  1.68±0.08  1.36±0.07  1.26±0.07  1.26±0.08
DDIM, eta = 1   8.06±0.02  4.89±0.15  3.17±0.16  2.29±0.10  1.86±0.06  1.39±0.04
ancestral      30.31±0.27 21.53±0.57 10.64±0.43  5.26±0.28  2.42±0.13  1.30±0.04

它们确实追近了,但从未反超。直至两百步,\(\eta = 0\) 在每个预算上的得分都比 \(\eta = 1\) 低三分之一到近一半,远远超出半极差;到千步时三者落入彼此约 0.2 以内,介于约 1.3 与 1.5 之间。在这个模型上,新鲜噪声从未奏效:没有任何预算下随机采样器能以超出半极差的优势击败 \(\eta = 0\),到千步时祖先链也只是打平。直至一百步,祖先链输得最惨——五十步时得分约 8 至 11,还不如十步 DDIM(略高于 5)。它的前向步方差适合与噪声等宽的数据,而服饰在低噪声下已几乎定型,多余方差化作噪点;下一小节末尾的图像行清晰呈现了这一现象。DDIM 自身在百步之后仅变动约十分之一,五十步时便以二十分之一的求值次数落到千步链的约三分之一差距内——这正是 J. Song 等 (2021年) 的核心发现。

关于新鲜噪声的这一结论只适用于当前模型,不应外推到大型模型。在 \(64 \times 64\) ImageNet 上,Karras 等 (2022年) 发现在每步 Heun 之前注入经过调节的少量噪声优于确定性采样器;Y. Song 等 (2021年) 的预测–校正采样器在求解器步间插入 Langevin 步以达同一目的;Restart 采样 (Xu 等 2023年) 则在大预算下获益最多。背后机制仍是前文所述的 Langevin 拉回效应:处理复杂数据的大型模型会产生可被后续噪声修正的误差,在步数充足时,校正收益压过新增噪声带来的方差。

第二张表按网络求值次数而非步数统计,因为求值次数才决定生成开销。它在三条网格(线性网格、\(\rho = 7\) 的 Karras 等人 EDM 网格,以及把步长从数据端移向高噪声端的 \(\rho = 3\) EDM 网格)上以约 10 至 100 次求值运行 Euler 法、Heun 法与多步采样器。Heun 法步数约为一半,且在有限起点水平的 EDM 网格上比预算少一次求值。

grids = {'linear': lin.sigma_bars, 'EDM': d2l.edm_grid,
         'EDM, rho = 3': lambda n: d2l.edm_grid(n, rho=3)}
solvers = {'Euler': d2l.ode_sample, 'Heun': d2l.heun_sample,
           'multistep': multistep_sample}
budgets = (10, 20, 50, 100)  # network evaluations per sample

def on_grid(solver, grid):  # a sampler (pred, noise, steps)
    return lambda p, z, n: solver(p, z, grid(n))

def num_steps(s, g, b):  # Heun skips its second slope only at sigma = inf, 0:
    # b // 2 + 1 steps on the linear grid (b evaluations, the first level is
    # infinite), b // 2 on the EDM grids (b - 1)
    return (b // 2 + (g == 'linear')) if s == 'Heun' else b

fd_ode = {(s, g): [fd_runs(on_grid(solver, grid), num_steps(s, g, b))
                   for b in budgets]
          for s, solver in solvers.items() for g, grid in grids.items()}
print('evaluations            ', ''.join(f'{b:>11d}' for b in budgets))
for (s, g), row in fd_ode.items():
    print(f'{s + ", " + g:23s}', ''.join(f'{mean_range(v):>11s}' for v in row))
evaluations                      10         20         50        100
Euler, linear             3.33±0.25  1.99±0.15  1.46±0.11  1.36±0.10
Euler, EDM                6.81±0.38  3.14±0.22  1.86±0.15  1.58±0.14
Euler, EDM, rho = 3       9.74±0.47  4.02±0.25  2.02±0.16  1.62±0.14
Heun, linear              1.60±0.12  1.27±0.07  1.20±0.08  1.25±0.09
Heun, EDM                11.71±0.29  1.69±0.08  1.32±0.10  1.37±0.11
Heun, EDM, rho = 3       84.52±0.45  8.10±0.26  1.47±0.11  1.39±0.11
multistep, linear         2.12±0.17  1.42±0.11  1.29±0.10  1.30±0.10
multistep, EDM            4.50±0.28  1.96±0.16  1.46±0.12  1.41±0.12
multistep, EDM, rho = 3   6.56±0.35  2.37±0.17  1.46±0.12  1.39±0.12
grids = {'linear': lin.sigma_bars, 'EDM': d2l.edm_grid,
         'EDM, rho = 3': lambda n: d2l.edm_grid(n, rho=3)}
solvers = {'Euler': d2l.ode_sample, 'Heun': d2l.heun_sample,
           'multistep': multistep_sample}
budgets = (10, 20, 50, 100)  # network evaluations per sample

def on_grid(solver, grid):  # a sampler (pred, noise, steps, key)
    return lambda p, z, n, k: solver(p, z, grid(n))

def num_steps(s, g, b):  # Heun skips its second slope only at sigma = inf, 0:
    # b // 2 + 1 steps on the linear grid (b evaluations, the first level is
    # infinite), b // 2 on the EDM grids (b - 1)
    return (b // 2 + (g == 'linear')) if s == 'Heun' else b

fd_ode = {(s, g): [fd_runs(on_grid(solver, grid), num_steps(s, g, b))
                   for b in budgets]
          for s, solver in solvers.items() for g, grid in grids.items()}
print('evaluations            ', ''.join(f'{b:>11d}' for b in budgets))
for (s, g), row in fd_ode.items():
    print(f'{s + ", " + g:23s}', ''.join(f'{mean_range(v):>11s}' for v in row))
evaluations                      10         20         50        100
Euler, linear             3.15±0.09  1.86±0.09  1.36±0.08  1.29±0.07
Euler, EDM                6.45±0.18  2.98±0.13  1.76±0.10  1.52±0.10
Euler, EDM, rho = 3       9.55±0.25  3.84±0.14  1.91±0.10  1.54±0.09
Heun, linear              1.55±0.04  1.22±0.03  1.14±0.05  1.19±0.06
Heun, EDM                14.47±0.12  1.81±0.03  1.30±0.08  1.34±0.08
Heun, EDM, rho = 3       86.59±0.46 10.59±0.26  1.51±0.09  1.37±0.09
multistep, linear         1.97±0.07  1.32±0.06  1.22±0.07  1.25±0.07
multistep, EDM            4.23±0.15  1.87±0.10  1.41±0.09  1.37±0.09
multistep, EDM, rho = 3   6.46±0.20  2.26±0.10  1.38±0.08  1.35±0.08

两张表如何衔接?下方曲线将第一张表的采样器与线性网格上的三种求解器画在同一条网络求值次数横轴上。

curves = {**{name: (steps, row) for name, row in fd_vp.items()},
          **{f'{s}, linear': (budgets, fd_ode[s, 'linear']) for s in solvers}}
d2l.plot([x for x, _ in curves.values()] + [[10, 1000]],
         [[np.mean(v) for v in row] for _, row in curves.values()]
         + [[np.mean(floors)] * 2], 'network evaluations', 'FD',
         legend=list(curves) + ['floor'], xscale='log', yscale='log',
         figsize=(6, 4), fmts=('o-', 's-', '^-', 'v--', 'D--', 'x-.', 'k:'))

curves = {**{name: (steps, row) for name, row in fd_vp.items()},
          **{f'{s}, linear': (budgets, fd_ode[s, 'linear']) for s in solvers}}
d2l.plot([x for x, _ in curves.values()] + [[10, 1000]],
         [[np.mean(v) for v in row] for _, row in curves.values()]
         + [[np.mean(floors)] * 2], 'network evaluations', 'FD',
         legend=list(curves) + ['floor'], xscale='log', yscale='log',
         figsize=(6, 4), fmts=('o-', 's-', '^-', 'v--', 'D--', 'x-.', 'k:'))

二阶方法率先抵达模型的渐近 FD 平台(\(\approx 1.1\)–\(1.3\),高出有限样本下限约 \(0.3\)):线性网格上的 Heun 法仅用 20 次函数求值即达 \(\approx 1.2\)–\(1.3\),二阶多步求解器到 50 次抵达,而 Euler 法需要 50 至 100 次。

步长排布与求解器阶数同等重要。在 10 次求值处,Euler 法在线性网格得分 \(\approx 3.2\)、在 VP 网格 \(\approx 5\)、在 EDM(\(\rho = 7\))网格 \(\approx 6.5\);Heun 法在线性网格得分 \(\approx 1.6\),在 EDM 网格却高达 \(12\)–\(15\)。将 \(\rho\) 降至 \(3\)(把步长从数据端移向高噪声端)进一步恶化了 10 次与 20 次求值的表现。在 \(\bar\sigma \approx 4\) 以上(像素标准差 \(\approx 0.7\) 的数倍),加噪图像近乎纯高斯噪声且轨迹几乎笔直;线性网格两步跨过 \(\bar\sigma > 4\)(\(\infty \to 9 \to 4\)),而十步 EDM 网格在那里耗费了四步,留给服饰结构成型的中间区间的步数过少。

17.5.2.5 积分误差、引导与采样器选择

至此仅凭 FD 评判采样器,而 FD 评估的是样本集合的分布,并不反映单个样本距同一噪声图像精确积分终点的距离。为看清 FD 之外求解器损失了什么,我们用 200 次求值的 Heun 法积分每张噪声图像作为参照,并度量各求解器相对它的逐像素均方根距离。

我们在两个向量场上重复这一测量,因为引导改变了被积分的场。无分类器引导(17.4.4.2 节)从无标签预测向有标签预测外推,\(\tilde{\mathbf{u}} = \mathbf{u}_\varnothing + \gamma(\mathbf{u}_c - \mathbf{u}_\varnothing)\),其中 \(\gamma = 1\) 即条件场,且每次引导求值消耗两次网络前向传播。越过两项基准外推的场沿轨迹理应变化更剧烈,因此我们预期在 \(\gamma = 2\) 下每个求解器都需要更多求值才能跟上。

def endpoints(solver, n, gamma):
    """Samples of a solver with n steps on the linear grid, per noise draw."""
    pred = d2l.make_pred(d2l.cfg(ema, labels, gamma), lin, 'velocity')
    return [solver(pred, z, lin.sigma_bars(n)).clamp(-1, 1) for z in noises]

for gamma in (1.0, 2.0):
    refs = endpoints(d2l.heun_sample, 101, gamma)    # 200 evaluations
    fds = [d2l.fid_score(features(x), f_test) for x in refs]
    print(f'gamma = {gamma:.0f}, reference: FD {mean_range(fds)}; '
          'FD and RMS distance to it')
    print('evaluations', ''.join(f'{b:>18d}' for b in (10, 20, 50)))
    for s, solver in solvers.items():
        cols = []
        for b in (10, 20, 50):
            xs = endpoints(solver, b // 2 + 1 if s == 'Heun' else b, gamma)
            fds = [d2l.fid_score(features(x), f_test) for x in xs]
            rms = np.mean([((x - r) ** 2).mean().sqrt().item()
                           for x, r in zip(xs, refs)])
            cols.append(f'  {mean_range(fds)} {rms:.3f}')
        print(f'  {s:9s}', ''.join(cols))
gamma = 1, reference: FD  1.29±0.09; FD and RMS distance to it
evaluations                 10                20                50
  Euler        3.33±0.25 0.108   1.99±0.15 0.063   1.46±0.11 0.030
  Heun         1.60±0.12 0.127   1.27±0.07 0.044   1.20±0.08 0.014
  multistep    2.12±0.17 0.094   1.42±0.11 0.044   1.29±0.10 0.015
gamma = 2, reference: FD  2.29±0.11; FD and RMS distance to it
evaluations                 10                20                50
  Euler        3.88±0.14 0.109   3.07±0.11 0.066   2.57±0.10 0.035
  Heun         3.51±0.15 0.142   2.77±0.10 0.066   2.43±0.10 0.021
  multistep    3.31±0.12 0.099   2.71±0.10 0.051   2.38±0.10 0.021
def endpoints(solver, n, gamma):
    """Samples of a solver with n steps on the linear grid, per noise draw."""
    keys = jax.random.split(next(run_keys), len(noises))  # unused: no noise
    return [sample(on_grid(solver, lin.sigma_bars), n, gamma, ema, labels,
                   z, k) for z, k in zip(noises, keys)]

for gamma in (1.0, 2.0):
    refs = endpoints(d2l.heun_sample, 101, gamma)    # 200 evaluations
    fds = [d2l.fid_score(features(x), f_test) for x in refs]
    print(f'gamma = {gamma:.0f}, reference: FD {mean_range(fds)}; '
          'FD and RMS distance to it')
    print('evaluations', ''.join(f'{b:>18d}' for b in (10, 20, 50)))
    for s, solver in solvers.items():
        cols = []
        for b in (10, 20, 50):
            xs = endpoints(solver, b // 2 + 1 if s == 'Heun' else b, gamma)
            fds = [d2l.fid_score(features(x), f_test) for x in xs]
            rms = np.mean([float(jnp.sqrt(((x - r) ** 2).mean()))
                           for x, r in zip(xs, refs)])
            cols.append(f'  {mean_range(fds)} {rms:.3f}')
        print(f'  {s:9s}', ''.join(cols))
gamma = 1, reference: FD  1.24±0.07; FD and RMS distance to it
evaluations                 10                20                50
  Euler        3.15±0.09 0.103   1.86±0.09 0.062   1.36±0.08 0.030
  Heun         1.55±0.04 0.117   1.22±0.03 0.037   1.14±0.05 0.013
  multistep    1.97±0.07 0.088   1.32±0.06 0.043   1.22±0.07 0.013
gamma = 2, reference: FD  2.12±0.12; FD and RMS distance to it
evaluations                 10                20                50
  Euler        4.01±0.17 0.099   3.09±0.17 0.059   2.47±0.14 0.028
  Heun         3.44±0.18 0.125   2.67±0.15 0.048   2.31±0.14 0.017
  multistep    3.32±0.17 0.086   2.64±0.16 0.042   2.23±0.13 0.014

两项指标给出不同排序,而这一分歧揭示了 FD 的特性。在无引导的十次求值处,Heun 样本距参照比 Euler 更远(距离 0.12 至 0.13 对比约 0.1),FD 却只有 Euler 的一半(约 1.6 对比约 3.2)。FD 衡量的是样本分布而非单张误差:求解器可以为某张噪声画出另一件服饰,却依然产出逼真的样本集。

如期所示,引导使场更难追踪。在 \(\gamma = 2\) 处,参照本身得分约 2.1 至 2.3,因为引导以逼真度换取类别一致性。到二十次求值时,所有求解器仍高出参照 0.4 至 1;到五十次时,多步采样器已进入参照区间或边缘,Heun 法仍高出 0.15 至 0.2,Euler 法约高出 0.3。逐像素距离部分印证了预期:在二十次求值处,Heun 相对参照的距离比无引导时大三分之一到一半,而 Euler 与多步采样器仅变动六分之一以下,且在十次与二十次求值处多步采样器最接近参照。由此可见,在引导下只有多步采样器在五十次求值(一百次网络前向传播)内触及平台;Heun 与 Euler 需要更多次,表中尚未触底。

积分误差也肉眼可见。下方展示了四种采样器从完全相同的八张噪声图像与标签生成的八张服饰:50 步祖先链、10 步与 50 步 DDIM,以及线性网格上 20 次求值的 Heun 法。

z8 = noises[0][:8]
pred8 = d2l.make_pred(d2l.conditional(ema, labels[:8]), lin, 'velocity')
rows = [d2l.ancestral_sample(pred8, z8, vp, 50),
        d2l.ddim_sample(pred8, z8, vp, 10), d2l.ddim_sample(pred8, z8, vp, 50),
        d2l.heun_sample(pred8, z8, lin.sigma_bars(11))]
d2l.show_gray(torch.cat(rows).clamp(-1, 1), 4, 8);

z8 = noises[0][:8]
pred8 = d2l.make_pred(d2l.conditional(ema, labels[:8]), lin, 'velocity')
rows = [d2l.ancestral_sample(pred8, z8, vp, 50, next(run_keys)),
        d2l.ddim_sample(pred8, z8, vp, 10), d2l.ddim_sample(pred8, z8, vp, 50),
        d2l.heun_sample(pred8, z8, lin.sigma_bars(11))]
d2l.show_gray(jnp.concatenate(rows).clip(-1, 1), 4, 8);

三行确定性采样器逐列一一对应,因为确定性采样器都在近似同一个噪声到图像的映射;10 步抹平了 50 步与 Heun 法共同保留的印花与边缘细节。祖先链那一行则布满颗粒,背景与面料均现噪点——第一张表中的超额方差在此一览无余。

那么,面对一个尚未测量的模型,应当如何选择采样器?固定一批噪声图像与一项指标,从模型自身训练路径的网格上的确定性求解器起步,不断将求值次数翻倍,直至分数变动小于运行间波动范围。剩余差距属于模型本身,采样器能做的极致就是不再额外引入误差。在这个模型上,该流程在曲线走平处停止——Heun 法约二十次求值,且新鲜噪声毫无帮助。在引导下它停得更晚——多步采样器约五十次求值,凭借每步单次求值与最小积分误差成为更优默认项。借用论文中的网格前同样应通过这一检验。到十次求值时没有任何求解器触及平台,要在一两步内抵达平台需要另一类模型(17.8 节)。

17.5.3 反演与编辑

确定性采样器积分的是微分方程,而微分方程可以双向运行。反向运行它就能为每张图像求得一张噪声图——它的编码(code),采样器由此可复现原图。编码支持图像间插值;同一个采样器若从部分加噪图像出发或在每步施加像素约束,还能完成图像编辑与修复,全程无需重新训练。

17.5.3.1 潜在编码

ddim_invert 向上运行确定性采样器,从 \(t = 0\) 处的图像走向噪声。每一步按如下 Euler 步从水平 \(t\) 走到下一水平 \(t' > t\):

\[\bar{\mathbf{x}}_{t'} = \bar{\mathbf{x}}_t + (\bar\sigma_{t'} - \bar\sigma_t)\, \hat{\boldsymbol\epsilon}(\bar{\mathbf{x}}_t, \bar\sigma_t), \tag{17.5.9}\]

其中噪声估计在低端求值——那是编码器唯一掌握的点。第一步位于预测器无定义的 \(\bar\sigma = 0\) 处,改用下一级的噪声水平读取图像。

@torch.no_grad()
def ddim_invert(pred, x, path, steps, t_end=1.0):
    """Deterministic DDIM run backwards, from data x at t = 0 to t_end."""
    a, s = path.grid(steps, 0.0, t_end)
    for i in range(steps):
        j = max(i, 1)  # at t = 0 (sigma = 0) x is read at the next level
        eps = pred(x, a[j], s[j])[1]
        x = a[i + 1] * (x - s[i] * eps) / a[i] + s[i + 1] * eps
    return x
def ddim_invert(pred, x, path, steps, t_end=1.0):
    """Deterministic DDIM run backwards, from data x at t = 0 to t_end."""
    a, s = path.grid(steps, 0.0, t_end)
    j = np.maximum(np.arange(steps), 1)  # at t = 0 x is read at the next level
    def step(x, inputs):
        a_t, s_t, a_s, s_s, a_j, s_j = inputs
        eps = pred(x, a_j, s_j)[1]
        return a_s * (x - s_t * eps) / a_t + s_s * eps, None
    return jax.lax.scan(step, x, (a[:-1], s[:-1], a[1:], s[1:], a[j], s[j]))[0]

解码器则使用高端求值的 \(\hat{\boldsymbol\epsilon}(\bar{\mathbf{x}}_{t'}, \bar\sigma_{t'})\) 退回。两次估计相差 \(\hat{\boldsymbol\epsilon}\) 在步内的变化量,因此即便使用精确向量场,往返重建也不精确,其误差应像任何一阶误差一样随步长缩小。往返过程双向运行的是同一个场,因此无论该场是否准确,往返误差度量的都是该场上的步长误差。不过学得的场沿轨迹可能比精确场变化得更剧烈,那样往返收敛就会更慢。我们在线性路径上以 10 至 200 步对 100 张测试图像(各带真实标签)编码再解码,并用精确场让 20,000 个混合分布点经历同样往返。

x0 = X_test[:100]
pred = d2l.make_pred(d2l.conditional(ema, y_test[:100]), lin, 'velocity')
codes = {n: d2l.ddim_invert(pred, x0, lin, n) for n in (10, 20, 50, 100, 200)}
recon = {n: d2l.ddim_sample(pred, code, lin, n) for n, code in codes.items()}
for n in codes:  # the mixture's points through its exact field, for contrast
    back = d2l.ddim_sample(pred_exact, d2l.ddim_invert(pred_exact, data, lin, n),
                           lin, n)
    print(f'{n:3d} steps: squared error per pixel '
          f'{((recon[n] - x0) ** 2).mean():.4f}, code std {codes[n].std():.2f}; '
          f'mixture {((back - data) ** 2).mean():.4f}')
d2l.show_gray(torch.cat([x0[:8], recon[10][:8], recon[50][:8]]), 3, 8);
 10 steps: squared error per pixel 0.0347, code std 0.69; mixture 0.3097
 20 steps: squared error per pixel 0.0148, code std 0.76; mixture 0.0878
 50 steps: squared error per pixel 0.0039, code std 0.81; mixture 0.0192
100 steps: squared error per pixel 0.0011, code std 0.84; mixture 0.0074
200 steps: squared error per pixel 0.0002, code std 0.86; mixture 0.0023

x0 = X_test[:100]
pred = d2l.make_pred(d2l.conditional(ema, y_test[:100]), lin, 'velocity')
codes = {n: d2l.ddim_invert(pred, x0, lin, n) for n in (10, 20, 50, 100, 200)}
recon = {n: d2l.ddim_sample(pred, code, lin, n) for n, code in codes.items()}
for n in codes:  # the mixture's points through its exact field, for contrast
    back = d2l.ddim_sample(pred_exact, d2l.ddim_invert(pred_exact, data, lin, n),
                           lin, n)
    print(f'{n:3d} steps: squared error per pixel '
          f'{((recon[n] - x0) ** 2).mean():.4f}, code std {codes[n].std():.2f}; '
          f'mixture {((back - data) ** 2).mean():.4f}')
d2l.show_gray(jnp.concatenate([x0[:8], recon[10][:8], recon[50][:8]]), 3, 8);
 10 steps: squared error per pixel 0.0349, code std 0.69; mixture 0.3113
 20 steps: squared error per pixel 0.0127, code std 0.74; mixture 0.0960
 50 steps: squared error per pixel 0.0028, code std 0.79; mixture 0.0189
100 steps: squared error per pixel 0.0008, code std 0.82; mixture 0.0067
200 steps: squared error per pixel 0.0002, code std 0.84; mixture 0.0026

两组往返均不精确,且误差都稳步下降:从 10 步到 100 步,两者的均方根误差均缩小约六倍(不及理想一阶误差的十倍),而从 50 步起图像误差的下降速度至少与混合分布相当。可见学得的场沿轨迹并不比精确场更粗糙,余下的是步长误差。在 50 步时,在 \(-1\) 到 \(1\) 的像素尺度上误差为每像素 0.05 至 0.06,第三行已贴近原图;在 10 步时误差约 0.19,第二行丢失了末件衬衫格纹等细节。

编码本身则不那么令人满意。它们的标准差在 10 步时约 0.7,到 200 步时仍低于 0.9——能复现图像的编码比采样器设计所用的标准噪声更窄。因此反演编码并非标准高斯噪声的典型抽样,在编码间插值或在其附近采样新编码时务必留意。

借助编码编辑真实照片还会遇到第二个独立难题。反演沿一个场的轨迹前进,而引导采样器积分的是另一个场,因此从反演编码出发做引导采样会偏离原轨迹,不再复现原图。空文本反演(Null-text inversion)(Mokady 等 2023年) 通过在每步优化空标签嵌入直至引导采样器从该编码复现原图来修复这一问题。

由于采样器是编码的连续函数,我们可以通过在两张图像的编码之间插值实现图像过渡。直线插值是糟糕的路径:两个等范数 \(r\)、夹角 \(\omega\) 的编码中点范数为 \(r \cos(\omega/2)\),当编码像独立噪声图那样近乎正交时范数缩小约 \(\sqrt{2}\) 倍,而解码器从未从如此短的编码启动过。球面插值改沿两个编码之间的大圆弧移动:

\[ \begin{aligned} \mathbf{z}_u &= \frac{\sin\big((1 - u)\omega\big)\, \mathbf{z}_0 + \sin(u \omega)\, \mathbf{z}_1}{\sin \omega}, \\ \cos \omega &= \frac{\mathbf{z}_0^\top \mathbf{z}_1}{\|\mathbf{z}_0\| \|\mathbf{z}_1\|}, \end{aligned} \]

从而全程保持端点的范数。我们在两张测试短靴图像的 50 步编码之间解码八个插值点;整行属于同一类别,使解码器可使用单个标签。

i, j = torch.nonzero(y_test[:100] == y_test[0])[:2, 0]  # one class: one field
z0, z1 = codes[50][i], codes[50][j]
omega = torch.arccos(((z0 * z1).sum() / (z0.norm() * z1.norm())).clamp(-1, 1))
u = torch.linspace(0, 1, 8, device=z0.device).reshape(-1, 1, 1, 1)
zs = (torch.sin((1 - u) * omega) * z0 + torch.sin(u * omega) * z1
      ) / torch.sin(omega)
pred_i = d2l.make_pred(d2l.conditional(ema, y_test[i].repeat(8)), lin,
                       'velocity')
d2l.show_gray(d2l.ddim_sample(pred_i, zs, lin, 50), 1, 8);

i, j = jnp.nonzero(y_test[:100] == y_test[0])[0][:2]  # one class: one field
z0, z1 = codes[50][i], codes[50][j]
omega = jnp.arccos(jnp.clip(
    (z0 * z1).sum() / (jnp.linalg.norm(z0) * jnp.linalg.norm(z1)), -1, 1))
u = jnp.linspace(0, 1, 8).reshape(-1, 1, 1, 1)
zs = (jnp.sin((1 - u) * omega) * z0 + jnp.sin(u * omega) * z1
      ) / jnp.sin(omega)
pred_i = d2l.make_pred(d2l.conditional(ema, jnp.full(8, y_test[i])), lin,
                       'velocity')
d2l.show_gray(d2l.ddim_sample(pred_i, zs, lin, 50), 1, 8);

形态从一只短靴渐变为另一只,但中间帧更像两只靴子的叠加,而非第三只新靴子。球面插值保证了编码范数正确,却并无任何机制迫使解码器把两只靴子之间的编码映射到第三只靴子。

17.5.3.2 通过部分加噪编辑

反演寻找精确复现图像的噪声;编辑想要的恰恰相反——一个忘掉输入细节、保留整体布局的起点。Meng 等 (2022年) 因此直接用新噪声将草图或粗糙拼贴等粗略输入 \(\mathbf{y}\) 加噪至中间时刻 \(t_0\)(\(\mathbf{x}_{t_0} = \alpha_{t_0} \mathbf{y} + \sigma_{t_0} \boldsymbol\epsilon\)),再从 \(t_0\) 反向积分回数据。噪声掩盖掉真实图像没有的粗糙细节,采样器以逼真细节取而代之,而粗略布局得以保留。时刻 \(t_0\) 控制输入忠实度与逼真度之间的平衡。这种平衡究竟能有多好?

我们以十张类别平均图像(不像任何真实服饰的模糊剪影)作为粗略输入,每张加噪一百次至 \(t_0 \in \{0.3, 0.5, 0.7, 1\}\),再在对应类别标签下用 25 步 DDIM 反向积分。我们打印到输入的逐像素平方距离(忠实度)以及 1,000 张输出的 FD(逼真度);\(t_0 = 0\) 行即输入本身。

means = torch.stack([X[y == c].mean(0) for c in range(10)])
inputs = means.repeat(100, 1, 1, 1)                  # 1,000 inputs, class i % 10
pred = d2l.make_pred(d2l.conditional(ema, labels), lin, 'velocity')
torch.manual_seed(2)
eps = torch.randn_like(inputs)
edits = {0.0: inputs}
for t0 in (0.3, 0.5, 0.7, 1.0):
    x_t0 = lin.sample(inputs, torch.full((1000,), t0, device=X.device), eps)
    edits[t0] = d2l.ddim_sample(pred, x_t0, lin, 25, t_start=t0).clamp(-1, 1)
for t0, x in edits.items():
    print(f't0 = {t0:.1f}: squared distance to the input '
          f'{((x - inputs) ** 2).mean():.3f}, '
          f'FD {d2l.fid_score(features(x), f_test):.2f}')
d2l.show_gray(torch.cat([x[:10] for x in edits.values()]), 5, 10);
t0 = 0.0: squared distance to the input 0.000, FD 87.04
t0 = 0.3: squared distance to the input 0.018, FD 30.71
t0 = 0.5: squared distance to the input 0.045, FD 12.19
t0 = 0.7: squared distance to the input 0.087, FD 4.01
t0 = 1.0: squared distance to the input 0.168, FD 1.88

means = jnp.stack([X[y == c].mean(0) for c in range(10)])
inputs = jnp.tile(means, (100, 1, 1, 1))             # 1,000 inputs, class i % 10
pred = d2l.make_pred(d2l.conditional(ema, labels), lin, 'velocity')
eps = jax.random.normal(jax.random.key(2), inputs.shape)
edits = {0.0: inputs}
for t0 in (0.3, 0.5, 0.7, 1.0):
    x_t0 = lin.sample(inputs, jnp.full((1000,), t0), eps)
    edits[t0] = d2l.ddim_sample(pred, x_t0, lin, 25, t_start=t0).clip(-1, 1)
for t0, x in edits.items():
    print(f't0 = {t0:.1f}: squared distance to the input '
          f'{((x - inputs) ** 2).mean():.3f}, '
          f'FD {d2l.fid_score(features(x), f_test):.2f}')
d2l.show_gray(jnp.concatenate([x[:10] for x in edits.values()]), 5, 10);
t0 = 0.0: squared distance to the input 0.000, FD 87.03
t0 = 0.3: squared distance to the input 0.019, FD 29.37
t0 = 0.5: squared distance to the input 0.047, FD 11.31
t0 = 0.7: squared distance to the input 0.088, FD 3.64
t0 = 1.0: squared distance to the input 0.169, FD 1.67

输入本身的 FD 高达 85 至 87;随着 \(t_0\) 增大,到输入的距离增大而 FD 下降。在 \(t_0 = 0.3\) 处,输出比均值图清晰些但显斑驳,FD 约 30(相当于十步祖先链,远逊于任何确定性采样器)。在 \(0.5\) 处,它们像带着怪异纹理的服饰(FD 11 至 12)。直到 \(0.7\) 处,FD 降至约 4,才接近十步确定性采样器的水平,而此时输入仅剩轮廓与姿态。到 \(t_0 = 1\) 时输入完全消失,每个输出都是该类的新样本(FD 低于 2);由于两行共享同一批噪声图像,\(0.7\) 与 \(1\) 两行常常非常相像。对于类别均值这样粗糙的输入,只有当 \(t_0\) 大到几乎抹去输入时才能获得逼真度。

17.5.3.3 图像修复

假设我们已知图像的一部分(例如上半部分),希望模型补全其余部分。记 \(\mathbf{m}\) 为在已知像素处取 1 的掩码,\(\mathbf{y}\) 为其像素值。在每个噪声水平,我们都知道 \(\mathbf{x}_s\) 中已知像素应有的样子:\(\alpha_s \mathbf{y}\) 加上尺度为 \(\sigma_s\) 的噪声。替换修复(replacement inpainting)(Y. Song 等 2021年; Lugmayr 等 2022年) 因此照常执行每一步采样,再在新水平上用 \(\mathbf{y}\) 的一份新加噪副本覆写已知像素:

\[\mathbf{x}_s \leftarrow \mathbf{m} \odot \big(\alpha_s \mathbf{y} + \sigma_s \boldsymbol\xi\big) + (\mathbf{1} - \mathbf{m}) \odot \mathbf{x}_s. \tag{17.5.10}\]

替换只是一种近似。每步把所有像素都当作自由变量移动,再把已知像素覆写为完全不顾先前移动轨迹的噪声。未知像素只能通过网络下一次观察加噪图像来获知已知区域,因此采样器并未严格从给定已知像素的条件分布抽样。inpaint 每次推进单步采样,为每步覆写留出空档。

@torch.no_grad()
def inpaint(pred, known, mask, path, steps):
    """DDIM from noise that resets the known pixels (mask 1) at each level."""
    a, s = path.grid(steps)
    x = torch.randn_like(known)
    for i in range(steps):
        x0, eps = pred(x, a[i], s[i])
        x = a[i + 1] * x0 + s[i + 1] * eps            # one DDIM step, eta = 0
        noised = a[i + 1] * known + s[i + 1] * torch.randn_like(x)
        x = mask * noised + (1 - mask) * x            # keep the known pixels
    return x
def inpaint(pred, known, mask, path, steps, key):
    """DDIM from noise that resets the known pixels (mask 1) at each level."""
    a, s = path.grid(steps)
    def step(x, inputs):
        a_t, s_t, a_s, s_s, key = inputs
        x0, eps = pred(x, a_t, s_t)
        x = a_s * x0 + s_s * eps                     # one DDIM step, eta = 0
        noised = a_s * known + s_s * jax.random.normal(key, x.shape)
        return mask * noised + (1 - mask) * x, None   # keep the known pixels
    keys = jax.random.split(key, steps + 1)
    x = jax.random.normal(keys[0], known.shape)
    return jax.lax.scan(step, x, (a[:-1], s[:-1], a[1:], s[1:], keys[1:]))[0]

我们保留八张测试图像的上半部分,并在各自类别标签下用不同噪声为每张图像生成三种补全。各行依次展示已知上半部、三种补全结果与原图。

mask = torch.zeros(1, 1, 28, 28, device=X.device)
mask[..., :14, :] = 1                                # the upper half is known
pred = d2l.make_pred(d2l.conditional(ema, y_test[:8].repeat(3)), lin,
                     'velocity')
torch.manual_seed(3)
fills = inpaint(pred, X_test[:8].repeat(3, 1, 1, 1), mask, lin, 50)
d2l.show_gray(torch.cat([X_test[:8] * mask, fills, X_test[:8]]), 5, 8);

mask = jnp.zeros((1, 28, 28, 1)).at[:, :14].set(1)  # the upper half is known
pred = d2l.make_pred(d2l.conditional(ema, jnp.tile(y_test[:8], 3)), lin,
                     'velocity')
fills = inpaint(pred, jnp.tile(X_test[:8], (3, 1, 1, 1)), mask, lin, 50,
                jax.random.key(3))
d2l.show_gray(jnp.concatenate([X_test[:8] * mask, fills, X_test[:8]]), 5, 8);

大多数补全都能将已知上半部延续为该类的合理服饰,且同一图像的三种补全各具差异。近似误差在接缝处显露无遗:多幅补全(衬衫尤为明显)的下半部呈现出与上半部不同的纹理或明暗(练习 5 度量并修复了这一问题)。

本节所有采样器积分的都是同一个训练好的向量场,区别仅在积分方式。向量场本身我们一直当作既定前提:它来自我们在选定目标上优化的无权重平方误差。下一节将追问为何这一损失合适,以及目标、路径与权重的选择究竟会改变什么。

17.5.4 小结

由于训练仅依赖每个时刻 \(t\) 处 \(\mathbf{x}_t\) 的边缘分布,单个训练好的网络即可支撑由随机强度 \(\eta \ge 0\) 参数化的整个 DDIM 采样器家族。在 \(\eta = 0\) 处,DDIM 是确定性的,与重缩放坐标 \((\bar{\mathbf{x}}, \bar\sigma) = (\mathbf{x}/\alpha_t, \sigma_t/\alpha_t)\) 下概率流 ODE \(d\bar{\mathbf{x}}/d\bar\sigma = \hat{\boldsymbol\epsilon}\) 的 Euler 法完全重合。在我们的 Fashion-MNIST 模型上,确定性 ODE 求解器在中低预算下持续优于随机采样器(\(\eta = 1\) 与祖先链):线性网格上的二阶 Heun 法约 20 次求值即达模型 FD 平台,而每步仅需一次求值的二阶 Adams–Bashforth 多步求解器在 50 次求值内触及引导平台。反向运行确定性 ODE(ddim_invert)可将任意图像映射为潜在噪声编码,从而无需重新训练即支持球面潜空间插值、部分加噪图像编辑与替换图像修复。

17.5.5 练习

  1. 前向步与马尔可夫成员。● 给定 \(\mathbf{x}_0\),用同一个 \(\boldsymbol\epsilon\) 抽取 \(\mathbf{x}_t = \alpha_t \mathbf{x}_0 + \sigma_t \boldsymbol\epsilon\),并按 式 17.5.2 抽取 \(\mathbf{x}_s\)。
    1. 通过对联合高斯分布求条件分布,计算给定 \(\mathbf{x}_s\) 与 \(\mathbf{x}_0\) 时 \(\mathbf{x}_t\) 的均值与协方差。
    2. 证明除非 \(\tilde\sigma\) 取 \(\eta = 1\) 处的值,否则该均值依赖 \(\mathbf{x}_0\);而取该值时条件分布恰好化为 17.2 节 加噪链的前向步 \(\mathbf{x}_t = (\alpha_t / \alpha_s) \mathbf{x}_s + \sqrt{\sigma_t^2 - (\alpha_t / \alpha_s)^2 \sigma_s^2}\, \boldsymbol\nu\),从而说明该链是家族中唯一前向过程为马尔可夫的成员。
    3. 证明每步取 \(\tilde\sigma = 0\) 时,前向过程为所有时刻共享同一个 \(\boldsymbol\epsilon\) 的 \(\mathbf{x}_t = \alpha_t \mathbf{x}_0 + \sigma_t \boldsymbol\epsilon\)。为何回归目标无法区分这些前向过程?
  2. 高斯数据。设一维数据服从 \(\mathcal{N}(0, v)\)。
    1. 在坐标 \((\bar x, \bar\sigma)\) 中,证明精确噪声估计为 \(\hat\epsilon = \bar\sigma \bar x / (v + \bar\sigma^2)\),从 \(\bar\sigma\) 到 \(\bar\sigma'\) 的一步确定性步长将 \(\bar x\) 乘以 \((v + \bar\sigma \bar\sigma') / (v + \bar\sigma^2)\),而精确概率流将其乘以 \(\sqrt{(v + \bar\sigma'^2) / (v + \bar\sigma^2)}\)。
    2. 证明单步因子永不超过精确因子,且仅在 \(\bar\sigma' = \bar\sigma\) 时取等。这对于任意网格上高斯数据的确定性样本方差意味着什么?
    3. 现取家族 式 17.5.3 中任意 \(0 \leq \eta \leq 1\) 的成员并假设估计精确。将从 \(x_t \sim \mathcal{N}(0, \alpha_t^2 v + \sigma_t^2)\) 迈一步后 \(x_s\) 的方差写成 \(c = \sqrt{\sigma_s^2 - \tilde\sigma^2}\) 的函数,并用 Cauchy–Schwarz 不等式证明它始终低于精确值 \(\alpha_s^2 v + \sigma_s^2\) 且随 \(\eta\) 增大而下降。这解释了本节打印的哪几组散布度?
    4. 取 \(v = 0.25\)(mix 单个模式每坐标的方差)。计算从 \(x_1 \sim \mathcal{N}(0, 1)\) 出发在 200、50、20、10 与 5 步保方差网格上确定性样本的标准差 \(s\)。将二维点云的散布度 \(2s^2\) 与真实数据的 \(0.5\) 以及本节打印的散布度作对比。单个高斯模式预测的收缩量与混合分布相比是相等、更多还是更少?
  3. [extended] 对数信噪比中的二阶采样器。●● DPM-Solver-2 (Lu 等 2022年) 用两次求值完成从 \(\bar\sigma\) 到 \(\bar\sigma'\) 的一步更新,第二次求值位于 \(\log \bar\sigma\) 的中点 \(\bar\sigma_m = \sqrt{\bar\sigma \bar\sigma'}\):\(\bar{\mathbf{x}}_m = \bar{\mathbf{x}} + (\bar\sigma_m - \bar\sigma)\, \hat{\boldsymbol\epsilon}(\bar{\mathbf{x}}, \bar\sigma)\),随后 \(\bar{\mathbf{x}}' = \bar{\mathbf{x}} + (\bar\sigma' - \bar\sigma)\, \hat{\boldsymbol\epsilon}(\bar{\mathbf{x}}_m, \bar\sigma_m)\)。
    1. 令 \(h = \log(\bar\sigma / \bar\sigma')\)。将步内 \(\bar{\mathbf{x}}\) 的精确变化写成沿轨迹对 \(\hat{\boldsymbol\epsilon}\) 的积分,并证明该更新的局部误差为 \(O(\bar\sigma h^3)\) 而 Euler 步为 \(O(\bar\sigma h^2)\)。假设 \(\hat{\boldsymbol\epsilon}\) 沿轨迹是 \(\log \bar\sigma\) 的光滑函数,且关于 \(\mathbf{x} = \bar{\mathbf{x}} / \sqrt{1 + \bar\sigma^2}\) 满足 Lipschitz 条件(从而在大 \(\bar\sigma\) 处关于 \(\bar{\mathbf{x}}\) 的 Lipschitz 常数为 \(1/\bar\sigma\) 量级)。
    2. 按接口 pred(x, alpha, sigma) 实现该更新(取 \(\alpha = 1 / \sqrt{1 + \bar\sigma^2}\) 与 \(\sigma = \bar\sigma \alpha\)),到达 \(\bar\sigma = 0\) 的最后一步用 Euler 法。在约 11、21 与 51 次求值处将其与 ode_sample、heun_sample 及 multistep_sample 对比:在混合分布上用 pred_exact 度量到千步参照的距离,在图像上度量 FD。
    3. 在 80 与 0.002 之间按 \(\log \bar\sigma\) 均匀排布水平重复上述实验。在每个预算下,哪种方法与网格的组合最佳?
  4. 最优逆向方差。● 从 \(t\) 到 \(s\) 的一步随机更新移动到后验均值 \(\alpha_s \hat{\mathbf{x}}_0 + \sigma_s \kappa \hat{\boldsymbol\epsilon}\),并加入每坐标方差为 \(v\) 的高斯噪声。Ho 等 (2020年) 尝试了前向步方差与后验方差;Bao 等 (2022年) 求出了适用于任意数据的最优 \(v\)。假设估计精确,并记 \(\bar e_t = \mathbb{E}\|\boldsymbol\epsilon - \hat{\boldsymbol\epsilon}\|^2 / d\) 为 \(d\) 维空间中时刻 \(t\) 精确噪声估计的每坐标误差。
    1. 17.3 节 的练习 3a 表明,真实逆向转移 \(q(\mathbf{x}_s \mid \mathbf{x}_t)\) 的协方差为 \(\tau^2 \mathbf{I} + c^2 \textrm{Cov}(\mathbf{x}_0 \mid \mathbf{x}_t)\),其中 \(c\) 是 \(q(\mathbf{x}_s \mid \mathbf{x}_t, \mathbf{x}_0)\) 均值中 \(\mathbf{x}_0\) 的系数。将该均值写作 \(\alpha_s \mathbf{x}_0 + \sigma_s \kappa \boldsymbol\epsilon\)(其中 \(\boldsymbol\epsilon = (\mathbf{x}_t - \alpha_t \mathbf{x}_0)/\sigma_t\)),由此得出 \(\tau^2 = \tilde\sigma^2\)(后验方差)与 \(c = k = \alpha_s - \sigma_s \kappa\, \alpha_t / \sigma_t\)。真实逆向转移的均值是什么?
    2. 证明最小化从 \(q(\mathbf{x}_s \mid \mathbf{x}_t)\) 到该高斯步期望 KL 散度的 \(v\) 为 \(v^\star = \tilde\sigma^2 + k^2 \bar\sigma_t^2 \bar e_t\),且 \(\bar e_t = 1 - \sigma_t^2\, \mathbb{E}\|\nabla \log p_t(\mathbf{x}_t)\|^2 / d\),从而 \(v^\star\) 仅由分数决定。
    3. 证明当数据为单点时 \(v^\star\) 等于后验方差,当数据为保方差路径上的标准高斯时它等于前向步方差。
    4. (选做,代码。)在 50 步保方差网格上用 pred_exact 估计混合分布的 \(\bar e_t\),并比较采用三种方差的随机步在 20,000 个样本上的散布度。
  5. [code] 带协调的图像修复。● inpaint 的补全结果可能在边界处与已知半幅不衔接。
    1. 度量接缝:计算补全图像第 13 行与第 14 行的平均绝对差,并与真实测试图像的同一数值作对比。
    2. RePaint (Lugmayr 等 2022年) 让上下两半充分交换信息:每执行完一步从 \(t\) 到 \(s\) 的更新后,用前向步重新加噪回 \(t\) 并重复该步,每个水平重复 \(r\) 次。在 50 个水平上实现 \(r \in \{1, 5, 10\}\) 并重新度量接缝。每次重复带来多少额外开销?
    3. 对每个 \(r\) 为同一张测试图像生成五种补全。它们的多样性如何?
  6. [code] 跨类别编辑。使用本节的类别条件模型,并以 d2l.make_pred(d2l.cfg(ema, c, gamma), lin, 'velocity') 引导,其中 c 保存每张图像的标签。
    1. 将 100 张长裤测试图像加噪至 \(t_0 \in \{0.3, 0.5, 0.7, 0.9\}\),并在 \(\gamma = 1\) 与 \(\gamma = 2\) 下朝连衣裙标签用 25 步 DDIM 反向积分。参照编辑代码单元,报告 cnn 判为连衣裙的输出比例以及到输入的逐像素平方距离。
    2. 从纯噪声出发,先以长裤标签与 \(\gamma = 1\) 从 \(t = 1\) 采样至 \(t^*\),再以连衣裙标签与(a)中的两个引导尺度采至 \(t = 0\)(ddim_sample 接受 t_start 与 t_end),其中 \(t^* \in \{0.3, 0.5, 0.7, 0.9\}\)。将判为连衣裙的比例随 \(t^*\) 的曲线与(a)中随 \(t_0\) 的曲线并列绘出,并与 17.3 节 练习 4 中混合分布的定型时间对比。
    3. 证明在精确网络下,相同 \(\gamma\) 与 \(t_0 = t^*\) 处的两个实验产出同分布的输出。两条曲线之间残留了哪些差异,它们从何而来?
    (a)改编自 Berkeley CS180/280A Project 5A(2025 秋)第 1.7.3 节。

讨论