16.7  超越 GAN 的对抗损失

预测房价等单个标量时,最小化均方误差(\(L_2\) 损失)是标准做法。但在条件图像生成问题上——例如超分辨率(将低分辨率缩略图 \(c\) 映射为高分辨率图像 \(x\))或草图转照片(pix2pix,Isola 等 (2017年))——逐像素 \(L_2\) 与 \(L_1\) 回归损失会产生模糊输出。许多截然不同的高分辨率纹理都对应同一个低分辨率输入,最小化逐像素平方误差迫使网络输出它们的条件均值 \(\mathbb{E}[x \mid c]\)——一种不属于任何合理清晰图像的模糊结果。将回归损失与评判输出在条件 \(c\) 下是否逼真的判别器 \(D(x, c)\) 配对,即可恢复锐利的高频细节。

这一机制解释了为何尽管扩散模型与流匹配模型(第 17 章)已取代独立 GAN 成为通用图像合成的主力,对抗损失依然被广泛使用。学习到的判别器仍在训练从多步扩散模型蒸馏出的单步生成器、潜在扩散模型所依赖的图像自编码器(词元化器),以及从频谱图重建语音波形的神经音频声码器。下面我们在极简双峰回归问题上分析条件均值平均效应,展示为何缺少判别器时从高噪声去噪教师蒸馏的单步学生会坍缩至条件均值,并总结对抗损失在现代生成流水线中的应用。

16.7.1 条件均值与多峰目标

16.7.1.1 条件均值分解

设 \(g(c)\) 是在给定条件 \(c\) 下对 \(x\) 的确定性预测器,并记 \(\mu(c) = \mathbb{E}[x \mid c]\) 为条件均值。在 \(\mathbb{E}[\|x - g(c)\|^2]\) 内部加减 \(\mu(c)\) 后,交叉项 \(2\,\mathbb{E}[\langle x - \mu(c), \mu(c) - g(c) \rangle] = 0\)(由给定 \(c\) 的迭代期望法则)消去,留下正交分解:

\[ \begin{aligned} \mathbb{E}\big[(x - g(c))^2\big] &= \mathbb{E}\big[(x - \mu(c))^2\big] + \mathbb{E}\big[(\mu(c) - g(c))^2\big]. \end{aligned} \tag{16.7.1}\]

第一项是不可约的条件方差 \(\operatorname{Var}(x \mid c)\),第二项是 \(g(c)\) 与 \(\mu(c)\) 之间的平方距离。因此,平方误差被条件均值 \(g^\star(c) = \mu(c)\) 唯一最小化。当 \(p(x \mid c)\) 单峰且集中时,\(\mu(c)\) 是有代表性的目标;当 \(p(x \mid c)\) 多峰时,\(\mu(c)\) 会落入模式之间的低密度空区。将 \(L_2\) 替换为 \(L_1\) 损失 \(\mathbb{E}[|x - g(c)|]\) 只是把条件均值换成逐坐标条件中位数(练习 2),它同样落在对称双峰分布的支集之外。

16.7.1.2 双峰双带基准

考虑一维条件分布,其中 \(c \sim \textrm{Uniform}[-1, 1]\),两条平行数据带之间隔着一条空白走廊:

\[ \begin{aligned} x &= c + b + 0.05\,\xi, \\ b &\in \{-1, +1\} \textrm{ with probability } \tfrac12 \textrm{ each}, \quad \xi \sim \mathcal{N}(0, 1). \end{aligned} \tag{16.7.2}\]

条件均值 \(\mu(c) = c\) 沿着两条数据带 \(x = c \pm 1\) 之间的空白走廊延伸,其平方误差为 \(\mathbb{E}[(x - \mu(c))^2] = 1 + 0.05^2 = 1.0025\)。相比之下,坚定选择上带的预测器 \(g(c) = c + 1\) 的平方误差为 \(\tfrac12(0) + \tfrac12(2^2) + 0.05^2 = 2.0025\)——足足大一倍。因此,平方误差反而惩罚对有效数据模式的坚定选择。

然而,条件判别器 \(D(x, c)\) 估计的是对数密度比(16.6 节):

\[ D^\star(x, c) = \log \frac{p(x, c)}{q(x, c)}. \]

在 \(p(x, c) \approx 0\) 的空白走廊中,\(D^\star(x, c)\) 为强负值,因此最小化非饱和对抗损失 \(-\log \sigma(D(\hat x, c))\) 会迫使预测器 \(\hat x = g(c)\) 落到其中一条高密度数据带上。

我们从相同初始权重出发训练两个完全相同的双隐藏层 \(\tanh\) MLP(g_mse 与 g_adv)以验证这一现象:g_mse 最小化平方误差,而 g_adv 使用 d2l.gan_loss_D 与 d2l.gan_loss_G(16.4 节)对抗一个 leaky-ReLU 判别器 \(D(x, c)\)。

