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 λ(x)=log⁡(p(x)/q(x))\lambda(x) = \log(p(x)/q(x)) and its minimax value is the Jensen–Shannon divergence—a quantity that saturates once the supports of pp and qq 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 T\mathcal{T} over which the critic optimizes. Unconstrained critics paired with classification losses evaluate ff-divergences, which depend only on the pointwise density ratio p(x)/q(x)p(x)/q(x). 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 (W1W_1), 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, softplus

16.2.1 A General Template#

In Section 16.1, the critic received log⁡σ(D(x))\log \sigma(D(x)) on real samples x∼px \sim p and log⁡σ(−D(x′))\log \sigma(-D(x')) on generated samples x′∼qx' \sim q. Replacing these log-likelihood terms with general payoff functions ℓp\ell_p and ℓq\ell_q over a critic class T\mathcal{T} yields the general adversarial discrepancy:

d(p,q)=sup⁡T∈T{Ex∼p[ℓp(T(x))]+Ex′∼q[ℓq(T(x′))]}.(16.2.1)\begin{aligned} d(p, q) &= \sup_{T \in \mathcal{T}} \Big\{ \mathbb{E}_{x \sim p}\big[\ell_p(T(x))\big] \\ &\qquad\qquad + \mathbb{E}_{x' \sim q}\big[\ell_q(T(x'))\big] \Big\}. \end{aligned} \tag{16.2.1}

Setting ℓp(t)=log⁡σ(t)\ell_p(t) = \log \sigma(t) and ℓq(t)=log⁡σ(−t)\ell_q(t) = \log \sigma(-t) with T\mathcal{T} unconstrained recovers 2 JS(p,q)−2log⁡22\,\mathrm{JS}(p, q) - 2\log 2. 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 T\mathcal{T} is unconstrained or regularized.

Table 16.2.1. Taxonomy of adversarial objectives by critic input and function-class constraint.
unconstrained criticconstrained or penalized critic
single-sample criticclassification losses (logistic, least squares, hinge) →\to ff-divergences of p/qp/qlinear payoffs on an RKHS ball (MMD) or Lipschitz ball (W1W_1); hinge loss with spectral normalization
pairwise criticrelativistic pairing loss (RpGAN, Section 16.3)pairing loss with zero-centered gradient penalties R1+R2R_1 + R_2 (R3GAN, Section 16.4, Section 16.5)

Note that for any fixed critic TT, the expectation inside (16.2.1) is linear in the distribution qq. Because the supremum of a family of linear functionals is convex, d(p,q)d(p, q) is always convex in the probability measure qq for fixed pp. However, because the set of distributions {qθ}\{q_\theta\} parameterized by a neural network GθG_\theta is not convex, convexity in distribution space does not imply convexity in the generator parameters θ\theta (Exercise 1).

16.2.2 Classification Losses and ff-Divergences#

16.2.2.1 A Two-Outcome Example#

Consider a binary outcome space (heads and tails) with data distribution p=(34,14)p = (\tfrac34, \tfrac14) and generator distribution q=(14,34)q = (\tfrac14, \tfrac34), sampled with equal prior probability 12\tfrac12. Given an outcome, the Bayes posterior probability that it came from pp is η=p/(p+q)\eta = p/(p + q), which equals 34\tfrac34 for heads and 14\tfrac14 for tails. A blind prediction (D=0D = 0) predicts 12\tfrac12 regardless of the outcome. The reduction in expected loss from observing the outcome depends on the classification loss:

  • Log loss: the optimal prediction η\eta achieves binary entropy Hb(34)=0.562H_b(\tfrac34) = 0.562 nats versus log⁡2=0.693\log 2 = 0.693 nats for a blind guess, saving 0.131 nats=JS(p,q)0.131\text{ nats} = \mathrm{JS}(p, q).
  • Squared error on probabilities: predicting η\eta achieves expected loss 34⋅14=316\tfrac34 \cdot \tfrac14 = \tfrac{3}{16} versus 14\tfrac14 for predicting 12\tfrac12, saving 116\tfrac{1}{16}.
  • Hinge loss on a score tt: the optimal scores t=+1t = +1 (heads) and t=−1t = -1 (tails) achieve expected loss 2⋅14=122 \cdot \tfrac14 = \tfrac12 versus 11 at t=0t = 0, saving 12=TV(p,q)=12∑∣p−q∣\tfrac12 = \mathrm{TV}(p, q) = \tfrac12 \sum |p - q|.

Each loss assigns a different nonnegative divergence to the same pair (p,q)(p, q) based on the same posterior η\eta. We now show that every margin-based classification loss defines an ff-divergence.

