16.3 Relativistic Objectives
A standard classifier critic scores each sample against a fixed zero threshold (). 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 and a generated sample and predict which one is real from their score difference .
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 ?
- What divergence does the pairwise objective measure at its optimum, and how does it compare to ?
- 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 with and , the relativistic pairing objective (RpGAN, Jolicoeur-Martineau (2019), Jolicoeur-Martineau (2020)) models the probability that is more realistic than via the Bradley–Terry likelihood (Bradley and Terry, 1952):
The critic maximizes (minimizes ). On a minibatch, rpgan_loss_D averages over aligned pairs , 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()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 (Figure 16.3.1). Adding any constant to leaves unchanged. Consequently, the sign of an individual score is arbitrary; the natural accuracy metric is instead the pairwise ranking accuracy .
Single-sample thresholding (left) versus pairwise difference scoring (right). Shifting all critic scores by a constant alters single-sample classification against zero, but leaves pairwise differences invariant.
In the single-sample log-loss objective, maximizing decoupled pointwise across . In (16.3.1), all points are coupled through the differences , but concavity still yields a closed-form optimum.
Proposition. is concave in , and when and share the same support, it is maximized by , uniquely up to an additive constant.
Proof. Because is linear and is strictly concave, is concave in and strictly concave in the score differences. Taking the functional derivative of with respect to (where appears both as the real sample and as the generated sample ) and using gives:
Evaluating at (where ) gives . Using , both terms in (16.3.2) equal , so everywhere. By strict concavity of in the score differences, is the unique maximizer up to a constant shift .
16.3.2 The Pairing Divergence#
16.3.2.1 A Two-State Example#
To see how the optimal value of relates to the Jensen–Shannon divergence, consider a two-state space with and . An ordered pair drawn with the real sample first follows the product distribution , whereas a pair with the real sample second follows :
| pair | ||||
|---|---|---|---|---|
| (real first) | 0.16 | 0.16 | 0.64 | 0.04 |
| (real second) | 0.16 | 0.16 | 0.04 | 0.64 |
Tied pairs and carry no information about which element is real, while mixed pairs and identify the real element with posterior probability (compared to from observing a single sample). At the optimal score difference , the gain over random guessing () is nats—which is larger than nats, and exactly equal to between the two pair distributions and :
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 as a single observation drawn either from (real first) or from (real second), and considering the standard log-loss objective of Section 16.1 on with a pair critic :
Lemma (Lifting to Product Space). Let and . Then:
- The log density ratio on the product space separates additively: .
- Every antisymmetric difference critic satisfies .
- Restricting to difference critics does not reduce the supremum: .
Proof. (1) follows immediately from . For (2), under we have and , so both expectations in equal . For (3), the unconstrained maximizer of is , which by (1) already has the difference form .
(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 that is not additively separable; see Exercise 4.)
Theorem. The calibrated pairing divergence satisfies
Proof. Combining Parts 2 and 3 of the Lifting Lemma with the Jensen–Shannon minimax identity (Section 16.1) gives , proving the first equality. Applying the entropy-gap identity (Section 16.1) and using yields the second equality.
Substituting directly into (16.3.1) also yields the explicit expectation form:
and the mutual-information identity (Section 16.1) on the pair space shows that for a randomly ordered pair with ordering label ,
16.3.2.3 Information Bounds#
Using (16.3.5), we can relate directly to . Each marginal element of the randomly ordered pair has distribution and carries nats about the ordering label , while and are conditionally independent given (). By the chain rule of mutual information:
Because , , and , we obtain the tight sandwich bounds:
Near equilibrium (), is fourth-order in while is second-order, so (Exercise 2). When and have disjoint supports, both and saturate at .
16.3.3 Ranking and Mode Coverage#
16.3.3.1 The Relativistic Rank Weight#
Differentiating with respect to the generator parameters through yields:
In the saturating zero-sum formulation (minimizing ), each generated sample is pushed along with weight —the softened probability that outranks a randomly drawn real sample . In the non-saturating formulation (rpgan_loss_G, minimizing ), the weight becomes . Unlike the single-sample weights , which compare only against zero, the relativistic weight compares against the distribution of real scores and is invariant to constant shifts of .
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 distinct real points and freely movable generated points evaluated at the exact best-response critic :
Here is the classic single-sample objective, is the fixed-pairing objective (where real point is permanently paired with generated point ), and averages over all real–generated pairs. A configuration where all 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 ( of them) is a strict local minimum of , whereas has a non-increasing escape path from every collision to the global minimum .
We can verify this directly for and . With empirical distributions and , and , while equals times the fraction of directed edges 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 ]
Moving from to 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 . To
check all 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 countRunning count_bad_minima for compares the number of
suboptimal strict local minima under each objective against the theoretical
collision count :
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 has zero collision minima, the all-pairs loss has all collision minima—just like . Because standard minibatch training resamples independent real and generated minibatches at every step, its expected objective over random pairings is , not (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 () and the non-saturating generator loss (rpgan_loss_G) share the global minimum . When and 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
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 ( in d2l.train_shift from Section 16.2.4.2), every generated sample is ranked far below every real sample (), driving the saturating rank weight 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
From , the saturating pairing generator has a median gradient below and remains stuck at after 1,500 steps, whereas the non-saturating pairing generator (rpgan_loss_G) receives gradients of and reaches 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 of ranking a real sample above a generated sample, recovering the log density ratio up to an additive constant. Lifting to the product space shows that the calibrated optimal value equals , which satisfies . Although a permanent one-to-one coupling eliminates discrete mode-dropping collision minima at the best-response critic, independent minibatch resampling averages back to the all-pairs objective and retains those minima. Finally, when generated samples lie far from the data, the saturating rank weight vanishes, whereas the non-saturating weight stays near 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 and generator distribution .
- Using
jsfrom the two-state cell, compute and , verifying that on the 25 pair states matches at ( and ). - Evaluate the saturating weight ((16.3.6)) and non-saturating weight at each state under , and compare their -expectations.
- At , show that , with equality if and only if , and that it vanishes as the supports of and separate.
- Run
d2l.train_shiftwith the pairing critic and both generator losses from initial offsetstheta0(three seeds each) to find the separation at which the saturating generator stalls.
- Using
-
Gap between and . ● Consider the randomly ordered pair and its ordering label from (16.3.5).
- Show that and are conditionally independent given and that for .
- When and have disjoint supports, compute directly from the pair mixture and verify that .
- For a local perturbation with , show that whereas , so as .
- Verify numerically on the 5-state distribution of Exercise 1.
-
Two Gaussians. Let and on .
- Show that is affine in and that in (16.3.4) is Gaussian; find its mean and variance.
- Express in the same form and find the scaling constant for which for all .
- Evaluate and by 1D quadrature for and compare their ratio against the local and large-separation limits.
-
Separability of the pair critic. ● Replace in (16.3.1) with a general concave payoff , giving .
- For the least-squares payoff , show that the unconstrained optimal pair critic on is with , which is not additively separable as .
- On the 5-state example of Exercise 1, compute the gap between the unconstrained pair optimum and .
- Under the logistic payoff with unbalanced ordering prior , derive the Bayes-optimal pair critic and show how the difference class must be augmented to attain it.
-
[code] Fixed coupling versus random re-pairing. ●●
- Prove the cycle rule used in
lossesfor : on any directed acyclic edge, the critic can make so its loss vanishes, whereas around a -cycle the differences sum to zero and concavity of gives a maximum of at equal scores. - Extend
count_bad_minimato (256 configurations) and verify the counts for , , and . - Define the permutation-averaged best-response objective and count its strict suboptimal local minima for . Compare this regime with a critic that adapts slowly across many random-pairing minibatches (which faces ).
- Prove the cycle rule used in