def make_bands(n):
    """Draw n pairs (c, x) from the two bands x = c + b + 0.05 xi."""
    c = torch.rand(n, 1) * 2 - 1
    b = torch.randint(0, 2, (n, 1)) * 2.0 - 1.0
    return c, c + b + 0.05 * torch.randn(n, 1)

torch.manual_seed(0)
g_mse = d2l.make_mlp([1, 32, 32, 1], nn.Tanh())
g_adv = d2l.make_mlp([1, 32, 32, 1], nn.Tanh())
g_adv.load_state_dict(g_mse.state_dict())  # both students start alike
D = d2l.make_mlp([2, 32, 32, 1], nn.LeakyReLU(0.2))
c_data, x_data = make_bands(200)  # a data sample for the plot
def make_bands(key, n):
    """Draw n pairs (c, x) from the two bands x = c + b + 0.05 xi."""
    k_c, k_b, k_xi = jax.random.split(key, 3)
    c = jax.random.uniform(k_c, (n, 1), minval=-1, maxval=1)
    b = jax.random.rademacher(k_b, (n, 1), dtype=jnp.float32)
    return c, c + b + 0.05 * jax.random.normal(k_xi, (n, 1))

rngs = nnx.Rngs(0)
g_mse = d2l.make_mlp([1, 32, 32, 1], nnx.tanh, rngs=rngs)
g_adv = nnx.clone(g_mse)  # both students start alike
D = d2l.make_mlp([2, 32, 32, 1], lambda h: nnx.leaky_relu(h, 0.2), rngs=rngs)
key_mse, key_adv, key_data = jax.random.split(rngs(), 3)
c_data, x_data = make_bands(key_data, 200)  # a data sample for the plot

第一个学生用 Adam 最小化平方误差,学习率在 2,000 步内按余弦从 0.01 衰减至零。我们无需实验就能预知其终点:由 式 16.7.1,它必沿直线 \(x = c\) 延伸,距两条带各差一个单位。它作为第二个学生的对照。

def train_mse(g, num_steps=2000, batch_size=128, lr=0.01):
    opt = torch.optim.Adam(g.parameters(), lr=lr)
    sched = torch.optim.lr_scheduler.CosineAnnealingLR(opt, num_steps)
    for _ in range(num_steps):
        c, x = make_bands(batch_size)  # a fresh batch at every step
        opt.zero_grad()
        ((g(c) - x) ** 2).mean().backward()
        opt.step()
        sched.step()

train_mse(g_mse)
@nnx.jit(static_argnums=3)
def mse_step(g, opt, key, batch_size):
    c, x = make_bands(key, batch_size)  # a fresh batch at every step
    opt.update(g, nnx.grad(lambda g_: ((g_(c) - x) ** 2).mean())(g))

def train_mse(g, key, num_steps=2000, batch_size=128, lr=0.01):
    schedule = optax.cosine_decay_schedule(lr, num_steps)
    opt = nnx.Optimizer(g, optax.adam(schedule), wrt=nnx.Param)
    for k in jax.random.split(key, num_steps):
        mse_step(g, opt, k, batch_size)

train_mse(g_mse, key_mse)

第二个学生运行对数损失博弈,采用 16.4 节 中的 d2l.gan_loss_D 与 d2l.gan_loss_G。每一步评判器先在真实对 \((x, c)\) 与预测对 \((\hat x, c)\) 上执行一步 logistic 回归更新,随后学生针对更新后的评判器在 \(-\log \sigma\big(D(\hat x, c)\big)\) 上执行一步更新。预测值带着与数据相同的观测噪声进入博弈,即 \(\hat x = g(c) + 0.05\,\xi'\)(每次新采 \(\xi' \sim \mathcal{N}(0, 1)\)),使两个分布的差异仅在于概率质量所处位置而非平滑程度。博弈比回归推进更慢,因此该学生训练 8,000 步;平方误差学生在 2,000 步时已达最优,继续训练也不会再移动。

def train_adversarial(g, D, num_steps=8000, batch_size=128):
    opt_G = torch.optim.Adam(g.parameters(), lr=1e-3)
    opt_D = torch.optim.Adam(D.parameters(), lr=2e-3)
    for _ in range(num_steps):
        c, x = make_bands(batch_size)
        x_hat = g(c) + 0.05 * torch.randn(batch_size, 1)  # the data's noise
        real, fake = torch.cat([c, x], 1), torch.cat([c, x_hat], 1)
        opt_D.zero_grad()
        d2l.gan_loss_D(D, real, fake.detach()).backward()
        opt_D.step()
        opt_G.zero_grad()
        d2l.gan_loss_G(D, real, fake).backward()
        opt_G.step()

