import itertools16.3 相对目标函数
标准分类器评判器针对固定的零阈值(\(D(x') > 0\))给每个样本打分。但在许多场景中,成对比较比绝对打分更自然——就像 Bradley–Terry 偏好模型(15.3 节),它将两个候选者的分数之差转化为胜出概率。Jolicoeur-Martineau (2019年) 提出了相对 GAN 评判器:输入一个真实样本 \(x \sim p\) 与一个生成样本 \(x' \sim q\),依据二者的分数差 \(D(x) - D(x')\) 预测哪一个是真实样本。
由于我们在 16.4 节 中构建并在本章余下部分使用的 R3GAN 方案依赖这一成对目标,本节剖析三个问题:
- 最优成对排序评判器是否仍然恢复对数密度比 \(\lambda(x) = \log(p(x)/q(x))\)?
- 成对目标在最优点处度量的是什么散度,与 \(\mathrm{JS}(p, q)\) 有何关系?
- 在何种条件下,成对排序能够消除模式遗漏的局部极小点?
import itertools16.3.1 对样本对打分
16.3.1.1 Bradley–Terry 配对评判器
给定独立样本对 \((x, x')\)(\(x \sim p\),\(x' \sim q\)),相对配对目标(RpGAN,Jolicoeur-Martineau (2019年); Jolicoeur-Martineau (2020年))通过 Bradley–Terry 似然 \(\sigma(D(x) - D(x'))\) (Bradley 和 Terry 1952年) 对 \(x\) 比 \(x'\) 更逼真的概率建模:
\[ \Phi(D) \;=\; \mathbb{E}_{x \sim p,\; x' \sim q}\big[\log \sigma\big(D(x) - D(x')\big)\big]. \tag{16.3.1}\]
评判器最大化 \(\Phi(D)\)(即最小化 \(-\Phi(D)\))。在小批量上,rpgan_loss_D 对对齐样本对 \((x_i, x'_i)\) 的 \(-\log \sigma(D(x_i) - D(x'_i)) = \operatorname{softplus}(D(x'_i) - D(x_i))\) 取平均,而 rpgan_loss_G 通过交换两个参数实现非饱和生成器损失:
def rpgan_loss_D(critic, real, fake):
"""Relativistic pairing critic loss -E[log sigma(D(x) - D(x'))]."""
return F.softplus(critic(fake) - critic(real)).mean()
def rpgan_loss_G(critic, real, fake):
"""Non-saturating pairing loss for the generator."""
return F.softplus(critic(real) - critic(fake)).mean()
def rpgan_loss_D(critic, real, fake):
"""Relativistic pairing critic loss -E[log sigma(D(x) - D(x'))]."""
return jax.nn.softplus(critic(fake) - critic(real)).mean()
def rpgan_loss_G(critic, real, fake):
"""Non-saturating pairing loss for the generator."""
return jax.nn.softplus(critic(real) - critic(fake)).mean()16.3.1.2 平移不变性与最优评判器
与对数损失固定了零阈值的单样本分类器不同,成对排序目标只依赖分数差 \(D(x) - D(x')\)(图 16.3.1)。给 \(D\) 加上任意常数 \(b\) 都保持 \(\Phi(D + b) = \Phi(D)\) 不变。因此,单个分数 \(D(x')\) 的正负号并无意义;更自然的准确率指标是成对排序准确率 \(P(D(x) > D(x'))\)。
在单样本对数损失目标中,最大化 \(V(D)\) 在各个 \(x\) 上逐点解耦。在 式 16.3.1 中,所有点通过差值 \(D(x) - D(x')\) 彼此耦合,但凹性依然给出闭式最优解。
命题。\(\Phi(D)\) 关于 \(D\) 是凹函数;当 \(p\) 与 \(q\) 具有相同支集时,其在加性常数意义下被 \(D^\star(x) = \lambda(x) = \log(p(x)/q(x))\) 唯一最大化。
证明。由于 \(D \mapsto D(x) - D(x')\) 是线性的且 \(\log \sigma\) 严格凹,因此 \(\Phi(D)\) 关于 \(D\) 凹、关于分数差严格凹。对 \(\Phi(D)\) 关于 \(D(t)\) 求泛函导数(\(t\) 既作为真实样本 \(x\) 出现,也作为生成样本 \(x'\) 出现),并利用 \(\tfrac{d}{du} \log \sigma(u) = \sigma(-u)\) 可得:
\[ \begin{aligned} \frac{\delta \Phi}{\delta D(t)} &= p(t)\, \mathbb{E}_{x' \sim q}\big[\sigma(D(x') - D(t))\big] \\ &\quad - q(t)\, \mathbb{E}_{x \sim p}\big[\sigma(D(t) - D(x))\big]. \end{aligned} \tag{16.3.2}\]
代入 \(D = \lambda = \log \rho\)(其中 \(\rho = p/q\)),得 \(\sigma(\lambda(x') - \lambda(t)) = \rho(x')/(\rho(x') + \rho(t))\)。利用 \(q\rho = p\),式 16.3.2 中的两项均等于 \(p(t) \int \frac{p(x)}{\rho(x) + \rho(t)}\,dx\),于是处处有 \(\frac{\delta \Phi}{\delta D(t)} = 0\)。由 \(\log \sigma\) 关于分数差的严格凹性,\(D^\star = \lambda + c\) 在加性常数 \(c\) 意义下是唯一极大值点。\(\blacksquare\)
16.3.2 配对散度
16.3.2.1 二态示例
为看清 \(\Phi(D)\) 的最优值与 Jensen–Shannon 散度的联系,考虑二态空间 \(\{0, 1\}\),设 \(p = (0.8, 0.2)\) 且 \(q = (0.2, 0.8)\)。真实样本在前的有序对 \((a_1, a_2)\) 服从乘积分布 \(P(a_1, a_2) = p(a_1)q(a_2)\),真实样本在后的有序对则服从 \(Q(a_1, a_2) = q(a_1)p(a_2)\):
| 样本对 \((a_1, a_2)\) | \((0, 0)\) | \((1, 1)\) | \((0, 1)\) | \((1, 0)\) |
|---|---|---|---|---|
| \(P = p \otimes q\)(真在前) | 0.16 | 0.16 | 0.64 | 0.04 |
| \(Q = q \otimes p\)(真在后) | 0.16 | 0.16 | 0.04 | 0.64 |
平局对 \((0, 0)\) 与 \((1, 1)\) 不携带任何关于谁是真实样本的信息,而混合对 \((0, 1)\) 与 \((1, 0)\) 则以 \(0.64/(0.64 + 0.04) = 16/17 \approx 0.94\) 的后验概率识别出真实样本(单样本观测仅为 \(0.80\))。在最优分数差 \(d = D^\star(0) - D^\star(1) = \lambda(0) - \lambda(1) = \log 16\) 处,相对随机猜测(\(\Phi(0) = -\log 2\))的增益为 \(\sup_D \Phi(D) + \log 2 = 0.68\big(\log 2 - H_b(\tfrac{1}{17})\big) \approx 0.319\) 奈特——这是 \(\mathrm{JS}(p, q) = \log 2 - H_b(0.8) \approx 0.193\) 奈特的 \(1.66\times\),并且恰好等于两个样本对分布 \(P\) 与 \(Q\) 之间的 \(\mathrm{JS}(P, Q)\):
def entropy(v):
v = v[v > 0] # the convention 0 log 0 = 0
return -(v * np.log(v)).sum()
def js(a, b):
return entropy((a + b) / 2) - (entropy(a) + entropy(b)) / 2
p, q = np.array([0.8, 0.2]), np.array([0.2, 0.8])
P, Q = np.outer(p, q), np.outer(q, p) # P[i, j]: real sample at i, generated at j
lam = np.log(p / q) # the optimal critic: lam[0] - lam[1] = log 16
U = lam[:, None] - lam[None, :] # U[i, j] = D(i) - D(j)
phi = (P * -np.logaddexp(0, -U)).sum() # Phi = E_P[log sigma(D(a_1) - D(a_2))]
print(f'JS(p, q) = {js(p, q):.3f} JS(P, Q) = {js(P.ravel(), Q.ravel()):.3f} '
f'sup Phi + log 2 = {phi + np.log(2):.3f}')JS(p, q) = 0.193 JS(P, Q) = 0.319 sup Phi + log 2 = 0.319
def entropy(v):
v = v[v > 0] # the convention 0 log 0 = 0
return -(v * np.log(v)).sum()
def js(a, b):
return entropy((a + b) / 2) - (entropy(a) + entropy(b)) / 2
p, q = np.array([0.8, 0.2]), np.array([0.2, 0.8])
P, Q = np.outer(p, q), np.outer(q, p) # P[i, j]: real sample at i, generated at j
lam = np.log(p / q) # the optimal critic: lam[0] - lam[1] = log 16
U = lam[:, None] - lam[None, :] # U[i, j] = D(i) - D(j)
phi = (P * -np.logaddexp(0, -U)).sum() # Phi = E_P[log sigma(D(a_1) - D(a_2))]
print(f'JS(p, q) = {js(p, q):.3f} JS(P, Q) = {js(P.ravel(), Q.ravel()):.3f} '
f'sup Phi + log 2 = {phi + np.log(2):.3f}')JS(p, q) = 0.193 JS(P, Q) = 0.319 sup Phi + log 2 = 0.319
16.3.2.2 提升至乘积测度
将有序对 \((a_1, a_2) \in \mathcal{X} \times \mathcal{X}\) 视作来自 \(P = p \otimes q\)(真在前)或 \(Q = q \otimes p\)(真在后)的单个观测,并在 \(\mathcal{X} \times \mathcal{X}\) 上用样本对评判器 \(\mathcal{D}(a_1, a_2)\) 考虑 16.1 节 的标准对数损失目标,即可在一般意义下证明上述等价性:
\[ \begin{aligned} V_{P,Q}(\mathcal{D}) &= \mathbb{E}_{(a_1, a_2) \sim P}\big[\log \sigma(\mathcal{D}(a_1, a_2))\big] \\ &\quad + \mathbb{E}_{(a_1, a_2) \sim Q}\big[\log \sigma(-\mathcal{D}(a_1, a_2))\big]. \end{aligned} \]
引理(提升至乘积空间)。令 \(P = p \otimes q\) 且 \(Q = q \otimes p\)。则:
- 乘积空间上的对数密度比可加分离:\(\log \frac{dP}{dQ}(a_1, a_2) = \lambda(a_1) - \lambda(a_2)\)。
- 任意反对称差分评判器 \(\mathcal{D}(a_1, a_2) = D(a_1) - D(a_2)\) 均满足 \(V_{P,Q}(\mathcal{D}) = 2\,\Phi(D)\)。
- 将 \(\mathcal{D}\) 限制在差分评判器 \(D(a_1) - D(a_2)\) 内不会降低上确界:\(\sup_{\mathcal{D}} V_{P,Q}(\mathcal{D}) = \sup_{D} V_{P,Q}\big(D(a_1) - D(a_2)\big)\)。
证明。(1)由 \(\frac{dP}{dQ}(a_1, a_2) = \frac{p(a_1)q(a_2)}{q(a_1)p(a_2)} = \frac{\rho(a_1)}{\rho(a_2)}\) 直接得出。对(2),在 \(Q\) 下有 \((a_1, a_2) \sim q \otimes p\) 且 \(-\mathcal{D}(a_1, a_2) = D(a_2) - D(a_1)\),因此 \(V_{P,Q}(\mathcal{D})\) 的两个期望均等于 \(\Phi(D)\)。对(3),\(V_{P,Q}(\mathcal{D})\) 的无约束极大值点为 \(\mathcal{D}^\star(a_1, a_2) = \log \frac{dP}{dQ}(a_1, a_2)\),由(1)知其天然具有差分形式 \(\lambda(a_1) - \lambda(a_2)\)。\(\blacksquare\)
(注意,性质 3 专门依赖 logistic 收益的对数连接;对于最小二乘等其他收益,最优样本对评判器是 \(\lambda(a_1) - \lambda(a_2)\) 的非线性函数,无法可加分离;见练习 4。)
定理。校准后的配对散度 \(d_{\mathrm{Rp}}(p, q) := \sup_D \Phi(D) + \log 2\) 满足
\[ \begin{aligned} d_{\mathrm{Rp}}(p, q) &= \mathrm{JS}\big(p \otimes q,\; q \otimes p\big) \\ &= H\Big(\tfrac{1}{2}\big(p \otimes q + q \otimes p\big)\Big) - H(p) - H(q). \end{aligned} \tag{16.3.3}\]
证明。结合提升引理的第 2、3 部分与 Jensen–Shannon 极小极大恒等式 \(\sup_{\mathcal{D}} V_{P,Q}(\mathcal{D}) = 2\,\mathrm{JS}(P, Q) - 2\log 2\)(16.1 节),可得 \(2\sup_D \Phi(D) = \sup_{\mathcal{D}} V_{P,Q}(\mathcal{D}) = 2\,\mathrm{JS}(P, Q) - 2\log 2\),证毕第一等式。应用熵差恒等式 \(\mathrm{JS}(P, Q) = H(\tfrac{1}{2}(P + Q)) - \tfrac{1}{2}(H(P) + H(Q))\)(16.1 节)及 \(H(p \otimes q) = H(q \otimes p) = H(p) + H(q)\),即得第二等式。\(\blacksquare\)
将 \(D^\star = \lambda\) 直接代入 式 16.3.1 也可得到显式期望形式:
\[ \begin{aligned} d_{\mathrm{Rp}}(p, q) &= \log 2 - \mathbb{E}_{x \sim p,\; x' \sim q}\Big[\log\Big(1 + \frac{q(x)\, p(x')}{p(x)\, q(x')}\Big)\Big], \end{aligned} \tag{16.3.4}\]
而在样本对空间上应用互信息恒等式 \(\mathrm{JS}(P, Q) = I((a_1, a_2); y)\)(16.1 节)表明,对带有顺序标签 \(y \in \{0, 1\}\) 的随机排序样本对 \((a_1, a_2)\),有
\[ \begin{aligned} d_{\mathrm{Rp}}(p, q) &= I\big((a_1, a_2);\, y\big) = \log 2 - H\big(y \mid a_1, a_2\big). \end{aligned} \tag{16.3.5}\]
16.3.2.3 信息界
利用 式 16.3.5,我们可以把 \(d_{\mathrm{Rp}}(p, q)\) 直接与 \(\mathrm{JS}(p, q)\) 联系起来。随机排序对中的每个边缘元素 \(a_k\) 都服从 \(m = (p+q)/2\),并携带关于顺序标签 \(y\) 的 \(I(a_k; y) = \mathrm{JS}(p, q)\) 奈特信息;同时给定 \(y\) 时 \(a_1\) 与 \(a_2\) 条件独立(\(H(a_2 \mid a_1, y) = H(a_2 \mid y)\))。由互信息链式法则:
\[ \begin{aligned} d_{\mathrm{Rp}}(p, q) &= I(a_1; y) + I(a_2; y \mid a_1) \\ &= I(a_1; y) + I(a_2; y) - I(a_1; a_2) \\ &= 2\, \mathrm{JS}(p, q) - I(a_1; a_2). \end{aligned} \]
由于 \(I(a_2; y \mid a_1) \geq 0\)、\(I(a_1; a_2) \geq 0\) 且 \(d_{\mathrm{Rp}}(p, q) \leq \log 2\),我们得到紧夹逼界:
\[ \begin{aligned} \mathrm{JS}(p, q) &\leq d_{\mathrm{Rp}}(p, q) \leq \min\big(2\,\mathrm{JS}(p, q),\, \log 2\big). \end{aligned} \]
在平衡点附近(\(q \to p\)),\(I(a_1; a_2)\) 是 \(p - q\) 的四阶小量,而 \(\mathrm{JS}(p, q)\) 是二阶小量,因此 \(d_{\mathrm{Rp}}(p, q) \approx 2\,\mathrm{JS}(p, q)\)(练习 2)。当 \(p\) 与 \(q\) 支集不相交时,\(\mathrm{JS}(p, q)\) 与 \(d_{\mathrm{Rp}}(p, q)\) 均在 \(\log 2\) 处饱和。
16.3.3 排序与模式覆盖
16.3.3.1 相对排序权重
通过 \(x' = G(z)\) 对 \(\Phi(D)\) 关于生成器参数 \(\theta\) 求导可得:
\[ \begin{aligned} \nabla_\theta \Phi &= -\,\mathbb{E}_{z}\big[w_{\textrm{Rp}}(G(z))\, \nabla_\theta D(G(z))\big], \\ w_{\textrm{Rp}}(x') &= \mathbb{E}_{x \sim p}\big[\sigma\big(D(x') - D(x)\big)\big]. \end{aligned} \tag{16.3.6}\]
在饱和零和形式(最小化 \(\Phi\))中,每个生成样本沿 \(\nabla_\theta D(G(z))\) 推移的权重为 \(w_{\textrm{Rp}}(x')\)——即 \(x'\) 排在随机真实样本 \(x \sim p\) 之上的软化概率。在非饱和形式(rpgan_loss_G,最小化 \(-\mathbb{E}[\log \sigma(D(x') - D(x))]\))中,权重变为 \(1 - w_{\textrm{Rp}}(x') = \mathbb{E}_{x \sim p}[\sigma(D(x) - D(x'))]\)。与仅将 \(D(x')\) 同零比较的单样本权重 \(\sigma(\pm D(x'))\) 不同,相对权重把 \(D(x')\) 与真实分数 \(D(x)\) 的分布相比较,且对 \(D\) 的常数平移不变。
16.3.3.2 固定配对与全配对损失地形
成对排序能否消除模式遗漏的局部极小点?Sun 等 (2020年) 分析了离散情形:给定 \(n\) 个互异真实点 \(x_1, \ldots, x_n\) 与 \(n\) 个可自由移动的生成点 \(x'_1, \ldots, x'_n\),并在精确最优响应评判器 \(D\) 下评估:
\[ \begin{aligned} \mathcal{E}_{\mathrm{GAN}} &= \sup_D \tfrac{1}{2n} \textstyle\sum_{i} \big[\log \sigma(D(x_i)) + \log \sigma(-D(x'_i))\big],\\ \mathcal{E}_{\mathrm{diag}} &= \sup_D \tfrac{1}{n} \textstyle\sum_{i} \log \sigma\big(D(x_i) - D(x'_i)\big),\\ \mathcal{E}_{\mathrm{all}} &= \sup_D \tfrac{1}{n^2} \textstyle\sum_{i, j} \log \sigma\big(D(x_i) - D(x'_j)\big). \end{aligned} \tag{16.3.7}\]
此处 \(\mathcal{E}_{\mathrm{GAN}}\) 是经典单样本目标,\(\mathcal{E}_{\mathrm{diag}}\) 是固定配对目标(真实点 \(x_i\) 与生成点 \(x'_i\) 永久配对),而 \(\mathcal{E}_{\mathrm{all}}\) 则对全部 \(n^2\) 对真伪样本取平均。当所有 \(x'_i\) 都落在真实点上但至少有两个重合(使某些真实点未被覆盖)时,该构型称为碰撞。Sun 等 (2020年) 证明,每一个碰撞(共 \(n^n - n!\) 个)都是 \(\mathcal{E}_{\mathrm{GAN}}\) 的严格局部极小点,而 \(\mathcal{E}_{\mathrm{diag}}\) 从任意碰撞出发都存在通向全局极小值 \(-\log 2\) 的非递增逃逸路径。
我们可以在 \(n = 2\) 与 \(n = 3\) 上直接验证这一结论。记经验分布为 \(\hat p\) 与 \(\hat q\),则 \(\mathcal{E}_{\mathrm{GAN}} = \mathrm{JS}(\hat p, \hat q) - \log 2\),\(\mathcal{E}_{\mathrm{all}} = \mathrm{JS}(\hat p \otimes \hat q, \hat q \otimes \hat p) - \log 2\),而 \(\mathcal{E}_{\mathrm{diag}}\) 等于 \(-\log 2\) 乘以落在有向环上的有向边 \(i \to \text{gen}[i]\) 所占比例(练习 5)。
def on_cycle(i, gen):
"""Does the arrow from real point i to its partner's position close a cycle?"""
j = gen[i]
for _ in range(len(gen)):
if j == i:
return True
if j not in range(len(gen)): # a position that holds no data point
return False
j = gen[j] # follow the arrow of the real point at j
return False
def losses(gen):
"""Best-response classical, all-pairs and paired losses of a configuration."""
n = len(gen)
support = sorted(set(range(n)) | set(gen))
p_hat = np.isin(support, range(n)) / n
q_hat = np.array([gen.count(s) for s in support]) / n
P, Q = np.outer(p_hat, q_hat).ravel(), np.outer(q_hat, p_hat).ravel()
paired = -np.log(2) * np.mean([on_cycle(i, gen) for i in range(n)])
return np.array([js(p_hat, q_hat) - np.log(2), js(P, Q) - np.log(2), paired])
print('gen classical, all pairs, paired: nats, multiples of log 2')
for gen in ([0, 0], [0, 0.1]): # both on x_1; then x'_2 steps off it
value = losses(gen)
print(f'{str(gen):12s}{np.round(value, 3)} {np.round(value / np.log(2), 2)}')gen classical, all pairs, paired: nats, multiples of log 2
[0, 0] [-0.477 -0.347 -0.347] [-0.69 -0.5 -0.5 ]
[0, 0.1] [-0.347 -0.173 -0.347] [-0.5 -0.25 -0.5 ]
def on_cycle(i, gen):
"""Does the arrow from real point i to its partner's position close a cycle?"""
j = gen[i]
for _ in range(len(gen)):
if j == i:
return True
if j not in range(len(gen)): # a position that holds no data point
return False
j = gen[j] # follow the arrow of the real point at j
return False
def losses(gen):
"""Best-response classical, all-pairs and paired losses of a configuration."""
n = len(gen)
support = sorted(set(range(n)) | set(gen))
p_hat = np.isin(support, range(n)) / n
q_hat = np.array([gen.count(s) for s in support]) / n
P, Q = np.outer(p_hat, q_hat).ravel(), np.outer(q_hat, p_hat).ravel()
paired = -np.log(2) * np.mean([on_cycle(i, gen) for i in range(n)])
return np.array([js(p_hat, q_hat) - np.log(2), js(P, Q) - np.log(2), paired])
print('gen classical, all pairs, paired: nats, multiples of log 2')
for gen in ([0, 0], [0, 0.1]): # both on x_1; then x'_2 steps off it
value = losses(gen)
print(f'{str(gen):12s}{np.round(value, 3)} {np.round(value / np.log(2), 2)}')gen classical, all pairs, paired: nats, multiples of log 2
[0, 0] [-0.477 -0.347 -0.347] [-0.69 -0.5 -0.5 ]
[0, 0.1] [-0.347 -0.173 -0.347] [-0.5 -0.25 -0.5 ]
将 \(x'_2\) 从 \(0\) 移到 \(0.1\) 会使经典损失与全配对损失均升高(证实碰撞 [0, 0] 对二者都是严格局部极小点),而固定配对损失保持在 \(-\frac{1}{2}\log 2\) 不变。为系统检查全部 \(n^n\) 种构型,count_bad_minima(n) 对每个指派检验 small_moves(gen) 产生的局部扰动:
def small_moves(gen):
"""Each generated point stays or steps to one of n fresh positions next to it."""
n = len(gen)
for steps in itertools.product(range(n + 1), repeat=n):
if any(steps):
yield [g + k / 10 if k else g for g, k in zip(gen, steps)]
def count_bad_minima(n):
"""Suboptimal strict local minima among the assignments, per loss."""
best, count = losses(list(range(n))), np.zeros(3, dtype=int)
for gen in itertools.product(range(n), repeat=n):
value = losses(list(gen))
rises = np.all([losses(m) > value + 1e-9 for m in small_moves(list(gen))],
axis=0)
count += rises & (value > best + 1e-9)
return countdef small_moves(gen):
"""Each generated point stays or steps to one of n fresh positions next to it."""
n = len(gen)
for steps in itertools.product(range(n + 1), repeat=n):
if any(steps):
yield [g + k / 10 if k else g for g, k in zip(gen, steps)]
def count_bad_minima(n):
"""Suboptimal strict local minima among the assignments, per loss."""
best, count = losses(list(range(n))), np.zeros(3, dtype=int)
for gen in itertools.product(range(n), repeat=n):
value = losses(list(gen))
rises = np.all([losses(m) > value + 1e-9 for m in small_moves(list(gen))],
axis=0)
count += rises & (value > best + 1e-9)
return count对 \(n \in \{2, 3\}\) 运行 count_bad_minima,将每种目标下的次优严格局部极小点数与理论碰撞数 \(n^n - n!\) 作对比:
for n in (2, 3):
c = count_bad_minima(n)
print(f'n = {n}: classical {c[0]}, all pairs {c[1]}, paired {c[2]}; '
f'n^n - n! = {n**n - math.factorial(n)}')n = 2: classical 2, all pairs 2, paired 0; n^n - n! = 2
n = 3: classical 21, all pairs 21, paired 0; n^n - n! = 21
for n in (2, 3):
c = count_bad_minima(n)
print(f'n = {n}: classical {c[0]}, all pairs {c[1]}, paired {c[2]}; '
f'n^n - n! = {n**n - math.factorial(n)}')n = 2: classical 2, all pairs 2, paired 0; n^n - n! = 2
n = 3: classical 21, all pairs 21, paired 0; n^n - n! = 21
关键在于,穷举结果表明:虽然固定耦合损失 \(\mathcal{E}_{\mathrm{diag}}\) 有零个碰撞极小点,但全配对损失 \(\mathcal{E}_{\mathrm{all}}\) 与 \(\mathcal{E}_{\mathrm{GAN}}\) 一样保留了全部 \(n^n - n!\) 个碰撞极小点。由于标准小批量训练每步都独立重采真实与生成小批量,它在随机配对下的期望目标是 \(\mathcal{E}_{\mathrm{all}}\) 而非 \(\mathcal{E}_{\mathrm{diag}}\)(练习 5)。因此,Sun 等 (2020年) 的损失地形定理仅适用于固定一对一耦合;小批量 RpGAN 在模式覆盖上是否受益,必须通过实验检验(16.4 节)。
16.3.3.3 训练中的饱和配对与非饱和配对
饱和生成器损失(\(\Phi\))与非饱和生成器损失(rpgan_loss_G)共享同一全局极小点 \(q = p\)。当 \(p\) 与 \(q\) 已经重叠时,例如在 16.2.4.3 节 的三峰高斯混合基准上,两种变体都收敛至千分之几奈特以内:
scores = lambda s: s # train_toy passes scores, so the critic is the identity
arms = {'non-saturating': (lambda r, f: d2l.rpgan_loss_D(scores, r, f),
lambda r, f: d2l.rpgan_loss_G(scores, r, f)),
'saturating': (lambda r, f: d2l.rpgan_loss_D(scores, r, f),
lambda r, f: -d2l.rpgan_loss_D(scores, r, f))}
def first_step_below(trace, level=0.01, every=200):
below = np.flatnonzero(trace < level)
return f'{every * below[0]:5d}' if len(below) else ' none'
print('pairing critic; generator loss, runs 0, 1, 2')
for name, (critic_loss, gen_loss) in arms.items():
traces = [d2l.train_toy(critic_loss, gen_loss, seed) for seed in range(3)]
medians = ' '.join(f'{np.median(t[-2000 // 200:]):.4f}' for t in traces)
firsts = ' '.join(first_step_below(t) for t in traces)
print(f'{name:15s} median JS {medians} first JS < 0.01 {firsts}')pairing critic; generator loss, runs 0, 1, 2
non-saturating median JS 0.0006 0.0005 0.0007 first JS < 0.01 2400 2600 2400
saturating median JS 0.0020 0.0017 0.0014 first JS < 0.01 1800 1800 1800
scores = lambda s: s # train_toy passes scores, so the critic is the identity
arms = {'non-saturating': (lambda r, f: d2l.rpgan_loss_D(scores, r, f),
lambda r, f: d2l.rpgan_loss_G(scores, r, f)),
'saturating': (lambda r, f: d2l.rpgan_loss_D(scores, r, f),
lambda r, f: -d2l.rpgan_loss_D(scores, r, f))}
def first_step_below(trace, level=0.01, every=200):
below = np.flatnonzero(trace < level)
return f'{every * below[0]:5d}' if len(below) else ' none'
print('pairing critic; generator loss, runs 0, 1, 2')
for name, (critic_loss, gen_loss) in arms.items():
traces = [d2l.train_toy(critic_loss, gen_loss, seed) for seed in range(3)]
medians = ' '.join(f'{np.median(t[-2000 // 200:]):.4f}' for t in traces)
firsts = ' '.join(first_step_below(t) for t in traces)
print(f'{name:15s} median JS {medians} first JS < 0.01 {firsts}')pairing critic; generator loss, runs 0, 1, 2
non-saturating median JS 0.0008 0.0009 0.0006 first JS < 0.01 2200 2400 2200
saturating median JS 0.0018 0.0024 0.0010 first JS < 0.01 1800 1800 1800
两组均拟合至千分之几奈特或更低。非饱和组在 2,200 至 2,600 步之间跨过 0.01 奈特,与 16.2 节 中的 logistic 损失表现相当,说明配对在拟合精度上毫无损失;而饱和组在数据附近权重并不小,反而在每次运行中都更早跨过阈值(第 1,800 步)。
然而,当生成器远离数据起步时(16.2.4.2 节 中 d2l.train_shift 的 \(\theta_0 = 6\)),每个生成样本的排序都远低于每个真实样本(\(D(x') \ll D(x)\)),将饱和排序权重 \(w_{\textrm{Rp}}(x')\) 压向零:
steps = (0, 100, 300, 1000, 1500)
print(f'{"":20s}|gradient| theta at steps {steps} first |theta| < 0.5')
for name, (critic_loss, gen_loss) in arms.items():
for seed in range(3):
thetas, grads, _ = d2l.train_shift(critic_loss, gen_loss, seed)
hit = np.flatnonzero(np.abs(thetas) < 0.5)
print(f'{name:15s} {seed} {np.median(np.abs(grads[:100])):8.3f} '
+ ''.join(f'{thetas[t]:7.2f}' for t in steps) + ' '
+ (f'{hit[0]:5d}' if len(hit) else 'not reached')) |gradient| theta at steps (0, 100, 300, 1000, 1500) first |theta| < 0.5
non-saturating 0 3.244 6.00 2.41 0.57 0.02 0.00 323
non-saturating 1 3.021 6.00 2.26 0.55 0.02 0.00 317
non-saturating 2 3.057 6.00 2.65 0.60 0.02 0.00 335
saturating 0 0.000 6.00 6.00 6.00 6.00 6.00 not reached
saturating 1 0.000 6.00 6.00 6.00 6.00 5.99 not reached
saturating 2 0.000 6.00 6.00 6.00 6.00 5.99 not reached
steps = (0, 100, 300, 1000, 1500)
print(f'{"":20s}|gradient| theta at steps {steps} first |theta| < 0.5')
for name, (critic_loss, gen_loss) in arms.items():
for seed in range(3):
thetas, grads, _ = d2l.train_shift(critic_loss, gen_loss, seed)
hit = np.flatnonzero(np.abs(thetas) < 0.5)
print(f'{name:15s} {seed} {np.median(np.abs(grads[:100])):8.3f} '
+ ''.join(f'{thetas[t]:7.2f}' for t in steps) + ' '
+ (f'{hit[0]:5d}' if len(hit) else 'not reached')) |gradient| theta at steps (0, 100, 300, 1000, 1500) first |theta| < 0.5
non-saturating 0 3.186 6.00 2.43 0.58 0.02 0.00 324
non-saturating 1 3.058 6.00 2.24 0.54 0.02 0.00 314
non-saturating 2 3.006 6.00 2.56 0.59 0.02 0.00 331
saturating 0 0.000 6.00 6.00 6.00 6.00 6.00 not reached
saturating 1 0.000 6.00 6.00 6.00 6.00 5.99 not reached
saturating 2 0.000 6.00 6.00 6.00 6.00 5.99 not reached
从 \(\theta_0 = 6\) 出发,饱和配对生成器的梯度中位数低于 \(5 \times 10^{-4}\),1,500 步后仍滞留在 \(\theta \approx 6.00\);而非饱和配对生成器(rpgan_loss_G)获得 \(\sim 3\) 的梯度,在所有随机种子上约第 330 步便达到 \(|\theta| < 0.5\)。因此,本章余下部分一律采用非饱和配对损失。
16.3.4 小结
相对配对目标(RpGAN)最大化将真实样本排在生成样本之上的 Bradley–Terry 对数似然 \(\Phi(D) = \mathbb{E}_{x \sim p, x' \sim q}[\log \sigma(D(x) - D(x'))]\),在加性常数意义下恢复对数密度比 \(D^\star(x) = \lambda(x) = \log(p(x)/q(x))\)。将 \((a_1, a_2)\) 提升至乘积空间 \(\mathcal{X} \times \mathcal{X}\) 表明,校准后的最优值 \(d_{\mathrm{Rp}}(p, q) = \sup_D \Phi(D) + \log 2\) 等于 \(\mathrm{JS}(p \otimes q, q \otimes p) = 2\,\mathrm{JS}(p, q) - I(a_1; a_2)\),满足 \(\mathrm{JS}(p, q) \leq d_{\mathrm{Rp}}(p, q) \leq \min(2\,\mathrm{JS}(p, q), \log 2)\)。虽然永久一对一耦合 \(\mathcal{E}_{\mathrm{diag}}\) 在最优响应评判器下消除了离散模式遗漏碰撞极小点,但独立小批量重采样平均回全配对目标 \(\mathcal{E}_{\mathrm{all}}\),仍保留这些极小点。最后,当生成样本远离数据时,饱和排序权重 \(w_{\textrm{Rp}}(x') = \mathbb{E}_{x \sim p}[\sigma(D(x') - D(x))]\) 消失,而非饱和权重 \(1 - w_{\textrm{Rp}}(x')\) 维持接近 \(1\),保留了生成器梯度。
16.3.5 练习
- [code] 饱和与非饱和排序权重。考虑一个五态离散空间,数据分布 \(p = (0.35, 0.25, 0.20, 0.12, 0.08)\),生成器分布 \(q = (0.02, 0.05, 0.13, 0.30, 0.50)\)。
- 使用二态示例单元中的
js,计算 \(\mathrm{JS}(p, q)\) 与 \(d_{\mathrm{Rp}}(p, q)\),验证 25 个样本对状态上的 \(\mathrm{JS}(P, Q)\) 与 \(D = \lambda\) 处的 \(\sup_D \Phi(D) + \log 2\) 一致(\(\approx 0.234\) 与 \(0.377\))。 - 在 \(D = \lambda\) 下计算每个状态处的饱和权重 \(w_{\mathrm{Rp}}\)(式 16.3.6)与非饱和权重 \(1 - w_{\mathrm{Rp}}\),并比较二者在 \(q\) 下的期望。
- 证明在 \(D = \lambda\) 处有 \(\mathbb{E}_{x' \sim q}[w_{\mathrm{Rp}}(x')] = \iint \frac{P Q}{P + Q}\, da_1\, da_2 \leq \tfrac12\),等号成立当且仅当 \(q = p\),且随着 \(p\) 与 \(q\) 支集分离该期望趋于零。
- 从初始偏移
theta0\(\in \{1, 2, 3, 4\}\) 出发(每个取三个随机种子),用配对评判器与两种生成器损失运行d2l.train_shift,找出饱和生成器开始停滞的分离距离。
- 使用二态示例单元中的
- \(d_{\mathrm{Rp}}\) 与 \(2\,\mathrm{JS}(p, q)\) 之间的差距。● 考虑 式 16.3.5 中的随机排序对 \((a_1, a_2)\) 及其顺序标签 \(y\)。
- 证明给定 \(y\) 时 \(a_1\) 与 \(a_2\) 条件独立,且对 \(k \in \{1, 2\}\) 有 \(I(a_k; y) = \mathrm{JS}(p, q)\)。
- 当 \(p\) 与 \(q\) 支集不相交时,直接从样本对混合 \(\tfrac12(P + Q)\) 计算 \(I(a_1; a_2)\),并验证 \(I(a_1; a_2) = \mathrm{JS}(p, q) = \log 2\)。
- 对满足 \(\mathbb{E}_p[v] = 0\) 的局部扰动 \(q = p\,(1 + \epsilon v)\),证明 \(\mathrm{JS}(p, q) = \Theta(\epsilon^2)\) 而 \(I(a_1; a_2) = \Theta(\epsilon^4)\),因此当 \(\epsilon \to 0\) 时 \(d_{\mathrm{Rp}}(p, q) / \mathrm{JS}(p, q) \to 2\)。
- 在练习 1 的五态分布上数值验证 \(d_{\mathrm{Rp}}(p, q) = 2\,\mathrm{JS}(p, q) - I(a_1; a_2)\)。
- 两个高斯分布。令 \(\mathbb{R}^d\) 上 \(p = \mathcal{N}(0, I_d)\) 且 \(q = \mathcal{N}(\mu, I_d)\)。
- 证明 \(\lambda(x)\) 是 \(x\) 的仿射函数,且 式 16.3.4 中的 \(u = \lambda(x') - \lambda(x)\) 服从高斯分布;求其均值与方差。
- 将 \(\mathrm{JS}(p, q)\) 写成相同形式,并求缩放常数 \(c\),使对所有 \(\mu\) 均有 \(\mathrm{JS}\big(p, \mathcal{N}(c\mu, I_d)\big) = d_{\mathrm{Rp}}(p, q)\)。
- 对 \(\|\mu\| \in \{0.1, 1, 2, 4\}\) 用一维数值积分计算 \(d_{\mathrm{Rp}}(p, q)\) 与 \(\mathrm{JS}(p, q)\),并将二者之比同局部极限和大分离极限作比较。
- 样本对评判器的可分离性。● 将 式 16.3.1 中的 \(\log \sigma\) 替换为一般凹收益 \(\ell\),得 \(\Phi_\ell(D) = \mathbb{E}_{x \sim p, x' \sim q}[\ell(D(x) - D(x'))]\)。
- 对最小二乘收益 \(\ell(t) = -(1 - t)^2\),证明 \(\mathcal{X} \times \mathcal{X}\) 上的无约束最优样本对评判器为 \(2\eta - 1 = \tanh\big(\tfrac{\lambda(a_1) - \lambda(a_2)}{2}\big)\)(其中 \(\eta = P/(P + Q)\)),它不能可加分离为 \(D(a_1) - D(a_2)\)。
- 在练习 1 的五态示例上,计算无约束样本对最优值与 \(\sup_{D \in \mathbb{R}^5} 2\,\Phi_\ell(D)\) 之间的差距。
- 在不均衡顺序先验 \(\alpha \neq \tfrac12\) 的 logistic 收益下,推导贝叶斯最优样本对评判器,并说明差分函数类 \(D(a_1) - D(a_2)\) 需如何扩充才能达到该最优解。
- [code] 固定耦合与随机重配对。●●
- 证明
losses中用于 \(\mathcal{E}_{\mathrm{diag}}\) 的环规则:在任意有向无环边上,评判器可令 \(D(x_i) - D(x'_i) \to +\infty\) 从而损失消失;而在 \(k\)-环上差值之和为零,由 \(\log \sigma\) 的凹性可知相等分数处取得最大值 \(-k\log 2\)。 - 将
count_bad_minima扩展至 \(n = 4\)(256 种构型),并验证 \(\mathcal{E}_{\mathrm{GAN}}\)、\(\mathcal{E}_{\mathrm{all}}\) 与 \(\mathcal{E}_{\mathrm{diag}}\) 的计数。 - 定义排列平均最优响应目标 \(\frac{1}{n!} \sum_\pi \sup_D \frac{1}{n} \sum_i \log \sigma(D(x_i) - D(x'_{\pi(i)}))\),统计 \(n = 3\) 时其严格次优局部极小点数。将该体制与跨越多个随机配对小批量缓慢适应的评判器(面对的是 \(\mathcal{E}_{\mathrm{all}}\))作比较。
- 证明