Generative Adversarial Networks
A generator and a discriminator locked in a game.
A GAN never writes down a probability. It trains a generator to fool a classifier and a classifier to catch the generator, and the only signal the generator ever receives is the gradient of a judgment about its fakes. Derive what that judgment converges to, why the original loss stalls, why training cycles and collapses, and what replaced the Jensen–Shannon divergence.
What you’ll learn
- Write the GAN value function and derive the optimal discriminator .
- Explain why the minimax generator loss saturates and derive the gradient of the non-saturating alternative.
- Implement an alternating GAN training step, and explain mode collapse, cycling and the DCGAN guidelines.
- Explain why Jensen–Shannon fails on disjoint supports, and how Wasserstein GANs with gradient penalties and spectral normalization constrain the critic.
The game
A generative adversarial network (Goodfellow et al., 2014) has two networks. The generator maps a latent vector , usually , to a sample ; the samples define a distribution that is never written down. The discriminator is a binary classifier that estimates the probability that came from the data rather than from .
Training is a two-player minimax game over one value function:
Three features set GANs apart from the other families. They are implicit: you can sample but not evaluate it, so there is no likelihood to report. Their loss is learned: instead of a fixed distance such as squared error, the discriminator learns whatever features currently separate real from fake, which is why GAN samples are sharp rather than averaged. And training is a game, not a minimization: the generator's objective changes every time the discriminator does.
In practice the two networks take turns: one or more discriminator steps on a batch of real and generated examples, then one generator step that backpropagates through the discriminator into the generator.
The optimal discriminator
What would a perfect discriminator do against a fixed generator? Write both expectations as integrals over , using for the distribution of :
The value function is an integral of a pointwise expression, so it is maximized by maximizing the integrand at every separately:
For not both zero, on is concave with derivative , which vanishes at . With and :
Substituting back and rearranging gives the value of the inner maximization in terms of the Jensen–Shannon divergence, with (the Artificial Intelligence course's Deep Layer lesson on GANs proves it):
with equality only when the distributions agree, so the generator's objective is minimized exactly at , where everywhere and . This is a statement about the game in function space, with unlimited capacity and an inner maximization solved exactly; it says nothing yet about networks trained by alternating gradient steps.
At some image the data density is and the generator's density is (in some unit). What does the optimal discriminator output there?
Show the answer
0.75
: three times as many real images as fakes land near , so the calibrated probability of "real" is . The generator's gradient pushes more of its mass toward such regions, where real data is underrepresented in its samples.
Saturation and the non-saturating loss
Early in training the generator's samples are obviously fake, the discriminator rejects them with confidence, and . Write with logit and look at the gradient the generator receives through under each candidate loss:
The minimax generator minimizes . Since :
The non-saturating generator instead minimizes , that is, it maximizes :
So exactly when the generator is worst, and the discriminator most confident, the minimax loss passes almost no gradient while the non-saturating loss passes a full-strength one. Both losses are stationary at the same point, with , but their dynamics differ. Goodfellow et al. (2014) proposed the switch in the original paper, and it is the default.
The switch is not free. Against the optimal discriminator the non-saturating loss no longer follows ; its expected gradient follows , and the reverse KL term penalizes putting mass where the data has none far more than missing data altogether, a mode-seeking bias (Arjovsky & Bottou, 2017; derived in the Artificial Intelligence course's Deep Layer lesson on GANs).
Early in training the discriminator outputs for most fakes. Which statement is right?
- Both generator losses give the same gradient, since they share a fixed point
- The minimax loss gives a near-zero gradient through the logit, about , while the non-saturating loss gives about
- The non-saturating loss gives a near-zero gradient, so the minimax loss is preferred early on
- Neither loss can train the generator until the discriminator is reset
Show the answer
B. The minimax loss gives a near-zero gradient through the logit, about , while the non-saturating loss gives about
Through the logit, and . A shared fixed point does not mean shared gradients away from it.
Training in practice: cycling and mode collapse
import torch
import torch.nn.functional as F
def gan_step(G, D, opt_G, opt_D, x_real, z_dim=128):
B = x_real.shape[0]
# discriminator step: real -> 1, fake -> 0 (D returns logits)
x_fake = G(torch.randn(B, z_dim)).detach() # no gradient into G here
l_real, l_fake = D(x_real), D(x_fake)
loss_D = (F.binary_cross_entropy_with_logits(l_real, torch.ones_like(l_real))
+ F.binary_cross_entropy_with_logits(l_fake, torch.zeros_like(l_fake)))
opt_D.zero_grad(); loss_D.backward(); opt_D.step()
# generator step, non-saturating: make D call the fakes real
l_gen = D(G(torch.randn(B, z_dim)))
loss_G = F.binary_cross_entropy_with_logits(l_gen, torch.ones_like(l_gen)) # -log D(G(z))
opt_G.zero_grad(); loss_G.backward(); opt_G.step()
return loss_D.item(), loss_G.item()Labeling fakes as "real" in the generator's cross-entropy is exactly the non-saturating loss. The generator's backward pass also leaves gradients in 's parameters, which the next opt_D.zero_grad() clears.
The function-space theorem assumed the inner maximization is solved exactly. Alternating single gradient steps solve nothing exactly, and two failure modes follow.
Cycling. Gradient play on a game need not converge even in the simplest cases: on the bilinear game , simultaneous gradient steps spiral outward (the Artificial Intelligence course's Deep Layer lesson on GANs analyzes this). On the toy ring of eight Gaussians, Metz et al. (2017) showed a standard GAN rotating through the modes, never converging to a fixed distribution.
Mode collapse. Hold fixed and the generator's best response is degenerate: minimizing is achieved by sending every to a maximizer of , a point mass. Nothing in a single generator step rewards spreading out; only the discriminator's later reaction punishes a pile-up, and then the pile moves. The result is a generator that covers a few modes, or hops among them.
A decade of engineering made GANs reliable. The DCGAN guidelines (Radford, Metz & Chintala, 2016) replaced pooling with strided convolutions in the discriminator and fractionally-strided (transposed) convolutions in the generator, used batch normalization in both networks, removed fully connected hidden layers in deeper models, used ReLU in the generator with a tanh output and LeakyReLU (slope ) in the discriminator, and trained with Adam at learning rate with , since the default made training oscillate. Other widely used tools:
- One-sided label smoothing and minibatch features (Salimans et al., 2016): soften the discriminator's targets for real data, and let it see statistics of the whole batch, so that a collapsed batch is easy to detect.
- Two time-scale updates (Heusel et al., 2017): give the discriminator its own, typically larger, learning rate; under stochastic-approximation assumptions this converges to a local Nash equilibrium.
- Gradient penalties on the discriminator, such as the penalty on real data (Mescheder, Geiger & Nowozin, 2018), which damp the discriminator near the data and restore local convergence.
Wasserstein GANs and Lipschitz critics
Real images lie near a low-dimensional set inside pixel space, and early in training the generator's outputs lie on another. When two distributions have disjoint supports, is stuck at its maximum and a perfect discriminator exists, so the generator's loss is flat. Arjovsky, Chintala & Bottou (2017) made this concrete with a one-line example.
A Wasserstein GAN trains a critic network to approximate the supremum and the generator to minimize . Everything hinges on keeping the critic Lipschitz. The original WGAN clipped every weight to and trained with RMSProp and five critic steps per generator step, a crude constraint that the authors themselves called terrible. Three better ways followed:
- Gradient penalty (WGAN-GP; Gulrajani et al., 2017): an optimal critic has gradient norm 1 almost everywhere along straight lines between coupled real and generated points, so penalize at random interpolates , , with , five critic steps, Adam with , , and no batch normalization in the critic, since it would couple the penalty across a batch.
- Spectral normalization (Miyato et al., 2018): divide each weight matrix by its largest singular value , estimated with one step of power iteration per update. A composition of maps is at most as Lipschitz as the product of their constants, so with 1-Lipschitz activations such as (leaky) ReLU, . For convolutions it normalizes the reshaped kernel matrix, a cheap stand-in for the layer's true operator norm. It works with the ordinary GAN loss as well and was widely adopted; BigGAN, for example, applies it to both networks.
- Penalties on real data only (, above), favored in later high-resolution GANs.
import torch
def gradient_penalty(critic, x_real, x_fake):
eps = torch.rand(x_real.shape[0], *[1] * (x_real.dim() - 1)) # one epsilon per example
x_hat = (eps * x_real + (1 - eps) * x_fake).requires_grad_(True)
grad, = torch.autograd.grad(critic(x_hat).sum(), x_hat, create_graph=True)
return ((grad.flatten(1).norm(dim=1) - 1) ** 2).mean()
# critic loss: critic(x_fake).mean() - critic(x_real).mean() + 10 * gradient_penalty(...)
# generator loss: -critic(G(z)).mean()create_graph=True keeps the graph of the input gradient so that the penalty itself can be differentiated with respect to the critic's weights: a gradient of a gradient.
In the parallel-lines example, the data is the segment at and the model's segment sits at . What happens if you move the model to ?
- drops from to about
- stays at while drops from to
- Both and stay constant until the segments overlap
- becomes infinite
Show the answer
B. stays at while drops from to
The supports are still disjoint, so is still : it cannot tell a near miss from a far one. measures how far the mass must move, so it falls from to and its gradient points toward the data.
Conditioning. A conditional GAN (Mirza & Osindero, 2014) feeds a condition , such as a class label, to both networks: generates, and judges whether is a real example of class , so that ignoring the condition is punished. Later designs inject through class-conditional normalization in the generator and a projection term in the discriminator, and the condition can be an entire image, which turns the GAN into an image-to-image translator.
Key takeaways
- A GAN plays : the discriminator is a real-versus-fake classifier and the generator learns to fool it, with no likelihood involved.
- For fixed , , and the generator then minimizes , which is minimized only at (in function space).
- The minimax generator loss saturates when ; the non-saturating loss keeps the gradient alive and is the default, at the price of a mode-seeking bias.
- Alternating gradient play can cycle, and a generator's best response to a fixed discriminator is a point mass: mode collapse. DCGAN's architecture rules, label smoothing, two time-scale updates and penalties made training practical.
- With disjoint supports JS is flat at while stays informative; WGANs estimate with a Lipschitz critic, enforced by gradient penalties or spectral normalization.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
For a fixed generator, what is the optimal discriminator in the original GAN game?
- everywhere
Show the answer
D.
Maximizing pointwise gives : the posterior probability of "real" when real and fake are mixed half and half.
Why do practitioners train the generator to maximize instead of minimizing ?
- It strengthens the generator's gradient exactly when the discriminator confidently rejects the fakes, where the minimax loss saturates
- It makes the game have a different optimum, closer to the data
- It turns the GAN into a maximum-likelihood method
- It removes the need to train the discriminator
Show the answer
A. It strengthens the generator's gradient exactly when the discriminator confidently rejects the fakes, where the minimax loss saturates
Through the logit, the minimax gradient is , which vanishes as , while the non-saturating gradient is , which stays near . The fixed point is the same.
Freeze the discriminator and let the generator train to convergence against it. What does the generator converge to?
- The data distribution, since the discriminator was trained on real data
- A distribution concentrated where is largest, ideally a single point: the seed of mode collapse
- The uniform distribution over the image space
- It cannot converge, because the loss has no minimum
Show the answer
B. A distribution concentrated where is largest, ideally a single point: the seed of mode collapse
For fixed , is minimized by sending every to a maximizer of . Only the discriminator's subsequent updates punish the pile-up, which is why alternating training can chase modes instead of covering them.
Where does WGAN-GP evaluate its gradient penalty, and what does it push toward?
- At the real data points only, pushing the critic's gradient toward zero
- At the generated samples only, pushing the critic's output toward zero
- At random points on straight lines between real and generated samples, pushing the critic's input-gradient norm toward 1
- On the weights, pushing every weight into
Show the answer
C. At random points on straight lines between real and generated samples, pushing the critic's input-gradient norm toward 1
An optimal 1-Lipschitz critic has gradient norm 1 along the lines that join coupled real and generated points, so WGAN-GP penalizes at interpolates , with weight .
Go deeper
- Style-Based Generators · StyleGAN’s mapping network, style modulation and controllable synthesis.
- Conditional GANs & Image-to-Image Translation · pix2pix, CycleGAN and turning one kind of image into another.
- Evaluating Generative Models · Likelihood, FID, precision and recall, memorization, and why metrics disagree.
Further reading
- I. Goodfellow, J. Pouget-Abadie, M. Mirza, B. Xu, D. Warde-Farley, S. Ozair, A. Courville & Y. Bengio, "Generative adversarial nets," NeurIPS (2014).
- A. Radford, L. Metz & S. Chintala, "Unsupervised representation learning with deep convolutional generative adversarial networks," ICLR (2016).
- I. Gulrajani, F. Ahmed, M. Arjovsky, V. Dumoulin & A. Courville, "Improved training of Wasserstein GANs," NeurIPS (2017).
- T. Miyato, T. Kataoka, M. Koyama & Y. Yoshida, "Spectral normalization for generative adversarial networks," ICLR (2018).