train_adversarial(g_adv, D)
@nnx.jit(static_argnums=5)
def adversarial_step(g, D, opt_G, opt_D, key, batch_size):
    k_data, k_xi = jax.random.split(key)
    c, x = make_bands(k_data, batch_size)
    xi = jax.random.normal(k_xi, (batch_size, 1))  # the data's noise
    real = jnp.concatenate([c, x], 1)
    fake = lambda g_: jnp.concatenate([c, g_(c) + 0.05 * xi], 1)
    loss_D = lambda D_: d2l.gan_loss_D(D_, real, fake(g))
    opt_D.update(D, nnx.grad(loss_D)(D))
    loss_G = lambda g_: d2l.gan_loss_G(D, real, fake(g_))
    opt_G.update(g, nnx.grad(loss_G)(g))

def train_adversarial(g, D, key, num_steps=8000, batch_size=128):
    opt_G = nnx.Optimizer(g, optax.adam(1e-3), wrt=nnx.Param)
    opt_D = nnx.Optimizer(D, optax.adam(2e-3), wrt=nnx.Param)
    for k in jax.random.split(key, num_steps):
        adversarial_step(g, D, opt_G, opt_D, k, batch_size)

train_adversarial(g_adv, D, key_adv)

在 201 个输入网格点上,用三个指标汇总每个学生:曲线到较近数据带的平均距离、到条件均值 \(x = c\) 的平均距离,以及曲线距两条带均超过 0.25 的输入比例。

cs = torch.linspace(-1, 1, 201).reshape(-1, 1)
with torch.no_grad():
    curves = {'squared error': g_mse(cs), 'adversarial': g_adv(cs)}
for name, x_hat in curves.items():
    to_band = torch.minimum((x_hat - cs - 1).abs(), (x_hat - cs + 1).abs())
    print(f'{name}: {to_band.mean():.2f} from the nearer band, '
          f'{(x_hat - cs).abs().mean():.2f} from x = c, '
          f'{(to_band > 0.25).float().mean():.0%} off the bands')
squared error: 0.98 from the nearer band, 0.02 from x = c, 100% off the bands
adversarial: 0.02 from the nearer band, 0.99 from x = c, 2% off the bands
cs = jnp.linspace(-1, 1, 201).reshape(-1, 1)
curves = {'squared error': g_mse(cs), 'adversarial': g_adv(cs)}
for name, x_hat in curves.items():
    to_band = jnp.minimum(jnp.abs(x_hat - cs - 1), jnp.abs(x_hat - cs + 1))
    print(f'{name}: {to_band.mean():.2f} from the nearer band, '
          f'{jnp.abs(x_hat - cs).mean():.2f} from x = c, '
          f'{(to_band > 0.25).mean():.0%} off the bands')
squared error: 0.98 from the nearer band, 0.02 from x = c, 100% off the bands
adversarial: 0.04 from the nearer band, 1.01 from x = c, 0% off the bands

将 curves 中的两条学习曲线叠画在训练样本 (c_data, x_data) 及虚线条件均值 \(x = c\) 之上,回归与对抗训练的差异一目了然:

d2l.plot([c_data, cs, cs, cs],
         [x_data, curves['squared error'], curves['adversarial'], cs],
         '$c$', '$x$', ['data', 'squared-error student',
                        'adversarial student', '$x = c$'],
         ylim=(-2.2, 3.6), fmts=('C0.', 'C2-', 'C1-', 'k--'),
         figsize=(5.5, 3.2))

d2l.plot([c_data, cs, cs, cs],
         [x_data, curves['squared error'], curves['adversarial'], cs],
         '$c$', '$x$', ['data', 'squared-error student',
                        'adversarial student', '$x = c$'],
         ylim=(-2.2, 3.6), fmts=('C0.', 'C2-', 'C1-', 'k--'),
         figsize=(5.5, 3.2))

正如预测,平方误差模型 g_mse 沿空白走廊紧贴条件均值 \(\mu(c) = c\)(距任一数据带约一个单位,\(100\%\) 的预测偏离数据带)。对抗模型 g_adv 则贴合有效数据带(到较近带的平均距离仅百分之几,至多 \(2\%\) 的点在分支切换处穿过走廊)。

注意此处根本性的感知–失真权衡 (Blau 和 Michaeli 2018年):即便是理想随机采样器 \(\hat x \sim p(x \mid c)\),其期望平方误差也是 \(2\,\operatorname{Var}(x \mid c)\)——模糊条件均值 \(\mu(c)\) 的两倍 MSE(或低 \(3\text{ dB}\) 的 PSNR;练习 1)。此外,由于确定性函数 \(g(c)\) 对每个输入 \(c\) 只能输出一个值,要同时覆盖两条数据带,必须与 \(c\) 一同传入随机潜变量 \(z\):\(\hat x = g(c, z)\)(练习 3)。

16.7.2 扩散蒸馏中的判别器

16.7.2.1 作为条件均值的去噪器

