import itertools16.3 Relativistic Objectives
A standard classifier critic scores each sample against a fixed zero threshold (\(D(x') > 0\)). In many settings, however, pairwise comparisons are more natural than absolute scores—much like Bradley–Terry preference models (Section 15.3), which turn the score difference between two candidates into a win probability. Jolicoeur-Martineau (2019) introduced relativistic GAN critics that take a real sample \(x \sim p\) and a generated sample \(x' \sim q\) and predict which one is real from their score difference \(D(x) - D(x')\).
Because the R3GAN recipe that we build in Section 16.4 and use in the rest of the chapter relies on this pairwise objective, we analyze three questions here:
- Does the optimal pairwise ranking critic still recover the log density ratio \(\lambda(x) = \log(p(x)/q(x))\)?
- What divergence does the pairwise objective measure at its optimum, and how does it compare to \(\mathrm{JS}(p, q)\)?
- Under what conditions does pairwise ranking eliminate mode-dropping local minima?
import itertools16.3.1 Scoring Pairs
16.3.1.1 The Bradley–Terry Pairing Critic
Given an independent pair \((x, x')\) with \(x \sim p\) and \(x' \sim q\), the relativistic pairing objective (RpGAN, Jolicoeur-Martineau (2019); Jolicoeur-Martineau (2020)) models the probability that \(x\) is more realistic than \(x'\) via the Bradley–Terry likelihood \(\sigma(D(x) - D(x'))\) (Bradley and Terry 1952):
\[ \Phi(D) \;=\; \mathbb{E}_{x \sim p,\; x' \sim q}\big[\log \sigma\big(D(x) - D(x')\big)\big]. \tag{16.3.1}\]
The critic maximizes \(\Phi(D)\) (minimizes \(-\Phi(D)\)). On a minibatch, rpgan_loss_D averages \(-\log \sigma(D(x_i) - D(x'_i)) = \operatorname{softplus}(D(x'_i) - D(x_i))\) over aligned pairs \((x_i, x'_i)\), while rpgan_loss_G implements the non-saturating generator loss by swapping the arguments:
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 Shift Invariance and the Optimal Critic
Unlike a single-sample classifier whose zero threshold is fixed by the log loss, a pairwise ranking objective depends only on differences \(D(x) - D(x')\) (Figure 16.3.1). Adding any constant \(b\) to \(D\) leaves \(\Phi(D + b) = \Phi(D)\) unchanged. Consequently, the sign of an individual score \(D(x')\) is arbitrary; the natural accuracy metric is instead the pairwise ranking accuracy \(P(D(x) > D(x'))\).
In the single-sample log-loss objective, maximizing \(V(D)\) decoupled pointwise across \(x\). In Equation 16.3.1, all points are coupled through the differences \(D(x) - D(x')\), but concavity still yields a closed-form optimum.
Proposition. \(\Phi(D)\) is concave in \(D\), and when \(p\) and \(q\) share the same support, it is maximized by \(D^\star(x) = \lambda(x) = \log(p(x)/q(x))\), uniquely up to an additive constant.
Proof. Because \(D \mapsto D(x) - D(x')\) is linear and \(\log \sigma\) is strictly concave, \(\Phi(D)\) is concave in \(D\) and strictly concave in the score differences. Taking the functional derivative of \(\Phi(D)\) with respect to \(D(t)\) (where \(t\) appears both as the real sample \(x\) and as the generated sample \(x'\)) and using \(\tfrac{d}{du} \log \sigma(u) = \sigma(-u)\) gives:
\[ \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}\]
Evaluating at \(D = \lambda = \log \rho\) (where \(\rho = p/q\)) gives \(\sigma(\lambda(x') - \lambda(t)) = \rho(x')/(\rho(x') + \rho(t))\). Using \(q\rho = p\), both terms in Equation 16.3.2 equal \(p(t) \int \frac{p(x)}{\rho(x) + \rho(t)}\,dx\), so \(\frac{\delta \Phi}{\delta D(t)} = 0\) everywhere. By strict concavity of \(\log \sigma\) in the score differences, \(D^\star = \lambda + c\) is the unique maximizer up to a constant shift \(c\). \(\blacksquare\)
16.3.2 The Pairing Divergence
16.3.2.1 A Two-State Example
To see how the optimal value of \(\Phi(D)\) relates to the Jensen–Shannon divergence, consider a two-state space \(\{0, 1\}\) with \(p = (0.8, 0.2)\) and \(q = (0.2, 0.8)\). An ordered pair \((a_1, a_2)\) drawn with the real sample first follows the product distribution \(P(a_1, a_2) = p(a_1)q(a_2)\), whereas a pair with the real sample second follows \(Q(a_1, a_2) = q(a_1)p(a_2)\):
| pair \((a_1, a_2)\) | \((0, 0)\) | \((1, 1)\) | \((0, 1)\) | \((1, 0)\) |
|---|---|---|---|---|
| \(P = p \otimes q\) (real first) | 0.16 | 0.16 | 0.64 | 0.04 |
| \(Q = q \otimes p\) (real second) | 0.16 | 0.16 | 0.04 | 0.64 |
Tied pairs \((0, 0)\) and \((1, 1)\) carry no information about which element is real, while mixed pairs \((0, 1)\) and \((1, 0)\) identify the real element with posterior probability \(0.64/(0.64 + 0.04) = 16/17 \approx 0.94\) (compared to \(0.80\) from observing a single sample). At the optimal score difference \(d = D^\star(0) - D^\star(1) = \lambda(0) - \lambda(1) = \log 16\), the gain over random guessing (\(\Phi(0) = -\log 2\)) is \(\sup_D \Phi(D) + \log 2 = 0.68\big(\log 2 - H_b(\tfrac{1}{17})\big) \approx 0.319\) nats—which is \(1.66\times\) larger than \(\mathrm{JS}(p, q) = \log 2 - H_b(0.8) \approx 0.193\) nats, and exactly equal to \(\mathrm{JS}(P, Q)\) between the two pair distributions \(P\) and \(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 Lifting to Product Measures
We can prove this equivalence in general by viewing the ordered pair \((a_1, a_2) \in \mathcal{X} \times \mathcal{X}\) as a single observation drawn either from \(P = p \otimes q\) (real first) or from \(Q = q \otimes p\) (real second), and considering the standard log-loss objective of Section 16.1 on \(\mathcal{X} \times \mathcal{X}\) with a pair critic \(\mathcal{D}(a_1, a_2)\):
\[ \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} \]
Lemma (Lifting to Product Space). Let \(P = p \otimes q\) and \(Q = q \otimes p\). Then:
- The log density ratio on the product space separates additively: \(\log \frac{dP}{dQ}(a_1, a_2) = \lambda(a_1) - \lambda(a_2)\).
- Every antisymmetric difference critic \(\mathcal{D}(a_1, a_2) = D(a_1) - D(a_2)\) satisfies \(V_{P,Q}(\mathcal{D}) = 2\,\Phi(D)\).
- Restricting \(\mathcal{D}\) to difference critics \(D(a_1) - D(a_2)\) does not reduce the supremum: \(\sup_{\mathcal{D}} V_{P,Q}(\mathcal{D}) = \sup_{D} V_{P,Q}\big(D(a_1) - D(a_2)\big)\).
Proof. (1) follows immediately from \(\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)}\). For (2), under \(Q\) we have \((a_1, a_2) \sim q \otimes p\) and \(-\mathcal{D}(a_1, a_2) = D(a_2) - D(a_1)\), so both expectations in \(V_{P,Q}(\mathcal{D})\) equal \(\Phi(D)\). For (3), the unconstrained maximizer of \(V_{P,Q}(\mathcal{D})\) is \(\mathcal{D}^\star(a_1, a_2) = \log \frac{dP}{dQ}(a_1, a_2)\), which by (1) already has the difference form \(\lambda(a_1) - \lambda(a_2)\). \(\blacksquare\)
(Note that Property 3 relies specifically on the logarithmic link of the logistic payoff; for other payoffs such as least squares, the optimal pair critic is a nonlinear function of \(\lambda(a_1) - \lambda(a_2)\) that is not additively separable; see Exercise 4.)
Theorem. The calibrated pairing divergence \(d_{\mathrm{Rp}}(p, q) := \sup_D \Phi(D) + \log 2\) satisfies
\[ \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}\]
Proof. Combining Parts 2 and 3 of the Lifting Lemma with the Jensen–Shannon minimax identity \(\sup_{\mathcal{D}} V_{P,Q}(\mathcal{D}) = 2\,\mathrm{JS}(P, Q) - 2\log 2\) (Section 16.1) gives \(2\sup_D \Phi(D) = \sup_{\mathcal{D}} V_{P,Q}(\mathcal{D}) = 2\,\mathrm{JS}(P, Q) - 2\log 2\), proving the first equality. Applying the entropy-gap identity \(\mathrm{JS}(P, Q) = H(\tfrac{1}{2}(P + Q)) - \tfrac{1}{2}(H(P) + H(Q))\) (Section 16.1) and using \(H(p \otimes q) = H(q \otimes p) = H(p) + H(q)\) yields the second equality. \(\blacksquare\)
Substituting \(D^\star = \lambda\) directly into Equation 16.3.1 also yields the explicit expectation form:
\[ \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}\]
and the mutual-information identity \(\mathrm{JS}(P, Q) = I((a_1, a_2); y)\) (Section 16.1) on the pair space shows that for a randomly ordered pair \((a_1, a_2)\) with ordering label \(y \in \{0, 1\}\),
\[ \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 Information Bounds
Using Equation 16.3.5, we can relate \(d_{\mathrm{Rp}}(p, q)\) directly to \(\mathrm{JS}(p, q)\). Each marginal element \(a_k\) of the randomly ordered pair has distribution \(m = (p+q)/2\) and carries \(I(a_k; y) = \mathrm{JS}(p, q)\) nats about the ordering label \(y\), while \(a_1\) and \(a_2\) are conditionally independent given \(y\) (\(H(a_2 \mid a_1, y) = H(a_2 \mid y)\)). By the chain rule of mutual information:
\[ \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} \]
Because \(I(a_2; y \mid a_1) \geq 0\), \(I(a_1; a_2) \geq 0\), and \(d_{\mathrm{Rp}}(p, q) \leq \log 2\), we obtain the tight sandwich bounds:
\[ \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} \]
Near equilibrium (\(q \to p\)), \(I(a_1; a_2)\) is fourth-order in \(p - q\) while \(\mathrm{JS}(p, q)\) is second-order, so \(d_{\mathrm{Rp}}(p, q) \approx 2\,\mathrm{JS}(p, q)\) (Exercise 2). When \(p\) and \(q\) have disjoint supports, both \(\mathrm{JS}(p, q)\) and \(d_{\mathrm{Rp}}(p, q)\) saturate at \(\log 2\).
16.3.3 Ranking and Mode Coverage
16.3.3.1 The Relativistic Rank Weight
Differentiating \(\Phi(D)\) with respect to the generator parameters \(\theta\) through \(x' = G(z)\) yields:
\[ \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}\]
In the saturating zero-sum formulation (minimizing \(\Phi\)), each generated sample is pushed along \(\nabla_\theta D(G(z))\) with weight \(w_{\textrm{Rp}}(x')\)—the softened probability that \(x'\) outranks a randomly drawn real sample \(x \sim p\). In the non-saturating formulation (rpgan_loss_G, minimizing \(-\mathbb{E}[\log \sigma(D(x') - D(x))]\)), the weight becomes \(1 - w_{\textrm{Rp}}(x') = \mathbb{E}_{x \sim p}[\sigma(D(x) - D(x'))]\). Unlike the single-sample weights \(\sigma(\pm D(x'))\), which compare \(D(x')\) only against zero, the relativistic weight compares \(D(x')\) against the distribution of real scores \(D(x)\) and is invariant to constant shifts of \(D\).
16.3.3.2 Fixed-Pairing versus All-Pairs Landscapes
Does pairwise ranking eliminate mode-dropping local minima? Sun et al. (2020) analyzed the discrete setting of \(n\) distinct real points \(x_1, \ldots, x_n\) and \(n\) freely movable generated points \(x'_1, \ldots, x'_n\) evaluated at the exact best-response critic \(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}\]
Here \(\mathcal{E}_{\mathrm{GAN}}\) is the classic single-sample objective, \(\mathcal{E}_{\mathrm{diag}}\) is the fixed-pairing objective (where real point \(x_i\) is permanently paired with generated point \(x'_i\)), and \(\mathcal{E}_{\mathrm{all}}\) averages over all \(n^2\) real–generated pairs. A configuration where all \(x'_i\) land on real points but at least two coincide (leaving some real point uncovered) is called a collision. Sun et al. (2020) proved that every collision (\(n^n - n!\) of them) is a strict local minimum of \(\mathcal{E}_{\mathrm{GAN}}\), whereas \(\mathcal{E}_{\mathrm{diag}}\) has a non-increasing escape path from every collision to the global minimum \(-\log 2\).
We can verify this directly for \(n = 2\) and \(n = 3\). With empirical distributions \(\hat p\) and \(\hat q\), \(\mathcal{E}_{\mathrm{GAN}} = \mathrm{JS}(\hat p, \hat q) - \log 2\) and \(\mathcal{E}_{\mathrm{all}} = \mathrm{JS}(\hat p \otimes \hat q, \hat q \otimes \hat p) - \log 2\), while \(\mathcal{E}_{\mathrm{diag}}\) equals \(-\log 2\) times the fraction of directed edges \(i \to \text{gen}[i]\) that lie on a cycle (Exercise 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 ]
Moving \(x'_2\) from \(0\) to \(0.1\) raises the classical and all-pairs losses (confirming that the collision [0, 0] is a strict local minimum for both) while leaving the fixed-pairing loss unchanged at \(-\frac{1}{2}\log 2\). To check all \(n^n\) configurations systematically, count_bad_minima(n) tests every assignment against local perturbations from 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 countRunning count_bad_minima for \(n \in \{2, 3\}\) compares the number of suboptimal strict local minima under each objective against the theoretical collision count \(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
Crucially, the enumeration shows that while the fixed-coupling loss \(\mathcal{E}_{\mathrm{diag}}\) has zero collision minima, the all-pairs loss \(\mathcal{E}_{\mathrm{all}}\) has all \(n^n - n!\) collision minima—just like \(\mathcal{E}_{\mathrm{GAN}}\). Because standard minibatch training resamples independent real and generated minibatches at every step, its expected objective over random pairings is \(\mathcal{E}_{\mathrm{all}}\), not \(\mathcal{E}_{\mathrm{diag}}\) (Exercise 5). Thus, the landscape theorem of Sun et al. (2020) applies only to a fixed one-to-one coupling, and any mode-coverage benefit of minibatch RpGAN must be tested empirically (Section 16.4).
16.3.3.3 Saturating versus Non-Saturating Pairing in Training
Both the saturating generator loss (\(\Phi\)) and the non-saturating generator loss (rpgan_loss_G) share the global minimum \(q = p\). When \(p\) and \(q\) already overlap, as on the 3-mode Gaussian mixture benchmark of Section 16.2.4.3, both variants converge to within a few thousandths of a nat:
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
Both arms fit, to a few thousandths of a nat or less. The non-saturating runs cross 0.01 nats between steps 2,200 and 2,600, as the logistic loss of Section 16.2 did, so pairing loses nothing in fit, and the saturating ones, whose weight is not small near the data, cross first, at step 1,800 in every run.
However, when the generator starts far from the data (\(\theta_0 = 6\) in d2l.train_shift from Section 16.2.4.2), every generated sample is ranked far below every real sample (\(D(x') \ll D(x)\)), driving the saturating rank weight \(w_{\textrm{Rp}}(x')\) to zero:
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
From \(\theta_0 = 6\), the saturating pairing generator has a median gradient below \(5 \times 10^{-4}\) and remains stuck at \(\theta \approx 6.00\) after 1,500 steps, whereas the non-saturating pairing generator (rpgan_loss_G) receives gradients of \(\sim 3\) and reaches \(|\theta| < 0.5\) around step 330 across all seeds. We therefore use the non-saturating pairing loss throughout the rest of the chapter.
16.3.4 Summary
The relativistic pairing objective (RpGAN) maximizes the Bradley–Terry log-likelihood \(\Phi(D) = \mathbb{E}_{x \sim p, x' \sim q}[\log \sigma(D(x) - D(x'))]\) of ranking a real sample above a generated sample, recovering the log density ratio \(D^\star(x) = \lambda(x) = \log(p(x)/q(x))\) up to an additive constant. Lifting \((a_1, a_2)\) to the product space \(\mathcal{X} \times \mathcal{X}\) shows that the calibrated optimal value \(d_{\mathrm{Rp}}(p, q) = \sup_D \Phi(D) + \log 2\) equals \(\mathrm{JS}(p \otimes q, q \otimes p) = 2\,\mathrm{JS}(p, q) - I(a_1; a_2)\), which satisfies \(\mathrm{JS}(p, q) \leq d_{\mathrm{Rp}}(p, q) \leq \min(2\,\mathrm{JS}(p, q), \log 2)\). Although a permanent one-to-one coupling \(\mathcal{E}_{\mathrm{diag}}\) eliminates discrete mode-dropping collision minima at the best-response critic, independent minibatch resampling averages back to the all-pairs objective \(\mathcal{E}_{\mathrm{all}}\) and retains those minima. Finally, when generated samples lie far from the data, the saturating rank weight \(w_{\textrm{Rp}}(x') = \mathbb{E}_{x \sim p}[\sigma(D(x') - D(x))]\) vanishes, whereas the non-saturating weight \(1 - w_{\textrm{Rp}}(x')\) stays near \(1\) and preserves the generator gradient.
16.3.5 Exercises
- [code] Saturating and non-saturating rank weights. Consider a 5-state discrete space with data distribution \(p = (0.35, 0.25, 0.20, 0.12, 0.08)\) and generator distribution \(q = (0.02, 0.05, 0.13, 0.30, 0.50)\).
- Using
jsfrom the two-state cell, compute \(\mathrm{JS}(p, q)\) and \(d_{\mathrm{Rp}}(p, q)\), verifying that \(\mathrm{JS}(P, Q)\) on the 25 pair states matches \(\sup_D \Phi(D) + \log 2\) at \(D = \lambda\) (\(\approx 0.234\) and \(0.377\)). - Evaluate the saturating weight \(w_{\mathrm{Rp}}\) (Equation 16.3.6) and non-saturating weight \(1 - w_{\mathrm{Rp}}\) at each state under \(D = \lambda\), and compare their \(q\)-expectations.
- At \(D = \lambda\), show that \(\mathbb{E}_{x' \sim q}[w_{\mathrm{Rp}}(x')] = \iint \frac{P Q}{P + Q}\, da_1\, da_2 \leq \tfrac12\), with equality if and only if \(q = p\), and that it vanishes as the supports of \(p\) and \(q\) separate.
- Run
d2l.train_shiftwith the pairing critic and both generator losses from initial offsetstheta0\(\in \{1, 2, 3, 4\}\) (three seeds each) to find the separation at which the saturating generator stalls.
- Using
- Gap between \(d_{\mathrm{Rp}}\) and \(2\,\mathrm{JS}(p, q)\). ● Consider the randomly ordered pair \((a_1, a_2)\) and its ordering label \(y\) from Equation 16.3.5.
- Show that \(a_1\) and \(a_2\) are conditionally independent given \(y\) and that \(I(a_k; y) = \mathrm{JS}(p, q)\) for \(k \in \{1, 2\}\).
- When \(p\) and \(q\) have disjoint supports, compute \(I(a_1; a_2)\) directly from the pair mixture \(\tfrac12(P + Q)\) and verify that \(I(a_1; a_2) = \mathrm{JS}(p, q) = \log 2\).
- For a local perturbation \(q = p\,(1 + \epsilon v)\) with \(\mathbb{E}_p[v] = 0\), show that \(\mathrm{JS}(p, q) = \Theta(\epsilon^2)\) whereas \(I(a_1; a_2) = \Theta(\epsilon^4)\), so \(d_{\mathrm{Rp}}(p, q) / \mathrm{JS}(p, q) \to 2\) as \(\epsilon \to 0\).
- Verify \(d_{\mathrm{Rp}}(p, q) = 2\,\mathrm{JS}(p, q) - I(a_1; a_2)\) numerically on the 5-state distribution of Exercise 1.
- Two Gaussians. Let \(p = \mathcal{N}(0, I_d)\) and \(q = \mathcal{N}(\mu, I_d)\) on \(\mathbb{R}^d\).
- Show that \(\lambda(x)\) is affine in \(x\) and that \(u = \lambda(x') - \lambda(x)\) in Equation 16.3.4 is Gaussian; find its mean and variance.
- Express \(\mathrm{JS}(p, q)\) in the same form and find the scaling constant \(c\) for which \(\mathrm{JS}\big(p, \mathcal{N}(c\mu, I_d)\big) = d_{\mathrm{Rp}}(p, q)\) for all \(\mu\).
- Evaluate \(d_{\mathrm{Rp}}(p, q)\) and \(\mathrm{JS}(p, q)\) by 1D quadrature for \(\|\mu\| \in \{0.1, 1, 2, 4\}\) and compare their ratio against the local and large-separation limits.
- Separability of the pair critic. ● Replace \(\log \sigma\) in Equation 16.3.1 with a general concave payoff \(\ell\), giving \(\Phi_\ell(D) = \mathbb{E}_{x \sim p, x' \sim q}[\ell(D(x) - D(x'))]\).
- For the least-squares payoff \(\ell(t) = -(1 - t)^2\), show that the unconstrained optimal pair critic on \(\mathcal{X} \times \mathcal{X}\) is \(2\eta - 1 = \tanh\big(\tfrac{\lambda(a_1) - \lambda(a_2)}{2}\big)\) with \(\eta = P/(P + Q)\), which is not additively separable as \(D(a_1) - D(a_2)\).
- On the 5-state example of Exercise 1, compute the gap between the unconstrained pair optimum and \(\sup_{D \in \mathbb{R}^5} 2\,\Phi_\ell(D)\).
- Under the logistic payoff with unbalanced ordering prior \(\alpha \neq \tfrac12\), derive the Bayes-optimal pair critic and show how the difference class \(D(a_1) - D(a_2)\) must be augmented to attain it.
- [code] Fixed coupling versus random re-pairing. ●●
- Prove the cycle rule used in
lossesfor \(\mathcal{E}_{\mathrm{diag}}\): on any directed acyclic edge, the critic can make \(D(x_i) - D(x'_i) \to +\infty\) so its loss vanishes, whereas around a \(k\)-cycle the differences sum to zero and concavity of \(\log \sigma\) gives a maximum of \(-k\log 2\) at equal scores. - Extend
count_bad_minimato \(n = 4\) (256 configurations) and verify the counts for \(\mathcal{E}_{\mathrm{GAN}}\), \(\mathcal{E}_{\mathrm{all}}\), and \(\mathcal{E}_{\mathrm{diag}}\). - Define the permutation-averaged best-response objective \(\frac{1}{n!} \sum_\pi \sup_D \frac{1}{n} \sum_i \log \sigma(D(x_i) - D(x'_{\pi(i)}))\) and count its strict suboptimal local minima for \(n = 3\). Compare this regime with a critic that adapts slowly across many random-pairing minibatches (which faces \(\mathcal{E}_{\mathrm{all}}\)).
- Prove the cycle rule used in