16.2 Adversarial Objectives and Divergences
Most GAN implementations offer several interchangeable training objectives: non-saturating logistic loss, least squares (LSGAN), hinge loss, and Wasserstein loss. Section 16.1 analyzed the logistic objective, showing that its optimal discriminator recovers the log density ratio and its minimax value is the Jensen–Shannon divergence—a quantity that saturates once the supports of and cease to overlap. What divergences do the other objectives measure? And when generated samples lie far from the data, does a vanishing gradient stem from the loss function, the critic architecture, or the underlying divergence?
Every objective in this family modifies either the scoring functions applied to the critic's outputs or the function class over which the critic optimizes. Unconstrained critics paired with classification losses evaluate -divergences, which depend only on the pointwise density ratio . Constraining the critic to a smooth function class with linear payoffs instead yields integral probability metrics (IPMs), such as Maximum Mean Discrepancy (MMD) and the Wasserstein-1 distance (), which remain sensitive to spatial distances even when supports are disjoint. Below, we derive both families and compare their behavior on separated 1D Gaussians and a 2D Gaussian mixture.
from torch.nn.functional import relu, softplus16.2.1 A General Template#
In Section 16.1, the critic received on real samples and on generated samples . Replacing these log-likelihood terms with general payoff functions and over a critic class yields the general adversarial discrepancy:
Setting and with unconstrained recovers . Throughout this section, the critic maximizes the sum of expected payoffs (equivalently, minimizes the negative payoffs, which we refer to as the critic loss).
Table 16.2.1 organizes the chapter's objectives along two axes: whether the critic scores individual samples or real–generated pairs, and whether the critic class is unconstrained or regularized.
| unconstrained critic | constrained or penalized critic | |
|---|---|---|
| single-sample critic | classification losses (logistic, least squares, hinge) -divergences of | linear payoffs on an RKHS ball (MMD) or Lipschitz ball (); hinge loss with spectral normalization |
| pairwise critic | relativistic pairing loss (RpGAN, Section 16.3) | pairing loss with zero-centered gradient penalties (R3GAN, Section 16.4, Section 16.5) |
Note that for any fixed critic , the expectation inside (16.2.1) is linear in the distribution . Because the supremum of a family of linear functionals is convex, is always convex in the probability measure for fixed . However, because the set of distributions parameterized by a neural network is not convex, convexity in distribution space does not imply convexity in the generator parameters (Exercise 1).
16.2.2 Classification Losses and -Divergences#
16.2.2.1 A Two-Outcome Example#
Consider a binary outcome space (heads and tails) with data distribution and generator distribution , sampled with equal prior probability . Given an outcome, the Bayes posterior probability that it came from is , which equals for heads and for tails. A blind prediction () predicts regardless of the outcome. The reduction in expected loss from observing the outcome depends on the classification loss:
- Log loss: the optimal prediction achieves binary entropy nats versus nats for a blind guess, saving .
- Squared error on probabilities: predicting achieves expected loss versus for predicting , saving .
- Hinge loss on a score : the optimal scores (heads) and (tails) achieve expected loss versus at , saving .
Each loss assigns a different nonnegative divergence to the same pair based on the same posterior . We now show that every margin-based classification loss defines an -divergence.
16.2.2.2 The Bayes-Risk Gap#
Symmetric classification losses apply a single margin payoff to on real samples and to on generated samples (, ):
Here the signed score ( on real data, on generated data) is the classification margin. At each point , , where and . The minimum pointwise expected loss at posterior is the conditional Bayes risk:
As an infimum of affine functions of , is concave on . A constant critic () achieves risk . The reduction in risk from observing is the Bayes-risk gap:
which determines the optimal value . By Jensen's inequality and , .
16.2.2.3 Bayes-Risk Gaps as -Divergences#
Recall from Section 25.3.1.2 that an -divergence averages a convex function (with ) of the density ratio under : .
Proposition. If the conditional Bayes risk is finite on , then
where is convex on with .
Proof. Substituting gives and , so
and moving inside the integral yields . Writing the concave function as the lower envelope of its tangent lines shows that is concave in ; hence is convex, and .
Thus, every symmetric classification loss with an unconstrained critic evaluates an -divergence, and its optimal critic is a monotone link function of the log density ratio .
16.2.2.4 Divergences of Common Classification Losses#
Table 16.2.2 summarizes four standard classification losses, their conditional Bayes risks , Bayes-risk gaps , optimal critic links , and the practical generator losses used with them.
| loss | margin loss | Bayes risk | gap | optimal critic link | generator loss |
|---|---|---|---|---|---|
| logistic | |||||
| least squares (LSGAN) | , | ||||
| squared hinge | |||||
| hinge |
In LSGAN (Mao et al., 2017), the critic regresses onto targets (real) and (fake), which under corresponds to squared margin loss and evaluates one-quarter of the Vincze–Le Cam divergence . The hinge loss (Lim and Ye, 2017) evaluates total variation , and its optimal critic outputs (with any value in optimal at ). The squared hinge loss shares the hinge margin and generator objective , but its smooth link preserves the magnitude of . In practice, each loss uses a non-saturating generator objective (final column) that shares the equilibrium .
16.2.2.5 The Fenchel–Young Variational Bound (-GAN)#
Because (16.2.2) applies the same payoff to and , its Bayes risk satisfies , so every classification gap is symmetric in and and bounded above by (Exercise 5). Reaching asymmetric or unbounded -divergences such as the forward KL divergence requires asymmetric payoffs .
Let be the convex conjugate of a convex divergence function . By the Fenchel–Young inequality, for all , with equality when . Setting and and taking the expectation under (using ) yields the variational lower bound of -GAN (Nowozin et al., 2016) (Section 25.3.4):
This matches our template (16.2.1) with and , and is tight at the optimal critic (Exercise 2). For the forward KL divergence, has conjugate and optimal critic .
16.2.2.6 Verifying Critic Link Functions Empirically#
We now verify that critics trained under the logistic, least-squares, hinge, and forward-KL objectives learn their respective theoretical link functions of : , , , and . We define as a uniform mixture of three 2D Gaussians and construct a perturbed 3-component mixture so that is known analytically everywhere.
mu_p = np.array([[0.0, 2.4], [-2.1, -1.2], [2.1, -1.2]]) # data
A_p = np.stack([0.7 * np.eye(2)] * 3)
mu_q = np.array([[0.2, 2.6], [-2.3, -1.0], [2.0, -1.3]]) # hand-set q
A_q = np.stack([np.diag([0.8, 0.55]), np.diag([0.5, 0.6]),
np.array([[0.65, 0.2], [-0.1, 0.7]])])
def mixture_logpdf(x, mus, As):
"""Log density of the uniform mixture of Gaussians N(mu_k, A_k^T A_k)."""
comps = []
for mu, A in zip(mus, As):
Sigma, diff = A.T @ A, x - mu
sol = np.linalg.solve(Sigma, diff.T).T
comps.append(-0.5 * ((diff * sol).sum(1)
+ np.linalg.slogdet(2 * np.pi * Sigma)[1]))
return np.logaddexp.reduce(np.stack(comps) - np.log(len(mus)), axis=0)
def sample_mixture(n, mus, As, rng):
"""n draws from the uniform mixture of Gaussians mu_k + z A_k."""
k = rng.integers(0, len(mus), n)
z = rng.standard_normal((n, 2))
return np.einsum('ni,nij->nj', z, As[k]) + mus[k]On a fixed grid, quadrature gives for any mixture of this form. Later in the section the same function scores a trained generator after every step.
grid_1d = np.linspace(-7.0, 7.0, 281)
grid_2d = np.stack([g.ravel() for g in np.meshgrid(grid_1d, grid_1d)], axis=1)
cell_area = (grid_1d[1] - grid_1d[0]) ** 2
def js_mixtures(mus_q, As_q, mus_p=mu_p, As_p=A_p):
"""JS(p, q) between two known mixtures, p the data by default, by
quadrature on grid_2d."""
logp = mixture_logpdf(grid_2d, mus_p, As_p)
logq = mixture_logpdf(grid_2d, mus_q, As_q)
p, q = np.exp(logp), np.exp(logq)
logm = np.log(np.maximum((p + q) / 2, 1e-300))
return 0.5 * (p * (logp - logm) + q * (logq - logm)).sum() * cell_area
print(f'JS(p, q) for the hand-set q: {js_mixtures(mu_q, A_q):.3f} nats')JS(p, q) for the hand-set q: 0.033 nats
The hand-set is a few hundredths of a nat from the data, a mismatch of the size a generator meets late in training. The critic is a small leaky-ReLU network with two hidden layers of 64 units.
TRUNC_STD = 0.8796 # standard deviation of N(0, 1) truncated at +-2
def make_critic():
"""Leaky-ReLU MLP with LeCun-normal weights and zero biases."""
D = nn.Sequential(nn.Linear(2, 64), nn.LeakyReLU(0.2),
nn.Linear(64, 64), nn.LeakyReLU(0.2), nn.Linear(64, 1))
for layer in D[::2]: # weight std 1/sqrt(fan_in) after truncation
s = layer.in_features ** -0.5 / TRUNC_STD
nn.init.trunc_normal_(layer.weight, std=s, a=-2 * s, b=2 * s)
nn.init.zeros_(layer.bias)
return DEach loss is stored as a pair, the critic's loss and the generator's loss of Table 16.2.2, both written on the critic's scores r of a real batch and f of a generated one.
losses = { # name: (critic loss, generator loss), both on the scores r, f
'logistic': (lambda r, f: (softplus(-r) + softplus(f)).mean(),
lambda r, f: softplus(-f).mean()),
'least squares': (lambda r, f: ((r - 1) ** 2 + f ** 2).mean() / 2,
lambda r, f: ((f - 1) ** 2).mean() / 2),
'hinge': (lambda r, f: (relu(1 - r) + relu(1 + f)).mean(),
lambda r, f: -f.mean()),
'squared hinge': (lambda r, f: (relu(1 - r) ** 2 + relu(1 + f) ** 2).mean(),
lambda r, f: -f.mean()),
}A link describes the best response to a fixed , so we train a fresh critic against the hand-set under three of the losses, and a fourth to maximize the forward-KL bound .
to_t = lambda a: torch.tensor(a, dtype=torch.float32)
def best_response(critic_loss, seed=0, steps=3000, batch=512, lr=1e-3):
"""Fresh critic trained against the fixed q, as a NumPy function."""
rng = np.random.default_rng(seed)
torch.manual_seed(seed)
D = make_critic()
opt = torch.optim.Adam(D.parameters(), lr)
for _ in range(steps):
X = to_t(sample_mixture(batch, mu_p, A_p, rng))
Y = to_t(sample_mixture(batch, mu_q, A_q, rng))
opt.zero_grad()
critic_loss(D(X), D(Y)).backward()
opt.step()
return lambda x: D(to_t(x)).squeeze(-1).detach().numpy()
kl_dual = lambda r, f: -(r.mean() - torch.exp(f - 1).mean())
critics = {name: best_response(losses[name][0])
for name in ('logistic', 'least squares', 'hinge')}
critics['forward KL'] = best_response(kl_dual)We evaluate each trained critic at 300 points from and 300 from , plotting its output against the true log density ratio alongside the theoretical link function (dashed curve).
rng = np.random.default_rng(7)
pts = np.concatenate([sample_mixture(300, mu_p, A_p, rng),
sample_mixture(300, mu_q, A_q, rng)])
lam = mixture_logpdf(pts, mu_p, A_p) - mixture_logpdf(pts, mu_q, A_q)
lam_line = np.linspace(lam.min(), lam.max(), 200)
links = {'logistic': lambda l: l, 'least squares': lambda l: 1 / (1 + np.exp(-l)),
'hinge': np.sign, 'forward KL': lambda l: 1 + l}
fig, axes = d2l.plt.subplots(1, 4, figsize=(12, 3))
for ax, (name, link) in zip(axes, links.items()):
out = critics[name](pts)
d2l.plot([lam[:300], lam[300:], lam_line],
[out[:300], out[300:], link(lam_line)], xlabel=r'$\lambda$',
fmts=('.', '.', 'k--'), axes=ax,
legend=['x ~ p', "x' ~ q", 'link'] if name == 'logistic' else None)
ax.set_title(name)
axes[0].set_ylabel('critic output')
fig.tight_layout()All four networks track their predicted theoretical links of : the identity , the sigmoid , the step function , and the shifted identity . Note the wider scatter of the hinge critic near , where any output in achieves the minimum conditional risk.
16.2.3 Integral Probability Metrics#
Whereas -divergences pair an unconstrained critic with nonlinear payoffs, integral probability metrics (IPMs) use linear payoffs and while restricting the critic to a symmetric function class (Section 25.4.1):
Without a constraint on , scaling by an arbitrary positive constant would send the difference of expectations to whenever . When consists of smooth functions, depends on the spatial geometry of rather than just the pointwise ratio .
16.2.3.1 Maximum Mean Discrepancy (MMD)#
Given a positive-definite kernel , such as the Gaussian RBF kernel with bandwidth , choosing to be the unit ball of the reproducing kernel Hilbert space (RKHS) associated with yields the Maximum Mean Discrepancy (Gretton et al., 2012) (Section 25.4.1), whose squared value has a closed form in terms of pairwise kernel expectations:
The optimal test function (up to scaling) is the witness function , which measures the difference between a point's average similarity to and its average similarity to . Because (16.2.7) requires no critic network, a generator can minimize the unbiased finite-sample estimator mmd2_unbiased directly (also used in Section 16.5 to compute KID).
def mmd2_unbiased(K_pp, K_qq, K_pq):
"""Unbiased MMD^2 from the kernel matrices within p, within q, and
across; the diagonals (a point with itself) are left out."""
m, n = len(K_pp), len(K_qq)
return ((K_pp.sum() - K_pp.diagonal().sum()) / (m * (m - 1))
+ (K_qq.sum() - K_qq.diagonal().sum()) / (n * (n - 1))
- 2 * K_pq.mean())16.2.3.2 Wasserstein-1 Distance ()#
Choosing to be the class of 1-Lipschitz functions ( for all ) yields the Wasserstein-1 (or Earth Mover's) distance via Kantorovich–Rubinstein duality (Section 25.4.2):
where is the set of joint transport plans with marginals and . An optimal 1-Lipschitz critic (a Kantorovich potential) has unit gradient norm along the optimal transport rays from to . In 1D, , so shifting a distribution by gives with constant unit slope at any separation.
In higher dimensions, Wasserstein GANs (WGANs) approximate the 1-Lipschitz constraint on a neural network critic via three main mechanisms:
- Weight clipping (Arjovsky et al., 2017) clamps weights to , enforcing -Lipschitzness for an architecture-dependent constant at the cost of restricting capacity.
- Gradient penalty (WGAN-GP) (Gulrajani et al., 2017) adds at random interpolants between real and generated samples.
- Spectral normalization (Miyato et al., 2018) normalizes each weight matrix by its largest singular value , bounding the Lipschitz constant of every linear layer by .
Notice that the hinge loss bridges the two families: when , its payoffs are linear, so an unconstrained hinge critic corresponds to the IPM over functions bounded by (evaluating ). Combining the hinge loss with spectral normalization (making both bounded and -Lipschitz, as in SAGAN and BigGAN) yields a critic whose value grows linearly like up to separation before saturating.
16.2.3.3 Sample Complexity in High Dimensions#
Fixed-kernel MMD and empirical differ sharply in sample complexity: the unbiased estimator converges at the dimension-independent rate (Gretton et al., 2012) (although the quantity being estimated, the of a given shift under a fixed kernel, can itself shrink as the dimension grows (Ramdas et al., 2015)), whereas the plug-in empirical distance in dimension suffers from the curse of dimensionality at rate (Weed and Bach, 2019). Meanwhile, variational -divergence estimators can suffer from high variance when is large: for example, in the forward-KL dual bound, the variance of under equals , which can diverge even when (Exercise 4).
16.2.4 Gradients Far from and Near the Data#
16.2.4.1 Divergence Slope versus Separation#
To see how the population divergences behave as two distributions separate, consider and as a function of the separation . Here has constant derivative , can be integrated numerically, and under the Gaussian RBF kernel of bandwidth has the exact Gaussian integral:
whose derivative with respect to peaks at ( for ) before decaying as .
xs = np.linspace(-10.0, 30.0, 8001) # fixed quadrature grid
def normal_pdf(x, mu, sigma=1.0):
return np.exp(-(x - mu) ** 2 / (2 * sigma ** 2)) / np.sqrt(
2 * np.pi * sigma ** 2)
def js_gap(p, q):
"""log 2 - JS(p, q) on xs, accurate even when tiny: the integral of
(p log(1 + q/p) + q log(1 + p/q)) / 2, with log(1 + e^a) computed as
logaddexp(0, a)."""
a = np.log(q) - np.log(p)
return 0.5 * np.trapezoid(p * np.logaddexp(0, a) + q * np.logaddexp(0, -a),
xs)
def js_1d(p, q):
return np.log(2) - js_gap(p, q)
s = 4.0 # RBF kernel bandwidth
mus = np.linspace(0.1, 20.0, 200) # separations mu
gaps = np.array([js_gap(normal_pdf(xs, 0.0), normal_pdf(xs, mu))
for mu in mus])
mmd2 = 2 * s / np.sqrt(s ** 2 + 2) * (1 - np.exp(-mus ** 2
/ (2 * (s ** 2 + 2))))
slopes = [-np.gradient(gaps, mus), np.gradient(mmd2, mus),
np.ones_like(mus)] # W1 = |mu| has slope one
for mu in (1.0, 7.0, 20.0):
js = js_1d(normal_pdf(xs, 0.0), normal_pdf(xs, mu))
print(f'mu = {mu:2.0f}: JS slope {np.interp(mu, mus, slopes[0]):.4g}, '
f'JS / log 2 = {js / np.log(2):.4f}, '
f'MMD^2 slope {np.interp(mu, mus, slopes[1]):.4g}')
peak = slopes[1].argmax()
print(f'MMD^2 slope peaks at mu = {mus[peak]:.1f} with {slopes[1][peak]:.3f}')
d2l.plot(mus, slopes, xlabel=r'separation $\mu$', ylabel='slope',
legend=['JS', 'MMD$^2$', '$W_1$'], yscale='log', figsize=(5, 3))mu = 1: JS slope 0.1987, JS / log 2 = 0.1607, MMD^2 slope 0.1019
mu = 7: JS slope 0.001264, JS / log 2 = 0.9990, MMD^2 slope 0.188
mu = 20: JS slope 1.549e-22, JS / log 2 = 1.0000, MMD^2 slope 3.303e-05
MMD^2 slope peaks at mu = 4.2 with 0.269
As shown in the plot and Figure 16.2.1, the derivative of drops by over two orders of magnitude by ( vs. at ) and reaches at . By contrast, maintains unit slope at every distance, and maintains a strong gradient up to separations on the order of the kernel bandwidth .
Optimal critics when (blue) and (orange) have disjoint supports. Left: the JS optimal critic takes values on and on , with zero slope on both. Middle: the Kantorovich potential is a linear ramp of unit slope. Right: the MMD witness is a smooth difference of kernel bumps whose tail slopes toward .
16.2.4.2 Trained Critics from a Separated Start#
Theoretical divergence curves assume an optimal critic over all measurable functions. In practice, the critic is a finite neural network trained for a few steps per generator update. To test how trained critics behave from a distant initialization, we fit a 1D location generator () starting at to , updating by vanilla SGD (so step sizes directly reflect gradient magnitudes) against a 2-hidden-layer ReLU critic updated 5 times per generator step.
def mmd2_loss(x, y, bandwidths=(0.5, 1.0, 2.0)):
"""Unbiased MMD^2 under the sum of RBF kernels of the given bandwidths."""
def kernel(a, b):
sq_dist = torch.cdist(a, b) ** 2
return sum(torch.exp(-sq_dist / (2 * s ** 2)) for s in bandwidths)
return mmd2_unbiased(kernel(x, x), kernel(y, y), kernel(x, y))
def mmd2_median(x, y):
"""MMD^2 with one RBF kernel, its bandwidth the median pairwise distance
of the pooled batch, held constant in the gradient."""
xy = torch.cat([x, y])
return mmd2_loss(x, y, (torch.cdist(xy, xy).median().detach(),))
def gradient_penalty(D, X, fake, u, one_sided=False):
"""Mean (|D'(x)| - 1)^2 at the points u X + (1 - u) fake (inputs 1-D);
one-sided, only slopes steeper than one pay: max(0, |D'(x)| - 1)^2."""
x = (u * X + (1 - u) * fake).requires_grad_()
grad, = torch.autograd.grad(D(x).sum(), x, create_graph=True)
excess = grad.abs() - 1
return ((excess.clamp(min=0) if one_sided else excess) ** 2).mean()train_shift gives the critic five Adam steps for every generator step, which keeps it near its best response. The generator takes plain gradient steps with learning rate : Adam would rescale every step to about its learning rate and hide the size of the gradient, which is what we want to see. The function records and the generator's gradient at every step. A positive gp adds the gradient penalty to the critic loss, and one_sided=True charges only slopes steeper than one, ; with critic_loss set to None, the generator minimizes gen_loss of the two batches.
class Shift(nn.Module):
"""The generator x' = theta + z."""
def __init__(self, theta0):
super().__init__()
self.theta = nn.Parameter(torch.tensor(theta0))
def forward(self, z):
return self.theta + z
def train_shift(critic_loss, gen_loss, seed, gp=0.0, one_sided=False,
theta0=6.0, steps=1500, n_critic=5, batch=256, lr_D=1e-2,
lr_G=1e-2):
"""Fit x' = theta + z to N(0, 1) by plain gradient steps on theta; return
theta0 and theta after every step, the gradient of every step, and the
critic."""
rng = np.random.default_rng(seed)
torch.manual_seed(seed)
G, D = Shift(theta0), d2l.make_mlp([1, 32, 32, 1], nn.ReLU())
opt_G = torch.optim.SGD(G.parameters(), lr_G)
opt_D = torch.optim.Adam(D.parameters(), lr_D, betas=(0.5, 0.9))
n = n_critic if critic_loss else 0
thetas, grads = [theta0], []
for _ in range(steps):
X, Z = (to_t(rng.standard_normal((n + 1, batch, 1))) for _ in range(2))
U = to_t(rng.uniform(size=(n, batch, 1))) # interpolation weights
for i in range(n):
fake = G(Z[i]).detach()
loss = critic_loss(D(X[i]), D(fake))
if gp:
loss = loss + gp * gradient_penalty(D, X[i], fake, U[i],
one_sided)
opt_D.zero_grad()
loss.backward()
opt_D.step()
fake = G(Z[-1])
loss = (gen_loss(X[-1], fake) if critic_loss is None
else gen_loss(D(X[-1]), D(fake)))
opt_G.zero_grad()
loss.backward()
grads.append(G.theta.grad.item())
opt_G.step()
thetas.append(G.theta.item())
return np.array(thetas), np.array(grads), DWe compare six configurations across three seeds each: saturating logistic, non-saturating logistic, hinge, WGAN-GP (, two-sided penalty ), WGAN-GP with a one-sided penalty , and median-bandwidth MMD. For each run we report the median generator gradient magnitude over the first 100 steps, the trajectory of , the arrival step (first step where ), and the farthest excursion after arrival.
w1 = (lambda r, f: f.mean() - r.mean(), lambda r, f: -f.mean())
arms = {'logistic, sat.': (losses['logistic'][0],
lambda r, f: -softplus(f).mean(), {}),
'logistic, NS': (*losses['logistic'], {}),
'hinge': (*losses['hinge'], {}),
'W1 + GP': (*w1, dict(gp=10.0)),
'W1 + 1-sided GP': (*w1, dict(gp=10.0, one_sided=True)),
'MMD, median': (None, mmd2_median, {})}
steps, w1_runs = (0, 100, 300, 1000, 1500), [] # (arm, seed, theta, critic)
print(f'{"":17s}|grad| theta at steps {", ".join(map(str, steps))}'
' arrival farthest')
for name, (critic_loss, gen_loss, kwargs) in arms.items():
for seed in range(3):
thetas, grads, D = train_shift(critic_loss, gen_loss, seed, **kwargs)
if name.startswith('W1'):
w1_runs.append((name, seed, thetas[-1], D))
hit = np.flatnonzero(np.abs(thetas) < 0.5) # arrival: hit[0]
print(f'{name:16s}{seed}{np.median(np.abs(grads[:100])):7.3f} '
+ ''.join(f'{thetas[t]:7.2f}' for t in steps)
+ (f'{hit[0]:9d}{np.abs(thetas[hit[0]:]).max():10.2f}'
if len(hit) else ' not reached')) |grad| theta at steps 0, 100, 300, 1000, 1500 arrival farthest
logistic, sat. 0 0.007 6.00 5.99 5.96 5.85 5.77 not reached
logistic, sat. 1 0.009 6.00 5.98 5.95 5.85 5.76 not reached
logistic, sat. 2 0.015 6.00 5.98 5.96 5.85 5.77 not reached
logistic, NS 0 2.812 6.00 3.30 0.79 0.03 0.00 383 0.50
logistic, NS 1 2.876 6.00 3.26 0.78 0.02 0.00 380 0.50
logistic, NS 2 2.730 6.00 3.35 0.80 0.02 0.00 388 0.50
hinge 0 1.451 6.00 4.64 3.31 0.02 0.04 812 0.49
hinge 1 1.558 6.00 4.50 3.50 0.00 -0.04 874 0.50
hinge 2 1.278 6.00 4.81 3.51 -0.06 -0.00 918 0.50
W1 + GP 0 1.262 6.00 4.74 2.39 0.30 0.30 477 1.48
W1 + GP 1 1.263 6.00 4.89 2.52 -4.13 -7.18 487 7.49
W1 + GP 2 1.252 6.00 4.97 2.60 -4.08 -7.61 495 7.61
W1 + 1-sided GP 0 1.265 6.00 4.75 2.40 0.01 0.02 478 0.49
W1 + 1-sided GP 1 1.262 6.00 4.74 2.39 -0.01 0.03 477 0.49
W1 + 1-sided GP 2 1.265 6.00 4.74 2.40 0.02 -0.05 477 0.50
MMD, median 0 0.210 6.00 5.79 5.34 3.34 1.32 not reached
MMD, median 1 0.210 6.00 5.79 5.34 3.34 1.32 not reached
MMD, median 2 0.210 6.00 5.79 5.34 3.35 1.32 not reached
The results clarify how practical neural critics differ from unconstrained theoretical optima:
- Saturating vs. non-saturating logistic: As in Section 16.1, the saturating generator gradient is tiny () and barely moves from to , whereas the non-saturating generator receives a strong gradient () and reaches the target before step 400.
- Hinge critic: Although the theoretical optimal hinge critic has zero slope inside both clouds, a finite ReLU MLP interpolates smoothly across the gap with slope , driving the generator to the target by steps .
- Median-bandwidth MMD: Besides the saturating arm, this is the only one that has not arrived by step 1,500, where . The generator is slow here, but it has not stalled. Because the median heuristic keeps the bandwidth comparable to the separation, the gradient never vanishes. At it is about six times smaller than the slope of the critics in the next item, and plain gradient steps of size need correspondingly longer.
- Two-sided vs. one-sided WGAN-GP: Both arms pull the generator inward at slope (minimizing gives ) and arrive near step 500. After arrival, however, every two-sided
W1 + GPrun overshoots heavily (farthest, up to ), whereas no one-sided run ever moves farther out than its arrival point (farthest), and by step 1,000 every one is within of the origin. Why? Once crosses , the critic must reverse its slope from negative to positive. Because the two-sided penalty penalizes a flat critic () by , it creates a potential barrier at zero slope that traps the critic on the old slope sign () or causes all ReLU units to die, as confirmed by inspecting the critic slopes and active ReLU counts at step 1,500 below:
def slope_and_units(D, x):
"""D'(x) and, per hidden layer, the number of ReLU units active at x."""
x = h = torch.tensor([[x]], dtype=torch.float32, requires_grad=True)
active = []
for layer in D:
h = layer(h)
if isinstance(layer, nn.ReLU):
active.append(int((h > 0).sum()))
slope, = torch.autograd.grad(h.sum(), x)
return slope.item(), active
print(f"{'':19s}theta D'(theta) active D'(0) active"
' (of 32 units per layer)')
for name, seed, theta, D in w1_runs:
(s_t, a_t), (s_0, a_0) = (slope_and_units(D, x) for x in (theta, 0.0))
print(f'{name:16s}{seed}{theta:7.2f}{s_t:10.2f}{a_t[0]:5d}{a_t[1]:3d}'
f'{s_0:9.2f}{a_0[0]:5d}{a_0[1]:3d}') theta D'(theta) active D'(0) active (of 32 units per layer)
W1 + GP 0 0.30 0.00 14 0 0.00 14 0
W1 + GP 1 -7.18 1.34 11 8 1.35 12 9
W1 + GP 2 -7.61 -0.65 12 7 -0.65 12 7
W1 + 1-sided GP 0 0.02 0.41 30 3 0.41 30 3
W1 + 1-sided GP 1 0.03 0.65 25 4 0.65 25 4
W1 + 1-sided GP 2 -0.05 -0.16 30 7 -0.16 30 7
The one-sided penalty imposes no penalty when , allowing the critic to pass freely through zero slope as reaches the data. Section 16.4 analyzes zero-centered penalties ( and ) that actively pull the critic slope to zero at equilibrium.
16.2.4.3 Comparing Five Objectives on a 2D Gaussian Mixture#
Next, we compare five objectives when the generator and data supports overlap: non-saturating logistic, least squares, hinge, squared hinge, and multi-bandwidth MMD (). The generator MixtureGenerator parameterizes a 3-component Gaussian mixture initialized with displaced means mu_0 and narrower scales A_0 = 0.4 * I ( nats).
mu_0 = np.array([[1.0, -1.0], [-4.3, -2.0], [-1.0, 3.8]]) # off the modes
A_0 = np.stack([0.4 * np.eye(2)] * 3) # below the data's scale of 0.7
print(f'JS(p, q) at the start: {js_mixtures(mu_0, A_0):.3f} nats')JS(p, q) at the start: 0.529 nats
The start is about half a nat from the data. The MMD arm minimizes the unbiased minibatch under the sum of three RBF kernels with bandwidths , and , a kernel sensitive at several scales.
class MixtureGenerator(nn.Module):
"""x = mu_k + z A_k for a uniformly drawn component k."""
def __init__(self, mu, A):
super().__init__()
self.mu = nn.Parameter(to_t(mu))
self.A = nn.Parameter(to_t(A))
def forward(self, z, k):
return torch.einsum('ni,nij->nj', z, self.A[k]) + self.mu[k]
def params_np(self):
return (self.mu.detach().numpy().copy(),
self.A.detach().numpy().copy())
losses['MMD'] = (None, mmd2_loss) # no critic: MMD^2 to the real batchtrain_toy takes the two losses as arguments and alternates one critic step with one generator step. The MMD arm, stored with the critic loss None, takes only the generator step, on mmd2_loss(X, fake) instead of the critic's scores. Every 200 steps it records the exact .
def train_toy(critic_loss, gen_loss, seed=0, steps=6000, batch=256, lr=1e-3):
"""Fit a MixtureGenerator from (mu_0, A_0) to the data mixture, one
critic step per generator step. The losses act on the critic's scores of
the real and generated batch; with critic_loss None, gen_loss acts on the
two batches. Returns the exact JS(p, q_t) every 200 steps."""
rng = np.random.default_rng(seed)
torch.manual_seed(seed)
G, D = MixtureGenerator(mu_0, A_0), make_critic()
opt_G = torch.optim.Adam(G.parameters(), lr)
opt_D = torch.optim.Adam(D.parameters(), 2 * lr)
trace = []
for t in range(steps):
X = to_t(sample_mixture(batch, mu_p, A_p, rng))
z = to_t(rng.standard_normal((batch, 2)))
k = torch.tensor(rng.integers(0, 3, batch))
if critic_loss is not None:
opt_D.zero_grad()
critic_loss(D(X), D(G(z, k).detach())).backward()
opt_D.step()
opt_G.zero_grad()
fake = G(z, k)
loss = (gen_loss(X, fake) if critic_loss is None
else gen_loss(D(X), D(fake)))
loss.backward()
opt_G.step()
if t % 200 == 0:
trace.append(js_mixtures(*G.params_np()))
return np.array(trace)For each of three seeds per objective, we report the median over the final 2,000 steps and the first step reaching and nats.
def first_below(trace, level):
"""First recorded step (one record per 200 steps) with JS below level."""
hits = np.flatnonzero(trace < level)
return f'{200 * hits[0]:6d}' if len(hits) else ' n/a'
runs = {name: [train_toy(*pair, seed=seed) for seed in range(3)]
for name, pair in losses.items()}
print(f'{"three runs:":14s}{"median JS, last 2,000 steps":>27s}'
f'{"first JS < 0.1":>21s}{"first JS < 0.01":>21s}')
for name, traces in runs.items():
medians = [np.median(trace[-2000 // 200:]) for trace in traces]
print(f'{name:14s} ' + ''.join(f'{m:8.4f}' for m in medians)
+ ' ' + ''.join(first_below(trace, 0.1) for trace in traces)
+ ' ' + ''.join(first_below(trace, 0.01) for trace in traces))
d2l.plot(np.arange(len(runs['logistic'][0])) * 200,
[traces[0] for traces in runs.values()], xlabel='step',
ylabel='JS(p, q_t)', yscale='log', legend=list(runs), figsize=(5, 3))three runs: median JS, last 2,000 steps first JS < 0.1 first JS < 0.01
logistic 0.0008 0.0008 0.0008 2000 2000 2200 2400 2400 2400
least squares 0.0009 0.0009 0.0008 2000 2200 1800 2200 2400 2200
hinge 0.0070 0.0071 0.0033 1800 1800 1400 2000 2000 2400
squared hinge 0.0013 0.0008 0.0024 1400 1400 1400 2200 2200 2200
MMD 0.0001 0.0001 0.0001 1200 1200 1200 2600 2600 2600
All five objectives reduce from nats to a few thousandths of a nat or less. Direct MMD minimization (which does not track a moving critic) achieves the tightest final fit ( nats), while the hinge loss settles slightly higher ( nats) than the smooth-link objectives (logistic, least squares, and squared hinge, all nats; Exercise 3). Next, Section 16.3 examines critics that compare real and generated samples in pairs rather than scoring each sample in isolation.
16.2.5 Summary#
Every single-sample adversarial objective takes a supremum of expected payoffs over a critic class ((16.2.1)), making it convex in the distribution even though it remains nonconvex in the generator parameters . With an unconstrained critic, symmetric margin classification losses evaluate the -divergence determined by their Bayes-risk gap (Table 16.2.2), with optimal critics outputting monotone links of , while the Fenchel–Young variational bound ((16.2.5)) extends this duality to asymmetric -divergences. Replacing nonlinear payoffs with linear expectations over a constrained function class instead defines integral probability metrics, notably Maximum Mean Discrepancy over an RKHS unit ball and Wasserstein-1 over 1-Lipschitz functions. When supports separate, -divergences saturate whereas maintains unit slope and provides informative gradients up to the kernel bandwidth; in practice, finite neural critics interpolate smoothly across gaps whenever paired with a non-saturating generator loss.
16.2.6 Exercises#
-
[code] Convexity in distribution space versus parameter space. Every objective of the form (16.2.1) is convex in , but a parametric generator varies rather than directly. Use
normal_pdf,js_1d, andxs.- Let and . Verify via second differences that is convex in along the linear mixture path .
- Now let and . Plot for and identify its local minima and maxima.
- Why do these nonconvex features in not contradict convexity in ?
-
Jensen–Shannon convex conjugate. Twice the Jensen–Shannon divergence corresponds to the divergence function .
- Derive its convex conjugate with domain .
- Show that under the reparameterization , the optimal critic corresponds to , and the variational bound (16.2.5) becomes , where is the classic log-loss GAN objective of Section 16.1.
-
[code] Generator weights and critic lag on the Gaussian mixture. ● Use
train_toyand the five objectives of Section 16.2.4.3.- Pair the logistic critic loss with the linear generator loss (weight ) and compare it with the non-saturating loss across three seeds by the first step at which nats. Explain the difference using their per-sample weights.
- Test whether the slightly higher final of the hinge loss is due to critic lag or minibatch noise by running two controls over three seeds: (i) 5 critic updates per generator update, and (ii) larger critic batch size.
-
[code] Sample complexity and dimension. ● Let and with , so in every dimension .
- Estimate from two samples of size via optimal linear assignment (
scipy.optimize.linear_sum_assignment) for and , and plot the relative error against on log–log axes. Compare with the unbiased estimator using an RBF kernel of bandwidth . - Measure the empirical distance between two independent samples of size drawn from the same distribution in dimension .
- Evaluate the forward-KL variational bound (16.2.5) for
critics['forward KL']by quadrature ongrid_2dand compare it with the true nats and with minibatch estimates of size 512. Why can a finite minibatch from overestimate the bound when overshoots in regions where is small?
- Estimate from two samples of size via optimal linear assignment (
-
Symmetric -divergences from classification losses. ●● Every margin classification loss (16.2.2) has a symmetric Bayes risk and thus evaluates a symmetric -divergence. Conversely (Nguyen et al. (2009), Corollary 3), let be convex on with , , and , and define
- Show that is concave, symmetric about , vanishes as or , and has Bayes-risk gap .
- For differentiable and , define the real-sample loss . Show that , that the conditional risk is minimized at with value , and that .
- Verify that applying this construction to the Jensen–Shannon divergence recovers the logistic loss.