扩散模型与流匹配模型(第 17 章)通过平方误差训练去噪网络,从加噪输入 \(x_\tau = x_0 + \tau\xi\)(\(\xi \sim \mathcal{N}(0, I)\))预测干净数据 \(x_0\)。由 式 16.7.1,最优去噪器计算的是后验条件均值 \(\mathbb{E}[x_0 \mid x_\tau]\)(17.1 节)。在高噪声水平 \(\tau\) 下,许多干净图像都与 \(x_\tau\) 相容,因此 \(\mathbb{E}[x_0 \mid x_\tau]\) 是模糊平均;多步采样器通过从高噪声逐步走许多小步降至 \(\tau \to 0\) 来避免直接返回这一平均。

将多步扩散教师蒸馏为快速单步学生生成器(17.8 节)时,一种常见做法是对学生输出 \(\hat x\) 施加噪声 \(\tau\xi\),并将 \(\hat x\) 回归到冻结教师的去噪估计 \(\mathbb{E}[x_0 \mid \hat x + \tau\xi]\)。然而在高噪声 \(\tau\) 下,教师的去噪目标本身就是条件均值——若不引入对抗评判器,会把单步学生拉回模糊平均。

16.7.2.2 双带基准上的闭式蒸馏

在双带问题 式 16.7.2 上,噪声水平 \(\tau\) 下的精确贝叶斯最优去噪教师存在闭式解。给定数据带 \(b \in \{-1, +1\}\) 上某点的加噪观测 \(\tilde x = x + \tau\xi\),有 \(\tilde x \mid c, b \sim \mathcal{N}(c + b, \tau^2 + 0.05^2)\)。由贝叶斯法则,\(b = +1\) 相对 \(b = -1\) 的后验对数几率为 \(2(\tilde x - c)/(\tau^2 + 0.05^2)\),从而给出后验平均带中心:

\[ \mathbb{E}[c + b \mid \tilde x, c] \;=\; c + \tanh\Big(\frac{\tilde x - c}{\tau^2 + 0.05^2}\Big). \tag{16.7.3}\]

现在我们为每个学生 \(g(c, z)\) 配备一维高斯潜变量 \(z \sim \mathcal{N}(0, 1)\) 使其具备覆盖两条带的能力,并在教师噪声水平 \(\tau = 2\) 下对比三种训练目标:

  1. 仅回归:最小化 \(\|\hat x - \operatorname{stop\_grad}(\text{teacher}(\hat x + \tau\xi, c, \tau))\|^2\)。由于 \(\tau = 2\) 时 式 16.7.3 关于 \(\tilde x\) 的斜率至多为 \((\tau^2 + 0.05^2)^{-1} \approx \tfrac14 < 1\),偏移量 \(u = g(c, z) - c\) 的不动点方程 \(u = \mathbb{E}_\xi[\tanh((u + \sqrt{\tau^2 + 0.05^2}\,\xi)/(\tau^2 + 0.05^2))]\) 具有唯一压缩不动点 \(u = 0\)(空白走廊)。
  2. 仅评判器:使用 d2l.gan_loss_D 与 d2l.gan_loss_G 针对条件判别器 \(D(x, c)\) 训练 \(g(c, z)\)。
  3. 评判器 + 回归:将对抗损失与教师回归损失等权相加(如同对抗扩散蒸馏 ADD,Sauer 等 (2023年))。
def teacher(x_tilde, c, tau):
    """Posterior mean of the band center c + b given x_tilde = x + tau xi."""
    return c + torch.tanh((x_tilde - c) / (tau ** 2 + 0.05 ** 2))

def train_student(g, D, lam, tau=2.0, num_steps=4000, batch_size=128):
    """Train g(c, z) on the critic's loss if D is given, plus lam times the
    squared error toward the teacher's estimate at noise level tau."""
    opt_G = torch.optim.Adam(g.parameters(), lr=1e-3)
    if D is not None:
        opt_D = torch.optim.Adam(D.parameters(), lr=2e-3)
    for _ in range(num_steps):
        c, x = make_bands(batch_size)
        z = torch.randn(batch_size, 1)  # the student's latent
        x_hat = g(torch.cat([c, z], 1)) + 0.05 * torch.randn(batch_size, 1)
        real, fake = torch.cat([c, x], 1), torch.cat([c, x_hat], 1)
        loss_G = 0
        if D is not None:
            opt_D.zero_grad()
            d2l.gan_loss_D(D, real, fake.detach()).backward()
            opt_D.step()
            loss_G = d2l.gan_loss_G(D, real, fake)
        with torch.no_grad():  # the teacher's estimate is a fixed target
            target = teacher(x_hat + tau * torch.randn(batch_size, 1), c, tau)
        loss_G = loss_G + lam * ((x_hat - target) ** 2).mean()
        opt_G.zero_grad()
        loss_G.backward()
        opt_G.step()
def teacher(x_tilde, c, tau):
    """Posterior mean of the band center c + b given x_tilde = x + tau xi."""
    return c + jnp.tanh((x_tilde - c) / (tau ** 2 + 0.05 ** 2))

