16.1 Generative Adversarial Networks
Goodfellow et al. (2014) introduced generative adversarial networks (GANs) by pairing a generator network with a binary classifier, called the discriminator or critic, that learns to distinguish real data from generated samples, much like the domain classifier used for covariate-shift correction in Section 3.6.2.
Two fundamental questions arise immediately:
- If a generator fools the discriminator, has it actually learned to match the data distribution ?
- When the discriminator can easily separate generated samples from real data, does its gradient still guide the generator toward ?
Because the optimal discriminator for a fixed generator can be derived in closed form, we can answer both questions analytically. We then verify our analysis on a 2D Gaussian problem where exact densities and KL divergences are available in closed form, and finally train a multilayer perceptron generator on Fashion-MNIST images.
16.1.1 From Likelihood to Two-Sample Comparison#
16.1.1.1 Implicit Generators#
Maximum likelihood estimation requires evaluating the model's log-density at each observation. By contrast, the generators in this chapter are implicit: they sample a latent vector and pass it through a deterministic network . When the latent dimension is smaller than the data dimension , generated samples lie on a low-dimensional manifold and do not admit a density with respect to Lebesgue measure on . Even when , computing the induced density via the change-of-variables formula requires to be invertible with a tractable Jacobian determinant.
Moreover, high test log-likelihood does not guarantee realistic samples (Theis et al., 2016). Consider a mixture of the true data distribution with uniform or Gaussian noise:
Because everywhere, its expected log-likelihood falls short of the true data distribution by at most nats—a negligible difference for images, whose log-likelihoods span thousands of nats. Yet 99% of samples drawn from are pure noise. Evaluating a sample generator therefore requires inspecting its samples directly.
16.1.1.2 Discriminating Real from Generated Samples#
A two-sample test checks whether two sets of samples come from the same distribution, and a natural way to implement one is to train a binary classifier to separate them. A GAN uses this classifier to provide gradients to the generator. Let be a balanced source label: if , we draw from the data distribution; if , we draw from the generator distribution. The marginal distribution of is the balanced mixture .
The critic (or discriminator) is a function that outputs a realness logit, so that estimates the posterior probability . Following Goodfellow et al. (2014), our code uses net_D and update_D for the discriminator network, while the text also uses the term critic to encompass non-probabilistic scoring networks later in the chapter. (Note that a GAN critic is distinct from the value-function critic in actor–critic reinforcement learning, Section 15.1.)
As shown in Figure 16.1.1, training alternates between the two networks: the discriminator is updated to separate real minibatches from generated minibatches, and the generator is updated via gradients backpropagated through the discriminator to make its samples harder to classify as fake.
Adversarial training. The generator maps latent draws to generated samples, and the critic scores both generated and real samples. The critic maximizes its score on real data and minimizes it on generated samples, while the generator uses gradients through to make the two distributions indistinguishable.
16.1.2 The Log-Loss Objective#
Training the discriminator by binary cross-entropy (log loss) on balanced real and generated samples yields the minimax value function of Goodfellow et al. (2014):
The discriminator maximizes , while the generator affects only the second term and seeks to minimize , resulting in the minimax problem .
16.1.2.1 The Optimal Critic#
For a fixed generator distribution , maximizing (16.1.2) decouples pointwise across . At each point , the integrand is . Writing , maximizing the strictly concave function via the first-order condition gives the unique optimum:
Thus, the optimal discriminator outputs the Bayes posterior , and its logit equals the log density ratio , where . Even though has no closed-form density, binary classification estimates directly from samples. Furthermore, the log-loss objective uniquely pins down the additive constant of : shifting by any nonzero constant strictly decreases (Exercise 1), so precisely where .
For example, for two unit-variance Gaussians and , the optimal logit is affine in :
which changes sign at the midpoint . When and have different covariance matrices, is quadratic in and requires a nonlinear discriminator.
16.1.2.2 Connection to Jensen–Shannon Divergence#
Substituting the optimal discriminator and back into (16.1.2) reveals what the generator minimizes against an optimal discriminator:
Using the definition of the Jensen–Shannon divergence, , we obtain:
Because with equality if and only if , minimizing uniquely recovers the data distribution at the global minimum (where everywhere and the discriminator is reduced to random guessing).
Expanding and in terms of differential entropies provides an information-theoretic interpretation:
That is, equals the mutual information between a sample and its binary source label . Because a binary label carries at most nats of information, , reaching whenever and have disjoint supports.
16.1.2.3 Disjoint Supports and Vanishing Gradients#
Because saturates at , the minimax objective becomes constant whenever the supports of and do not overlap. For instance, if and are point masses on , then for every , yielding zero gradient with respect to no matter how close is to . Even when supports overlap in their tails, as for and , equals , , and nats at , and at it lies within of . Figure 16.1.2 shows the whole curve: it is flat long before the two Gaussians stop overlapping in any formal sense.
The Jensen–Shannon divergence between and as a function of the shift . The divergence reaches its ceiling within a few standard deviations. Beyond that the curve is flat, and a flat curve gives the generator no gradient.
In high dimensions, disjoint supports are the norm rather than the exception: both natural images and the outputs of a generator with concentrate on low-dimensional manifolds whose intersection typically has measure zero (Arjovsky and Bottou, 2017). When the discriminator separates them perfectly, the minimax value saturates.
The most direct remedy is to make the supports overlap. Suppose we add independent Gaussian noise of scale to every real and every generated sample before the discriminator sees it. The discriminator then compares two smoothed densities, which are positive everywhere. For the point masses above they are and , and their divergence is the curve of Figure 16.1.2 read at : the generator receives a gradient as long as lies within a few multiples of . This is instance noise (Sønderby et al., 2017; Arjovsky and Bottou, 2017). Unfortunately the generator now matches the blurred data rather than the data, so has to be annealed toward zero during training. The idea returns in Section 16.7, where the samples are noised by a diffusion model.
16.1.3 The Generator's Gradient#
In practice, the generator takes gradient steps against a fixed discriminator rather than minimizing directly. Let us examine the gradient of the generator objective.
16.1.3.1 Saturating versus Non-Saturating Weights#
In the literal minimax formulation, the generator minimizes with respect to its parameters . Using and , the gradient is:
Each generated sample is pushed uphill along , weighted by —the discriminator's estimated probability that is real. When the discriminator confidently rejects a sample (), this weight becomes exponentially small, causing the generator gradient to saturate precisely when the generator most needs to improve.
To avoid this saturation, Goodfellow et al. (2014) trained the generator to maximize the log-probability of its samples being classified as real, minimizing . Since , its gradient is:
Both objectives push each sample in the same direction , differing only in the per-sample scalar weight:
As shown in Figure 16.1.3, the non-saturating weight approaches for confidently rejected samples (), whereas decays as (a ratio of , or at and at ).
Per-sample generator gradient weights as a function of the discriminator logit on a log scale. For confidently rejected samples (), the saturating weight decays exponentially, whereas the non-saturating weight remains near 1.
16.1.3.2 Effective Divergence of the Non-Saturating Loss#
What divergence does the non-saturating generator loss descend when the discriminator is held at its optimal response ? Using , we can decompose the non-saturating objective as:
With fixed at , the first term on the right has the same gradient with respect to as the reverse KL divergence , while the second term is minus the minimax loss, whose gradient is by the envelope theorem that of (Arjovsky and Bottou, 2017) (Exercise 5). Combining the integrals using and yields:
Thus, against an optimal critic, the non-saturating generator descends , the softened reverse KL divergence (Shannon et al., 2020), which shares the unique global minimum .
Inspecting reveals an asymmetry in how errors are penalized:
- Where but (spurious samples outside the data support), and , heavily penalizing unrealistic samples.
- Where but (dropped modes of the data), and the integrand contributes only , a small finite penalty.
16.1.3.3 Mode Dropping#
When a generator covers only a subset of the modes of a multimodal distribution , it exhibits mode dropping (or mode collapse). Suppose is an equal mixture of two disjoint modes and matches one mode perfectly while omitting the other. On the covered mode, , so nats, nats, and nats. Dropping half of the data distribution costs only a quarter of a nat. By contrast, maximum likelihood minimizes the forward KL divergence , which is infinite whenever any part of is assigned zero density.
Worse still, at the optimal discriminator response on the covered mode, is constant across the support of , so : the local gradient on the covered mode vanishes and provides no signal pointing toward the missing mode. Even with an imperfect discriminator that assigns, say, to generated samples on the covered mode and to real samples on the uncovered mode, each generated sample is weighted only against the fixed zero threshold via , and the higher scores on the uncovered real mode never enter the generator update. Section 16.3 examines whether comparing generated scores directly against real scores helps address this.
16.1.4 Verifying the Theory on a 2D Gaussian#
To test the theoretical predictions quantitatively, we first train a linear generator on 2D Gaussian data, where , , , and can all be computed in closed form.
16.1.4.1 Alternating Update Rules#
We define update_D, update_G, and the alternating training loop train_gan once and save them to d2l for reuse across the chapter. First, update_D performs one discriminator step maximizing (16.1.2) (minimizing binary cross-entropy with label for real samples and for detached generated samples). Dividing the summed loss by the batch size estimates , which equals when .
def update_D(X, Z, net_D, net_G, trainer_D):
"""Update the critic; return its log loss summed over both batches
(per sample, the sum of two means: 2 log 2 at equilibrium)."""
trainer_D.zero_grad()
real_Y = net_D(X)
# The generator is the fixed player here: detach its output
fake_Y = net_D(net_G(Z).detach())
loss_D = (F.binary_cross_entropy_with_logits(
real_Y, torch.ones_like(real_Y), reduction='sum') +
F.binary_cross_entropy_with_logits(
fake_Y, torch.zeros_like(fake_Y), reduction='sum'))
loss_D.backward()
trainer_D.step()
return loss_DNext, update_G performs one generator step minimizing the non-saturating loss , implemented as binary cross-entropy on the recomputed discriminator scores net_D(net_G(Z)) with target label , which equals per sample when :
def update_G(Z, net_D, net_G, trainer_G):
"""Update the generator on the non-saturating loss; return its sum."""
trainer_G.zero_grad()
# net_D changed in its half-step, so recompute the scores
fake_Y = net_D(net_G(Z))
loss_G = F.binary_cross_entropy_with_logits(
fake_Y, torch.ones_like(fake_Y), reduction='sum')
loss_G.backward() # also fills net_D's .grad (update_D zeroes it)
trainer_G.step()
return loss_Gtrain_gan alternates update_D and step_G across minibatches using Adam with (Radford et al., 2015) so that momentum adapts quickly to the changing objective. It also supports an optional per-epoch callback on_epoch and exponential moving average ema.
def train_gan(net_D, net_G, data_iter, num_epochs, latent_dim, lr_D, lr_G,
step_G=update_G, seed=None, on_epoch=None, ema=None):
"""Alternate update_D and step_G over the minibatches with Adam
(beta_1 = 0.5), calling ema.update(net_G) after every generator step
and on_epoch(epoch) after each epoch if given; return each epoch's
per-sample losses (loss_D, the sum of the critic's two batch means,
and loss_G)."""
if seed is not None:
torch.manual_seed(seed)
trainer_D = torch.optim.Adam(net_D.parameters(), lr=lr_D,
betas=(0.5, 0.999))
trainer_G = torch.optim.Adam(net_G.parameters(), lr=lr_G,
betas=(0.5, 0.999))
history = []
for epoch in range(1, num_epochs + 1):
loss_D, loss_G, n = 0, 0, 0 # summed on the device, read once
for X, *_ in data_iter: # labels, if any, are ignored
Z = torch.randn(X.shape[0], latent_dim, device=X.device)
loss_D += update_D(X, Z, net_D, net_G, trainer_D).detach()
loss_G += step_G(Z, net_D, net_G, trainer_G).detach()
if ema is not None:
ema.update(net_G)
n += X.shape[0]
history.append(torch.stack([loss_D, loss_G]) / n)
if on_epoch is not None:
on_epoch(epoch)
return torch.stack(history).cpu().numpy()16.1.4.2 A Linear Generator with Known Densities#
We generate 1,000 training points from with , so that the true data distribution is the tilted elliptical Gaussian .
torch.manual_seed(0)
Z = torch.normal(0.0, 1.0, (1000, 2))
A = torch.tensor([[1.0, 2.0], [-0.1, 0.5]])
b = torch.tensor([1.0, 2.0])
data = Z @ A + b
print(f'covariance of the data distribution:\n{A.T @ A}')covariance of the data distribution:
tensor([[1.0100, 1.9500],
[1.9500, 4.2500]])
The generator is a single linear layer , which induces the Gaussian distribution . Because the log density ratio between two Gaussians with different covariances is quadratic, the discriminator uses a 3-layer MLP with two hidden layers of 16 leaky ReLU units (negative slope ; Exercise 3 examines what happens when saturating activations are used instead).
def make_nets(seed=7):
"""The linear generator and the critic, all weights and offsets drawn
from N(0, 0.02^2) by a generator seeded with seed."""
gen = torch.Generator().manual_seed(seed)
net_G = nn.Sequential(nn.Linear(2, 2))
net_D = nn.Sequential(nn.Linear(2, 16), nn.LeakyReLU(0.2),
nn.Linear(16, 16), nn.LeakyReLU(0.2),
nn.Linear(16, 1))
for w in [*net_G.parameters(), *net_D.parameters()]:
nn.init.normal_(w, 0, 0.02, generator=gen)
return net_G, net_DWe train for 20 epochs with batch size 8, setting lr_D=0.05 and lr_G=0.005 so the discriminator tracks its optimal response as the generator moves.
data_iter = d2l.load_array((data,), batch_size=8)
net_G, net_D = make_nets()
history = train_gan(net_D, net_G, data_iter, num_epochs=20, latent_dim=2,
lr_D=0.05, lr_G=0.005, seed=1)
with torch.no_grad():
fake = net_G(torch.normal(0, 1, (200, 2)))We now plot the per-epoch critic and generator losses in history against
their theoretical equilibrium values ( and ) alongside a
scatter plot of real (data) and generated (fake) samples:
fig, axes = d2l.plt.subplots(1, 2, figsize=(9, 3.2))
epochs = list(range(1, len(history) + 1))
d2l.plot(epochs, [history[:, 0], history[:, 1], [2 * math.log(2)] * len(epochs),
[math.log(2)] * len(epochs)],
'epoch', 'loss',
legend=['critic', 'generator', '2 log 2', 'log 2'],
fmts=('C0-', 'C1--', 'C0:', 'C1:'), axes=axes[0])
d2l.plot([data[:100, 0], fake[:100, 0]], [data[:100, 1], fake[:100, 1]],
legend=['real', 'generated'], fmts=('C0.', 'C1.'), axes=axes[1])
fig.tight_layout()Within 10 epochs, the discriminator loss rises to the equilibrium value , the generator loss settles to , and the generated point cloud matches the target ellipse.
16.1.4.3 Quantifying the Fit in Nats#
Because defines a Gaussian with , we can evaluate the exact KL divergence in dimensions (Kullback, 1959):
def generator_gaussian(net_G):
A_qT, b_q = net_G[0].weight.detach(), net_G[0].bias.detach()
return b_q, A_qT @ A_qT.T # nn.Linear stores A_q.T
def kl_gaussians(mu0, S0, mu1, S1):
diff = mu1 - mu0
return 0.5 * (torch.trace(torch.linalg.solve(S1, S0))
+ diff @ torch.linalg.solve(S1, diff) - len(mu0)
+ torch.logdet(S1) - torch.logdet(S0))
mu_p, Sigma_p = b, A.T @ A
for name, net in [('at initialization', make_nets()[0]),
('after training ', net_G)]:
mu_q, Sigma_q = generator_gaussian(net)
print(f'KL(q || p) {name}: '
f'{kl_gaussians(mu_q, Sigma_q, mu_p, Sigma_p):.3f} nats')KL(q || p) at initialization: 7.501 nats
KL(q || p) after training : 0.021 nats
Without ever evaluating the density of , adversarial training reduces from nats at initialization (dominated by the low entropy of the initial weights) to a few hundredths of a nat.
16.1.4.4 Verifying the Learned Log Density Ratio#
To test whether a trained discriminator accurately recovers ((16.1.3)), we fix a generator with and ( nats) and train a fresh discriminator against this frozen for 2,000 steps.
net_G_q, net_D_q = make_nets() # a fresh critic
with torch.no_grad(): # the hand-set generator; nn.Linear stores A_q.T
net_G_q[0].weight.copy_(torch.tensor([[1.0, -0.5], [2.0, 0.5]]))
net_G_q[0].bias.copy_(torch.tensor([1.5, 1.5]))
trainer_D = torch.optim.Adam(net_D_q.parameters(), lr=0.01)
torch.manual_seed(2)
for _ in range(2000): # critic-only steps against the frozen generator
X = data[torch.randint(0, len(data), (256,))]
Zb = torch.normal(0, 1, (256, 2))
update_D(X, Zb, net_D_q, net_G_q, trainer_D)We evaluate both the discriminator logit and the exact log density ratio across 200 real and 200 generated points, reporting their correlation and explained variance .
def gaussian_logpdf(x, mu, Sigma):
diff = x - mu
sol = torch.linalg.solve(Sigma, diff.T).T
return -0.5 * ((diff * sol).sum(1)
+ torch.logdet(2 * torch.pi * Sigma))
mu_q, Sigma_q = generator_gaussian(net_G_q)
with torch.no_grad():
xs = torch.cat([data[:200], net_G_q(torch.normal(0, 1, (200, 2)))])
lam = (gaussian_logpdf(xs, b, A.T @ A)
- gaussian_logpdf(xs, mu_q, Sigma_q))
D_out = net_D_q(xs).squeeze()
r2 = 1 - ((D_out - lam) ** 2).mean() / ((lam - lam.mean()) ** 2).mean()
print(f'correlation {torch.corrcoef(torch.stack([lam, D_out]))[0, 1]:.3f}, '
f'R^2 {r2:.3f}')correlation 0.982, R^2 0.962
Plotting the critic logits D_out against the exact log density ratio lam
across the 200 real and 200 generated samples visualizes how closely
tracks the identity line :
lims = [float(lam.min()), float(lam.max())]
d2l.plot([lam[:200], lam[200:], lims], [D_out[:200], D_out[200:], lims],
r'analytic $\lambda = \log(p/q)$', 'critic output $D$',
legend=['at real samples', 'at generated samples', r'$D = \lambda$'],
fmts=('C0.', 'C1.', 'k--'), figsize=(4.2, 3.4))The learned logits closely track the true log density ratio (, ). Deviations appear only at extreme negative values of (generated samples where ): the piecewise-linear leaky-ReLU network extrapolates linearly rather than quadratically into the tails, and because when , the log loss exerts almost no gradient to steepen the discriminator further once it is already confident.
16.1.4.5 Saturating versus Non-Saturating Generator Loss#
To compare the saturating and non-saturating weights ((16.1.6)) when the generator starts far from the data, we shift the initial generator bias by ( units from the data mean, nats) and compare update_G against update_G_saturating, which minimizes directly.
def update_G_saturating(Z, net_D, net_G, trainer_G):
trainer_G.zero_grad()
fake_Y = net_D(net_G(Z))
# log sigma(-D) is minus the cross-entropy under the label zero
loss_G = -F.binary_cross_entropy_with_logits(
fake_Y, torch.zeros_like(fake_Y), reduction='sum')
loss_G.backward()
trainer_G.step()
return loss_GWe run three seeds for each generator objective from identical initializations and minibatches (lr_G=0.01, lr_D=0.05).
def far_start():
"""make_nets with the generator's offset moved by (-6, 6)."""
net_G, net_D = make_nets()
with torch.no_grad():
net_G[0].bias += torch.tensor([-6.0, 6.0])
return net_G, net_D
mu_q, Sigma_q = generator_gaussian(far_start()[0])
print(f'start of every run: KL(q || p) = '
f'{kl_gaussians(mu_q, Sigma_q, mu_p, Sigma_p):.2f} nats')
torch.manual_seed(3)
Z_show = torch.randn(200, 2) # one latent sample for every snapshot
runs = {} # name: (losses, snapshots) of the first run, for the plot
for name, step in [('non-saturating', update_G),
('saturating', update_G_saturating)]:
kls = []
for seed in (1, 2, 3): # both arms see the same minibatches and draws
net_G_ab, net_D_ab = far_start()
snaps = {} # epoch: generated samples
hist = train_gan(net_D_ab, net_G_ab, data_iter, num_epochs=20,
latent_dim=2, lr_D=0.05, lr_G=0.01, step_G=step,
seed=seed, on_epoch=lambda epoch: snaps.update(
{epoch: net_G_ab(Z_show).detach()}))
runs.setdefault(name, (hist, snaps))
mu_q, Sigma_q = generator_gaussian(net_G_ab)
kls.append(f'{kl_gaussians(mu_q, Sigma_q, mu_p, Sigma_p):.2f}')
print(f'{name}: final KL(q || p) = {", ".join(kls)} nats')start of every run: KL(q || p) = 344.20 nats
non-saturating: final KL(q || p) = 0.03, 0.02, 0.03 nats
saturating: final KL(q || p) = 337.75, 334.37, 336.51 nats
To see why the final KL divergences differ so starkly, we plot the generated
point clouds snaps at epochs 5 and 20 for each objective alongside their
critic loss trajectories:
fig, axes = d2l.plt.subplots(1, 3, figsize=(10.5, 3.2))
for ax, (name, (hist, snaps)) in zip(axes[:2], runs.items()):
d2l.plot([data[:150, 0], snaps[5][:, 0], snaps[20][:, 0]],
[data[:150, 1], snaps[5][:, 1], snaps[20][:, 1]],
legend=['real', 'epoch 5', 'epoch 20'],
fmts=('C0.', 'C1+', 'C1.'), axes=ax)
ax.set_title(name)
epochs = list(range(1, 21))
d2l.plot(epochs, [runs['non-saturating'][0][:, 0],
runs['saturating'][0][:, 0], [2 * math.log(2)] * 20],
'epoch', 'critic loss', legend=['non-saturating', 'saturating',
'2 log 2'],
fmts=('-', '--', 'k:'), axes=axes[2])
fig.tight_layout()In the first two epochs, both discriminators easily separate the distant generated points from the data, driving the discriminator loss near zero and . Because , the saturating generator stalls completely (still nats from the data after 20 epochs). By contrast, the non-saturating weight preserves the discriminator's spatial gradient , pulling the generator onto the data distribution within 20 epochs ( of a few hundredths of a nat). Note that only rescales ; it relies on the leaky-ReLU discriminator having a nonzero spatial slope at .
16.1.5 Training an MLP GAN on Fashion-MNIST#
On images, neither nor is known in closed form, so we must monitor sample quality and the training losses. As a first image experiment, we train two leaky-ReLU MLPs on the 60,000 grayscale images of Fashion-MNIST (Section 3.2), scaled to . The generator maps a 100-dimensional latent vector through hidden layers of 256 and 512 units to 784 pixels with a output activation; the discriminator maps 784 pixels through 512 and 256 units to a single logit. We save the helper make_mlp for building simple MLPs in later sections.
def make_mlp(sizes, act):
"""Linear layers of the given widths with the activation module act
between them; weights uniform in +-1/sqrt(fan_in), zero biases."""
layers = []
for d_in, d_out in zip(sizes[:-1], sizes[1:]):
linear = nn.Linear(d_in, d_out) # weights uniform by default
nn.init.zeros_(linear.bias)
layers += [linear, act]
return nn.Sequential(*layers[:-1])Using make_mlp, we rescale the 60,000 Fashion-MNIST training images to
-dimensional vectors in , build the minibatch loader
image_iter, and instantiate the generator net_G_img (ending with tanh)
and discriminator net_D_img:
torch.manual_seed(0)
fmnist = d2l.FashionMNIST()
# All 60,000 training images as rows of 784 pixels in [-1, 1]
images = fmnist.train.data.reshape(-1, 784).float() / 127.5 - 1
image_iter = d2l.load_array((images,), batch_size=64)
leaky = nn.LeakyReLU(0.2)
net_G_img = nn.Sequential(make_mlp([100, 256, 512, 784], leaky), nn.Tanh())
net_D_img = make_mlp([784, 512, 256, 1], leaky)We train both networks with learning rate and batch size 64 for 20 epochs ( steps).
history_img = train_gan(net_D_img, net_G_img, image_iter, num_epochs=20,
latent_dim=100, lr_D=2e-4, lr_G=2e-4, seed=1)
print(f'last epoch: critic loss {history_img[-1, 0]:.2f}, '
f'generator loss {history_img[-1, 1]:.2f}')last epoch: critic loss 1.05, generator loss 1.37
After training, we draw 30 latent vectors from , pass
them through net_G_img, and reshape the outputs to images to
inspect the generated garments:
with torch.no_grad():
fake_img = net_G_img(torch.randn(30, 100))
d2l.show_images(fake_img.reshape(30, 28, 28), 2, 15, scale=0.9, cmap='gray');We also plot the per-epoch critic and generator losses in history_img against
the reference levels and :
epochs = list(range(1, len(history_img) + 1))
fig, axes = d2l.plt.subplots(1, 2, figsize=(9, 3), sharex=True)
for ax, loss, ref, name, ref_name, fmt in zip(
axes, history_img.T, (2 * math.log(2), math.log(2)),
('critic', 'generator'), ('2 log 2', 'log 2'), ('C0-', 'C1--')):
d2l.plot(epochs, [loss, [ref] * len(epochs)], 'epoch', f'{name} loss',
legend=[name, ref_name], fmts=(fmt, 'k:'), axes=ax)
fig.tight_layout()The generated images capture recognizable garment silhouettes (shirts, trousers, shoes, bags), though with grainy pixel noise because an MLP lacks the spatial inductive bias of convolutions. Notice that even after 20 epochs, the discriminator loss () remains below its equilibrium value and the generator loss () above . Unlike the 2D Gaussian setting, loss curves alone on images cannot distinguish imperfect generation from discriminator overfitting (Exercise 6) or reveal whether all garment categories are covered equally (Exercise 4).
16.1.6 Summary#
A generative adversarial network trains an implicit generator without an explicit likelihood by pairing it with a discriminator (or critic) that separates real data from generated samples . Under binary log loss, the optimal discriminator logit recovers the log density ratio , and the optimal value function reduces to , where is the mutual information between a sample from and its source label. When generated samples are confidently rejected (), the literal minimax generator weight vanishes exponentially, whereas the non-saturating generator loss maintains near-unit weight . Against an optimal discriminator, the non-saturating loss descends , which heavily penalizes out-of-support samples while assigning only a bounded penalty to dropped modes.
16.1.7 Exercises#
- Excess loss and the additive constant. Let and let be the KL divergence between Bernoulli distributions with parameters and .
- Show that every critic satisfies , so that is the unique maximizer of (16.1.2) up to -null sets.
- Conclude that for every constant .
- Expand to second order in to show
with coefficient in . When and are nearly disjoint, how tightly do finite samples pin down the additive constant of ?
-
Supports of measure zero.
- A generator with a 1D latent places its samples on a line in . Show that against the 2D Gaussian data distribution for every and .
- Show that for the empirical distribution of the 1,000 training points and every continuous density (including ).
- For a -Lipschitz critic , use Kantorovich–Rubinstein duality (Section 25.4.2) to show that replacing by in (16.1.2) changes by at most . Why does restricting the Lipschitz constant make training on empirical samples informative?
-
[code] Saturating critic activations. ● Replace the leaky-ReLU activations in
make_netswith units and hidden widths of 5 and 3.- Rerun the non-saturating arm of Section 16.1.4.5 for five seeds and record the final and critic loss.
- For a stalled run, inspect the hidden activations and at real and generated samples. Why does saturating the critic's hidden units prevent the non-saturating generator loss from recovering?
- Both a converged generator () and a constant critic () yield a critic loss of . Which diagnostic in this section distinguishes the two?
-
[code] Class coverage of the Fashion-MNIST generator. ●
- Train LeNet (Section 6.6) on Fashion-MNIST, classify 1,000 samples from
net_G_img, and compare the predicted class histogram against the uniform data distribution. - Repeat for generators trained for 5 and 40 epochs. Does longer training make the class distribution more uniform?
- How does forced classification into 10 classes bias the histogram when some generated images are blurry or ambiguous? Relate your findings to mode dropping (Section 16.1.3.3).
- Train LeNet (Section 6.6) on Fashion-MNIST, classify 1,000 samples from
-
Generator weights and their divergences. ●● A generator loss with fixed critic has gradient where . Assume is held at the optimal log density ratio for the current generator , and write .
- Using , show that the unweighted loss () has gradient at .
- For the -divergence (Section 25.3.1.2), show that , so a weight function corresponds to the -divergence satisfying .
- Identify the divergences corresponding to , , (Goodfellow, 2016), and (Theorem 2.5 of Arjovsky and Bottou (2017)).
- Use (16.1.7) to evaluate when has equal disjoint modes and covers only one of them, and compare its growth in with .
Adapted from Stefano Ermon and Aditya Grover's CS236: Deep Generative Models.
-
[extended] Finite samples and critic capacity. ●● When the sample size exceeds the number of critic parameters by a factor of , the empirical critic value concentrates within of its population value (Arora et al., 2017). Fix the generator to the true data distribution (, so ).
- Train 2-hidden-layer critics of width 4, 16, 128, and 1,024 on fixed training points from (Adam at , 4,000 steps of batch size 256). Plot the generalization gap between the training loss and the population loss on fresh draws against parameter count.
- The Fashion-MNIST critic in Section 16.1.5 has parameters and trains on 60,000 images. Design and run a test using the Fashion-MNIST test set to check whether its sub- loss reflects memorization of the training set or genuine discrepancy between and .