16.2.2.2 The Bayes-Risk Gap#

Symmetric classification losses apply a single margin payoff ℓ\ell to D(x)D(x) on real samples and to −D(x′)-D(x') on generated samples (ℓp(t)=ℓ(t)\ell_p(t) = \ell(t), ℓq(t)=ℓ(−t)\ell_q(t) = \ell(-t)):

Vℓ(D)  =  Ex∼p[ℓ(D(x))]+Ex′∼q[ℓ(−D(x′))].(16.2.2)V_\ell(D) \;=\; \mathbb{E}_{x \sim p}\big[\ell(D(x))\big] + \mathbb{E}_{x' \sim q}\big[\ell(-D(x'))\big]. \tag{16.2.2}

Here the signed score tt (+D(x)+D(x) on real data, −D(x′)-D(x') on generated data) is the classification margin. At each point xx, p(x)ℓ(t)+q(x)ℓ(−t)=2m(x)[η(x)ℓ(t)+(1−η(x))ℓ(−t)]p(x)\ell(t) + q(x)\ell(-t) = 2m(x)\big[\eta(x)\ell(t) + (1 - \eta(x))\ell(-t)\big], where m=(p+q)/2m = (p+q)/2 and η(x)=p(x)/(p(x)+q(x))\eta(x) = p(x)/(p(x)+q(x)). The minimum pointwise expected loss at posterior η\eta is the conditional Bayes risk:

L(η)  =  inf⁡t{η (−ℓ(t))+(1−η) (−ℓ(−t))}.(16.2.3)L(\eta) \;=\; \inf_{t} \Big\{ \eta \, \big({-\ell(t)}\big) + (1 - \eta)\, \big({-\ell(-t)}\big) \Big\}. \tag{16.2.3}

As an infimum of affine functions of η\eta, L(η)L(\eta) is concave on [0,1][0, 1]. A constant critic (t=0t = 0) achieves risk L(12)L(\tfrac12). The reduction in risk from observing xx is the Bayes-risk gap:

Δℓ(p,q)  =  L(12)−Ex∼m[L(η(x))],(16.2.4)\Delta_\ell(p, q) \;=\; L(\tfrac12) - \mathbb{E}_{x \sim m}\big[L(\eta(x))\big], \tag{16.2.4}

which determines the optimal value sup⁡DVℓ(D)=2Δℓ(p,q)−2L(12)\sup_D V_\ell(D) = 2\Delta_\ell(p, q) - 2L(\tfrac12). By Jensen's inequality and Em[η]=12\mathbb{E}_m[\eta] = \tfrac12, Δℓ(p,q)≥0\Delta_\ell(p, q) \geq 0.

16.2.2.3 Bayes-Risk Gaps as ff-Divergences#

Recall from Section 25.3.1.2 that an ff-divergence averages a convex function ff (with f(1)=0f(1) = 0) of the density ratio ρ(x)=p(x)/q(x)\rho(x) = p(x)/q(x) under qq: Df(p ∥ q)=Ex∼q[f(ρ(x))]D_f(p \,\|\, q) = \mathbb{E}_{x \sim q}[f(\rho(x))].

Proposition. If the conditional Bayes risk LL is finite on [0,1][0, 1], then

Δℓ(p,q)=Df(p ∥ q)withf(u)=L(12)−u+12 L ⁣(uu+1),\begin{aligned} \Delta_\ell(p, q) &= D_f(p \,\|\, q) \\ \textrm{with}\quad f(u) &= L(\tfrac12) - \frac{u+1}{2}\, L\!\left(\frac{u}{u+1}\right), \end{aligned}

where ff is convex on [0,∞)[0, \infty) with f(1)=0f(1) = 0.

Proof. Substituting u=ρ=p/qu = \rho = p/q gives m=q (u+1)/2m = q\,(u+1)/2 and η=u/(u+1)\eta = u/(u+1), so

Ex∼m[L(η(x))]=∫q u+12 L ⁣(uu+1),\mathbb{E}_{x \sim m}\big[L(\eta(x))\big] = \int q \, \frac{u+1}{2}\, L\!\left(\frac{u}{u+1}\right),

and moving L(12)=∫q L(12)L(\tfrac12) = \int q\, L(\tfrac12) inside the integral yields Δℓ(p,q)=Eq[f(ρ)]\Delta_\ell(p, q) = \mathbb{E}_q[f(\rho)]. Writing the concave function L(v)=inf⁡j{αjv+βj}L(v) = \inf_j \{\alpha_j v + \beta_j\} as the lower envelope of its tangent lines shows that (u+1)L(u/(u+1))=inf⁡j{αju+βj(u+1)}(u+1)L(u/(u+1)) = \inf_j \{\alpha_j u + \beta_j(u+1)\} is concave in uu; hence f(u)f(u) is convex, and f(1)=L(12)−L(12)=0f(1) = L(\tfrac12) - L(\tfrac12) = 0. ■\blacksquare

Thus, every symmetric classification loss with an unconstrained critic evaluates an ff-divergence, and its optimal critic D⋆(x)D^\star(x) is a monotone link function of the log density ratio λ(x)=log⁡(p(x)/q(x))\lambda(x) = \log(p(x)/q(x)).

16.2.2.4 Divergences of Common Classification Losses#

Table 16.2.2 summarizes four standard classification losses, their conditional Bayes risks L(η)L(\eta), Bayes-risk gaps Δℓ(p,q)\Delta_\ell(p, q), optimal critic links D⋆(λ)D^\star(\lambda), and the practical generator losses used with them.

Table 16.2.2. Classification losses with an unconstrained critic: margin loss −ℓ(t)-\ell(t), Bayes risk L(η)L(\eta), Bayes-risk gap Δℓ(p,q)\Delta_\ell(p, q), optimal critic link D⋆(λ)D^\star(\lambda), and practical generator loss on D=D(x′)D = D(x').
lossmargin loss −ℓ(t)-\ell(t)Bayes risk L(η)L(\eta)gap Δℓ(p,q)\Delta_\ell(p,q)optimal critic linkgenerator loss
logisticlog⁡(1+e−t)\log(1 + e^{-t})Hb(η)H_b(\eta)JS(p,q)\mathrm{JS}(p,q)λ\lambda−log⁡σ(D)-\log \sigma(D)
least squares (LSGAN)14(1−t)2\tfrac14 (1 - t)^2, t=2D−1t = 2D - 1η(1−η)\eta(1-\eta)18∫(p−q)2p+q\tfrac{1}{8}\int \frac{(p-q)^2}{p+q}σ(λ)\sigma(\lambda)12(D−1)2\tfrac12 (D - 1)^2
squared hingemax⁡(0,1−t)2\max(0, 1 - t)^24η(1−η)4\eta(1-\eta)12∫(p−q)2p+q\tfrac{1}{2}\int \frac{(p-q)^2}{p+q}tanh⁡(λ/2)\tanh(\lambda/2)−D-D
hingemax⁡(0,1−t)\max(0, 1 - t)2min⁡(η,1−η)2\min(\eta, 1-\eta)TV(p,q)\mathrm{TV}(p,q)sign⁡λ\operatorname{sign} \lambda−D-D

In LSGAN (Mao et al., 2017), the critic regresses onto targets 11 (real) and 00 (fake), which under t=2D−1t = 2D - 1 corresponds to squared margin loss 14(1−t)2\tfrac14(1 - t)^2 and evaluates one-quarter of the Vincze–Le Cam divergence χ2(p ∥ m)=12∫(p−q)2/(p+q)\chi^2(p \,\|\, m) = \tfrac12 \int (p-q)^2/(p+q). The hinge loss (Lim and Ye, 2017) evaluates total variation TV(p,q)=12∫∣p−q∣\mathrm{TV}(p, q) = \tfrac12 \int |p - q|, and its optimal critic outputs sign⁡λ\operatorname{sign} \lambda (with any value in [−1,1][-1, 1] optimal at η=12\eta = \tfrac12). The squared hinge loss shares the hinge margin and generator objective −D(x′)-D(x'), but its smooth link tanh⁡(λ/2)\tanh(\lambda/2) preserves the magnitude of λ\lambda. In practice, each loss uses a non-saturating generator objective (final column) that shares the equilibrium q=pq = p.

16.2.2.5 The Fenchel–Young Variational Bound (ff-GAN)#

Because (16.2.2) applies the same payoff to DD and −D-D, its Bayes risk satisfies L(η)=L(1−η)L(\eta) = L(1 - \eta), so every classification gap Δℓ(p,q)\Delta_\ell(p, q) is symmetric in pp and qq and bounded above by L(12)L(\tfrac12) (Exercise 5). Reaching asymmetric or unbounded ff-divergences such as the forward KL divergence DKL(p ∥ q)D_{\textrm{KL}}(p \,\|\, q) requires asymmetric payoffs ℓp≠ℓq\ell_p \neq \ell_q.

Let f∗(t)=sup⁡u{ut−f(u)}f^*(t) = \sup_u \{ut - f(u)\} be the convex conjugate of a convex divergence function ff. By the Fenchel–Young inequality, f(u)≥ut−f∗(t)f(u) \geq ut - f^*(t) for all u,tu, t, with equality when t=f′(u)t = f'(u). Setting u=ρ(x)=p(x)/q(x)u = \rho(x) = p(x)/q(x) and t=T(x)t = T(x) and taking the expectation under qq (using Eq[ρ T]=Ep[T]\mathbb{E}_q[\rho\, T] = \mathbb{E}_p[T]) yields the variational lower bound of ff-GAN (Nowozin et al., 2016) (Section 25.3.4):

Df(p ∥ q)  ≥  Ex∼p[T(x)]−Ex′∼q[f∗(T(x′))].(16.2.5)D_f(p \,\|\, q) \;\geq\; \mathbb{E}_{x \sim p}\big[T(x)\big] - \mathbb{E}_{x' \sim q}\big[f^*(T(x'))\big]. \tag{16.2.5}

This matches our template (16.2.1) with ℓp(t)=t\ell_p(t) = t and ℓq(t)=−f∗(t)\ell_q(t) = -f^*(t), and is tight at the optimal critic T⋆(x)=f′(ρ(x))T^\star(x) = f'(\rho(x)) (Exercise 2). For the forward KL divergence, f(u)=ulog⁡uf(u) = u \log u has conjugate f∗(t)=et−1f^*(t) = e^{t-1} and optimal critic T⋆(x)=1+log⁡ρ(x)=1+λ(x)T^\star(x) = 1 + \log \rho(x) = 1 + \lambda(x).

We now verify that critics trained under the logistic, least-squares, hinge, and forward-KL objectives learn their respective theoretical link functions of λ(x)\lambda(x): λ\lambda, σ(λ)\sigma(\lambda), sign⁡λ\operatorname{sign} \lambda, and 1+λ1 + \lambda. We define pp as a uniform mixture of three 2D Gaussians and construct a perturbed 3-component mixture qq so that λ(x)\lambda(x) 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 JS(p,q)\mathrm{JS}(p, q) for any mixture qq 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 qq 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 D

Each 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 qq, so we train a fresh critic against the hand-set qq under three of the losses, and a fourth to maximize the forward-KL bound Ep[T]−Eq[eT−1]\mathbb{E}_p[T] - \mathbb{E}_q[e^{T-1}].

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 pp and 300 from qq, plotting its output against the true log density ratio λ(x)\lambda(x) 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 λ(x)\lambda(x): the identity λ\lambda, the sigmoid σ(λ)\sigma(\lambda), the step function sign⁡λ\operatorname{sign} \lambda, and the shifted identity 1+λ1 + \lambda. Note the wider scatter of the hinge critic near λ=0\lambda = 0, where any output in [−1,1][-1, 1] achieves the minimum conditional risk.

16.2.3 Integral Probability Metrics#

Whereas ff-divergences pair an unconstrained critic with nonlinear payoffs, integral probability metrics (IPMs) use linear payoffs ℓp(t)=t\ell_p(t) = t and ℓq(t)=−t\ell_q(t) = -t while restricting the critic to a symmetric function class F\mathcal{F} (Section 25.4.1):

dF(p,q)  =  sup⁡T∈F{Ex∼p[T(x)]−Ex′∼q[T(x′)]}.(16.2.6)d_{\mathcal{F}}(p, q) \;=\; \sup_{T \in \mathcal{F}} \Big\{ \mathbb{E}_{x \sim p}\big[T(x)\big] - \mathbb{E}_{x' \sim q}\big[T(x')\big] \Big\}. \tag{16.2.6}

Without a constraint on F\mathcal{F}, scaling TT by an arbitrary positive constant would send the difference of expectations to +∞+\infty whenever p≠qp \neq q. When F\mathcal{F} consists of smooth functions, dF(p,q)d_{\mathcal{F}}(p, q) depends on the spatial geometry of X\mathcal{X} rather than just the pointwise ratio p(x)/q(x)p(x)/q(x).

16.2.3.1 Maximum Mean Discrepancy (MMD)#

Given a positive-definite kernel k(x,x′)k(x, x'), such as the Gaussian RBF kernel k(x,x′)=exp⁡(−∥x−x′∥2/(2s2))k(x, x') = \exp(-\|x - x'\|^2/(2s^2)) with bandwidth ss, choosing F\mathcal{F} to be the unit ball of the reproducing kernel Hilbert space (RKHS) associated with kk 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:

MMD2(p,q)=Ex,x~∼p[k(x,x~)]+Ex′,x~′∼q[k(x′,x~′)]−2 Ex∼p, x′∼q[k(x,x′)].(16.2.7)\begin{aligned} \mathrm{MMD}^2(p, q) &= \mathbb{E}_{x, \tilde x \sim p}\big[k(x, \tilde x)\big] + \mathbb{E}_{x', \tilde x' \sim q}\big[k(x', \tilde x')\big] \\ &\quad - 2\, \mathbb{E}_{x \sim p,\, x' \sim q}\big[k(x, x')\big]. \end{aligned} \tag{16.2.7}

The optimal test function (up to scaling) is the witness function w(x)=Ex~∼p[k(x,x~)]−Ex~′∼q[k(x,x~′)]w(x) = \mathbb{E}_{\tilde x \sim p}[k(x, \tilde x)] - \mathbb{E}_{\tilde x' \sim q}[k(x, \tilde x')], which measures the difference between a point's average similarity to pp and its average similarity to qq. 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 (W1W_1)#