@nnx.jit(static_argnums=7)
def student_step(g, D, opt_G, opt_D, key, lam, tau, batch_size):
    k_data, k_z, k_xi, k_tau = jax.random.split(key, 4)
    c, x = make_bands(k_data, batch_size)
    z = jax.random.normal(k_z, (batch_size, 1))  # the student's latent
    xi = jax.random.normal(k_xi, (batch_size, 1))  # the data's noise
    sample = lambda g_: g_(jnp.concatenate([c, z], 1)) + 0.05 * xi
    real = jnp.concatenate([c, x], 1)
    fake = lambda g_: jnp.concatenate([c, sample(g_)], 1)
    if D is not None:
        loss_D = lambda D_: d2l.gan_loss_D(D_, real, fake(g))
        opt_D.update(D, nnx.grad(loss_D)(D))
    noise = tau * jax.random.normal(k_tau, (batch_size, 1))
    def loss_G(g_):
        x_hat = sample(g_)  # the teacher's estimate is a fixed target
        target = jax.lax.stop_gradient(teacher(x_hat + noise, c, tau))
        loss = lam * ((x_hat - target) ** 2).mean()
        if D is not None:
            loss += d2l.gan_loss_G(D, real, fake(g_))
        return loss
    opt_G.update(g, nnx.grad(loss_G)(g))

def train_student(g, D, lam, key, tau=2.0, num_steps=4000, batch_size=128):
    """Train g(c, z) on the critic's loss if D is given, plus lam times the
    squared error toward the teacher's estimate at noise level tau."""
    opt_G = nnx.Optimizer(g, optax.adam(1e-3), wrt=nnx.Param)
    opt_D = (None if D is None
             else nnx.Optimizer(D, optax.adam(2e-3), wrt=nnx.Param))
    for k in jax.random.split(key, num_steps):
        student_step(g, D, opt_G, opt_D, k, lam, tau, batch_size)

学生现在在每个 \(c\) 处输出一个分布。函数 band_shares 在第一个实验的 201 个输入及潜变量的 64 个等距分位数上评估学生,返回到较近带的平均距离,以及落在上带与下带 0.25 范围内的输出占比。

def band_shares(g, cs):
    """Mean distance of g(c, z) to the nearer band, and its shares on the
    upper and the lower band, over the inputs cs and 64 quantiles z."""
    zs = torch.special.ndtri((torch.arange(64) + 0.5) / 64)
    c, z = (v.reshape(-1, 1) for v in torch.meshgrid(
        cs.flatten(), zs, indexing='ij'))
    with torch.no_grad():
        u = g(torch.cat([c, z], 1)) - c  # offset from the corridor
    to_band = torch.minimum((u - 1).abs(), (u + 1).abs())
    return (to_band.mean(), ((u - 1).abs() < 0.25).float().mean(),
            ((u + 1).abs() < 0.25).float().mean())
def band_shares(g, cs):
    """Mean distance of g(c, z) to the nearer band, and its shares on the
    upper and the lower band, over the inputs cs and 64 quantiles z."""
    zs = jax.scipy.special.ndtri((jnp.arange(64) + 0.5) / 64)
    c, z = (v.reshape(-1, 1) for v in jnp.meshgrid(
        cs.flatten(), zs, indexing='ij'))
    u = g(jnp.concatenate([c, z], 1)) - c  # offset from the corridor
    to_band = jnp.minimum(jnp.abs(u - 1), jnp.abs(u + 1))
    return (to_band.mean(), (jnp.abs(u - 1) < 0.25).mean(),
            (jnp.abs(u + 1) < 0.25).mean())

每个学生均运行三个随机种子。在同一随机种子内,三个学生从相同权重出发并见到相同数据。

students = {'regression': (False, 1.0), 'critic': (True, 0.0),
            'critic + regression': (True, 1.0)}
for name, (has_critic, lam) in students.items():
    for seed in range(3):
        torch.manual_seed(seed)
        g = d2l.make_mlp([2, 32, 32, 1], nn.Tanh())
        D = d2l.make_mlp([2, 32, 32, 1], nn.LeakyReLU(0.2))
        train_student(g, D if has_critic else None, lam)
        dist, upper, lower = band_shares(g, cs)
        print(f'{name}, seed {seed}: {dist:.2f} from the nearer band, '
              f'{upper:.0%} upper, {lower:.0%} lower, '
              f'{1 - upper - lower:.0%} off the bands')
regression, seed 0: 0.97 from the nearer band, 0% upper, 0% lower, 100% off the bands
regression, seed 1: 0.98 from the nearer band, 0% upper, 0% lower, 100% off the bands
regression, seed 2: 0.98 from the nearer band, 0% upper, 0% lower, 100% off the bands
critic, seed 0: 0.03 from the nearer band, 49% upper, 50% lower, 1% off the bands
critic, seed 1: 0.08 from the nearer band, 50% upper, 49% lower, 1% off the bands
critic, seed 2: 0.04 from the nearer band, 50% upper, 49% lower, 1% off the bands
critic + regression, seed 0: 0.05 from the nearer band, 48% upper, 50% lower, 2% off the bands
critic + regression, seed 1: 0.06 from the nearer band, 50% upper, 48% lower, 2% off the bands
critic + regression, seed 2: 0.04 from the nearer band, 48% upper, 51% lower, 1% off the bands
students = {'regression': (False, 1.0), 'critic': (True, 0.0),
            'critic + regression': (True, 1.0)}
