def dirac_field(theta, psi, gamma=0.0):
"""Simultaneous gradient field of the Dirac-GAN with the logistic loss."""
w = 1.0 / (1.0 + np.exp(-psi * theta)) # l'(-psi theta) = w_sat
return np.array([psi * w, -theta * w - gamma * psi])
def euler_step(x, h, gamma): # one simultaneous step
return x + h * dirac_field(*x, gamma)
def alt_step(x, h, gamma): # critic first, then generator
theta, psi = x
psi = psi + h * dirac_field(theta, psi, gamma)[1]
return np.array([theta + h * dirac_field(theta, psi, gamma)[0], psi])
def rk4_step(x, h, gamma): # one RK4 step of the ODE
k1 = dirac_field(*x, gamma)
k2 = dirac_field(*(x + h / 2 * k1), gamma)
k3 = dirac_field(*(x + h / 2 * k2), gamma)
k4 = dirac_field(*(x + h * k3), gamma)
return x + h / 6 * (k1 + 2 * k2 + 2 * k3 + k4)
def trajectory(step, x0, h, steps, gamma=0.0):
xs = [np.array(x0)]
for _ in range(steps):
xs.append(step(xs[-1], h, gamma))
return np.stack(xs)16.4 梯度惩罚与收敛性
在 16.1 节 的 Fashion-MNIST 实验中,判别器损失与生成器损失均未收敛到各自的理论平衡值。究竟是交替梯度下降收敛缓慢,还是它会围绕平衡点永无止境地盘旋而无法抵达?16.1 节–16.3 节 的总体散度分析刻画的是评判器处于精确最优解 \(D^\star\) 时的极小极大目标,但在实践中两个网络执行的是小步长的同步或交替梯度更新,每次更新都在改变对方所面对的目标函数。
为直接分析梯度训练的动力学,Mescheder 等 (2018年) 提出了 Dirac-GAN——一个极简的双参数问题,由点质量数据分布、点质量生成器与线性评判器构成。即便在这个仅有两参数的系统上,无正则化的梯度下降也无法收敛,而惩罚评判器输入梯度的平方范数(\(R_1\) 与 \(R_2\))则使平衡点局部渐近稳定。将这些零中心梯度惩罚与 16.3 节 的相对配对目标相结合,即得本章余下部分采用的 R3GAN 方案 (Huang 等 2024年)。
16.4.1 Dirac-GAN
16.4.1.1 双参数极小极大系统
设数据分布为原点处的点质量 \(p = \delta_0\),生成器在 \(\theta \in \mathbb{R}\) 处放置点质量 \(q_\theta = \delta_\theta\)(从而 \(q_\theta = p\) 当且仅当 \(\theta = 0\)),评判器为无偏置线性函数 \(D_\psi(x) = \psi x\)。在对称间隔目标 \(V_\ell(D) = \mathbb{E}_{x \sim p}[\ell(D(x))] + \mathbb{E}_{x' \sim q}[\ell(-D(x'))]\)(16.2 节)下,两个期望均化简为单点求值:
\[ \begin{aligned} V(\theta, \psi) &= \ell\big(D_\psi(0)\big) + \ell\big({-D_\psi(\theta)}\big) \\ &= \ell(0) + \ell(-\psi\theta). \end{aligned} \tag{16.4.1}\]
我们取 logistic 收益 \(\ell(t) = \log \sigma(t)\),它满足 \(\ell'(t) = \sigma(-t) > 0\) 且 \(\ell''(t) = -\sigma(t)\sigma(-t) < 0\),其中 \(\ell'(0) = \tfrac12\)、\(\ell''(0) = -\tfrac14\)。
对任意 \(\theta \neq 0\),\(p\) 与 \(q_\theta\) 的支集不相交:对 \(\psi\) 最大化 \(V(\theta, \psi)\) 会令 \(\psi\theta \to -\infty\),使所有 \(\theta \neq 0\) 处均取常数 \(\sup_\psi V(\theta, \psi) = \ell(0)\),关于 \(\theta\) 的梯度为零。
16.4.1.2 连续时间中的无阻尼振荡
梯度训练并非直接求解 \(\sup_\psi V(\theta, \psi)\),而是从当前值出发增量更新 \(\theta\) 与 \(\psi\)。式 16.4.1 的唯一驻点是平衡点 \((\theta, \psi) = (0, 0)\)。在同步连续时间梯度流(\(\dot\theta = -\partial_\theta V\),\(\dot\psi = +\partial_\psi V\))下,
\[ \begin{aligned} \dot\theta &= -\partial_\theta V = \psi\, \ell'(-\psi\theta), \\ \dot\psi &= +\partial_\psi V = -\theta\, \ell'(-\psi\theta). \end{aligned} \tag{16.4.2}\]
由于速度向量 \(\mathbf{u}(\theta, \psi) = \ell'(-\psi\theta)\,(\psi, -\theta)\) 处处与状态向量 \((\theta, \psi)\) 正交,到原点的平方距离守恒:
\[ \begin{aligned} \frac{d}{dt}\big(\theta^2 + \psi^2\big) &= 2\theta\psi\,\ell'(-\psi\theta) - 2\psi\theta\,\ell'(-\psi\theta) = 0 . \end{aligned} \]
对任意严格递增收益 \(\ell\),每条轨迹都是围绕 \((0, 0)\) 的等半径闭合圆周:生成器参数 \(\theta\) 跨越 \(0\) 来回振荡,永远不会收敛。
在 \((\theta, \psi) = (0, 0)\) 附近对 式 16.4.2 线性化(38.1.2.5 节),可得雅可比矩阵及其特征值:
\[ J = \begin{pmatrix} 0 & \ell'(0) \\ -\ell'(0) & 0 \end{pmatrix}, \qquad \nu_{1,2} = \pm\, i\, \ell'(0). \tag{16.4.3}\]
纯虚特征值对应线性中心(即双线性鞍点问题 \(\min_\theta \max_\psi \theta\psi\),Daskalakis 等 (2018年))。注意标量因子 \(\ell'(-\psi\theta) = \sigma(D_\psi(\theta)) = w_{\textrm{sat}}\) 同时乘在两个分量上,因此只会缩放沿圆周运动的角速度。
16.4.1.3 离散时间中的向外螺旋与极限环
在离散时间下,步长为 \(h > 0\) 的同步梯度下降执行更新 \((\theta, \psi) \mapsto (\theta, \psi) + h\,\mathbf{u}(\theta, \psi)\)。由于 \(\mathbf{u}(\theta, \psi) \perp (\theta, \psi)\),由勾股定理得:
\[ \begin{aligned} \big\| (\theta, \psi) + h\, \mathbf{u} \big\|^2 &= \big\| (\theta, \psi) \big\|^2 + h^2 \big\| \mathbf{u} \big\|^2 . \end{aligned} \]
因此,对任意 \(h > 0\),每一步同步离散更新都严格增大到平衡点的距离,导致迭代点向外螺旋发散(练习 1)。
交替梯度更新(先更新 \(\psi\),再用更新后的 \(\psi\) 更新 \(\theta\))略胜一筹:在 \((0, 0)\) 附近,每半步都是保面积的线性错切,因此复合雅可比矩阵的行列式为 \(1\)。当 \(h\,\ell'(0) \leq 2\) 时,两个特征值均位于单位圆上 (Mescheder 等 2018年),交替迭代点在原点周围的有界环带内盘旋而不收敛(练习 4)。无论是非饱和生成器损失(在原点处具有相同的线性化矩阵 \(J\))还是相对配对损失(\(\ell(D_\psi(0) - D_\psi(\theta)) = \ell(-\psi\theta)\),具有完全相同的梯度场),都无法改变这些局部特征值。
16.4.2 零中心梯度惩罚
要使平衡点 \((\theta, \psi) = (0, 0)\) 局部渐近稳定,必须将雅可比矩阵的特征值从虚轴移入左开半平面 \(\operatorname{Re}(\nu) < 0\)。由于平衡态评判器必然平坦(当 \(q = p\) 时 \(\nabla_x D^\star(x) = 0\)),惩罚评判器输入梯度的平方范数既能为评判器引入阻尼,又不会移动平衡点 \(q = p\)。
Mescheder 等 (2018年) 定义了两种零中心梯度惩罚:\(R_1\)(在真实数据 \(x \sim p\) 处计算)与 \(R_2\)(在生成样本 \(x' \sim q\) 处计算):
\[ \begin{aligned} R_1 &= \frac{\gamma}{2}\, \mathbb{E}_{x \sim p}\Big[ \big\| \nabla_x D(x) \big\|^2 \Big], \\ R_2 &= \frac{\gamma}{2}\, \mathbb{E}_{x' \sim q}\Big[ \big\| \nabla_{x'} D(x') \big\|^2 \Big], \end{aligned} \tag{16.4.4}\]
其中惩罚权重 \(\gamma > 0\)。评判器最大化 \(V_\ell(D) - R_1 - R_2\),生成器目标保持不变。记 \(m = (p + q)/2\),二者之和即为混合分布下的期望平方梯度范数:
\[ \begin{aligned} R_1 + R_2 &= \gamma\, \mathbb{E}_{x \sim m}\Big[ \big\| \nabla_x D(x) \big\|^2 \Big], \qquad m = \frac{p + q}{2}. \end{aligned} \tag{16.4.5}\]
16.4.2.1 为 Dirac-GAN 引入阻尼
对线性评判器 \(D_\psi(x) = \psi x\),处处有 \(\nabla_x D_\psi(x) = \psi\),于是 \(R_1 = R_2 = \tfrac{\gamma}{2}\psi^2\)。从评判器目标中减去 \(\tfrac{\gamma}{2}\psi^2\) 会向 \(\dot\psi\) 加入线性阻尼项 \(-\gamma\psi\)(若同时包含 \(R_1\) 与 \(R_2\) 则为 \(-2\gamma\psi\)):
\[ \dot\theta = \psi\,\ell'(-\psi\theta), \qquad \dot\psi = -\theta\,\ell'(-\psi\theta) - \gamma\psi . \]
\((0, 0)\) 处的雅可比矩阵与特征值变为:
\[ J_\gamma = \begin{pmatrix} 0 & \ell'(0) \\ -\ell'(0) & -\gamma \end{pmatrix}, \qquad \nu_{1,2} \;=\; -\frac{\gamma}{2} \pm \sqrt{ \frac{\gamma^2}{4} - \ell'(0)^2 } . \tag{16.4.6}\]
对任意 \(\gamma > 0\),两个特征值均具有严格负实部(\(\operatorname{Re}(\nu_{1,2}) < 0\)),从而平衡点 \((0, 0)\) 局部指数稳定。特征多项式 \(\nu^2 + \gamma\nu + \ell'(0)^2 = 0\) 与阻尼谐振子完全相同(38.1.2.5 节),呈现三种状态:
- 欠阻尼(\(\gamma < 2\ell'(0)\)):一对实部为 \(-\gamma/2\) 的共轭复特征值;轨迹向内螺旋收敛(在同步欧拉步下当 \(h < \gamma / \ell'(0)^2\) 时收敛,见练习 1)。
- 临界阻尼(\(\gamma = 2\ell'(0)\),对 logistic 损失即 \(\gamma = 1\)):重实特征值 \(\nu = -\ell'(0)\),给出最快的无振荡衰减。
- 过阻尼(\(\gamma > 2\ell'(0)\)):两个负实特征值,其中慢模态 \(\nu \approx -\ell'(0)^2/\gamma\) 随着 \(\gamma\) 增大而衰减变慢。
16.4.2.2 相图
我们从 \((\theta_0, \psi_0) = (1, 1)\)(初始半径 \(\sqrt{2} \approx 1.41\))出发,分别用四阶龙格–库塔(rk4_step)、同步前向欧拉(euler_step)与交替梯度更新(alt_step)积分 式 16.4.2,验证上述四种动力学状态。
def dirac_field(theta, psi, gamma=0.0):
"""Simultaneous gradient field of the Dirac-GAN with the logistic loss."""
w = 1.0 / (1.0 + np.exp(-psi * theta)) # l'(-psi theta) = w_sat
return np.array([psi * w, -theta * w - gamma * psi])
def euler_step(x, h, gamma): # one simultaneous step
return x + h * dirac_field(*x, gamma)
def alt_step(x, h, gamma): # critic first, then generator
theta, psi = x
psi = psi + h * dirac_field(theta, psi, gamma)[1]
return np.array([theta + h * dirac_field(theta, psi, gamma)[0], psi])
def rk4_step(x, h, gamma): # one RK4 step of the ODE
k1 = dirac_field(*x, gamma)
k2 = dirac_field(*(x + h / 2 * k1), gamma)
k3 = dirac_field(*(x + h / 2 * k2), gamma)
k4 = dirac_field(*(x + h * k3), gamma)
return x + h / 6 * (k1 + 2 * k2 + 2 * k3 + k4)
def trajectory(step, x0, h, steps, gamma=0.0):
xs = [np.array(x0)]
for _ in range(steps):
xs.append(step(xs[-1], h, gamma))
return np.stack(xs)所有轨迹均始于红点 \((\theta, \psi) = (1, 1)\),距黑叉标出的平衡点距离为 \(\sqrt 2 \approx 1.41\)。左图展示连续流;中图展示步长 \(h = 0.2\) 的 300 步同步更新与 2,000 步交替更新;右图展示同样步长下带惩罚的 300 步同步更新,分别取欠阻尼的 \(\gamma = 0.3\) 与临界阻尼的 \(\gamma = 1\)。
x0 = np.array([1.0, 1.0])
panels = {'flow': {'RK4': trajectory(rk4_step, x0, 0.05, 800)},
'steps': {'simultaneous': trajectory(euler_step, x0, 0.2, 300),
'alternating': trajectory(alt_step, x0, 0.2, 2000)},
'penalized': {
'gamma = 0.3': trajectory(euler_step, x0, 0.2, 300, gamma=0.3),
'gamma = 1': trajectory(euler_step, x0, 0.2, 300, gamma=1.0)}}
fig, axes = d2l.plt.subplots(1, 3, figsize=(9.5, 3.4))
for ax, (title, paths) in zip(axes, panels.items()):
for name, P in paths.items():
r = np.linalg.norm(P, axis=1) # distance to the equilibrium
late = r[len(r) // 2:]
print(f'{title}, {name}: {r[0]:.3g} -> {r[-1]:.3g} in {len(r) - 1} '
f'steps; second half in [{late.min():.3g}, {late.max():.3g}]')
lim = 1.25 * max(np.abs(P).max() for P in paths.values())
d2l.plot([P[:, 0] for P in paths.values()] + [x0[:1], [0.0]],
[P[:, 1] for P in paths.values()] + [x0[1:], [0.0]],
r'$\theta$', r'$\psi$', list(paths) if len(paths) > 1 else None,
xlim=(-lim, lim), ylim=(-lim, lim), axes=ax,
fmts=('C0-', 'C1-')[:len(paths)] + ('C3o', 'k+'),
legend_loc='lower right' if title == 'penalized' else None)
ax.set_title(title)
ax.set_aspect('equal')
fig.tight_layout()flow, RK4: 1.41 -> 1.41 in 800 steps; second half in [1.41, 1.41]
steps, simultaneous: 1.41 -> 2.87 in 300 steps; second half in [2.44, 2.87]
steps, alternating: 1.41 -> 1.36 in 2000 steps; second half in [1.34, 1.42]
penalized, gamma = 0.3: 1.41 -> 0.000652 in 300 steps; second half in [0.000652, 0.0396]
penalized, gamma = 1: 1.41 -> 6.97e-12 in 300 steps; second half in [6.97e-12, 2.33e-05]
x0 = np.array([1.0, 1.0])
panels = {'flow': {'RK4': trajectory(rk4_step, x0, 0.05, 800)},
'steps': {'simultaneous': trajectory(euler_step, x0, 0.2, 300),
'alternating': trajectory(alt_step, x0, 0.2, 2000)},
'penalized': {
'gamma = 0.3': trajectory(euler_step, x0, 0.2, 300, gamma=0.3),
'gamma = 1': trajectory(euler_step, x0, 0.2, 300, gamma=1.0)}}
fig, axes = d2l.plt.subplots(1, 3, figsize=(9.5, 3.4))
for ax, (title, paths) in zip(axes, panels.items()):
for name, P in paths.items():
r = np.linalg.norm(P, axis=1) # distance to the equilibrium
late = r[len(r) // 2:]
print(f'{title}, {name}: {r[0]:.3g} -> {r[-1]:.3g} in {len(r) - 1} '
f'steps; second half in [{late.min():.3g}, {late.max():.3g}]')
lim = 1.25 * max(np.abs(P).max() for P in paths.values())
d2l.plot([P[:, 0] for P in paths.values()] + [x0[:1], [0.0]],
[P[:, 1] for P in paths.values()] + [x0[1:], [0.0]],
r'$\theta$', r'$\psi$', list(paths) if len(paths) > 1 else None,
xlim=(-lim, lim), ylim=(-lim, lim), axes=ax,
fmts=('C0-', 'C1-')[:len(paths)] + ('C3o', 'k+'),
legend_loc='lower right' if title == 'penalized' else None)
ax.set_title(title)
ax.set_aspect('equal')
fig.tight_layout()flow, RK4: 1.41 -> 1.41 in 800 steps; second half in [1.41, 1.41]
steps, simultaneous: 1.41 -> 2.87 in 300 steps; second half in [2.44, 2.87]
steps, alternating: 1.41 -> 1.36 in 2000 steps; second half in [1.34, 1.42]
penalized, gamma = 0.3: 1.41 -> 0.000652 in 300 steps; second half in [0.000652, 0.0396]
penalized, gamma = 1: 1.41 -> 6.97e-12 in 300 steps; second half in [6.97e-12, 2.33e-05]
相图完全印证了四项预测:连续流(RK4)沿半径 \(1.41\) 的圆周盘旋;300 步同步欧拉更新向外螺旋至半径 \(2.87\);交替更新在 \([1.34, 1.42]\) 的环带内盘旋;加入零中心惩罚后,同步欧拉更新直奔原点(欠阻尼 \(\gamma = 0.3\) 处达 \(6.5 \times 10^{-4}\),临界阻尼 \(\gamma = 1\) 处达 \(7 \times 10^{-12}\))。
16.4.2.3 一般网络的局部收敛性与惩罚比较
Mescheder 等 (2018年) 将这一局部稳定性分析从双参数 Dirac-GAN 推广至一般神经网络:在生成器表示数据分布 \(p\) 且评判器在 \(\operatorname{supp}(p)\) 上平坦的平衡点附近,只要评判器具备足够的局部容量以检测一阶生成器扰动,带有 \(R_1\) 或 \(R_2\)(且严格凹损失满足 \(\ell'(0) \neq 0, \ell''(0) < 0\))的同步与交替梯度更新都会指数收敛至平衡流形(Huang 等 (2024年) 为相对配对目标建立了类似的局部收敛定理)。
上述分析同样解释了两项重要的实践设计选择:
- 零中心(\(R_1, R_2\))对比 1-中心(WGAN-GP)惩罚:WGAN-GP 惩罚 \((\|\nabla_x D\| - 1)^2\),即使在 \(q = p\) 时也强迫评判器保持单位斜率。在采用线性收益 \(\ell(t) = t\) 的 Dirac-GAN 上,1-中心惩罚会阻止收敛到 \(\theta = 0\):当 \(\gamma \geq 2\) 时,它将生成器停驻在 \(|\theta| = \gamma\) 处(Wasserstein 梯度与惩罚平衡);当 \(\gamma\) 更小时,生成器越过该点并持续循环(练习 6)。
- 同时使用 \(R_1\) 与 \(R_2\) 对比单用 \(R_1\):在 \(q = p\) 附近,\(R_1\) 与 \(R_2\) 等价。但在远离平衡点时,\(R_1\) 只惩罚真实数据点 \(x \sim p\) 处的评判器斜率,对生成样本 \(x' \sim q\) 处的斜率不加约束(例如 \(D_c(x) = -cx^2\) 在 \(p = \delta_0\) 处斜率为零、故 \(R_1 = 0\),允许 \(c \to \infty\) 并在 \(x' = 1\) 处引发生成器梯度爆炸;练习 3)。加入 \(R_2\) 可一并约束生成样本处的评判器梯度。
16.4.3 梯度惩罚对价值函数的影响
零中心惩罚 \(R_1 + R_2 = \gamma\,\mathbb{E}_m[\|\nabla_x D\|^2]\) 会如何改变生成器在平衡点附近最小化的散度?
16.4.3.1 局部二次近似与高斯平移
在 \(q = p\) 附近,最优评判器 \(D\) 很小。将 \(V_\ell(D)\) 内的 \(\ell(t) \approx \ell(0) + \ell'(0)t - \tfrac12|\ell''(0)|t^2\) 对 \(D\) 展开至二阶,得:
\[ \begin{aligned} V_\ell(D) &\approx 2\ell(0) + \ell'(0)\, \langle p - q,\, D \rangle - |\ell''(0)| \int m\, D^2 , \end{aligned} \]
其中 \(\langle p - q, D \rangle = \mathbb{E}_p[D] - \mathbb{E}_q[D]\)。考虑相距微小偏移 \(\mu\) 的两个单位方差高斯分布 \(p = \mathcal{N}(0, 1)\) 与 \(q = \mathcal{N}(\mu, 1)\),以及线性评判器 \(D(x) = cx\)。对 \(\mu\) 取主导阶,\(\langle p - q, D \rangle = -c\mu\),\(\int m\,D^2 \approx c^2\),惩罚项为 \(\gamma\int m\,\|\nabla_x D\|^2 = \gamma c^2\)。对 \(c\) 最大化凹二次函数 \(-\ell'(0)\mu c - (|\ell''(0)| + \gamma)c^2\),可得最优斜率 \(c^\star = -\frac{\ell'(0)\mu}{2(|\ell''(0)| + \gamma)}\) 与价值:
\[ \begin{aligned} \frac{\ell'(0)^2 \mu^2}{4\,(|\ell''(0)| + \gamma)} &= \frac{\mu^2}{4 + 16\gamma} \\ &\text{for the logistic loss, at slope } c^\star = -\frac{\mu}{1 + 4\gamma} . \end{aligned} \]
可见惩罚项将评判器斜率与局部价值同时缩小 \(1 + 4\gamma\) 倍。当 \(\gamma = 0\) 时恢复 \(\mu^2/4 \approx 2\,\mathrm{JS}(p, q)\);当 \(\gamma\) 较大时,价值按 \(\mu^2/(16\gamma) = \tfrac{\ell'(0)^2}{4\gamma} W_2(p, q)^2\) 缩放。下面我们在 1D 网格上用牛顿法求精确带惩罚最优解,验证这一闭式近似。
def penalized_value(p, q, gamma, x, newton_steps=30):
"""Value of the logistic game minus gamma E_m[D'^2], on a grid."""
dx, m = x[1] - x[0], (p + q) / 2
diff = np.diff(np.eye(len(x)), axis=0) / dx # D -> D'
K = 2 * gamma * dx * diff.T @ (((m[1:] + m[:-1]) / 2)[:, None] * diff)
D = np.zeros_like(x)
for _ in range(newton_steps): # Newton ascent on D
s = 1 / (1 + np.exp(-D)) # sigma(D)
grad = (p * (1 - s) - q * s) * dx - K @ D # gradient of the value
neg_hess = np.diag(2 * m * s * (1 - s) * dx) + K # minus its Hessian
D = D + np.linalg.solve(neg_hess, grad)
value = -(p * np.logaddexp(0, -D) + q * np.logaddexp(0, D)).sum() * dx
return value - D @ K @ D / 2 + 2 * np.log(2) # minus 2 l(0)
x = np.linspace(-8, 8, 401)
for mu in (0.2, 1, 3):
p, q = [np.exp(-(x - c) ** 2 / 2) / np.sqrt(2 * np.pi) for c in (0, mu)]
for gamma in (0, 0.01, 1, 10):
exact = penalized_value(p, q, gamma, x)
local = mu ** 2 / (4 + 16 * gamma)
large = mu ** 2 / (16 * gamma) if gamma else np.inf
print(f'mu {mu:>3}, gamma {gamma:>4}: exact {exact:.3e}, local '
f'{local:.3e} ({local / exact:.2f}x), large-gamma {large:.3e} '
f'({large / exact:.2f}x)')mu 0.2, gamma 0: exact 9.950e-03, local 1.000e-02 (1.00x), large-gamma inf (infx)
mu 0.2, gamma 0.01: exact 9.566e-03, local 9.615e-03 (1.01x), large-gamma 2.500e-01 (26.13x)
mu 0.2, gamma 1: exact 1.996e-03, local 2.000e-03 (1.00x), large-gamma 2.500e-03 (1.25x)
mu 0.2, gamma 10: exact 2.438e-04, local 2.439e-04 (1.00x), large-gamma 2.500e-04 (1.03x)
mu 1, gamma 0: exact 2.228e-01, local 2.500e-01 (1.12x), large-gamma inf (infx)
mu 1, gamma 0.01: exact 2.135e-01, local 2.404e-01 (1.13x), large-gamma 6.250e+00 (29.27x)
mu 1, gamma 1: exact 4.818e-02, local 5.000e-02 (1.04x), large-gamma 6.250e-02 (1.30x)
mu 1, gamma 10: exact 6.120e-03, local 6.098e-03 (1.00x), large-gamma 6.250e-03 (1.02x)
mu 3, gamma 0: exact 1.054e+00, local 2.250e+00 (2.14x), large-gamma inf (infx)
mu 3, gamma 0.01: exact 1.012e+00, local 2.163e+00 (2.14x), large-gamma 5.625e+01 (55.57x)
mu 3, gamma 1: exact 3.909e-01, local 4.500e-01 (1.15x), large-gamma 5.625e-01 (1.44x)
mu 3, gamma 10: exact 6.862e-02, local 5.488e-02 (0.80x), large-gamma 5.625e-02 (0.82x)
def penalized_value(p, q, gamma, x, newton_steps=30):
"""Value of the logistic game minus gamma E_m[D'^2], on a grid."""
dx, m = x[1] - x[0], (p + q) / 2
diff = np.diff(np.eye(len(x)), axis=0) / dx # D -> D'
K = 2 * gamma * dx * diff.T @ (((m[1:] + m[:-1]) / 2)[:, None] * diff)
D = np.zeros_like(x)
for _ in range(newton_steps): # Newton ascent on D
s = 1 / (1 + np.exp(-D)) # sigma(D)
grad = (p * (1 - s) - q * s) * dx - K @ D # gradient of the value
neg_hess = np.diag(2 * m * s * (1 - s) * dx) + K # minus its Hessian
D = D + np.linalg.solve(neg_hess, grad)
value = -(p * np.logaddexp(0, -D) + q * np.logaddexp(0, D)).sum() * dx
return value - D @ K @ D / 2 + 2 * np.log(2) # minus 2 l(0)
x = np.linspace(-8, 8, 401)
for mu in (0.2, 1, 3):
p, q = [np.exp(-(x - c) ** 2 / 2) / np.sqrt(2 * np.pi) for c in (0, mu)]
for gamma in (0, 0.01, 1, 10):
exact = penalized_value(p, q, gamma, x)
local = mu ** 2 / (4 + 16 * gamma)
large = mu ** 2 / (16 * gamma) if gamma else np.inf
print(f'mu {mu:>3}, gamma {gamma:>4}: exact {exact:.3e}, local '
f'{local:.3e} ({local / exact:.2f}x), large-gamma {large:.3e} '
f'({large / exact:.2f}x)')mu 0.2, gamma 0: exact 9.950e-03, local 1.000e-02 (1.00x), large-gamma inf (infx)
mu 0.2, gamma 0.01: exact 9.566e-03, local 9.615e-03 (1.01x), large-gamma 2.500e-01 (26.13x)
mu 0.2, gamma 1: exact 1.996e-03, local 2.000e-03 (1.00x), large-gamma 2.500e-03 (1.25x)
mu 0.2, gamma 10: exact 2.438e-04, local 2.439e-04 (1.00x), large-gamma 2.500e-04 (1.03x)
mu 1, gamma 0: exact 2.228e-01, local 2.500e-01 (1.12x), large-gamma inf (infx)
mu 1, gamma 0.01: exact 2.135e-01, local 2.404e-01 (1.13x), large-gamma 6.250e+00 (29.27x)
mu 1, gamma 1: exact 4.818e-02, local 5.000e-02 (1.04x), large-gamma 6.250e-02 (1.30x)
mu 1, gamma 10: exact 6.120e-03, local 6.098e-03 (1.00x), large-gamma 6.250e-03 (1.02x)
mu 3, gamma 0: exact 1.054e+00, local 2.250e+00 (2.14x), large-gamma inf (infx)
mu 3, gamma 0.01: exact 1.012e+00, local 2.163e+00 (2.14x), large-gamma 5.625e+01 (55.57x)
mu 3, gamma 1: exact 3.909e-01, local 4.500e-01 (1.15x), large-gamma 5.625e-01 (1.44x)
mu 3, gamma 10: exact 6.862e-02, local 5.488e-02 (0.80x), large-gamma 5.625e-02 (0.82x)
对小偏移(\(\mu = 0.2\)),二次公式 \(\mu^2/(4 + 16\gamma)\) 在所有 \(\gamma\) 上与精确数值解吻合至 1% 以内。
16.4.3.2 对偶 Sobolev 范数与低通滤波
对于平衡点附近的一般分布 \(p\) 与 \(q\),分部积分可将梯度惩罚写成 \(\int m\,\|\nabla_x D\|^2 = \langle D, \mathcal{L}_m D \rangle\),其中 \(\mathcal{L}_m D = -\nabla \cdot (m \nabla D)\) 为 \(m\)-加权拉普拉斯算子。在所有函数 \(D\) 上最大化局部二次近似可得(练习 5):
\[ \begin{aligned} &\sup_{D} \Big\{ \ell'(0)\, \langle p - q,\, D \rangle - |\ell''(0)| \int m\, D^2 - \gamma \int m\, \| \nabla_x D \|^2 \Big\} \\ &\qquad = \frac{\ell'(0)^2}{4}\, \big\langle p - q,\, \big(|\ell''(0)|\, m + \gamma \mathcal{L}_m\big)^{-1} (p - q) \big\rangle . \end{aligned} \tag{16.4.7}\]
当 \(\gamma \to 0\) 时,它退化为 \(\tfrac{\ell'(0)^2}{4|\ell''(0)|} \int (p - q)^2/m \approx 2\,\mathrm{JS}(p, q)\)。当 \(\gamma \to \infty\) 时,它趋近于平方对偶 Sobolev 范数 \(\dot H^{-1}(m)\) 的倍数:
\[ \begin{aligned} &\frac{\ell'(0)^2}{4\gamma}\, \big\| p - q \big\|^2_{\dot H^{-1}(m)}, \\ &\|v\|_{\dot H^{-1}(m)} = \sup\Big\{ \langle v, D\rangle : \int m \|\nabla_x D\|^2 \leq 1 \Big\}. \end{aligned} \tag{16.4.8}\]
在 \(m\) 近似均匀的区域,\(\mathcal{L}_m\) 将波数为 \(\omega\) 的傅里叶模态乘以 \(m\omega^2\),从而赋予该模态权重 \((|\ell''(0)| + \gamma\omega^2)^{-1}\) 而非 \(|\ell''(0)|^{-1}\)。因此,\(R_1 + R_2\) 相当于作用在 \(p - q\) 上的空间低通滤波器,截止长度尺度为 \(\sqrt{\gamma / |\ell''(0)|}\)(logistic 损失下为 \(2\sqrt{\gamma}\))。由于 \(\nabla_x D\) 的量纲是长度的倒数,\(\gamma\) 具有长度平方的量纲,并随数据分辨率与范数缩放。此外要注意,\(R_1 + R_2\) 仅在 \(m = (p+q)/2\) 的支集上惩罚 \(\nabla_x D\);跨越不相交支集之间的空白空间时,梯度仍依赖神经网络评判器的光滑性(练习 2)。
16.4.4 R3GAN 方案
R3GAN (Huang 等 2024年) 将相对配对损失(16.3 节 中的 d2l.rpgan_loss_D 与 d2l.rpgan_loss_G)与两个零中心梯度惩罚 \(R_1\) 和 \(R_2\) 结合起来。
16.4.4.1 损失与惩罚的实现
为便于对比,我们也以相同的 (critic, real, fake) 接口保存 gan_loss_D 与 gan_loss_G,分别实现 16.1 节 的经典 logistic 判别器损失与非饱和生成器损失。
def gan_loss_D(critic, real, fake):
"""Logistic critic loss -E[log sigma(D(x))] - E[log sigma(-D(x'))]: the
sum of two batch means, 2 log 2 at equilibrium, as update_D."""
return F.softplus(-critic(real)).mean() + F.softplus(critic(fake)).mean()
def gan_loss_G(critic, real, fake):
"""Non-saturating generator loss -E[log sigma(D(x'))]; real is unused."""
return F.softplus(-critic(fake)).mean()
def gan_loss_D(critic, real, fake):
"""Logistic critic loss -E[log sigma(D(x))] - E[log sigma(-D(x'))]: the
sum of two batch means, 2 log 2 at equilibrium, as update_D."""
return (jax.nn.softplus(-critic(real)).mean()
+ jax.nn.softplus(critic(fake)).mean())
def gan_loss_G(critic, real, fake):
"""Non-saturating generator loss -E[log sigma(D(x'))]; real is unused."""
return jax.nn.softplus(-critic(fake)).mean()惩罚函数返回两个小批量上的逐样本平方输入梯度(尚未乘以系数 \(\gamma/2\))。它对评判器打分之和关于输入小批量求导:由于每个分数只依赖自身所在行,一次反向传播即可得到所有样本的输入梯度(会混合行间信息的批量归一化会破坏这一性质)。输入梯度保留在自动微分计算图中,以便优化器进一步对评判器参数求惩罚项的导数;样本本身保持常量。二次求导使一次带惩罚评判器更新的开销约等于两次反向传播。
create_graph=True 为二次求导保留输入梯度的计算图,detach 将样本固定为常量。
对打分之和调用 jax.grad 得到输入梯度;对惩罚项关于评判器参数求导会在其外再嵌套一层梯度,而 jax.lax.stop_gradient 将样本固定为常量。
def r1_r2_penalty(critic, real, fake):
"""Per-sample squared critic input gradients on real (R1) and fake (R2),
before the gamma/2 scale."""
def sq_grad_norm(x):
x = x.detach().requires_grad_(True)
grad, = torch.autograd.grad(critic(x).sum(), x, create_graph=True)
return grad.reshape(x.shape[0], -1).pow(2).sum(dim=1)
return sq_grad_norm(real), sq_grad_norm(fake)
def r1_r2_penalty(critic, real, fake):
"""Per-sample squared critic input gradients on real (R1) and fake (R2),
before the gamma/2 scale."""
def sq_grad_norm(x):
# Rows are independent, so the gradient of the sum is per-sample
grad = jax.grad(lambda x: critic(x).sum())(jax.lax.stop_gradient(x))
return (grad.reshape(x.shape[0], -1) ** 2).sum(axis=1)
return sq_grad_norm(real), sq_grad_norm(fake)16.4.4.2 训练步
训练循环在双方之间每次交替执行一步。critic_step 固定生成小批量,对评判器损失加上 \(\gamma/2\) 倍两项惩罚执行一次优化器更新,并返回损失以及真实与生成样本上平方输入梯度的小批量均值(未乘 \(\gamma/2\) 前的 \(R_1\) 与 \(R_2\)),以便循环记录评判器的陡峭程度。随后 generator_step 针对更新后的评判器执行一步生成器损失更新。可选标签 y 用于 16.6 节 的条件评判器。
def critic_step(net_D, opt_D, loss_D, real, fake, gamma, y=None):
"""One critic step on loss_D + gamma/2 (R1 + R2); return the loss and
the batch means of R1 and R2."""
critic = net_D if y is None else lambda x: net_D(x, y)
fake = fake.detach() # the generator is held fixed
r1, r2 = r1_r2_penalty(critic, real, fake)
loss = loss_D(critic, real, fake)
opt_D.zero_grad()
(loss + gamma / 2 * (r1 + r2).mean()).backward()
opt_D.step()
return loss.detach(), r1.mean().detach(), r2.mean().detach()
def generator_step(net_G, opt_G, loss_G, net_D, real, z, y=None):
"""One generator step on loss_G against the critic; return the loss."""
critic = net_D if y is None else lambda x: net_D(x, y)
loss = loss_G(critic, real, net_G(z) if y is None else net_G(z, y))
opt_G.zero_grad()
loss.backward()
opt_G.step()
return loss.detach()
@nnx.jit(static_argnums=2)
def critic_step(net_D, opt_D, loss_D, real, fake, gamma, y=None):
"""One critic step on loss_D + gamma/2 (R1 + R2); return the loss and
the batch means of R1 and R2."""
def objective(net_D):
critic = net_D if y is None else lambda x: net_D(x, y)
r1, r2 = r1_r2_penalty(critic, real, fake)
loss = loss_D(critic, real, fake)
return (loss + gamma / 2 * (r1 + r2).mean(),
(loss, r1.mean(), r2.mean()))
(_, logs), grads = nnx.value_and_grad(objective, has_aux=True)(net_D)
opt_D.update(net_D, grads)
return logs
@nnx.jit(static_argnums=2)
def generator_step(net_G, opt_G, loss_G, net_D, real, z, y=None):
"""One generator step on loss_G against the critic; return the loss."""
def objective(net_G):
critic = net_D if y is None else lambda x: net_D(x, y)
return loss_G(critic, real, net_G(z) if y is None else net_G(z, y))
loss, grads = nnx.value_and_grad(objective)(net_G)
opt_G.update(net_G, grads)
return loss损失函数是编译步的静态参数,因此每对损失只需编译一次;而 \(\gamma\) 是被追踪的动态值,修改它无需重新编译。
16.4.4.3 25 高斯网格上的模式覆盖
为检验 \(R_1 + R_2\) 与成对排序在神经网络中对模式覆盖的影响,我们在 \(5 \times 5\) 二维高斯网格(间距 \(2.0\),标准差 \(\sigma = 0.05\))上训练 3 层 MLP 生成器(64 维潜变量,两个 256 单元 ReLU 隐藏层)与 3 层 leaky-ReLU MLP 评判器。我们用四项指标评估 10,000 个生成样本:
- 覆盖模式数:获得的模式内样本数至少达到均分份额(\(1/25\))之 \(1/5\) 的模式个数。
- 模式内比例:落在最近模式中心 \(3\sigma = 0.15\) 范围内的样本比例(真实分布为 \(98.9\%\))。
- 到最近中心的平均距离(真实分布 \(\approx 0.06\))。
- 生成样本处的评判器陡峭度 \(\mathbb{E}_q[\|\nabla_x D(x')\|^2]\)。
def grid_centers(side=5, spacing=2.0):
coords = (torch.arange(side, dtype=torch.float32) - (side - 1) / 2)
gx, gy = torch.meshgrid(coords * spacing, coords * spacing, indexing='ij')
return torch.stack([gx.reshape(-1), gy.reshape(-1)], dim=1)
def sample_modes(centers, n, width=0.05):
idx = torch.randint(0, centers.shape[0], (n,), device=centers.device)
return centers[idx] + width * torch.randn(n, 2, device=centers.device)def grid_centers(side=5, spacing=2.0):
coords = (jnp.arange(side) - (side - 1) / 2) * spacing
gx, gy = jnp.meshgrid(coords, coords, indexing='ij')
return jnp.stack([gx.reshape(-1), gy.reshape(-1)], axis=1)
def sample_modes(key, centers, n, width=0.05):
k1, k2 = jax.random.split(key)
idx = jax.random.randint(k1, (n,), 0, centers.shape[0])
return centers[idx] + width * jax.random.normal(k2, (n, 2))为对照网格中心 centers 评估生成点云,mode_stats 将每个样本分配给最近的模式中心,并返回覆盖模式数、落在 \(3\sigma\) 内的样本比例以及到最近中心的平均距离:
def mode_stats(x, centers, width=0.05):
"""Modes covered (each holds a fifth of an even share of the on-mode
samples), fraction within three widths, mean distance."""
dist = np.linalg.norm(x[:, None] - centers[None], axis=-1)
near, idx = dist.min(axis=1), dist.argmin(axis=1)
on = near <= 3 * width
counts = np.bincount(idx[on], minlength=len(centers))
covered = (counts >= on.sum() / len(centers) / 5).sum()
return covered, on.mean(), near.mean()def mode_stats(x, centers, width=0.05):
"""Modes covered (each holds a fifth of an even share of the on-mode
samples), fraction within three widths, mean distance."""
dist = np.linalg.norm(x[:, None] - centers[None], axis=-1)
near, idx = dist.min(axis=1), dist.argmin(axis=1)
on = near <= 3 * width
counts = np.bincount(idx[on], minlength=len(centers))
covered = (counts >= on.sum() / len(centers) / 5).sum()
return covered, on.mean(), near.mean()train_grid 交替运行 critic_step 与 generator_step 共 10,000 步(批量大小 1,024),使用 \(\beta_1 = 0\) 的 Adam(遵循 R3GAN,因为旋转向量场中的正一阶动量会缩小稳定域),并将学习率从 \(2 \times 10^{-3}\) 余弦衰减至 \(2 \times 10^{-4}\)。
def train_grid(centers, loss_D, loss_G, gamma, steps=10000, lr=2e-3,
batch=1024, latent=64, seed=0, checkpoints=8):
"""Alternate critic and generator steps; at each checkpoint record the
on-mode fraction of 2,000 samples, and the critic loss and E_q|grad D|^2
averaged over the steps since the previous checkpoint."""
torch.manual_seed(seed)
dev, grid = centers.device, centers.cpu().numpy()
net_G = d2l.make_mlp([latent, 256, 256, 2], nn.ReLU()).to(dev)
net_D = d2l.make_mlp([2, 256, 256, 1], nn.LeakyReLU(0.2)).to(dev)
opt_G, opt_D = [torch.optim.Adam(net.parameters(), # lr on the device
torch.tensor(lr, device=dev),
betas=(0.0, 0.99),
capturable=dev.type == 'cuda')
for net in (net_G, net_D)]
scheds = [torch.optim.lr_scheduler.CosineAnnealingLR(opt, steps, lr / 10)
for opt in (opt_G, opt_D)]
logs, every = torch.zeros(2, device=dev), steps // checkpoints
def step():
real = sample_modes(centers, batch)
with torch.no_grad():
fake = net_G(torch.randn(batch, latent, device=dev))
loss, _, grad_q = critic_step(net_D, opt_D, loss_D, real, fake, gamma)
logs.add_(torch.stack([loss, grad_q])) # summed on the device
z = torch.randn(batch, latent, device=dev)
generator_step(net_G, opt_G, loss_G, net_D,
sample_modes(centers, batch), z)
step, trace = d2l.cuda_graphed(step, dev), []
for t in range(1, steps + 1):
step()
for sched in scheds:
sched.step()
if t % every == 0: # checkpoint
with torch.no_grad():
x = net_G(torch.randn(2000, latent, device=dev)).cpu().numpy()
trace.append((mode_stats(x, grid)[1], *(logs / every).tolist()))
logs.zero_()
return net_G, tracedef train_grid(centers, loss_D, loss_G, gamma, steps=10000, lr=2e-3,
batch=1024, latent=64, seed=0, checkpoints=8):
"""Alternate critic and generator steps; at each checkpoint record the
on-mode fraction of 2,000 samples, and the critic loss and E_q|grad D|^2
averaged over the steps since the previous checkpoint."""
rngs = nnx.Rngs(seed)
net_G = d2l.make_mlp([latent, 256, 256, 2], nnx.relu, rngs=rngs)
net_D = d2l.make_mlp([2, 256, 256, 1], lambda x: nnx.leaky_relu(x, 0.2),
rngs=rngs)
adam = optax.adam(optax.cosine_decay_schedule(lr, steps, alpha=0.1),
b1=0.0, b2=0.99)
opt_G, opt_D = (nnx.Optimizer(net, adam, wrt=nnx.Param)
for net in (net_G, net_D))
@nnx.jit
def step(net_G, net_D, opt_G, opt_D, key, logs):
k1, k2 = jax.random.split(key)
z = jax.random.normal(k1, (2, batch, latent)) # critic, generator
real = sample_modes(k2, centers, 2 * batch).reshape(2, batch, 2)
fake = net_G(z[0])
loss, _, grad_q = critic_step(net_D, opt_D, loss_D, real[0], fake,
gamma)
generator_step(net_G, opt_G, loss_G, net_D, real[1], z[1])
return logs + jnp.stack([loss, grad_q]) # summed on the device
step = nnx.cached_partial(step, net_G, net_D, opt_G, opt_D)
trace, every, grid = [], steps // checkpoints, np.asarray(centers)
keys = jax.random.split(rngs(), steps).reshape(checkpoints, every)
for chunk in keys: # one checkpoint each
logs = jnp.zeros(2)
for key in chunk:
logs = step(key, logs)
x = np.asarray(net_G(jax.random.normal(rngs(), (2000, latent))))
trace.append((mode_stats(x, grid)[1], *(logs / every).tolist()))
return net_G, trace我们执行 \(2 \times 2\) 因子实验,交叉组合两种目标(经典非饱和 NS 与 pairing)以及 \(\gamma = 0\)(无惩罚)与 \(\gamma = 1\)(\(R_1 + R_2\)),每组运行三个随机种子,外加一组 \(\gamma = 10\) 的过阻尼对照。
centers, latent = grid_centers().to(d2l.try_gpu()), 64
ns, pairing = (gan_loss_D, gan_loss_G), (d2l.rpgan_loss_D, d2l.rpgan_loss_G)
arms = {'NS': (*ns, 0.0, 3), 'NS + R1 + R2': (*ns, 1.0, 3),
'pairing': (*pairing, 0.0, 3), 'pairing + R1 + R2': (*pairing, 1.0, 3),
'pairing + R1 + R2, gamma=10': (*pairing, 10.0, 1)}
runs = {name: [] for name in arms} # per run: samples, trace
for name, (loss_D, loss_G, gamma, n_runs) in arms.items():
for seed in range(n_runs):
net_G, trace = train_grid(centers, loss_D, loss_G, gamma,
latent=latent, seed=seed)
with torch.no_grad():
z = torch.randn(10000, latent, device=centers.device)
runs[name].append((net_G(z).cpu().numpy(), trace))
grid = centers.cpu().numpy()centers, latent = grid_centers(), 64
ns, pairing = (gan_loss_D, gan_loss_G), (d2l.rpgan_loss_D, d2l.rpgan_loss_G)
arms = {'NS': (*ns, 0.0, 3), 'NS + R1 + R2': (*ns, 1.0, 3),
'pairing': (*pairing, 0.0, 3), 'pairing + R1 + R2': (*pairing, 1.0, 3),
'pairing + R1 + R2, gamma=10': (*pairing, 10.0, 1)}
runs, key = {name: [] for name in arms}, jax.random.key(1) # samples, trace
for name, (loss_D, loss_G, gamma, n_runs) in arms.items():
for seed in range(n_runs):
net_G, trace = train_grid(centers, loss_D, loss_G, gamma,
latent=latent, seed=seed)
key, subkey = jax.random.split(key)
z = jax.random.normal(subkey, (10000, latent))
runs[name].append((np.asarray(net_G(z)), trace))
grid = np.asarray(centers)下面我们汇总各次运行 10,000 个生成样本上的 mode_stats,并列出评判器最终的平方梯度范数 \(\mathbb{E}_q[\|\nabla_x D(x')\|^2]\):
print(f'{"arm":28} run modes on-mode distance E_q|grad D|^2')
for name, results in runs.items():
for seed, (x, trace) in enumerate(results):
modes, on, dist = mode_stats(x, grid)
print(f'{name:28} {seed:3} {modes:2}/25 {on:7.2f} {dist:8.2f}'
f' {trace[-1][2]:13.1e}')arm run modes on-mode distance E_q|grad D|^2
NS 0 16/25 0.70 0.20 1.7e+01
NS 1 25/25 0.90 0.10 2.2e+00
NS 2 24/25 0.76 0.16 5.6e+00
NS + R1 + R2 0 25/25 0.77 0.15 8.9e-04
NS + R1 + R2 1 25/25 0.83 0.13 6.8e-04
NS + R1 + R2 2 25/25 0.86 0.11 3.6e-04
pairing 0 25/25 0.82 0.13 3.9e+00
pairing 1 15/25 0.76 0.17 1.2e+01
pairing 2 23/25 0.80 0.15 5.1e+00
pairing + R1 + R2 0 25/25 0.86 0.12 3.3e-04
pairing + R1 + R2 1 25/25 0.89 0.09 1.9e-04
pairing + R1 + R2 2 25/25 0.85 0.12 5.0e-04
pairing + R1 + R2, gamma=10 0 23/25 0.19 0.46 1.2e-04
print(f'{"arm":28} run modes on-mode distance E_q|grad D|^2')
for name, results in runs.items():
for seed, (x, trace) in enumerate(results):
modes, on, dist = mode_stats(x, grid)
print(f'{name:28} {seed:3} {modes:2}/25 {on:7.2f} {dist:8.2f}'
f' {trace[-1][2]:13.1e}')arm run modes on-mode distance E_q|grad D|^2
NS 0 12/25 0.81 0.15 1.0e+01
NS 1 15/25 0.94 0.08 7.2e-01
NS 2 24/25 0.74 0.17 5.9e+00
NS + R1 + R2 0 25/25 0.67 0.21 2.4e-03
NS + R1 + R2 1 25/25 0.87 0.11 4.1e-04
NS + R1 + R2 2 25/25 0.79 0.14 8.2e-04
pairing 0 20/25 0.64 0.24 3.1e+00
pairing 1 17/25 0.78 0.15 1.3e+01
pairing 2 23/25 0.77 0.16 6.3e+00
pairing + R1 + R2 0 25/25 0.79 0.15 8.2e-04
pairing + R1 + R2 1 25/25 0.70 0.19 1.4e-03
pairing + R1 + R2 2 25/25 0.79 0.15 7.4e-04
pairing + R1 + R2, gamma=10 0 25/25 0.28 0.39 9.0e-05
将四个主实验组首次运行各 3,000 个生成样本与 25 个模式中心(grid)叠画,即可直观看出模式覆盖的差异:
fig, axes = d2l.plt.subplots(1, 4, figsize=(10, 2.9))
for ax, name in zip(axes, list(runs)[:4]):
x = runs[name][0][0][:3000] # run 0; centers drawn last
d2l.plot([x[:, 0], grid[:, 0]], [x[:, 1], grid[:, 1]],
fmts=('C1.', 'C0x'), xlim=(-5, 5), ylim=(-5, 5), axes=ax)
ax.set_title(name)
ax.set_aspect('equal')
fig.tight_layout()fig, axes = d2l.plt.subplots(1, 4, figsize=(10, 2.9))
for ax, name in zip(axes, list(runs)[:4]):
x = runs[name][0][0][:3000] # run 0; centers drawn last
d2l.plot([x[:, 0], grid[:, 0]], [x[:, 1], grid[:, 1]],
fmts=('C1.', 'C0x'), xlim=(-5, 5), ylim=(-5, 5), axes=ax)
ax.set_title(name)
ax.set_aspect('equal')
fig.tight_layout()实验结果清晰分离了梯度惩罚与配对损失各自的作用:
- 梯度惩罚驱动模式覆盖:无惩罚(\(\gamma = 0\))时,评判器梯度保持陡峭(\(\mathbb{E}_q\|\nabla_x D\|^2 \in [0.7, 17]\)),模式覆盖极不稳定(随随机种子跌至 12–25 个模式)。加入 \(\gamma = 1\) 的 \(R_1 + R_2\) 后,评判器梯度下降三个数量级(\(\sim 10^{-3}\)),在
NS与pairing下每次运行都覆盖全部 25 个模式。 - 大 \(\gamma\) 导致过阻尼:将 \(\gamma\) 增至 \(10\) 会使评判器过度平坦(\(\sim 10^{-4}\)),显著拖慢收敛,10,000 步后仅有 20–30% 的样本落在模式 \(3\sigma\) 范围内。
最后,查看检查点轨迹可说明为何平稳的评判器损失曲线必须谨慎解读:
traces = {name: np.array(results[0][1]) for name, results in runs.items()}
for col, stat in enumerate(['on-mode fraction', 'critic loss']):
print(f'{stat} of run 0 at every 1,250 steps')
for name, trace in traces.items(): # trace: (checkpoint, stat)
print(f' {name:28}', ' '.join(f'{v:4.2f}' for v in trace[:, col]))on-mode fraction of run 0 at every 1,250 steps
NS 0.01 0.03 0.08 0.16 0.29 0.54 0.69 0.72
NS + R1 + R2 0.02 0.03 0.09 0.08 0.26 0.64 0.68 0.79
pairing 0.02 0.07 0.17 0.31 0.50 0.73 0.74 0.82
pairing + R1 + R2 0.02 0.01 0.04 0.16 0.50 0.74 0.81 0.86
pairing + R1 + R2, gamma=10 0.02 0.03 0.02 0.05 0.09 0.09 0.16 0.21
critic loss of run 0 at every 1,250 steps
NS 1.35 1.21 1.04 1.00 1.01 1.03 1.05 1.07
NS + R1 + R2 1.38 1.37 1.36 1.37 1.38 1.38 1.38 1.38
pairing 0.68 0.65 0.57 0.57 0.60 0.62 0.63 0.64
pairing + R1 + R2 0.68 0.68 0.67 0.68 0.69 0.69 0.69 0.69
pairing + R1 + R2, gamma=10 0.69 0.70 0.69 0.69 0.69 0.69 0.69 0.69
traces = {name: np.array(results[0][1]) for name, results in runs.items()}
for col, stat in enumerate(['on-mode fraction', 'critic loss']):
print(f'{stat} of run 0 at every 1,250 steps')
for name, trace in traces.items(): # trace: (checkpoint, stat)
print(f' {name:28}', ' '.join(f'{v:4.2f}' for v in trace[:, col]))on-mode fraction of run 0 at every 1,250 steps
NS 0.01 0.02 0.06 0.15 0.52 0.68 0.78 0.81
NS + R1 + R2 0.03 0.03 0.06 0.11 0.27 0.36 0.59 0.68
pairing 0.01 0.07 0.15 0.25 0.27 0.46 0.59 0.62
pairing + R1 + R2 0.03 0.03 0.04 0.07 0.51 0.61 0.71 0.79
pairing + R1 + R2, gamma=10 0.02 0.02 0.03 0.05 0.06 0.09 0.20 0.27
critic loss of run 0 at every 1,250 steps
NS 1.34 1.15 0.95 0.93 0.94 0.95 0.96 0.96
NS + R1 + R2 1.38 1.37 1.36 1.37 1.37 1.38 1.38 1.38
pairing 0.68 0.67 0.64 0.61 0.59 0.58 0.58 0.58
pairing + R1 + R2 0.68 0.68 0.67 0.68 0.68 0.69 0.69 0.69
pairing + R1 + R2, gamma=10 0.69 0.70 0.69 0.69 0.69 0.69 0.69 0.69
在带惩罚运行中,从第一个检查点起评判器损失就紧贴其平衡值(NS 为 \(2\log 2 \approx 1.39\),pairing 为 \(\log 2 \approx 0.69\)),即便此时仅有 1–3% 的生成样本落在模式上——这是因为梯度惩罚处处压低了 \(D(x)\)。处于平衡值的评判器损失只表明评判器平坦,并不必然说明生成器已经收敛。
16.4.5 小结
在双参数 Dirac-GAN(\(p = \delta_0, q_\theta = \delta_\theta, D_\psi(x) = \psi x\))上,连续时间梯度流沿等半径圆周盘旋,同步离散步向外螺旋发散,交替离散步则困在有界环带中。减去零中心梯度惩罚 \(R_1 = \frac{\gamma}{2}\mathbb{E}_p[\|\nabla_x D(x)\|^2]\) 与 \(R_2 = \frac{\gamma}{2}\mathbb{E}_q[\|\nabla_{x'} D(x')\|^2]\) 可对任意 \(\gamma > 0\) 将雅可比特征值移入左开半平面(\(\operatorname{Re}(\nu_{1,2}) < 0\)),使平衡点局部指数稳定。在平衡点附近,\(R_1 + R_2\) 作为作用于 \(p - q\) 的空间低通滤波器(logistic 损失下截止长度尺度为 \(2\sqrt{\gamma}\)),在大尺度上接近 \(2\,\mathrm{JS}(p, q)\),在细尺度上过渡到平方对偶 Sobolev 范数 \(\|p - q\|_{\dot H^{-1}(m)}^2\)。实验上,在 25 高斯网格中,取 \(\gamma = 1\) 的 \(R_1 + R_2\) 将评判器陡峭度降低三个数量级,使经典 logistic 与相对配对两种目标均实现完整模式覆盖。
16.4.6 练习
- [code] Dirac-GAN 的离散时间稳定性。步长为 \(h\) 的同步梯度下降执行映射 \((\theta, \psi) \mapsto (\theta, \psi) + h\,\mathbf{u}(\theta, \psi)\)。
- 证明当 \(\gamma = 0\) 时,离散更新在 \((0, 0)\) 处的雅可比特征值为 \(1 \pm i\,h\,\ell'(0)\),对任意 \(h > 0\) 其模长 \(\sqrt{1 + h^2\ell'(0)^2} > 1\)。
- 当 \(\gamma > 0\) 时,特征值为 \(1 + h\nu_{1,2}\),其中 \(\nu_{1,2}\) 来自 式 16.4.6。证明在欠阻尼区 \(\gamma < 2\ell'(0)\) 内,离散更新局部稳定(\(|1 + h\nu_{1,2}| < 1\))当且仅当 \(h < \gamma / \ell'(0)^2\)。
- 在 \(h = 1.1\) 与 \(h = 1.3\) 处运行
trajectory(euler_step, (0.1, 0.1), h, 3000, gamma=0.3),验证 \(\gamma = 0.3\)(\(\ell'(0) = \tfrac12\),阈值 \(h = 1.2\))处的这一阈值。
- Dirac-GAN 上的带惩罚最优响应。考虑采用 \(\ell = \log \sigma\) 的 Dirac-GAN 上的 \(V_\gamma(\theta) = \sup_\psi \{V(\theta, \psi) - \gamma\psi^2\}\)。
- 证明对小 \(\theta\),最大化斜率为 \(\psi^\star \approx -\ell'(0)\theta / (2\gamma)\) 且 \(V_\gamma(\theta) = 2\ell(0) + \frac{\ell'(0)^2}{4\gamma}\theta^2 + O(\theta^4)\),与 \(W_2(\delta_0, \delta_\theta) = |\theta|\) 下的 式 16.4.8 一致。
- 现令 \(D\) 取遍受 \(\gamma\int m\,\|\nabla_x D\|^2\) 惩罚的所有可微函数。证明对点质量 \(p = \delta_0\) 与 \(q_\theta = \delta_\theta\)(\(\theta \neq 0\)),\(\sup_D \{V_\ell(D) - R_1 - R_2\} = 2\sup_t \ell(t)\) 与 \(\theta\) 无关。为何有限神经网络评判器仍能跨越间隔提供非零梯度?
- 单用 \(R_1\) 与联用 \(R_1 + R_2\) 的对比。令 \(p = \delta_0\)、\(q = \delta_1\)、\(\ell = \log \sigma\),考虑二次评判器 \(D_c(x) = -cx^2\)(\(c \geq 0\))。
- 计算 \(D_c\) 的 \(R_1\) 与 \(R_2\),并证明 \(V_\ell(D_c) - R_1\) 关于 \(c\) 严格递增,因而不存在有限极大值点。
- 证明在非饱和生成器损失 \(-\log \sigma(D_c(x'))\) 下,\(x' = 1\) 处的生成器梯度幅值随 \(c\) 无界增长,而减去 \(R_1 + R_2\) 则给出有限极大值点 \(c^\star < 1/(8\gamma)\)。
- [code] Dirac-GAN 上的交替更新。● 交替更新先执行 \(\psi_{k+1} = \psi_k + h\,u_\psi(\theta_k, \psi_k)\),再执行 \(\theta_{k+1} = \theta_k + h\,u_\theta(\theta_k, \psi_{k+1})\)。
- 对 \(\gamma = 0\) 在 \((0, 0)\) 处线性化组合更新,证明其雅可比行列式为 \(1\),且特征值位于单位圆上当且仅当 \(h\,\ell'(0) \leq 2\)。
- 在 \(\gamma = 0\) 下对 \(h \in \{0.2, 1, 3, 5\}\) 运行
trajectory(alt_step, (0.1, 0.1), h, 10**5),记录最后 \(10^4\) 步的最小与最大半径,并与 \(h = 0.2\)、\(\gamma = 0.3\) 的情形对比。
- [code] 局部二次价值与低通滤波。● 记 \(\mathcal{A} = |\ell''(0)|\,m + \gamma\mathcal{L}_m\),其中 \(\mathcal{L}_m D = -\nabla \cdot (m \nabla D)\)。
利用分部积分证明
\[|\ell''(0)|\int m\,D^2 + \gamma\int m\,\|\nabla_x D\|^2 = \langle D, \mathcal{A}D \rangle\]
并通过沿射线 \(t D_0\) 最大化及应用柯西–施瓦茨不等式推导 式 16.4.7。
令 \(p = \mathcal{N}(0, 1)\) 与 \(q(x) = p(x)(1 + 0.1\sin(\omega x))\)。利用
penalized_value对 \(\omega \in \{0.5, 2, 8\}\) 计算 \(\gamma \in \{0.01, 0.1, 1\}\) 处的带惩罚价值与 \(\gamma = 0\) 处无惩罚价值之比,并与均匀 \(m\) 时的傅里叶衰减因子 \((1 + 4\gamma\omega^2)^{-1}\) 对比。
- [code] Dirac-GAN 上的 1-中心惩罚动力学。● 考虑 WGAN 线性收益 \(\ell(t) = t\)(\(\ell'(0) = 1\)),并从评判器目标中减去 1-中心惩罚 \(\frac{\gamma}{2}(|\psi| - 1)^2\)。
- 证明同步梯度场对任意 \(\psi \neq 0\) 永不为零,并求出其在 \(\psi \to 0^\pm\) 时的单侧极限为零的生成器位置 \(\theta\)。
- 修改
dirac_field以使用 1-中心惩罚,从 \((1, 1)\) 出发以 \(h = 0.01\) 在 \(\gamma = 1\) 与 \(\gamma = 3\) 下各运行trajectory40,000 步,验证在 \(\gamma = 3\) 处生成器停滞在 \(\theta = 3\)。