Choosing F\mathcal{F} to be the class of 1-Lipschitz functions (∣T(x)−T(y)∣≤∥x−y∥|T(x) - T(y)| \leq \|x - y\| for all x,yx, y) yields the Wasserstein-1 (or Earth Mover's) distance via Kantorovich–Rubinstein duality (Section 25.4.2):

W1(p,q)  =  inf⁡π∈Π(p,q)E(x,x′)∼π[∥x−x′∥],W_1(p, q) \;=\; \inf_{\pi \in \Pi(p, q)} \mathbb{E}_{(x, x') \sim \pi}\big[\|x - x'\|\big],

where Π(p,q)\Pi(p, q) is the set of joint transport plans with marginals pp and qq. An optimal 1-Lipschitz critic (a Kantorovich potential) has unit gradient norm along the optimal transport rays from qq to pp. In 1D, W1(p,q)=∫−∞∞∣Fp(t)−Fq(t)∣ dtW_1(p, q) = \int_{-\infty}^\infty |F_p(t) - F_q(t)|\,dt, so shifting a distribution by μ\mu gives W1(p,q)=∣μ∣W_1(p, q) = |\mu| with constant unit slope at any separation.

In higher dimensions, Wasserstein GANs (WGANs) approximate the 1-Lipschitz constraint on a neural network critic TT via three main mechanisms:

  1. Weight clipping (Arjovsky et al., 2017) clamps weights to [−c,c][-c, c], enforcing κ\kappa-Lipschitzness for an architecture-dependent constant κ\kappa at the cost of restricting capacity.
  2. Gradient penalty (WGAN-GP) (Gulrajani et al., 2017) adds γ E[(∥∇xT(x~)∥−1)2]\gamma\,\mathbb{E}[(\|\nabla_x T(\tilde x)\| - 1)^2] at random interpolants x~=ux+(1−u)x′\tilde x = u x + (1-u)x' between real and generated samples.
  3. Spectral normalization (Miyato et al., 2018) normalizes each weight matrix by its largest singular value σmax⁡(W)\sigma_{\max}(W), bounding the Lipschitz constant of every linear layer by 11.

Notice that the hinge loss bridges the two families: when ∣D(x)∣≤1|D(x)| \leq 1, its payoffs are linear, so an unconstrained hinge critic corresponds to the IPM over functions bounded by ∣D(x)∣≤1|D(x)| \leq 1 (evaluating 2 TV(p,q)−22\,\mathrm{TV}(p, q) - 2). Combining the hinge loss with spectral normalization (making DD both bounded and κ\kappa-Lipschitz, as in SAGAN and BigGAN) yields a critic whose value grows linearly like κ W1\kappa\,W_1 up to separation 2/κ2/\kappa before saturating.

16.2.3.3 Sample Complexity in High Dimensions#

Fixed-kernel MMD and empirical W1W_1 differ sharply in sample complexity: the unbiased MMD2\mathrm{MMD}^2 estimator converges at the dimension-independent rate O(n−1/2)O(n^{-1/2}) (Gretton et al., 2012) (although the quantity being estimated, the MMD2\mathrm{MMD}^2 of a given shift under a fixed kernel, can itself shrink as the dimension grows (Ramdas et al., 2015)), whereas the plug-in empirical W1W_1 distance in dimension dx>2d_x > 2 suffers from the curse of dimensionality at rate O(n−1/dx)O(n^{-1/d_x}) (Weed and Bach, 2019). Meanwhile, variational ff-divergence estimators can suffer from high variance when ρ=p/q\rho = p/q is large: for example, in the forward-KL dual bound, the variance of eT⋆(x′)−1=ρ(x′)e^{T^\star(x') - 1} = \rho(x') under qq equals χ2(p ∥ q)\chi^2(p \,\|\, q), which can diverge even when DKL(p ∥ q)<∞D_{\textrm{KL}}(p \,\|\, q) \lt \infty (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 p=N(0,1)p = \mathcal{N}(0, 1) and q=N(μ,1)q = \mathcal{N}(\mu, 1) as a function of the separation μ>0\mu > 0. Here W1(p,q)=μW_1(p, q) = \mu has constant derivative 11, JS(p,q)\mathrm{JS}(p, q) can be integrated numerically, and MMD2(p,q)\mathrm{MMD}^2(p, q) under the Gaussian RBF kernel of bandwidth ss has the exact Gaussian integral:

MMD2(p,q)  =  2ss2+2(1−exp⁡ ⁣(−μ22(s2+2))),(16.2.8)\mathrm{MMD}^2(p, q) \;=\; \frac{2s}{\sqrt{s^2 + 2}} \left( 1 - \exp\!\left( -\frac{\mu^2}{2(s^2 + 2)} \right) \right), \tag{16.2.8}

whose derivative with respect to μ\mu peaks at μ=s2+2\mu = \sqrt{s^2 + 2} (≈4.2\approx 4.2 for s=4s = 4) before decaying as e−μ2/(2(s2+2))e^{-\mu^2/(2(s^2+2))}.

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 JS(p,q)\mathrm{JS}(p, q) drops by over two orders of magnitude by μ=7\mu = 7 (0.00130.0013 vs. 0.200.20 at μ=1\mu = 1) and reaches 1.5×10−221.5 \times 10^{-22} at μ=20\mu = 20. By contrast, W1W_1 maintains unit slope at every distance, and MMD2\mathrm{MMD}^2 maintains a strong gradient up to separations on the order of the kernel bandwidth ss.

Figure 16.2.1:

Optimal critics when pp (blue) and qq (orange) have disjoint supports. Left: the JS optimal critic log⁡(p/q)\log(p/q) takes values +∞+\infty on supp⁡(p)\operatorname{supp}(p) and −∞-\infty on supp⁡(q)\operatorname{supp}(q), with zero slope on both. Middle: the W1W_1 Kantorovich potential is a linear ramp of unit slope. Right: the MMD witness Ep[k(x,⋅)]−Eq[k(x,⋅)]\mathbb{E}_p[k(x, \cdot)] - \mathbb{E}_q[k(x, \cdot)] is a smooth difference of kernel bumps whose tail slopes toward pp.

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 qθ=N(θ,1)q_\theta = \mathcal{N}(\theta, 1) (x′=θ+zx' = \theta + z) starting at θ0=6\theta_0 = 6 to p=N(0,1)p = \mathcal{N}(0, 1), updating θ\theta 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 0.010.01: 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 θ\theta 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, max⁡(0,∣T′∣−1)2\max(0, |T'| - 1)^2; 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), D

We compare six configurations across three seeds each: saturating logistic, non-saturating logistic, hinge, WGAN-GP (γ=10\gamma = 10, two-sided penalty (∣T′∣−1)2(|T'| - 1)^2), WGAN-GP with a one-sided penalty max⁡(0,∣T′∣−1)2\max(0, |T'| - 1)^2, and median-bandwidth MMD. For each run we report the median generator gradient magnitude over the first 100 steps, the trajectory of θ\theta, the arrival step (first step where ∣θ∣<0.5|\theta| \lt 0.5), and the farthest excursion max⁡∣θ∣\max |\theta| 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 (∼0.01\sim 0.01) and θ\theta barely moves from 6.06.0 to 5.765.76, whereas the non-saturating generator receives a strong gradient (∼3\sim 3) and reaches the target before step 400.
  • Hinge critic: Although the theoretical optimal hinge critic sign⁡λ\operatorname{sign} \lambda has zero slope inside both clouds, a finite ReLU MLP interpolates smoothly across the gap with slope 1.1–1.71.1\text{--}1.7, driving the generator to the target by steps 700–950700\text{--}950.
  • Median-bandwidth MMD: Besides the saturating arm, this is the only one that has not arrived by step 1,500, where θ≈1.3\theta \approx 1.3. 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 ∼0.2\sim 0.2 it is about six times smaller than the slope of the W1W_1 critics in the next item, and plain gradient steps of size 0.010.01 need correspondingly longer.
  • Two-sided vs. one-sided WGAN-GP: Both W1W_1 arms pull the generator inward at slope ≈1.26\approx 1.26 (minimizing −ad+10(a−1)2-ad + 10(a-1)^2 gives a=1+d/20a = 1 + d/20) and arrive near step 500. After arrival, however, every two-sided W1 + GP run overshoots heavily (farthest >1> 1, up to >7> 7), whereas no one-sided run ever moves farther out than its arrival point (farthest ≤0.5\le 0.5), and by step 1,000 every one is within 0.060.06 of the origin. Why? Once θ\theta crosses 00, the critic must reverse its slope from negative to positive. Because the two-sided penalty (∣T′∣−1)2(|T'| - 1)^2 penalizes a flat critic (T′=0T' = 0) by γ\gamma, it creates a potential barrier at zero slope that traps the critic on the old slope sign (1−d/201 - d/20) 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 max⁡(0,∣T′∣−1)2\max(0, |T'| - 1)^2 imposes no penalty when ∣T′∣≤1|T'| \leq 1, allowing the critic to pass freely through zero slope as θ\theta reaches the data. Section 16.4 analyzes zero-centered penalties (R1R_1 and R2R_2) 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 (s∈{0.5,1.0,2.0}s \in \{0.5, 1.0, 2.0\}). The generator MixtureGenerator parameterizes a 3-component Gaussian mixture initialized with displaced means mu_0 and narrower scales A_0 = 0.4 * I (JS(p,q0)≈0.53\mathrm{JS}(p, q_0) \approx 0.53 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 MMD2\mathrm{MMD}^2 under the sum of three RBF kernels with bandwidths 0.50.5, 11 and 22, 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 batch

train_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 JS(p,qt)\mathrm{JS}(p, q_t).

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 JS(p,qt)\mathrm{JS}(p, q_t) over the final 2,000 steps and the first step reaching JS(p,qt)<0.1\mathrm{JS}(p, q_t) \lt 0.1 and <0.01\lt 0.01 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 JS(p,qt)\mathrm{JS}(p, q_t) from 0.530.53 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 (0.00010.0001 nats), while the hinge loss settles slightly higher (0.003–0.0070.003\text{--}0.007 nats) than the smooth-link objectives (logistic, least squares, and squared hinge, all ≤0.0024\leq 0.0024 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 T\mathcal{T} ((16.2.1)), making it convex in the distribution qq even though it remains nonconvex in the generator parameters θ\theta. With an unconstrained critic, symmetric margin classification losses evaluate the ff-divergence determined by their Bayes-risk gap Δℓ(p,q)\Delta_\ell(p, q) (Table 16.2.2), with optimal critics outputting monotone links of λ=log⁡(p/q)\lambda = \log(p/q), while the Fenchel–Young variational bound ((16.2.5)) extends this duality to asymmetric ff-divergences. Replacing nonlinear payoffs with linear expectations over a constrained function class F\mathcal{F} instead defines integral probability metrics, notably Maximum Mean Discrepancy over an RKHS unit ball and Wasserstein-1 over 1-Lipschitz functions. When supports separate, ff-divergences saturate whereas W1W_1 maintains unit slope and MMD2\mathrm{MMD}^2 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#

  1. [code] Convexity in distribution space versus parameter space. Every objective of the form (16.2.1) is convex in qq, but a parametric generator varies θ\theta rather than qq directly. Use normal_pdf, js_1d, and xs.

    1. Let p=N(0,1)p = \mathcal{N}(0, 1) and q0=N(8,1)q_0 = \mathcal{N}(8, 1). Verify via second differences that JS(p,qt)\mathrm{JS}(p, q_t) is convex in t∈[0,1]t \in [0, 1] along the linear mixture path qt=(1−t) q0+t pq_t = (1 - t)\, q_0 + t\, p.
    2. Now let p=0.7 N(−4,1)+0.3 N(4,1)p = 0.7\, \mathcal{N}(-4, 1) + 0.3\, \mathcal{N}(4, 1) and qθ=N(θ,1)q_\theta = \mathcal{N}(\theta, 1). Plot JS(p,qθ)\mathrm{JS}(p, q_\theta) for θ∈[−6,6]\theta \in [-6, 6] and identify its local minima and maxima.
    3. Why do these nonconvex features in θ\theta not contradict convexity in qq?
  2. Jensen–Shannon convex conjugate. Twice the Jensen–Shannon divergence corresponds to the divergence function f(u)=ulog⁡u−(u+1)log⁡u+12f(u) = u \log u - (u + 1) \log \frac{u + 1}{2}.

    1. Derive its convex conjugate f∗(t)=−log⁡(2−et)f^*(t) = -\log(2 - e^t) with domain t<log⁡2t \lt \log 2.
    2. Show that under the reparameterization T(x)=log⁡(2σ(D(x)))T(x) = \log(2 \sigma(D(x))), the optimal critic T⋆=f′(ρ)T^\star = f'(\rho) corresponds to D⋆=λD^\star = \lambda, and the variational bound (16.2.5) becomes 2log⁡2+V(D)2 \log 2 + V(D), where V(D)V(D) is the classic log-loss GAN objective of Section 16.1.
  3. [code] Generator weights and critic lag on the Gaussian mixture. ● Use train_toy and the five objectives of Section 16.2.4.3.

    1. Pair the logistic critic loss with the linear generator loss −D(x′)-D(x') (weight w=1w = 1) and compare it with the non-saturating loss −log⁡σ(D(x′))-\log \sigma(D(x')) across three seeds by the first step at which JS(p,qt)<0.1\mathrm{JS}(p, q_t) \lt 0.1 nats. Explain the difference using their per-sample weights.
    2. Test whether the slightly higher final JS\mathrm{JS} 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) 4×4\times larger critic batch size.
  4. [code] Sample complexity and dimension. ● Let p=N(0,Idx)p = \mathcal{N}(\mathbf{0}, \mathbf{I}_{d_x}) and q=N(μ,Idx)q = \mathcal{N}(\boldsymbol{\mu}, \mathbf{I}_{d_x}) with ∥μ∥=1\|\boldsymbol{\mu}\| = 1, so W1(p,q)=1W_1(p, q) = 1 in every dimension dxd_x.

    1. Estimate W1W_1 from two samples of size nn via optimal linear assignment (scipy.optimize.linear_sum_assignment) for dx∈{1,2,10,50}d_x \in \{1, 2, 10, 50\} and n∈{100,400,1600}n \in \{100, 400, 1600\}, and plot the relative error against nn on log–log axes. Compare with the unbiased MMD2\mathrm{MMD}^2 estimator using an RBF kernel of bandwidth s=dxs = \sqrt{d_x}.
    2. Measure the empirical W1W_1 distance between two independent samples of size n=256n = 256 drawn from the same distribution pp in dimension dx=50d_x = 50.
    3. Evaluate the forward-KL variational bound (16.2.5) for critics['forward KL'] by quadrature on grid_2d and compare it with the true DKL(p ∥ q)≈0.16D_{\textrm{KL}}(p \,\|\, q) \approx 0.16 nats and with minibatch estimates of size 512. Why can a finite minibatch from qq overestimate the bound when T(x′)T(x') overshoots 1+λ(x′)1 + \lambda(x') in regions where q(x′)q(x') is small?
  5. Symmetric ff-divergences from classification losses. ●● Every margin classification loss (16.2.2) has a symmetric Bayes risk L(η)=L(1−η)L(\eta) = L(1 - \eta) and thus evaluates a symmetric ff-divergence. Conversely (Nguyen et al. (2009), Corollary 3), let ff be convex on (0,∞)(0, \infty) with f(1)=0f(1) = 0, f(u)=uf(1/u)f(u) = u f(1/u), and f(0)=lim⁡u→0f(u)<∞f(0) = \lim_{u \to 0} f(u) \lt \infty, and define

L(η)=2f(0)−2(1−η) f ⁣(η1−η),0<η<1.L(\eta) = 2 f(0) - 2 (1 - \eta)\, f\!\left( \frac{\eta}{1 - \eta} \right), \qquad 0 \lt \eta \lt 1.
  1. Show that L(η)L(\eta) is concave, symmetric about 12\tfrac12, vanishes as η→0\eta \to 0 or 11, and has Bayes-risk gap Δℓ(p,q)=Df(p ∥ q)\Delta_\ell(p, q) = D_f(p \,\|\, q).
  2. For differentiable LL and η^=σ(t)\hat\eta = \sigma(t), define the real-sample loss −ℓ(t)=L(η^)+(1−η^)L′(η^)-\ell(t) = L(\hat\eta) + (1 - \hat\eta) L'(\hat\eta). Show that −ℓ(−t)=L(η^)−η^L′(η^)-\ell(-t) = L(\hat\eta) - \hat\eta L'(\hat\eta), that the conditional risk is minimized at η^=η\hat\eta = \eta with value L(η)L(\eta), and that −ℓ(t)≥0-\ell(t) \geq 0.
  3. Verify that applying this construction to the Jensen–Shannon divergence recovers the logistic loss.

Discussions