for name, (has_critic, lam) in students.items():
    for seed in range(3):
        rngs = nnx.Rngs(seed)
        g = d2l.make_mlp([2, 32, 32, 1], nnx.tanh, rngs=rngs)
        D = d2l.make_mlp([2, 32, 32, 1], lambda h: nnx.leaky_relu(h, 0.2),
                         rngs=rngs)
        train_student(g, D if has_critic else None, lam, rngs())
        dist, upper, lower = band_shares(g, cs)
        print(f'{name}, seed {seed}: {dist:.2f} from the nearer band, '
              f'{upper:.0%} upper, {lower:.0%} lower, '
              f'{1 - upper - lower:.0%} off the bands')
regression, seed 0: 0.96 from the nearer band, 0% upper, 0% lower, 100% off the bands
regression, seed 1: 0.97 from the nearer band, 0% upper, 0% lower, 100% off the bands
regression, seed 2: 0.97 from the nearer band, 0% upper, 0% lower, 100% off the bands
critic, seed 0: 0.03 from the nearer band, 52% upper, 47% lower, 1% off the bands
critic, seed 1: 0.06 from the nearer band, 50% upper, 49% lower, 1% off the bands
critic, seed 2: 0.03 from the nearer band, 52% upper, 47% lower, 2% off the bands
critic + regression, seed 0: 0.04 from the nearer band, 48% upper, 50% lower, 1% off the bands
critic + regression, seed 1: 0.04 from the nearer band, 49% upper, 50% lower, 1% off the bands
critic + regression, seed 2: 0.04 from the nearer band, 49% upper, 49% lower, 1% off the bands

三随机种子实验结果印证了不动点分析:

  • 仅向高噪声教师回归将 \(100\%\) 的输出坍缩进空白走廊(距任一带约一个单位),完全忽略潜变量 \(z\)。
  • 仅评判器与评判器 + 回归都将 \(98\text{--}99\%\) 的输出直接落在两条数据带上(平均距离百分之几,始终低于 \(0.1\)),并通过潜变量 \(z\) 将概率质量均匀分配在上下两条带(\(\sim 49\% / 49\%\))。由于数据带宽度极窄(\(\sigma = 0.05\)),最优评判器的恢复斜率(\(\delta / 0.05^2 = 400\delta\))轻松压倒高噪声教师微弱的向内拉力。

16.7.2.3 大规模蒸馏、自编码器与声码器

这种“回归/感知锚点 + 对抗判别器”的组合广泛出现在三大类现代生成系统中:

  1. 对抗扩散蒸馏(ADD 与 DMD2):ADD (Sauer 等 2023年) 将去噪教师回归损失与建立在冻结 DINOv2 特征上的判别器结合,训练单步图像生成器,观察到与上述实验相同的排序(仅用教师回归产生模糊图像,加入判别器后产出锐利单步样本)。分布匹配蒸馏(DMD,Yin, Gharbi, Zhang, 等 (2024年))利用冻结教师分数 \(\nabla_x \log p_\tau\) 与伪分布扩散模型分数 \(\nabla_x \log q_\tau\) 之差沿 \(D_{\textrm{KL}}(q_\tau \,\|\, p_\tau)\) 下降。我们此前已见过这一差值:\(\nabla_x \log p_\tau - \nabla_x \log q_\tau = \nabla_x \lambda_\tau\) 正是加噪分布间最优评判器 \(\lambda_\tau = \log(p_\tau/q_\tau)\) 的输入梯度。因此,DMD 的生成器更新正是练习 5 中的无权重(\(w = 1\))反向 KL 更新,只不过评判器斜率由两个分数网络而非判别器提供。由于两个分布均已加噪,它们的支集在每个噪声水平 \(\tau > 0\) 下都重叠——这正是 16.1.2.3 节 中的实例噪声。DMD2 (Yin, Gharbi, Park, 等 2024年) 进一步加入针对真实图像的对抗判别器,使单步学生的质量能够超越教师。
  2. 潜在图像自编码器(词元化器):潜在扩散模型(17.7 节)借助自编码器(如 VQGAN 或 Stable Diffusion VAE,Esser 等 (2021年); Rombach 等 (2022年))将图像压缩至低维潜空间。由于压缩后的潜在编码无法唯一确定细粒度局部纹理,解码器训练除逐像素 \(L_1/L_2\) 与感知(LPIPS)损失外,还叠加图块级判别器(PatchGAN)以确保清晰的高频纹理。
  3. 神经语音声码器:文本转语音流水线通常先预测梅尔频谱图(给出帧级频率幅度但丢弃相位),再由 HiFi-GAN (Kong 等 2020年) 等声码器将频谱图反演为音频波形。由于正弦波 \(\sin(\omega n + \vartheta)\) 在未知相位 \(\vartheta \sim \textrm{Uniform}[-a, a]\) 上的期望幅值衰减为 \(\sin(a)/a\)(当 \(\vartheta \sim \textrm{Uniform}[-\pi, \pi]\) 时彻底归零,见练习 5),直接波形回归会坍缩为静音;HiFi-GAN 改为将梅尔频谱图 \(L_1\) 损失和判别器激活上的特征匹配损失与多周期、多尺度波形判别器配对。

