16.2  对抗目标函数与散度

大多数 GAN 实现都提供多种可互换的训练目标:非饱和 logistic 损失、最小二乘损失(LSGAN)、合页损失以及 Wasserstein 损失。16.1 节 分析了 logistic 目标,表明其最优判别器恢复对数密度比 \(\lambda(x) = \log(p(x)/q(x))\),极小极大值等于 Jensen–Shannon 散度——一个在 \(p\) 与 \(q\) 支集不再重叠时便发生饱和的量。其他目标函数分别度量什么散度?当生成样本远离数据时,梯度消失究竟源于损失函数、评判器架构,还是底层的散度?

这一族目标函数中的每一种,要么改变了施加在评判器输出上的打分函数,要么改变了评判器优化所用的函数类 \(\mathcal{T}\)。无约束评判器配合分类损失所计算的是 \(f\)-散度,它们仅依赖逐点密度比 \(p(x)/q(x)\)。相反,若将评判器限制在光滑函数类上并使用线性收益,则得到积分概率度量(IPM),例如最大均值差异(MMD)与 Wasserstein-1 距离(\(W_1\)),即便支集不相交,它们仍对空间距离保持敏感。下面我们推导这两类目标,并在分离的一维高斯分布与二维高斯混合分布上比较它们的表现。

# Deterministic GPU kernels; JAX reads XLA_FLAGS once, before the imports
import os
os.environ['XLA_FLAGS'] = (os.environ.get('XLA_FLAGS', '') +
                           ' --xla_gpu_deterministic_ops=true').strip()
from torch.nn.functional import relu, softplus
from jax.nn import relu, softplus

16.2.1 通用模板

在 16.1 节 中,评判器在真实样本 \(x \sim p\) 上获得 \(\log \sigma(D(x))\),在生成样本 \(x' \sim q\) 上获得 \(\log \sigma(-D(x'))\)。将这些对数似然项替换为定义在评判器函数类 \(\mathcal{T}\) 上的一般收益函数 \(\ell_p\) 与 \(\ell_q\),便得到通用对抗差异:

\[ \begin{aligned} d(p, q) &= \sup_{T \in \mathcal{T}} \Big\{ \mathbb{E}_{x \sim p}\big[\ell_p(T(x))\big] \\ &\qquad\qquad + \mathbb{E}_{x' \sim q}\big[\ell_q(T(x'))\big] \Big\}. \end{aligned} \tag{16.2.1}\]

取 \(\ell_p(t) = \log \sigma(t)\)、\(\ell_q(t) = \log \sigma(-t)\) 且 \(\mathcal{T}\) 无约束时,即恢复 \(2\,\mathrm{JS}(p, q) - 2\log 2\)。本节通篇采用评判器最大化期望收益之和的约定(等价于最小化负收益,称为评判器损失)。

表 16.2.1 按两个维度梳理了本章的目标函数:评判器是对单个样本打分还是对真伪样本对打分,以及评判器函数类 \(\mathcal{T}\) 是无约束还是带正则化的。

表 16.2.1: 按评判器输入与函数类约束划分的对抗目标分类。
无约束评判器 受约束或带惩罚评判器
单样本评判器 分类损失(logistic、最小二乘、合页)\(\to\) 关于 \(p/q\) 的 \(f\)-散度 RKHS 球(MMD)或 Lipschitz 球(\(W_1\))上的线性收益;带谱归一化的合页损失
成对评判器 相对配对损失(RpGAN,16.3 节) 带零中心梯度惩罚 \(R_1 + R_2\) 的配对损失(R3GAN,16.4 节、16.5 节)

注意,对任意固定评判器 \(T\),式 16.2.1 中的期望都是分布 \(q\) 的线性泛函。由于一族线性泛函的上确界是凸函数,固定 \(p\) 时 \(d(p, q)\) 关于概率测度 \(q\) 总是凸的。然而,由于神经网络 \(G_\theta\) 所参数化的分布集合 \(\{q_\theta\}\) 并非凸集,分布空间中的凸性并不意味着关于生成器参数 \(\theta\) 的凸性(练习 1)。

16.2.2 分类损失与 \(f\)-散度

16.2.2.1 二元结果示例

考虑二元结果空间(正面与反面),数据分布为 \(p = (\tfrac34, \tfrac14)\),生成器分布为 \(q = (\tfrac14, \tfrac34)\),两者以相等先验概率 \(\tfrac12\) 采样。给定观测结果,它来自 \(p\) 的贝叶斯后验概率为 \(\eta = p/(p + q)\),正面取 \(\tfrac34\),反面取 \(\tfrac14\)。盲猜(\(D = 0\))无论结果如何均预测 \(\tfrac12\)。观测结果带来的期望损失降幅取决于所用的分类损失:

  • 对数损失:最优预测 \(\eta\) 达到二元熵 \(H_b(\tfrac34) = 0.562\) 奈特,而盲猜为 \(\log 2 = 0.693\) 奈特,节省 \(0.131\text{ nats} = \mathrm{JS}(p, q)\)。
  • 概率上的平方误差:预测 \(\eta\) 的期望损失为 \(\tfrac34 \cdot \tfrac14 = \tfrac{3}{16}\),而预测 \(\tfrac12\) 为 \(\tfrac14\),节省 \(\tfrac{1}{16}\)。
  • 分数 \(t\) 上的合页损失:最优分数 \(t = +1\)(正面)与 \(t = -1\)(反面)的期望损失为 \(2 \cdot \tfrac14 = \tfrac12\),而 \(t = 0\) 为 \(1\),节省 \(\tfrac12 = \mathrm{TV}(p, q) = \tfrac12 \sum |p - q|\)。

每种损失都基于同一后验 \(\eta\),为同一对 \((p, q)\) 赋予了不同的非负散度。下面我们证明,每一种基于间隔的分类损失都定义一个 \(f\)-散度。

16.2.2.2 贝叶斯风险差

对称分类损失将同一个间隔收益 \(\ell\) 分别作用于真实样本的 \(D(x)\) 与生成样本的 \(-D(x')\)(\(\ell_p(t) = \ell(t)\),\(\ell_q(t) = \ell(-t)\)):

\[ V_\ell(D) \;=\; \mathbb{E}_{x \sim p}\big[\ell(D(x))\big] + \mathbb{E}_{x' \sim q}\big[\ell(-D(x'))\big]. \tag{16.2.2}\]

此处带符号分数 \(t\)(真实数据上为 \(+D(x)\),生成数据上为 \(-D(x')\))即为分类间隔。在每个点 \(x\) 处,有 \(p(x)\ell(t) + q(x)\ell(-t) = 2m(x)\big[\eta(x)\ell(t) + (1 - \eta(x))\ell(-t)\big]\),其中 \(m = (p+q)/2\) 且 \(\eta(x) = p(x)/(p(x)+q(x))\)。在后验 \(\eta\) 处的逐点最小期望损失称为条件贝叶斯风险:

\[ L(\eta) \;=\; \inf_{t} \Big\{ \eta \, \big({-\ell(t)}\big) + (1 - \eta)\, \big({-\ell(-t)}\big) \Big\}. \tag{16.2.3}\]

作为关于 \(\eta\) 的仿射函数族的下确界,\(L(\eta)\) 在 \([0, 1]\) 上是凹函数。常数评判器(\(t = 0\))的风险为 \(L(\tfrac12)\)。观测 \(x\) 所带来的风险降幅称为贝叶斯风险差:

\[ \Delta_\ell(p, q) \;=\; L(\tfrac12) - \mathbb{E}_{x \sim m}\big[L(\eta(x))\big], \tag{16.2.4}\]

它决定了最优值 \(\sup_D V_\ell(D) = 2\Delta_\ell(p, q) - 2L(\tfrac12)\)。由詹森不等式及 \(\mathbb{E}_m[\eta] = \tfrac12\),有 \(\Delta_\ell(p, q) \geq 0\)。

16.2.2.3 作为 \(f\)-散度的贝叶斯风险差

回顾 37.3.1.2 节,\(f\)-散度是在 \(q\) 下对密度比 \(\rho(x) = p(x)/q(x)\) 的凸函数 \(f\)(满足 \(f(1) = 0\))取平均:\(D_f(p \,\|\, q) = \mathbb{E}_{x \sim q}[f(\rho(x))]\)。

命题。若条件贝叶斯风险 \(L\) 在 \([0, 1]\) 上有限,则

\[ \begin{aligned} \Delta_\ell(p, q) &= D_f(p \,\|\, q) \\ \textrm{with}\quad f(u) &= L(\tfrac12) - \frac{u+1}{2}\, L\!\left(\frac{u}{u+1}\right), \end{aligned} \]

其中 \(f\) 在 \([0, \infty)\) 上为凸函数且满足 \(f(1) = 0\)。

证明。代入 \(u = \rho = p/q\) 得 \(m = q\,(u+1)/2\) 与 \(\eta = u/(u+1)\),于是

\[ \mathbb{E}_{x \sim m}\big[L(\eta(x))\big] = \int q \, \frac{u+1}{2}\, L\!\left(\frac{u}{u+1}\right), \]

将 \(L(\tfrac12) = \int q\, L(\tfrac12)\) 移入积分号内即得 \(\Delta_\ell(p, q) = \mathbb{E}_q[f(\rho)]\)。将凹函数 \(L(v) = \inf_j \{\alpha_j v + \beta_j\}\) 写为其切线的下包络,可见 \((u+1)L(u/(u+1)) = \inf_j \{\alpha_j u + \beta_j(u+1)\}\) 关于 \(u\) 为凹函数;因此 \(f(u)\) 为凸函数,且 \(f(1) = L(\tfrac12) - L(\tfrac12) = 0\)。\(\blacksquare\)

因此,任意搭配无约束评判器的对称分类损失都在计算某个 \(f\)-散度,且其最优评判器 \(D^\star(x)\) 是对数密度比 \(\lambda(x) = \log(p(x)/q(x))\) 的单调连接函数。

16.2.2.4 常见分类损失对应的散度

表 16.2.2 汇总了四种标准分类损失及其条件贝叶斯风险 \(L(\eta)\)、贝叶斯风险差 \(\Delta_\ell(p, q)\)、最优评判器连接 \(D^\star(\lambda)\) 以及配套的实用生成器损失。

表 16.2.2: 搭配无约束评判器的分类损失:间隔损失 \(-\ell(t)\)、贝叶斯风险 \(L(\eta)\)、贝叶斯风险差 \(\Delta_\ell(p, q)\)、最优评判器连接 \(D^\star(\lambda)\),以及作用于 \(D = D(x')\) 的实用生成器损失。
损失 间隔损失 \(-\ell(t)\) 贝叶斯风险 \(L(\eta)\) 风险差 \(\Delta_\ell(p,q)\) 最优评判器连接 生成器损失
logistic \(\log(1 + e^{-t})\) \(H_b(\eta)\) \(\mathrm{JS}(p,q)\) \(\lambda\) \(-\log \sigma(D)\)
最小二乘(LSGAN) \(\tfrac14 (1 - t)^2\),\(t = 2D - 1\) \(\eta(1-\eta)\) \(\tfrac{1}{8}\int \frac{(p-q)^2}{p+q}\) \(\sigma(\lambda)\) \(\tfrac12 (D - 1)^2\)
平方合页 \(\max(0, 1 - t)^2\) \(4\eta(1-\eta)\) \(\tfrac{1}{2}\int \frac{(p-q)^2}{p+q}\) \(\tanh(\lambda/2)\) \(-D\)
合页 \(\max(0, 1 - t)\) \(2\min(\eta, 1-\eta)\) \(\mathrm{TV}(p,q)\) \(\operatorname{sign} \lambda\) \(-D\)

在 LSGAN (Mao 等 2017年) 中,评判器回归到目标 \(1\)(真实)与 \(0\)(伪造),在 \(t = 2D - 1\) 下对应平方间隔损失 \(\tfrac14(1 - t)^2\),度量的是 Vincze–Le Cam 散度 \(\chi^2(p \,\|\, m) = \tfrac12 \int (p-q)^2/(p+q)\) 的四分之一。合页损失 (Lim 和 Ye 2017年) 度量全变差距离 \(\mathrm{TV}(p, q) = \tfrac12 \int |p - q|\),其最优评判器输出 \(\operatorname{sign} \lambda\)(在 \(\eta = \tfrac12\) 处,\([-1, 1]\) 内任意值均最优)。平方合页损失与合页损失共享相同的间隔和生成器目标 \(-D(x')\),但其平滑连接 \(\tanh(\lambda/2)\) 保留了 \(\lambda\) 的幅值信息。实践中,每种损失都采用与 \(q = p\) 共享同一平衡点的非饱和生成器目标(最后一列)。

16.2.2.5 Fenchel–Young 变分界(\(f\)-GAN)

由于 式 16.2.2 对 \(D\) 与 \(-D\) 施加相同的收益,其贝叶斯风险满足 \(L(\eta) = L(1 - \eta)\),从而每个分类风险差 \(\Delta_\ell(p, q)\) 关于 \(p\) 与 \(q\) 均对称且上界为 \(L(\tfrac12)\)(练习 5)。要触及非对称或无界的 \(f\)-散度(如前向 KL 散度 \(D_{\textrm{KL}}(p \,\|\, q)\)),就需要非对称收益 \(\ell_p \neq \ell_q\)。

设 \(f^*(t) = \sup_u \{ut - f(u)\}\) 为凸散度函数 \(f\) 的凸共轭。由 Fenchel–Young 不等式,对所有 \(u, t\) 有 \(f(u) \geq ut - f^*(t)\),等号在 \(t = f'(u)\) 时成立。令 \(u = \rho(x) = p(x)/q(x)\)、\(t = T(x)\) 并在 \(q\) 下取期望(利用 \(\mathbb{E}_q[\rho\, T] = \mathbb{E}_p[T]\)),即得 \(f\)-GAN (Nowozin 等 2016年) 的变分下界(37.3.4 节):

\[ D_f(p \,\|\, q) \;\geq\; \mathbb{E}_{x \sim p}\big[T(x)\big] - \mathbb{E}_{x' \sim q}\big[f^*(T(x'))\big]. \tag{16.2.5}\]

这恰好契合模板 式 16.2.1,其中 \(\ell_p(t) = t\)、\(\ell_q(t) = -f^*(t)\),且在最优评判器 \(T^\star(x) = f'(\rho(x))\) 处取紧(练习 2)。对前向 KL 散度,\(f(u) = u \log u\) 的凸共轭为 \(f^*(t) = e^{t-1}\),最优评判器为 \(T^\star(x) = 1 + \log \rho(x) = 1 + \lambda(x)\)。

16.2.2.6 实验验证评判器连接函数

现在我们验证在 logistic、最小二乘、合页与前向 KL 目标下训练的评判器是否各自学到了关于 \(\lambda(x)\) 的理论连接函数:\(\lambda\)、\(\sigma(\lambda)\)、\(\operatorname{sign} \lambda\) 与 \(1 + \lambda\)。我们将 \(p\) 定义为三个二维高斯的等权混合,并构造一个扰动后的三成分混合 \(q\),使 \(\lambda(x)\) 处处解析已知。

mu_p = np.array([[0.0, 2.4], [-2.1, -1.2], [2.1, -1.2]])     # data
A_p = np.stack([0.7 * np.eye(2)] * 3)

mu_q = np.array([[0.2, 2.6], [-2.3, -1.0], [2.0, -1.3]])     # hand-set q
A_q = np.stack([np.diag([0.8, 0.55]), np.diag([0.5, 0.6]),
                np.array([[0.65, 0.2], [-0.1, 0.7]])])


def mixture_logpdf(x, mus, As):
    """Log density of the uniform mixture of Gaussians N(mu_k, A_k^T A_k)."""
    comps = []
    for mu, A in zip(mus, As):
        Sigma, diff = A.T @ A, x - mu
        sol = np.linalg.solve(Sigma, diff.T).T
        comps.append(-0.5 * ((diff * sol).sum(1)
                             + np.linalg.slogdet(2 * np.pi * Sigma)[1]))
    return np.logaddexp.reduce(np.stack(comps) - np.log(len(mus)), axis=0)


def sample_mixture(n, mus, As, rng):
    """n draws from the uniform mixture of Gaussians mu_k + z A_k."""
    k = rng.integers(0, len(mus), n)
    z = rng.standard_normal((n, 2))
    return np.einsum('ni,nij->nj', z, As[k]) + mus[k]

mu_p = np.array([[0.0, 2.4], [-2.1, -1.2], [2.1, -1.2]])     # data
A_p = np.stack([0.7 * np.eye(2)] * 3)

mu_q = np.array([[0.2, 2.6], [-2.3, -1.0], [2.0, -1.3]])     # hand-set q
A_q = np.stack([np.diag([0.8, 0.55]), np.diag([0.5, 0.6]),
                np.array([[0.65, 0.2], [-0.1, 0.7]])])


def mixture_logpdf(x, mus, As):
    """Log density of the uniform mixture of Gaussians N(mu_k, A_k^T A_k)."""
    comps = []
    for mu, A in zip(mus, As):
        Sigma, diff = A.T @ A, x - mu
        sol = np.linalg.solve(Sigma, diff.T).T
        comps.append(-0.5 * ((diff * sol).sum(1)
                             + np.linalg.slogdet(2 * np.pi * Sigma)[1]))
    return np.logaddexp.reduce(np.stack(comps) - np.log(len(mus)), axis=0)


def sample_mixture(n, mus, As, rng):
    """n draws from the uniform mixture of Gaussians mu_k + z A_k."""
    k = rng.integers(0, len(mus), n)
    z = rng.standard_normal((n, 2))
    return np.einsum('ni,nij->nj', z, As[k]) + mus[k]

在固定网格上做数值积分即可求出任意此类混合分布 \(q\) 的 \(\mathrm{JS}(p, q)\)。本节后文也将用同一函数在每一步为训练中的生成器打分。

grid_1d = np.linspace(-7.0, 7.0, 281)
grid_2d = np.stack([g.ravel() for g in np.meshgrid(grid_1d, grid_1d)], axis=1)
cell_area = (grid_1d[1] - grid_1d[0]) ** 2


def js_mixtures(mus_q, As_q, mus_p=mu_p, As_p=A_p):
    """JS(p, q) between two known mixtures, p the data by default, by
    quadrature on grid_2d."""
    logp = mixture_logpdf(grid_2d, mus_p, As_p)
    logq = mixture_logpdf(grid_2d, mus_q, As_q)
    p, q = np.exp(logp), np.exp(logq)
    logm = np.log(np.maximum((p + q) / 2, 1e-300))
    return 0.5 * (p * (logp - logm) + q * (logq - logm)).sum() * cell_area

print(f'JS(p, q) for the hand-set q: {js_mixtures(mu_q, A_q):.3f} nats')
JS(p, q) for the hand-set q: 0.033 nats

grid_1d = np.linspace(-7.0, 7.0, 281)
grid_2d = np.stack([g.ravel() for g in np.meshgrid(grid_1d, grid_1d)], axis=1)
cell_area = (grid_1d[1] - grid_1d[0]) ** 2


def js_mixtures(mus_q, As_q, mus_p=mu_p, As_p=A_p):
    """JS(p, q) between two known mixtures, p the data by default, by
    quadrature on grid_2d."""
    logp = mixture_logpdf(grid_2d, mus_p, As_p)
    logq = mixture_logpdf(grid_2d, mus_q, As_q)
    p, q = np.exp(logp), np.exp(logq)
    logm = np.log(np.maximum((p + q) / 2, 1e-300))
    return 0.5 * (p * (logp - logm) + q * (logq - logm)).sum() * cell_area

print(f'JS(p, q) for the hand-set q: {js_mixtures(mu_q, A_q):.3f} nats')
JS(p, q) for the hand-set q: 0.033 nats

手工设定的 \(q\) 距数据仅有百分之几奈特,大致对应训练后期生成器面临的失配规模。评判器是一个小型 leaky-ReLU 网络,包含两个各 64 单元的隐藏层。

TRUNC_STD = 0.8796  # standard deviation of N(0, 1) truncated at +-2


def make_critic():
    """Leaky-ReLU MLP with LeCun-normal weights and zero biases."""
    D = nn.Sequential(nn.Linear(2, 64), nn.LeakyReLU(0.2),
                      nn.Linear(64, 64), nn.LeakyReLU(0.2), nn.Linear(64, 1))
    for layer in D[::2]:  # weight std 1/sqrt(fan_in) after truncation
        s = layer.in_features ** -0.5 / TRUNC_STD
        nn.init.trunc_normal_(layer.weight, std=s, a=-2 * s, b=2 * s)
        nn.init.zeros_(layer.bias)
    return D

def make_critic(rngs):
    """Leaky-ReLU MLP; nnx.Linear gives LeCun-normal weights, zero biases."""
    leaky = lambda x: nnx.leaky_relu(x, 0.2)
    return nnx.Sequential(nnx.Linear(2, 64, rngs=rngs), leaky,
                          nnx.Linear(64, 64, rngs=rngs), leaky,
                          nnx.Linear(64, 1, rngs=rngs))

每种损失都以二元组形式存储——即 表 16.2.2 中的评判器损失与生成器损失,二者均基于评判器对真实小批量的打分 r 与对生成小批量的打分 f 写出。

losses = {  # name: (critic loss, generator loss), both on the scores r, f
    'logistic': (lambda r, f: (softplus(-r) + softplus(f)).mean(),
                 lambda r, f: softplus(-f).mean()),
    'least squares': (lambda r, f: ((r - 1) ** 2 + f ** 2).mean() / 2,
                      lambda r, f: ((f - 1) ** 2).mean() / 2),
    'hinge': (lambda r, f: (relu(1 - r) + relu(1 + f)).mean(),
              lambda r, f: -f.mean()),
    'squared hinge': (lambda r, f: (relu(1 - r) ** 2 + relu(1 + f) ** 2).mean(),
                      lambda r, f: -f.mean()),
}
losses = {  # name: (critic loss, generator loss), both on the scores r, f
    'logistic': (lambda r, f: (softplus(-r) + softplus(f)).mean(),
                 lambda r, f: softplus(-f).mean()),
    'least squares': (lambda r, f: ((r - 1) ** 2 + f ** 2).mean() / 2,
                      lambda r, f: ((f - 1) ** 2).mean() / 2),
    'hinge': (lambda r, f: (relu(1 - r) + relu(1 + f)).mean(),
              lambda r, f: -f.mean()),
    'squared hinge': (lambda r, f: (relu(1 - r) ** 2 + relu(1 + f) ** 2).mean(),
                      lambda r, f: -f.mean()),
}

连接函数刻画的是面对固定 \(q\) 时的最优响应,因此我们针对手工设定的 \(q\),分别用上述三种损失从头训练新评判器,再用第四个评判器最大化前向 KL 下界 \(\mathbb{E}_p[T] - \mathbb{E}_q[e^{T-1}]\)。

to_t = lambda a: torch.tensor(a, dtype=torch.float32)

def best_response(critic_loss, seed=0, steps=3000, batch=512, lr=1e-3):
    """Fresh critic trained against the fixed q, as a NumPy function."""
    rng = np.random.default_rng(seed)
    torch.manual_seed(seed)
    D = make_critic()
    opt = torch.optim.Adam(D.parameters(), lr)
    for _ in range(steps):
        X = to_t(sample_mixture(batch, mu_p, A_p, rng))
        Y = to_t(sample_mixture(batch, mu_q, A_q, rng))
        opt.zero_grad()
        critic_loss(D(X), D(Y)).backward()
        opt.step()
    return lambda x: D(to_t(x)).squeeze(-1).detach().numpy()

kl_dual = lambda r, f: -(r.mean() - torch.exp(f - 1).mean())
critics = {name: best_response(losses[name][0])
           for name in ('logistic', 'least squares', 'hinge')}
critics['forward KL'] = best_response(kl_dual)
@nnx.jit(static_argnums=0)
def best_response_step(critic_loss, D, opt, X, Y):
    opt.update(D, nnx.grad(lambda D_: critic_loss(D_(X), D_(Y)))(D))

def best_response(critic_loss, seed=0, steps=3000, batch=512, lr=1e-3):
    """Fresh critic trained against the fixed q, as a NumPy function."""
    rng = np.random.default_rng(seed)
    D = make_critic(nnx.Rngs(seed))
    opt = nnx.Optimizer(D, optax.adam(lr), wrt=nnx.Param)
    for _ in range(steps):
        X = jnp.asarray(sample_mixture(batch, mu_p, A_p, rng), jnp.float32)
        Y = jnp.asarray(sample_mixture(batch, mu_q, A_q, rng), jnp.float32)
        best_response_step(critic_loss, D, opt, X, Y)
    return lambda x: np.asarray(D(jnp.asarray(x, jnp.float32))).squeeze(-1)

kl_dual = lambda r, f: -(r.mean() - jnp.exp(f - 1).mean())
critics = {name: best_response(losses[name][0])
           for name in ('logistic', 'least squares', 'hinge')}
critics['forward KL'] = best_response(kl_dual)

我们在来自 \(p\) 的 300 个点与来自 \(q\) 的 300 个点上评估每个训练好的评判器,将其输出对真实对数密度比 \(\lambda(x)\) 作图,并与理论连接函数(虚线)对照。

rng = np.random.default_rng(7)
pts = np.concatenate([sample_mixture(300, mu_p, A_p, rng),
                      sample_mixture(300, mu_q, A_q, rng)])
lam = mixture_logpdf(pts, mu_p, A_p) - mixture_logpdf(pts, mu_q, A_q)
lam_line = np.linspace(lam.min(), lam.max(), 200)
links = {'logistic': lambda l: l, 'least squares': lambda l: 1 / (1 + np.exp(-l)),
         'hinge': np.sign, 'forward KL': lambda l: 1 + l}
fig, axes = d2l.plt.subplots(1, 4, figsize=(12, 3))
for ax, (name, link) in zip(axes, links.items()):
    out = critics[name](pts)
    d2l.plot([lam[:300], lam[300:], lam_line],
             [out[:300], out[300:], link(lam_line)], xlabel=r'$\lambda$',
             fmts=('.', '.', 'k--'), axes=ax,
             legend=['x ~ p', "x' ~ q", 'link'] if name == 'logistic' else None)
    ax.set_title(name)
axes[0].set_ylabel('critic output')
fig.tight_layout()

四个网络全部紧贴各自预测的 \(\lambda(x)\) 理论连接:恒等映射 \(\lambda\)、sigmoid 函数 \(\sigma(\lambda)\)、阶跃函数 \(\operatorname{sign} \lambda\) 以及平移恒等映射 \(1 + \lambda\)。注意合页评判器在 \(\lambda = 0\) 附近的散点较宽,因为此处 \([-1, 1]\) 内的任意输出都能达到最小条件风险。

16.2.3 积分概率度量

\(f\)-散度将无约束评判器与非线性收益配对,而积分概率度量(IPM)则采用线性收益 \(\ell_p(t) = t\) 与 \(\ell_q(t) = -t\),并将评判器限制在对称函数类 \(\mathcal{F}\) 内(37.4.1 节):

\[ d_{\mathcal{F}}(p, q) \;=\; \sup_{T \in \mathcal{F}} \Big\{ \mathbb{E}_{x \sim p}\big[T(x)\big] - \mathbb{E}_{x' \sim q}\big[T(x')\big] \Big\}. \tag{16.2.6}\]

如果不对 \(\mathcal{F}\) 施加约束,只要 \(p \neq q\),将 \(T\) 乘以任意大正数就会让期望之差趋于 \(+\infty\)。当 \(\mathcal{F}\) 由光滑函数构成时,\(d_{\mathcal{F}}(p, q)\) 反映的是 \(\mathcal{X}\) 的空间几何,而不仅仅是逐点密度比 \(p(x)/q(x)\)。

16.2.3.1 最大均值差异(MMD)

给定正定核 \(k(x, x')\)——例如带宽为 \(s\) 的高斯 RBF 核 \(k(x, x') = \exp(-\|x - x'\|^2/(2s^2))\)——取 \(\mathcal{F}\) 为与 \(k\) 对应的再生核希尔伯特空间(RKHS)的单位球,即得最大均值差异 (Gretton 等 2012年)(37.4.1 节),其平方可用成对核期望闭式表示:

\[ \begin{aligned} \mathrm{MMD}^2(p, q) &= \mathbb{E}_{x, \tilde x \sim p}\big[k(x, \tilde x)\big] + \mathbb{E}_{x', \tilde x' \sim q}\big[k(x', \tilde x')\big] \\ &\quad - 2\, \mathbb{E}_{x \sim p,\, x' \sim q}\big[k(x, x')\big]. \end{aligned} \tag{16.2.7}\]

最优检验函数(在缩放意义下)为见证函数 \(w(x) = \mathbb{E}_{\tilde x \sim p}[k(x, \tilde x)] - \mathbb{E}_{\tilde x' \sim q}[k(x, \tilde x')]\),它度量某点对 \(p\) 与对 \(q\) 平均相似度之差。由于 式 16.2.7 无需评判器网络,生成器可以直接最小化无偏有限样本估计量 mmd2_unbiased(16.5 节 也用它计算 KID)。

def mmd2_unbiased(K_pp, K_qq, K_pq):
    """Unbiased MMD^2 from the kernel matrices within p, within q, and
    across; the diagonals (a point with itself) are left out."""
    m, n = len(K_pp), len(K_qq)
    return ((K_pp.sum() - K_pp.diagonal().sum()) / (m * (m - 1))
            + (K_qq.sum() - K_qq.diagonal().sum()) / (n * (n - 1))
            - 2 * K_pq.mean())

def mmd2_unbiased(K_pp, K_qq, K_pq):
    """Unbiased MMD^2 from the kernel matrices within p, within q, and
    across; the diagonals (a point with itself) are left out."""
    m, n = len(K_pp), len(K_qq)
    return ((K_pp.sum() - K_pp.diagonal().sum()) / (m * (m - 1))
            + (K_qq.sum() - K_qq.diagonal().sum()) / (n * (n - 1))
            - 2 * K_pq.mean())

16.2.3.2 Wasserstein-1 距离(\(W_1\))

取 \(\mathcal{F}\) 为 1-Lipschitz 函数类(对所有 \(x, y\) 满足 \(|T(x) - T(y)| \leq \|x - y\|\)),由 Kantorovich–Rubinstein 对偶(37.4.2 节)即得 Wasserstein-1(又称推土机)距离:

\[ W_1(p, q) \;=\; \inf_{\pi \in \Pi(p, q)} \mathbb{E}_{(x, x') \sim \pi}\big[\|x - x'\|\big], \]

其中 \(\Pi(p, q)\) 是边缘分布为 \(p\) 与 \(q\) 的联合传输方案集合。最优 1-Lipschitz 评判器(Kantorovich 势)沿从 \(q\) 到 \(p\) 的最优传输射线具有单位梯度范数。在一维情形下,\(W_1(p, q) = \int_{-\infty}^\infty |F_p(t) - F_q(t)|\,dt\),因此将分布平移 \(\mu\) 恰好给出 \(W_1(p, q) = |\mu|\),无论相距多远都保持恒定的单位斜率。

在高维空间中,Wasserstein GAN(WGAN)主要通过三种机制在神经网络评判器 \(T\) 上近似 1-Lipschitz 约束:

  1. 权重裁剪 (Arjovsky 等 2017年):将权重截断至 \([-c, c]\),以牺牲网络容量为代价强制满足某个依赖架构的常数 \(\kappa\) 下的 \(\kappa\)-Lipschitz 连续性。
  2. 梯度惩罚(WGAN-GP)(Gulrajani 等 2017年):在真实样本与生成样本之间的随机插值点 \(\tilde x = u x + (1-u)x'\) 处加入 \(\gamma\,\mathbb{E}[(\|\nabla_x T(\tilde x)\| - 1)^2]\)。
  3. 谱归一化 (Miyato 等 2018年):用每个权重矩阵的最大奇异值 \(\sigma_{\max}(W)\) 对其归一化,将每个线性层的 Lipschitz 常数限制在 \(1\) 以内。

注意合页损失架起了两类度量之间的桥梁:当 \(|D(x)| \leq 1\) 时其收益是线性的,因此无约束合页评判器对应受限于 \(|D(x)| \leq 1\) 的函数类上的 IPM(度量为 \(2\,\mathrm{TV}(p, q) - 2\))。将合页损失与谱归一化结合(使 \(D\) 同时有界且 \(\kappa\)-Lipschitz,如 SAGAN 与 BigGAN 所示),所得到的评判器在距离不超过 \(2/\kappa\) 时像 \(\kappa\,W_1\) 一样线性增长,超出后才饱和。

16.2.3.3 高维空间中的样本复杂度

固定核 MMD 与经验 \(W_1\) 在样本复杂度上差异显著:无偏 \(\mathrm{MMD}^2\) 估计量以与维度无关的速率 \(O(n^{-1/2})\) 收敛 (Gretton 等 2012年)(尽管在固定核下,给定偏移量对应的真实 \(\mathrm{MMD}^2\) 本身可能随维度升高而缩小 (Ramdas 等 2015年)),而在维度 \(d_x > 2\) 时,代入式经验 \(W_1\) 距离受维度灾难制约,收敛速率仅为 \(O(n^{-1/d_x})\) (Weed 和 Bach 2019年)。与此同时,当 \(\rho = p/q\) 较大时,变分 \(f\)-散度估计量可能出现极高方差:例如在前向 KL 对偶界中,\(e^{T^\star(x') - 1} = \rho(x')\) 在 \(q\) 下的方差等于 \(\chi^2(p \,\|\, q)\),即便 \(D_{\textrm{KL}}(p \,\|\, q) < \infty\) 也可能发散(练习 4)。

16.2.4 远离数据与靠近数据时的梯度

16.2.4.1 散度斜率与分离距离

为观察总体散度随两个分布分离的变化,考虑 \(p = \mathcal{N}(0, 1)\) 与 \(q = \mathcal{N}(\mu, 1)\) 关于分离距离 \(\mu > 0\) 的函数。此处 \(W_1(p, q) = \mu\) 具有恒定导数 \(1\),\(\mathrm{JS}(p, q)\) 可通过数值积分求得,而带宽为 \(s\) 的高斯 RBF 核下的 \(\mathrm{MMD}^2(p, q)\) 具有精确高斯积分:

\[ \mathrm{MMD}^2(p, q) \;=\; \frac{2s}{\sqrt{s^2 + 2}} \left( 1 - \exp\!\left( -\frac{\mu^2}{2(s^2 + 2)} \right) \right), \tag{16.2.8}\]

其关于 \(\mu\) 的导数在 \(\mu = \sqrt{s^2 + 2}\)(\(s = 4\) 时 \(\approx 4.2\))处达到峰值,随后按 \(e^{-\mu^2/(2(s^2+2))}\) 衰减。

xs = np.linspace(-10.0, 30.0, 8001)           # fixed quadrature grid

def normal_pdf(x, mu, sigma=1.0):
    return np.exp(-(x - mu) ** 2 / (2 * sigma ** 2)) / np.sqrt(
        2 * np.pi * sigma ** 2)

def js_gap(p, q):
    """log 2 - JS(p, q) on xs, accurate even when tiny: the integral of
    (p log(1 + q/p) + q log(1 + p/q)) / 2, with log(1 + e^a) computed as
    logaddexp(0, a)."""
    a = np.log(q) - np.log(p)
    return 0.5 * np.trapezoid(p * np.logaddexp(0, a) + q * np.logaddexp(0, -a),
                              xs)

def js_1d(p, q):
    return np.log(2) - js_gap(p, q)

s = 4.0                                        # RBF kernel bandwidth
mus = np.linspace(0.1, 20.0, 200)              # separations mu
gaps = np.array([js_gap(normal_pdf(xs, 0.0), normal_pdf(xs, mu))
                 for mu in mus])
mmd2 = 2 * s / np.sqrt(s ** 2 + 2) * (1 - np.exp(-mus ** 2
                                                 / (2 * (s ** 2 + 2))))
slopes = [-np.gradient(gaps, mus), np.gradient(mmd2, mus),
          np.ones_like(mus)]                   # W1 = |mu| has slope one
for mu in (1.0, 7.0, 20.0):
    js = js_1d(normal_pdf(xs, 0.0), normal_pdf(xs, mu))
    print(f'mu = {mu:2.0f}: JS slope {np.interp(mu, mus, slopes[0]):.4g}, '
          f'JS / log 2 = {js / np.log(2):.4f}, '
          f'MMD^2 slope {np.interp(mu, mus, slopes[1]):.4g}')
peak = slopes[1].argmax()
print(f'MMD^2 slope peaks at mu = {mus[peak]:.1f} with {slopes[1][peak]:.3f}')
d2l.plot(mus, slopes, xlabel=r'separation $\mu$', ylabel='slope',
         legend=['JS', 'MMD$^2$', '$W_1$'], yscale='log', figsize=(5, 3))
mu =  1: JS slope 0.1987, JS / log 2 = 0.1607, MMD^2 slope 0.1019
mu =  7: JS slope 0.001264, JS / log 2 = 0.9990, MMD^2 slope 0.188
mu = 20: JS slope 1.549e-22, JS / log 2 = 1.0000, MMD^2 slope 3.303e-05
MMD^2 slope peaks at mu = 4.2 with 0.269

xs = np.linspace(-10.0, 30.0, 8001)           # fixed quadrature grid

def normal_pdf(x, mu, sigma=1.0):
    return np.exp(-(x - mu) ** 2 / (2 * sigma ** 2)) / np.sqrt(
        2 * np.pi * sigma ** 2)

def js_gap(p, q):
    """log 2 - JS(p, q) on xs, accurate even when tiny: the integral of
    (p log(1 + q/p) + q log(1 + p/q)) / 2, with log(1 + e^a) computed as
    logaddexp(0, a)."""
    a = np.log(q) - np.log(p)
    return 0.5 * np.trapezoid(p * np.logaddexp(0, a) + q * np.logaddexp(0, -a),
                              xs)

def js_1d(p, q):
    return np.log(2) - js_gap(p, q)

s = 4.0                                        # RBF kernel bandwidth
mus = np.linspace(0.1, 20.0, 200)              # separations mu
gaps = np.array([js_gap(normal_pdf(xs, 0.0), normal_pdf(xs, mu))
                 for mu in mus])
mmd2 = 2 * s / np.sqrt(s ** 2 + 2) * (1 - np.exp(-mus ** 2
                                                 / (2 * (s ** 2 + 2))))
slopes = [-np.gradient(gaps, mus), np.gradient(mmd2, mus),
          np.ones_like(mus)]                   # W1 = |mu| has slope one
for mu in (1.0, 7.0, 20.0):
    js = js_1d(normal_pdf(xs, 0.0), normal_pdf(xs, mu))
    print(f'mu = {mu:2.0f}: JS slope {np.interp(mu, mus, slopes[0]):.4g}, '
          f'JS / log 2 = {js / np.log(2):.4f}, '
          f'MMD^2 slope {np.interp(mu, mus, slopes[1]):.4g}')
peak = slopes[1].argmax()
print(f'MMD^2 slope peaks at mu = {mus[peak]:.1f} with {slopes[1][peak]:.3f}')
d2l.plot(mus, slopes, xlabel=r'separation $\mu$', ylabel='slope',
         legend=['JS', 'MMD$^2$', '$W_1$'], yscale='log', figsize=(5, 3))
mu =  1: JS slope 0.1987, JS / log 2 = 0.1607, MMD^2 slope 0.1019
mu =  7: JS slope 0.001264, JS / log 2 = 0.9990, MMD^2 slope 0.188
mu = 20: JS slope 1.549e-22, JS / log 2 = 1.0000, MMD^2 slope 3.303e-05
MMD^2 slope peaks at mu = 4.2 with 0.269

如上图与 图 16.2.1 所示,\(\mathrm{JS}(p, q)\) 的导数到 \(\mu = 7\) 时已下降超过两个数量级(\(0.0013\) 对比 \(\mu = 1\) 时的 \(0.20\)),在 \(\mu = 20\) 时更是跌至 \(1.5 \times 10^{-22}\)。相比之下,\(W_1\) 在任意距离上都保持单位斜率,而 \(\mathrm{MMD}^2\) 在高达核带宽 \(s\) 量级的分离距离内都能维持强劲梯度。

图 16.2.1: 当 \(p\)(蓝)与 \(q\)(橙)支集不相交时的最优评判器。左:JS 最优评判器 \(\log(p/q)\) 在 \(\operatorname{supp}(p)\) 上取 \(+\infty\)、在 \(\operatorname{supp}(q)\) 上取 \(-\infty\),在两者上斜率均为零。中:\(W_1\) 的 Kantorovich 势是单位斜率的线性斜坡。右:MMD 见证函数 \(\mathbb{E}_p[k(x, \cdot)] - \mathbb{E}_q[k(x, \cdot)]\) 是核峰的光滑之差,其尾部朝向 \(p\) 倾斜。

16.2.4.2 从分离起点训练的评判器

理论散度曲线假定评判器在所有可测函数上达到最优。实践中,评判器是一个有限规模的神经网络,每步生成器更新前只训练寥寥数步。为检验训练中的评判器在远距离初始化下的表现,我们从 \(\theta_0 = 6\) 出发,用一维位置生成器 \(q_\theta = \mathcal{N}(\theta, 1)\)(\(x' = \theta + z\))去拟合 \(p = \mathcal{N}(0, 1)\);生成器采用朴素 SGD 更新 \(\theta\)(使步长直接反映梯度幅值),评判器为双隐藏层 ReLU 网络,每步生成器更新前更新 5 次。

def mmd2_loss(x, y, bandwidths=(0.5, 1.0, 2.0)):
    """Unbiased MMD^2 under the sum of RBF kernels of the given bandwidths."""
    def kernel(a, b):
        sq_dist = torch.cdist(a, b) ** 2
        return sum(torch.exp(-sq_dist / (2 * s ** 2)) for s in bandwidths)
    return mmd2_unbiased(kernel(x, x), kernel(y, y), kernel(x, y))

def mmd2_median(x, y):
    """MMD^2 with one RBF kernel, its bandwidth the median pairwise distance
    of the pooled batch, held constant in the gradient."""
    xy = torch.cat([x, y])
    return mmd2_loss(x, y, (torch.cdist(xy, xy).median().detach(),))


def gradient_penalty(D, X, fake, u, one_sided=False):
    """Mean (|D'(x)| - 1)^2 at the points u X + (1 - u) fake (inputs 1-D);
    one-sided, only slopes steeper than one pay: max(0, |D'(x)| - 1)^2."""
    x = (u * X + (1 - u) * fake).requires_grad_()
    grad, = torch.autograd.grad(D(x).sum(), x, create_graph=True)
    excess = grad.abs() - 1
    return ((excess.clamp(min=0) if one_sided else excess) ** 2).mean()
def mmd2_loss(x, y, bandwidths=(0.5, 1.0, 2.0)):
    """Unbiased MMD^2 under the sum of RBF kernels of the given bandwidths."""
    def kernel(a, b):
        sq_dist = ((a[:, None] - b[None]) ** 2).sum(-1)
        return sum(jnp.exp(-sq_dist / (2 * s ** 2)) for s in bandwidths)
    return mmd2_unbiased(kernel(x, x), kernel(y, y), kernel(x, y))

def mmd2_median(x, y):
    """MMD^2 with one RBF kernel, its bandwidth the median pairwise distance
    of the pooled batch, held constant in the gradient."""
    xy = jnp.concatenate([x, y])
    dist = jnp.sqrt(((xy[:, None] - xy[None]) ** 2).sum(-1))
    return mmd2_loss(x, y, (jax.lax.stop_gradient(jnp.median(dist)),))


def gradient_penalty(D, X, fake, u, one_sided=False):
    """Mean (|D'(x)| - 1)^2 at the points u X + (1 - u) fake (inputs 1-D);
    one-sided, only slopes steeper than one pay: max(0, |D'(x)| - 1)^2."""
    grad = jax.grad(lambda x: D(x).sum())(u * X + (1 - u) * fake)
    excess = jnp.abs(grad) - 1
    return ((jnp.maximum(excess, 0) if one_sided else excess) ** 2).mean()

train_shift 对每步生成器更新执行五步 Adam 评判器更新,使评判器保持在最优响应附近。生成器采用学习率为 \(0.01\) 的朴素梯度步:若用 Adam,每一步都会被缩放到接近学习率的量级,从而掩盖我们真正想观察的梯度大小。该函数记录每步的 \(\theta\) 与生成器梯度。正的 gp 向评判器损失中加入梯度惩罚,one_sided=True 仅惩罚大于 1 的斜率 \(\max(0, |T'| - 1)^2\);当 critic_loss 设为 None 时,生成器直接最小化两个小批量上的 gen_loss。

class Shift(nn.Module):
    """The generator x' = theta + z."""
    def __init__(self, theta0):
        super().__init__()
        self.theta = nn.Parameter(torch.tensor(theta0))

    def forward(self, z):
        return self.theta + z


def train_shift(critic_loss, gen_loss, seed, gp=0.0, one_sided=False,
                theta0=6.0, steps=1500, n_critic=5, batch=256, lr_D=1e-2,
                lr_G=1e-2):
    """Fit x' = theta + z to N(0, 1) by plain gradient steps on theta; return
    theta0 and theta after every step, the gradient of every step, and the
    critic."""
    rng = np.random.default_rng(seed)
    torch.manual_seed(seed)
    G, D = Shift(theta0), d2l.make_mlp([1, 32, 32, 1], nn.ReLU())
    opt_G = torch.optim.SGD(G.parameters(), lr_G)
    opt_D = torch.optim.Adam(D.parameters(), lr_D, betas=(0.5, 0.9))
    n = n_critic if critic_loss else 0
    thetas, grads = [theta0], []
    for _ in range(steps):
        X, Z = (to_t(rng.standard_normal((n + 1, batch, 1))) for _ in range(2))
        U = to_t(rng.uniform(size=(n, batch, 1)))   # interpolation weights
        for i in range(n):
            fake = G(Z[i]).detach()
            loss = critic_loss(D(X[i]), D(fake))
            if gp:
                loss = loss + gp * gradient_penalty(D, X[i], fake, U[i],
                                                    one_sided)
            opt_D.zero_grad()
            loss.backward()
            opt_D.step()
        fake = G(Z[-1])
        loss = (gen_loss(X[-1], fake) if critic_loss is None
                else gen_loss(D(X[-1]), D(fake)))
        opt_G.zero_grad()
        loss.backward()
        grads.append(G.theta.grad.item())
        opt_G.step()
        thetas.append(G.theta.item())
    return np.array(thetas), np.array(grads), D

class Shift(nnx.Module):
    """The generator x' = theta + z."""
    def __init__(self, theta0):
        self.theta = nnx.Param(jnp.array(theta0))

    def __call__(self, z):
        return self.theta + z


@nnx.jit(static_argnums=(0, 1, 2, 3))
def shift_step(critic_loss, gen_loss, gp, one_sided, G, D, opt_G, opt_D, X, Z,
               U):
    """One critic step per row of U, then one generator step; returns the
    generator's gradient."""
    for i in range(len(U)):
        fake = G(Z[i])
        def d_loss(D_):
            loss = critic_loss(D_(X[i]), D_(fake))
            if gp:
                loss = loss + gp * gradient_penalty(D_, X[i], fake, U[i],
                                                    one_sided)
            return loss
        opt_D.update(D, nnx.grad(d_loss)(D))
    def g_loss(G_):
        fake = G_(Z[-1])
        return (gen_loss(X[-1], fake) if critic_loss is None
                else gen_loss(D(X[-1]), D(fake)))
    grad = nnx.grad(g_loss)(G)
    opt_G.update(G, grad)
    return grad.theta[...]


def train_shift(critic_loss, gen_loss, seed, gp=0.0, one_sided=False,
                theta0=6.0, steps=1500, n_critic=5, batch=256, lr_D=1e-2,
                lr_G=1e-2):
    """Fit x' = theta + z to N(0, 1) by plain gradient steps on theta; return
    theta0 and theta after every step, the gradient of every step, and the
    critic."""
    rng = np.random.default_rng(seed)
    G = Shift(theta0)
    D = d2l.make_mlp([1, 32, 32, 1], nnx.relu, rngs=nnx.Rngs(seed))
    opt_G = nnx.Optimizer(G, optax.sgd(lr_G), wrt=nnx.Param)
    opt_D = nnx.Optimizer(D, optax.adam(lr_D, 0.5, 0.9), wrt=nnx.Param)
    n = n_critic if critic_loss else 0
    thetas, grads = [theta0], []
    for _ in range(steps):
        X, Z = (jnp.asarray(rng.standard_normal((n + 1, batch, 1)),
                            jnp.float32) for _ in range(2))
        U = jnp.asarray(rng.uniform(size=(n, batch, 1)), jnp.float32)
        grad = shift_step(critic_loss, gen_loss, gp, one_sided, G, D, opt_G,
                          opt_D, X, Z, U)
        grads.append(grad)                      # device scalars,
        thetas.append(G.theta[...])             # converted once below
    return np.asarray(jnp.stack(thetas)), np.asarray(jnp.stack(grads)), D

我们在三个随机种子上对比六种配置:饱和 logistic、非饱和 logistic、合页、WGAN-GP(\(\gamma = 10\),双侧惩罚 \((|T'| - 1)^2\))、单侧惩罚 \(\max(0, |T'| - 1)^2\) 的 WGAN-GP,以及中位数带宽 MMD。每次运行均报告前 100 步生成器梯度幅值的中位数、\(\theta\) 的轨迹、到达步数(首次满足 \(|\theta| < 0.5\) 的步数),以及到达后的最远偏离 \(\max |\theta|\)。

w1 = (lambda r, f: f.mean() - r.mean(), lambda r, f: -f.mean())
arms = {'logistic, sat.': (losses['logistic'][0],
                           lambda r, f: -softplus(f).mean(), {}),
        'logistic, NS': (*losses['logistic'], {}),
        'hinge': (*losses['hinge'], {}),
        'W1 + GP': (*w1, dict(gp=10.0)),
        'W1 + 1-sided GP': (*w1, dict(gp=10.0, one_sided=True)),
        'MMD, median': (None, mmd2_median, {})}
steps, w1_runs = (0, 100, 300, 1000, 1500), []  # (arm, seed, theta, critic)
print(f'{"":17s}|grad|   theta at steps {", ".join(map(str, steps))}'
      '  arrival  farthest')
for name, (critic_loss, gen_loss, kwargs) in arms.items():
    for seed in range(3):
        thetas, grads, D = train_shift(critic_loss, gen_loss, seed, **kwargs)
        if name.startswith('W1'):
            w1_runs.append((name, seed, thetas[-1], D))
        hit = np.flatnonzero(np.abs(thetas) < 0.5)  # arrival: hit[0]
        print(f'{name:16s}{seed}{np.median(np.abs(grads[:100])):7.3f} '
              + ''.join(f'{thetas[t]:7.2f}' for t in steps)
              + (f'{hit[0]:9d}{np.abs(thetas[hit[0]:]).max():10.2f}'
                 if len(hit) else '  not reached'))
                 |grad|   theta at steps 0, 100, 300, 1000, 1500  arrival  farthest
logistic, sat.  0  0.007    6.00   5.99   5.96   5.85   5.77  not reached
logistic, sat.  1  0.009    6.00   5.98   5.95   5.85   5.76  not reached
logistic, sat.  2  0.015    6.00   5.98   5.96   5.85   5.77  not reached
logistic, NS    0  2.812    6.00   3.30   0.79   0.03   0.00      383      0.50
logistic, NS    1  2.876    6.00   3.26   0.78   0.02   0.00      380      0.50
logistic, NS    2  2.730    6.00   3.35   0.80   0.02   0.00      388      0.50
hinge           0  1.451    6.00   4.64   3.31   0.02   0.04      812      0.49
hinge           1  1.558    6.00   4.50   3.50   0.00  -0.04      874      0.50
hinge           2  1.278    6.00   4.81   3.51  -0.06  -0.00      918      0.50
W1 + GP         0  1.262    6.00   4.74   2.39   0.30   0.30      477      1.48
W1 + GP         1  1.263    6.00   4.89   2.52  -4.13  -7.18      487      7.49
W1 + GP         2  1.252    6.00   4.97   2.60  -4.08  -7.61      495      7.61
W1 + 1-sided GP 0  1.265    6.00   4.75   2.40   0.01   0.02      478      0.49
W1 + 1-sided GP 1  1.262    6.00   4.74   2.39  -0.01   0.03      477      0.49
W1 + 1-sided GP 2  1.265    6.00   4.74   2.40   0.02  -0.05      477      0.50
MMD, median     0  0.210    6.00   5.79   5.34   3.34   1.32  not reached
MMD, median     1  0.210    6.00   5.79   5.34   3.34   1.32  not reached
MMD, median     2  0.210    6.00   5.79   5.34   3.35   1.32  not reached
w1 = (lambda r, f: f.mean() - r.mean(), lambda r, f: -f.mean())
arms = {'logistic, sat.': (losses['logistic'][0],
                           lambda r, f: -softplus(f).mean(), {}),
        'logistic, NS': (*losses['logistic'], {}),
        'hinge': (*losses['hinge'], {}),
        'W1 + GP': (*w1, dict(gp=10.0)),
        'W1 + 1-sided GP': (*w1, dict(gp=10.0, one_sided=True)),
        'MMD, median': (None, mmd2_median, {})}
steps, w1_runs = (0, 100, 300, 1000, 1500), []  # (arm, seed, theta, critic)
print(f'{"":17s}|grad|   theta at steps {", ".join(map(str, steps))}'
      '  arrival  farthest')
for name, (critic_loss, gen_loss, kwargs) in arms.items():
    for seed in range(3):
        thetas, grads, D = train_shift(critic_loss, gen_loss, seed, **kwargs)
        if name.startswith('W1'):
            w1_runs.append((name, seed, thetas[-1], D))
        hit = np.flatnonzero(np.abs(thetas) < 0.5)  # arrival: hit[0]
        print(f'{name:16s}{seed}{np.median(np.abs(grads[:100])):7.3f} '
              + ''.join(f'{thetas[t]:7.2f}' for t in steps)
              + (f'{hit[0]:9d}{np.abs(thetas[hit[0]:]).max():10.2f}'
                 if len(hit) else '  not reached'))
                 |grad|   theta at steps 0, 100, 300, 1000, 1500  arrival  farthest
logistic, sat.  0  0.006    6.00   5.99   5.96   5.85   5.76  not reached
logistic, sat.  1  0.009    6.00   5.98   5.95   5.85   5.75  not reached
logistic, sat.  2  0.013    6.00   5.98   5.96   5.85   5.77  not reached
logistic, NS    0  2.819    6.00   3.27   0.78   0.03   0.00      381      0.50
logistic, NS    1  2.724    6.00   3.42   0.81   0.02   0.00      387      0.50
logistic, NS    2  2.896    6.00   3.14   0.76   0.02   0.01      378      0.50
hinge           0  1.633    6.00   4.48   3.22   0.00   0.04      748      0.50
hinge           1  1.071    6.00   4.98   3.59   0.06   0.04      938      0.49
hinge           2  1.485    6.00   4.57   3.21   0.01  -0.02      743      0.50
W1 + GP         0  1.254    6.00   5.13   2.74  -1.13  -1.13      508      1.13
W1 + GP         1  1.256    6.00   4.96   2.59  -4.08  -7.30      494      7.47
W1 + GP         2  1.259    6.00   4.74   2.39  -1.22  -1.22      477      1.22
W1 + 1-sided GP 0  1.257    6.00   4.75   2.40  -0.06  -0.06      479      0.49
W1 + 1-sided GP 1  1.262    6.00   4.74   2.39  -0.00   0.01      476      0.50
W1 + 1-sided GP 2  1.265    6.00   4.74   2.39  -0.00  -0.02      476      0.50
MMD, median     0  0.210    6.00   5.79   5.34   3.34   1.32  not reached
MMD, median     1  0.210    6.00   5.79   5.34   3.34   1.32  not reached
MMD, median     2  0.210    6.00   5.79   5.34   3.35   1.32  not reached

实验结果清楚揭示了实用神经评判器与无约束理论最优解之间的差异:

  • 饱和与非饱和 logistic:与 16.1 节 一致,饱和生成器梯度极小(\(\sim 0.01\)),\(\theta\) 几乎纹丝不动(仅从 \(6.0\) 移至 \(5.76\));而非饱和生成器获得强劲梯度(\(\sim 3\)),在 400 步之前便抵达目标。
  • 合页评判器:尽管理论最优合页评判器 \(\operatorname{sign} \lambda\) 在两个点云内部斜率均为零,有限 ReLU MLP 却以 \(1.1\text{--}1.7\) 的斜率平滑跨越空白间隔,在 \(700\text{--}950\) 步将生成器推向目标。
  • 中位数带宽 MMD:除饱和组外,这是唯一在 1,500 步时仍未到达的一组(此时 \(\theta \approx 1.3\))。这里的生成器推进较慢,但并未停滞。由于中位数启发式使带宽始终与分离距离同量级,梯度从未消失;不过其幅值 \(\sim 0.2\) 约为下一项 \(W_1\) 评判器斜率的六分之一,因此步长 \(0.01\) 的朴素梯度步相应需要更多步数。
  • 双侧与单侧 WGAN-GP:两组 \(W_1\) 都以 \(\approx 1.26\) 的斜率将生成器向内拉动(最小化 \(-ad + 10(a-1)^2\) 得 \(a = 1 + d/20\)),并在约 500 步时到达。然而到达之后,每一次双侧 W1 + GP 运行都出现剧烈过冲(farthest \(> 1\),甚至达 \(> 7\)),而单侧运行从未偏离超过到达点(farthest \(\le 0.5\)),到 1,000 步时全部落在原点 \(0.06\) 以内。原因何在?一旦 \(\theta\) 跨过 \(0\),评判器必须将斜率从负反转为正。由于双侧惩罚 \((|T'| - 1)^2\) 对平坦评判器(\(T' = 0\))施加高达 \(\gamma\) 的惩罚,它在零斜率处制造了一道势垒,把评判器困在旧斜率符号上(\(1 - d/20\))或导致所有 ReLU 单元失活,正如我们在下方第 1,500 步检查评判器斜率与活跃 ReLU 数目时所证实的:
def slope_and_units(D, x):
    """D'(x) and, per hidden layer, the number of ReLU units active at x."""
    x = h = torch.tensor([[x]], dtype=torch.float32, requires_grad=True)
    active = []
    for layer in D:
        h = layer(h)
        if isinstance(layer, nn.ReLU):
            active.append(int((h > 0).sum()))
    slope, = torch.autograd.grad(h.sum(), x)
    return slope.item(), active

print(f"{'':19s}theta D'(theta)  active    D'(0)  active"
      '  (of 32 units per layer)')
for name, seed, theta, D in w1_runs:
    (s_t, a_t), (s_0, a_0) = (slope_and_units(D, x) for x in (theta, 0.0))
    print(f'{name:16s}{seed}{theta:7.2f}{s_t:10.2f}{a_t[0]:5d}{a_t[1]:3d}'
          f'{s_0:9.2f}{a_0[0]:5d}{a_0[1]:3d}')
                   theta D'(theta)  active    D'(0)  active  (of 32 units per layer)
W1 + GP         0   0.30      0.00   14  0     0.00   14  0
W1 + GP         1  -7.18      1.34   11  8     1.35   12  9
W1 + GP         2  -7.61     -0.65   12  7    -0.65   12  7
W1 + 1-sided GP 0   0.02      0.41   30  3     0.41   30  3
W1 + 1-sided GP 1   0.03      0.65   25  4     0.65   25  4
W1 + 1-sided GP 2  -0.05     -0.16   30  7    -0.16   30  7
def slope_and_units(D, x):
    """D'(x) and, per hidden layer, the number of ReLU units active at x."""
    def forward(x):
        h, active = x, []
        for layer in D.layers:
            h = layer(h)
            if not isinstance(layer, nnx.Linear):  # an activation
                active.append((h > 0).sum())
        return h.sum(), active
    slope, active = jax.grad(forward, has_aux=True)(jnp.array([[x]]))
    return float(slope.squeeze()), [int(a) for a in active]

print(f"{'':19s}theta D'(theta)  active    D'(0)  active"
      '  (of 32 units per layer)')
for name, seed, theta, D in w1_runs:
    (s_t, a_t), (s_0, a_0) = (slope_and_units(D, x) for x in (theta, 0.0))
    print(f'{name:16s}{seed}{theta:7.2f}{s_t:10.2f}{a_t[0]:5d}{a_t[1]:3d}'
          f'{s_0:9.2f}{a_0[0]:5d}{a_0[1]:3d}')
                   theta D'(theta)  active    D'(0)  active  (of 32 units per layer)
W1 + GP         0  -1.13      0.00    6  0     0.00    9  0
W1 + GP         1  -7.30      1.33   16  2     1.44   17  2
W1 + GP         2  -1.22      0.00   26  0     0.00   29  0
W1 + 1-sided GP 0  -0.06      0.00   32  0     0.00   32  0
W1 + 1-sided GP 1   0.01      0.56   30  4     0.56   30  4
W1 + 1-sided GP 2  -0.02      0.47   32  7     0.47   32  7

单侧惩罚 \(\max(0, |T'| - 1)^2\) 在 \(|T'| \leq 1\) 时不施加任何惩罚,允许评判器在 \(\theta\) 抵达数据时自由穿过零斜率。16.4 节 将进一步分析在平衡点处主动把评判器斜率拉向零的零中心惩罚(\(R_1\) 与 \(R_2\))。

16.2.4.3 在二维高斯混合上对比五种目标函数

接下来,我们在生成器与数据支集重叠的情形下对比五种目标:非饱和 logistic、最小二乘、合页、平方合页以及多带宽 MMD(\(s \in \{0.5, 1.0, 2.0\}\))。生成器 MixtureGenerator 参数化一个三成分高斯混合,初始均值偏移为 mu_0,初始尺度较窄 A_0 = 0.4 * I(\(\mathrm{JS}(p, q_0) \approx 0.53\) 奈特)。

mu_0 = np.array([[1.0, -1.0], [-4.3, -2.0], [-1.0, 3.8]])  # off the modes
A_0 = np.stack([0.4 * np.eye(2)] * 3)      # below the data's scale of 0.7

print(f'JS(p, q) at the start: {js_mixtures(mu_0, A_0):.3f} nats')
JS(p, q) at the start: 0.529 nats

mu_0 = np.array([[1.0, -1.0], [-4.3, -2.0], [-1.0, 3.8]])  # off the modes
A_0 = np.stack([0.4 * np.eye(2)] * 3)      # below the data's scale of 0.7

print(f'JS(p, q) at the start: {js_mixtures(mu_0, A_0):.3f} nats')
JS(p, q) at the start: 0.529 nats

初始分布距数据约半奈特。MMD 组在带宽为 \(0.5\)、\(1\) 和 \(2\) 的三个 RBF 核之和下最小化无偏小批量 \(\mathrm{MMD}^2\),从而在多个尺度上都保持敏感。

class MixtureGenerator(nn.Module):
    """x = mu_k + z A_k for a uniformly drawn component k."""
    def __init__(self, mu, A):
        super().__init__()
        self.mu = nn.Parameter(to_t(mu))
        self.A = nn.Parameter(to_t(A))

    def forward(self, z, k):
        return torch.einsum('ni,nij->nj', z, self.A[k]) + self.mu[k]

    def params_np(self):
        return (self.mu.detach().numpy().copy(),
                self.A.detach().numpy().copy())

losses['MMD'] = (None, mmd2_loss)   # no critic: MMD^2 to the real batch

class MixtureGenerator(nnx.Module):
    """x = mu_k + z A_k for a uniformly drawn component k."""
    def __init__(self, mu, A):
        self.mu = nnx.Param(jnp.asarray(mu, jnp.float32))
        self.A = nnx.Param(jnp.asarray(A, jnp.float32))

    def __call__(self, z, k):
        return jnp.einsum('ni,nij->nj', z, self.A[k]) + self.mu[k]

    def params_np(self):
        return np.asarray(self.mu[...]), np.asarray(self.A[...])

losses['MMD'] = (None, mmd2_loss)   # no critic: MMD^2 to the real batch

train_toy 接收两个损失函数作为参数,交替执行一步评判器更新与一步生成器更新。评判器损失设为 None 的 MMD 组仅执行生成器步,直接作用于 mmd2_loss(X, fake) 而非评判器打分。每隔 200 步记录一次精确的 \(\mathrm{JS}(p, q_t)\)。

def train_toy(critic_loss, gen_loss, seed=0, steps=6000, batch=256, lr=1e-3):
    """Fit a MixtureGenerator from (mu_0, A_0) to the data mixture, one
    critic step per generator step. The losses act on the critic's scores of
    the real and generated batch; with critic_loss None, gen_loss acts on the
    two batches. Returns the exact JS(p, q_t) every 200 steps."""
    rng = np.random.default_rng(seed)
    torch.manual_seed(seed)
    G, D = MixtureGenerator(mu_0, A_0), make_critic()
    opt_G = torch.optim.Adam(G.parameters(), lr)
    opt_D = torch.optim.Adam(D.parameters(), 2 * lr)
    trace = []
    for t in range(steps):
        X = to_t(sample_mixture(batch, mu_p, A_p, rng))
        z = to_t(rng.standard_normal((batch, 2)))
        k = torch.tensor(rng.integers(0, 3, batch))
        if critic_loss is not None:
            opt_D.zero_grad()
            critic_loss(D(X), D(G(z, k).detach())).backward()
            opt_D.step()
        opt_G.zero_grad()
        fake = G(z, k)
        loss = (gen_loss(X, fake) if critic_loss is None
                else gen_loss(D(X), D(fake)))
        loss.backward()
        opt_G.step()
        if t % 200 == 0:
            trace.append(js_mixtures(*G.params_np()))
    return np.array(trace)

@nnx.jit(static_argnums=(0, 1))
def train_toy_step(critic_loss, gen_loss, G, D, opt_G, opt_D, X, z, k):
    """A critic step (unless critic_loss is None), then a generator step."""
    if critic_loss is not None:            # the generator is fixed here
        fake = G(z, k)
        opt_D.update(D, nnx.grad(lambda D_: critic_loss(D_(X), D_(fake)))(D))
    def g_loss(G_):
        fake = G_(z, k)
        return (gen_loss(X, fake) if critic_loss is None
                else gen_loss(D(X), D(fake)))
    opt_G.update(G, nnx.grad(g_loss)(G))


def train_toy(critic_loss, gen_loss, seed=0, steps=6000, batch=256, lr=1e-3):
    """Fit a MixtureGenerator from (mu_0, A_0) to the data mixture, one
    critic step per generator step. The losses act on the critic's scores of
    the real and generated batch; with critic_loss None, gen_loss acts on the
    two batches. Returns the exact JS(p, q_t) every 200 steps."""
    rng = np.random.default_rng(seed)
    G, D = MixtureGenerator(mu_0, A_0), make_critic(nnx.Rngs(seed))
    opt_G = nnx.Optimizer(G, optax.adam(lr), wrt=nnx.Param)
    opt_D = nnx.Optimizer(D, optax.adam(2 * lr), wrt=nnx.Param)
    trace = []
    for t in range(steps):
        X = jnp.asarray(sample_mixture(batch, mu_p, A_p, rng), jnp.float32)
        z = jnp.asarray(rng.standard_normal((batch, 2)), jnp.float32)
        k = jnp.asarray(rng.integers(0, 3, batch))
        train_toy_step(critic_loss, gen_loss, G, D, opt_G, opt_D, X, z, k)
        if t % 200 == 0:
            trace.append(js_mixtures(*G.params_np()))
    return np.array(trace)

对每种目标的三个随机种子,我们报告最后 2,000 步内 \(\mathrm{JS}(p, q_t)\) 的中位数,以及首次达到 \(\mathrm{JS}(p, q_t) < 0.1\) 与 \(< 0.01\) 奈特的步数。

def first_below(trace, level):
    """First recorded step (one record per 200 steps) with JS below level."""
    hits = np.flatnonzero(trace < level)
    return f'{200 * hits[0]:6d}' if len(hits) else '   n/a'

runs = {name: [train_toy(*pair, seed=seed) for seed in range(3)]
        for name, pair in losses.items()}
print(f'{"three runs:":14s}{"median JS, last 2,000 steps":>27s}'
      f'{"first JS < 0.1":>21s}{"first JS < 0.01":>21s}')
for name, traces in runs.items():
    medians = [np.median(trace[-2000 // 200:]) for trace in traces]
    print(f'{name:14s}   ' + ''.join(f'{m:8.4f}' for m in medians)
          + '   ' + ''.join(first_below(trace, 0.1) for trace in traces)
          + '   ' + ''.join(first_below(trace, 0.01) for trace in traces))
d2l.plot(np.arange(len(runs['logistic'][0])) * 200,
         [traces[0] for traces in runs.values()], xlabel='step',
         ylabel='JS(p, q_t)', yscale='log', legend=list(runs), figsize=(5, 3))
three runs:   median JS, last 2,000 steps       first JS < 0.1      first JS < 0.01
logistic           0.0008  0.0008  0.0008     2000  2000  2200     2400  2400  2400
least squares      0.0009  0.0009  0.0008     2000  2200  1800     2200  2400  2200
hinge              0.0070  0.0071  0.0033     1800  1800  1400     2000  2000  2400
squared hinge      0.0013  0.0008  0.0024     1400  1400  1400     2200  2200  2200
MMD                0.0001  0.0001  0.0001     1200  1200  1200     2600  2600  2600

def first_below(trace, level):
    """First recorded step (one record per 200 steps) with JS below level."""
    hits = np.flatnonzero(trace < level)
    return f'{200 * hits[0]:6d}' if len(hits) else '   n/a'

runs = {name: [train_toy(*pair, seed=seed) for seed in range(3)]
        for name, pair in losses.items()}
print(f'{"three runs:":14s}{"median JS, last 2,000 steps":>27s}'
      f'{"first JS < 0.1":>21s}{"first JS < 0.01":>21s}')
for name, traces in runs.items():
    medians = [np.median(trace[-2000 // 200:]) for trace in traces]
    print(f'{name:14s}   ' + ''.join(f'{m:8.4f}' for m in medians)
          + '   ' + ''.join(first_below(trace, 0.1) for trace in traces)
          + '   ' + ''.join(first_below(trace, 0.01) for trace in traces))
d2l.plot(np.arange(len(runs['logistic'][0])) * 200,
         [traces[0] for traces in runs.values()], xlabel='step',
         ylabel='JS(p, q_t)', yscale='log', legend=list(runs), figsize=(5, 3))
three runs:   median JS, last 2,000 steps       first JS < 0.1      first JS < 0.01
logistic           0.0011  0.0008  0.0019     2200  2200  1800     2400  2400  2400
least squares      0.0010  0.0007  0.0006     2200  2000  1800     2400  2200  2000
hinge              0.0069  0.0036  0.0064     1400  1400  1800     2000  2200  2000
squared hinge      0.0012  0.0007  0.0009     1400  1400  1200     2000  2000  2400
MMD                0.0001  0.0001  0.0001     1200  1200  1200     2600  2600  2600

五种目标全部将 \(\mathrm{JS}(p, q_t)\) 从 \(0.53\) 奈特降至千分之几奈特乃至更低。无需跟踪移动评判器的直接 MMD 最小化取得了最紧的最终拟合(\(0.0001\) 奈特),而合页损失的稳态略高(\(0.003\text{--}0.007\) 奈特),高于平滑连接目标(logistic、最小二乘与平方合页均 \(\leq 0.0024\) 奈特;练习 3)。接下来,16.3 节 将考察成对比较真实样本与生成样本、而非孤立打分的评判器。

16.2.5 小结

每一种单样本对抗目标都是在评判器函数类 \(\mathcal{T}\) 上对期望收益取上确界(式 16.2.1),因而虽然关于生成器参数 \(\theta\) 仍然非凸,关于分布 \(q\) 却是凸的。当评判器无约束时,对称间隔分类损失度量由其贝叶斯风险差 \(\Delta_\ell(p, q)\) 决定的 \(f\)-散度(表 16.2.2),最优评判器输出 \(\lambda = \log(p/q)\) 的单调连接函数;而 Fenchel–Young 变分界(式 16.2.5)则将这一对偶推广至非对称 \(f\)-散度。若将非线性收益替换为受约束函数类 \(\mathcal{F}\) 上的线性期望,则定义积分概率度量,典型代表是 RKHS 单位球上的最大均值差异与 1-Lipschitz 函数类上的 Wasserstein-1 距离。当支集分离时,\(f\)-散度会饱和,而 \(W_1\) 保持单位斜率、\(\mathrm{MMD}^2\) 在核带宽范围内仍提供有效梯度;在实践中,只要搭配非饱和生成器损失,有限神经评判器便能平滑插值跨越间隔。

16.2.6 练习

  1. [code] 分布空间与参数空间中的凸性。每个形如 式 16.2.1 的目标函数关于 \(q\) 均为凸函数,但参数化生成器调整的是 \(\theta\) 而非直接调整 \(q\)。使用 normal_pdf、js_1d 与 xs 完成以下任务。

    1. 令 \(p = \mathcal{N}(0, 1)\) 与 \(q_0 = \mathcal{N}(8, 1)\)。通过二阶差分验证沿线性混合路径 \(q_t = (1 - t)\, q_0 + t\, p\),\(\mathrm{JS}(p, q_t)\) 关于 \(t \in [0, 1]\) 是凸函数。
    2. 现令 \(p = 0.7\, \mathcal{N}(-4, 1) + 0.3\, \mathcal{N}(4, 1)\) 与 \(q_\theta = \mathcal{N}(\theta, 1)\)。绘制 \(\theta \in [-6, 6]\) 上的 \(\mathrm{JS}(p, q_\theta)\),并指出其局部极小值与局部极大值。
    3. 为何关于 \(\theta\) 的这些非凸特征并不与关于 \(q\) 的凸性矛盾?
  2. Jensen–Shannon 凸共轭。两倍 Jensen–Shannon 散度对应散度函数 \(f(u) = u \log u - (u + 1) \log \frac{u + 1}{2}\)。

    1. 推导其凸共轭 \(f^*(t) = -\log(2 - e^t)\),定义域为 \(t < \log 2\)。
    2. 证明在重参数化 \(T(x) = \log(2 \sigma(D(x)))\) 下,最优评判器 \(T^\star = f'(\rho)\) 对应 \(D^\star = \lambda\),且变分界 式 16.2.5 化为 \(2 \log 2 + V(D)\),其中 \(V(D)\) 是 16.1 节 中的经典对数损失 GAN 目标。
  3. [code] 高斯混合上的生成器权重与评判器滞后。● 使用 16.2.4.3 节 中的 train_toy 与五种目标函数。

    1. 将 logistic 评判器损失与线性生成器损失 \(-D(x')\)(权重 \(w = 1\))配对,并在三个随机种子上按首次达到 \(\mathrm{JS}(p, q_t) < 0.1\) 奈特的步数,与非饱和损失 \(-\log \sigma(D(x'))\) 作比较。利用二者的逐样本权重解释差异。
    2. 通过在三个随机种子上运行两组对照实验,检验合页损失略高的最终 \(\mathrm{JS}\) 究竟源于评判器滞后还是小批量噪声:(i)每步生成器更新配 5 步评判器更新;(ii)将评判器批量大小增大至 \(4\times\)。
  4. [code] 样本复杂度与维度。● 令 \(p = \mathcal{N}(\mathbf{0}, \mathbf{I}_{d_x})\) 与 \(q = \mathcal{N}(\boldsymbol{\mu}, \mathbf{I}_{d_x})\),其中 \(\|\boldsymbol{\mu}\| = 1\),从而在任意维度 \(d_x\) 下均有 \(W_1(p, q) = 1\)。

    1. 对 \(d_x \in \{1, 2, 10, 50\}\) 与 \(n \in \{100, 400, 1600\}\),通过最优线性指派(scipy.optimize.linear_sum_assignment)从两个大小为 \(n\) 的样本集估计 \(W_1\),并在双对数坐标上绘制相对误差随 \(n\) 的变化。与带宽 \(s = \sqrt{d_x}\) 的 RBF 核无偏 \(\mathrm{MMD}^2\) 估计量作对比。
    2. 测量维度 \(d_x = 50\) 下从同一分布 \(p\) 抽取的两个大小为 \(n = 256\) 的独立样本集之间的经验 \(W_1\) 距离。
    3. 在 grid_2d 上通过数值积分计算 critics['forward KL'] 的前向 KL 变分界 式 16.2.5,并将其与真实值 \(D_{\textrm{KL}}(p \,\|\, q) \approx 0.16\) 奈特以及大小为 512 的小批量估计值作对比。当 \(T(x')\) 在 \(q(x')\) 很小的区域超过 \(1 + \lambda(x')\) 时,为何来自 \(q\) 的有限小批量可能高估该下界?
  5. 分类损失诱导的对称 \(f\)-散度。●● 每个间隔分类损失 式 16.2.2 都具有对称的贝叶斯风险 \(L(\eta) = L(1 - \eta)\),从而度量一个对称 \(f\)-散度。反之(Nguyen 等 (2009年),推论 3),设 \(f\) 在 \((0, \infty)\) 上为凸函数,满足 \(f(1) = 0\)、\(f(u) = u f(1/u)\) 及 \(f(0) = \lim_{u \to 0} f(u) < \infty\),并定义

    \[ L(\eta) = 2 f(0) - 2 (1 - \eta)\, f\!\left( \frac{\eta}{1 - \eta} \right), \qquad 0 < \eta < 1. \]

    1. 证明 \(L(\eta)\) 是凹函数、关于 \(\tfrac12\) 对称、当 \(\eta \to 0\) 或 \(1\) 时趋于零,且其贝叶斯风险差满足 \(\Delta_\ell(p, q) = D_f(p \,\|\, q)\)。
    2. 对可微的 \(L\) 与 \(\hat\eta = \sigma(t)\),定义真实样本损失 \(-\ell(t) = L(\hat\eta) + (1 - \hat\eta) L'(\hat\eta)\)。证明 \(-\ell(-t) = L(\hat\eta) - \hat\eta L'(\hat\eta)\),条件风险在 \(\hat\eta = \eta\) 处取最小值 \(L(\eta)\),且 \(-\ell(t) \geq 0\)。
    3. 验证将该构造应用于 Jensen–Shannon 散度恰好恢复 logistic 损失。

讨论