16.7.3 比较本章的对抗目标函数

表 16.7.1 从三个维度综合对比了本章研究的六种对抗表述:最优评判器估计什么、它如何对输入打分,以及评判器函数类如何正则化。

表 16.7.1: 本章分析的对抗目标函数汇总。
目标函数 最优评判器估计 打分规则 评判器约束 / 正则化 不相交支集上的表现(最优评判器处)
对数损失 / \(f\)-GAN(16.1 节、16.2 节) \(\log(p/q)\) 或 \(f'(p/q)\) 单样本分类 无约束 饱和
合页(16.2 节) \(\operatorname{sign}\log(p/q)\) 间隔分类 无约束(或谱归一化) 饱和(\(\kappa\)-Lipschitz 评判器下在 \(2/\kappa\) 内线性)
MMD(16.2 节) 核平滑的 \(p - q\)(见证函数) 均值之差 RKHS 单位球 核带宽 \(s\) 内梯度非零
Wasserstein-1(16.2 节) Kantorovich 势 均值之差 1-Lipschitz 球(如 WGAN-GP) 任意分离距离均为单位斜率
RpGAN(16.3 节) \(\log(p/q) + c\) 成对 Bradley–Terry 排序 无约束 饱和
R3GAN:RpGAN + \(R_1 + R_2\)(16.4 节) 尺度 \(2\sqrt{\gamma}\) 以下低通滤波的 \(\log(p/q)\) 成对 Bradley–Terry 排序 \(p\) 与 \(q\) 上的零中心输入梯度惩罚 带惩罚网络平滑插值跨越间隔

与迭代式扩散和流模型(第 17 章)相比,对抗生成器在欠定逆问题上提供单步推理与锐利输出,但也伴随四项固有挑战:(i)无法显式评估似然;(ii)耦合的双网络极小极大动力学需要精心调节梯度惩罚;(iii)对模式遗漏的内在惩罚偏弱(16.1.3.3 节);(iv)大规模训练时可能出现不稳定性 (Brock 等 2019年)。在下一章(第 17 章),我们将转向扩散模型与流匹配模型,以多步迭代去噪取代极小极大训练。

16.7.4 小结

最小化平方误差 \(\mathbb{E}[\|x - g(c)\|^2]\) 会将预测器推向条件均值 \(\mu(c) = \mathbb{E}[x \mid c]\)(式 16.7.1),只要目标 \(x\) 在给定 \(c\) 下存在歧义,它就会跨不同模式取平均。将预测器与估计 \(\log(p(x, c)/q(x, c))\) 的条件判别器 \(D(x, c)\) 配对,可惩罚落在模式间低密度走廊里的预测并迫使输出回到数据流形上,以至多两倍 MSE(\(3\text{ dB}\) PSNR)的代价换取感知逼真度 (Blau 和 Michaeli 2018年)。由于扩散去噪器同样计算后验均值 \(\mathbb{E}[x_0 \mid x_\tau]\),直接向高噪声去噪器回归来蒸馏单步生成器会把预测压缩回模糊平均,除非引入对抗评判器。出于同样的原因,对抗判别器依然是潜在图像自编码器、神经语音声码器与单步蒸馏扩散生成器的核心组件。

16.7.5 练习

  1. 理想采样器的感知–失真权衡。设 \(\hat x \sim p(x \mid c)\) 在给定 \(c\) 时与 \(x\) 独立抽取,使预测器精确匹配真实条件分布 \(p(x \mid c)\) (Blau 和 Michaeli 2018年)。
    1. 利用 式 16.7.1 证明 \(\mathbb{E}\big[(x - \hat x)^2\big] = 2\, \mathbb{E}\big[(x - \mu(c))^2\big]\)。精确采样器相对于条件均值 \(\mu(c)\) 会损失多少分贝的 PSNR(\(10 \log_{10}(x_{\max}^2 / \text{MSE})\))?
    2. 在双带分布 式 16.7.2 上,比较精确采样器、\(\mu(c) = c\)(\(1.0025\))与单带预测器 \(g(c) = c + 1\)(\(2.0025\))的期望平方误差。三者之中哪一个无法被最优评判器 \(D(x, c)\) 与真实数据区分开?
    3. 设 \(x \sim \mathcal{N}(0, 1)\) 且 \(c = x + \tau\xi\)(\(\xi \sim \mathcal{N}(0, 1)\) 独立)。证明确定性线性预测器 \(\hat x = c / \sqrt{1 + \tau^2}\) 匹配 \(x\) 的边缘分布 \(\mathcal{N}(0, 1)\),并计算 \(\tau \in \{0.1, 1, 10\}\) 时其 MSE 与条件均值 \(\mathbb{E}[x \mid c]\) 的 MSE 之比。
  2. [code] 条件均值对比条件中位数(\(L_2\) 对比 \(L_1\))。最小化绝对误差 \(\mathbb{E}[|x - g(c)|]\) 得到满足 \(P(x \leq x_{\textrm{med}}(c) \mid c) = \tfrac12\) 的条件中位数 \(x_{\textrm{med}}(c)\)。
    1. 若 式 16.7.2 中的偏移 \(b\) 以概率 \((\tfrac13, \tfrac13, \tfrac13)\) 或 \((\tfrac14, \tfrac14, \tfrac12)\) 取值 \((-1, 0, +1)\),分别求出两种情况下的条件均值与条件中位数,并判断各自是否落在数据带上。
    2. 在具有非对称先验 \(P(b = +1) = r\) 的双带问题上,求作为 \(r\) 函数的条件均值,证明当 \(r = \tfrac34\) 时条件中位数落在上带,并刻画 \(r = \tfrac12\) 时走廊 \(g(c) - c \in (-1, 1)\) 上的 \(L_1\) 风险。
    3. 在(a)与(b)的设定下用 \(L_1\) 损失训练 g_mse 的副本,并将学到的曲线与你的解析预测对比。
  3. [code] 加入二元潜在变量。● 为 16.7.1.2 节 中的学生增加独立的均匀二元潜变量 \(z \in \{-1, +1\}\) 使 \(\hat x = g(c, z)\),而评判器仍对 \((x, c)\) 样本对打分。
    1. 分别用平方误差与对抗方式各训练一个学生,检查 \(z = -1\) 与 \(z = +1\) 分别映射到哪条带。为何平方误差学生忽略了 \(z\)?
    2. 隐式最大似然估计(IMLE,Li 和 Malik (2018年))无需评判器,直接最小化 \(\mathbb{E}_{(c, x)}[\min_{z \in \{-1, +1\}} (g(c, z) - x)^2]\)。用该损失训练一个学生,并解释为何对每个数据点在 \(z\) 上取最小值会迫使两个潜在状态覆盖不同的数据带。
  4. 直接判别优化(DDO)。DDO (Zheng 等 2025年) 从 \(\theta = \theta_{\textrm{ref}}\) 出发,通过将评判器直接参数化为对数似然比 \(D_\theta(x) = \log(q_\theta(x) / q_{\textrm{ref}}(x))\),并最小化 logistic 判别器损失 \(J(\theta) = -\mathbb{E}_{x \sim p}[\log \sigma(D_\theta(x))] - \mathbb{E}_{x \sim q_{\textrm{ref}}}[\log \sigma(-D_\theta(x))]\),相对冻结参考副本 \(q_{\textrm{ref}}\) 微调似然模型 \(q_\theta\)。
    1. 证明若 \(q_\theta = p\),则 \(D_\theta(x)\) 等于 \(p\) 与 \(q_{\textrm{ref}}\) 之间的最优评判器 \(D^\star(x)\)。
    2. 利用 \(\mathbb{E}_{x \sim q_\theta}[\nabla_\theta \log q_\theta(x)] = 0\),证明在初始化(\(\theta = \theta_{\textrm{ref}}\),此时 \(D_\theta(x) = 0\))处,梯度 \(\nabla_\theta J(\theta)\) 等于负对数似然梯度 \(-\nabla_\theta \mathbb{E}_{x \sim p}[\log q_\theta(x)]\) 的 \(\tfrac12\) 倍。
  5. 语音声码器中的相位歧义与波形平均。将长度为 \(N\) 的单个音频帧建模为正弦波 \(x_n = \sin(\omega n + \vartheta)\)(\(n = 0, \ldots, N - 1\)),其中频率 \(\omega\) 由频谱图已知,相位 \(\vartheta \sim \textrm{Uniform}[-a, a]\)(\(0 < a \leq \pi\))未观测。
    1. 证明条件均值波形 \(\mathbb{E}_\vartheta[x_n] = \frac{\sin a}{a}\sin(\omega n)\) 的幅值衰减为 \(\frac{\sin a}{a}\)(当 \(a = \pi\) 时归零为静音)。
    2. 对 \(\omega = 2\pi k / N\)(\(0 < k < N/2\)),证明离散傅里叶变换幅度 \(|\hat x_m|\) 与 \(\vartheta\) 无关。
    3. 若两个相邻帧以独立相位 \(\vartheta_1 \neq \vartheta_2\) 生成,帧级 DFT 幅度损失在每一帧上均为零。帧边界处会出现何种伪影?为何时域波形判别器能够检测到它?

讨论