Simple Algorithm
Deep Learning · Representation · 24 min

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 D∗=pdata/(pdata+pg)D^*=p_{\text{data}}/(p_{\text{data}}+p_g).
  • 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 GθG_{\boldsymbol\theta} maps a latent vector z∼p(z)\mathbf z\sim p(\mathbf z), usually N(0,I)\mathcal N(\mathbf 0,I), to a sample Gθ(z)G_{\boldsymbol\theta}(\mathbf z); the samples define a distribution pgp_g that is never written down. The discriminator Dψ(x)∈(0,1)D_{\boldsymbol\psi}(\mathbf x)\in(0,1) is a binary classifier that estimates the probability that x\mathbf x came from the data rather than from GG.

Training is a two-player minimax game over one value function:

min⁡Gmax⁡D  V(D,G)=Ex∼pdata[log⁡D(x)]+Ez∼p(z)[log⁡(1−D(G(z)))]\min_{G}\max_{D}\;V(D,G)=\E_{\mathbf x\sim p_{\text{data}}}\big[\log D(\mathbf x)\big]+\E_{\mathbf z\sim p(\mathbf z)}\big[\log\big(1-D(G(\mathbf z))\big)\big]
For fixed GG, maximizing VV over DD is exactly minimizing the binary cross-entropy of a classifier that labels data 11 and samples 00. The generator then moves its samples to make that classifier's job as hard as possible.

Three features set GANs apart from the other families. They are implicit: you can sample pgp_g 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 x\mathbf x, using pgp_g for the distribution of G(z)G(\mathbf z):

DerivationD* for a fixed generator (Goodfellow et al., 2014)
  1. V(D,G)=∫[pdata(x)log⁡D(x)+pg(x)log⁡(1−D(x))] dxV(D,G)=\int\Big[p_{\text{data}}(\mathbf x)\log D(\mathbf x)+p_g(\mathbf x)\log\big(1-D(\mathbf x)\big)\Big]\,d\mathbf x

    The value function is an integral of a pointwise expression, so it is maximized by maximizing the integrand at every x\mathbf x separately:

  2. DG∗(x)=pdata(x)pdata(x)+pg(x)D^*_G(\mathbf x)=\frac{p_{\text{data}}(\mathbf x)}{p_{\text{data}}(\mathbf x)+p_g(\mathbf x)}

    For a,b≥0a,b\ge0 not both zero, y↦alog⁡y+blog⁡(1−y)y\mapsto a\log y+b\log(1-y) on (0,1)(0,1) is concave with derivative a/y−b/(1−y)a/y-b/(1-y), which vanishes at y=a/(a+b)y=a/(a+b). With a=pdata(x)a=p_{\text{data}}(\mathbf x) and b=pg(x)b=p_g(\mathbf x):

  3. max⁡DV(D,G)=V(DG∗,G)=−log⁡4+2 JS(pdata ∥ pg)\max_DV(D,G)=V(D^*_G,G)=-\log4+2\,\mathrm{JS}(p_{\text{data}}\,\|\,p_g)

    Substituting DG∗D^*_G back and rearranging gives the value of the inner maximization in terms of the Jensen–Shannon divergence, JS(P ∥ Q)=12DKL(P ∥ M)+12DKL(Q ∥ M)\mathrm{JS}(P\,\|\,Q)=\tfrac12\KL(P\,\|\,M)+\tfrac12\KL(Q\,\|\,M) with M=12(P+Q)M=\tfrac12(P+Q) (the Artificial Intelligence course's Deep Layer lesson on GANs proves it):

  4. JS≥0\mathrm{JS}\ge0 with equality only when the distributions agree, so the generator's objective is minimized exactly at pg=pdatap_g=p_{\text{data}}, where D∗=12D^*=\tfrac12 everywhere and V=−log⁡4V=-\log4. 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.

Predict before you look

At some image x\mathbf x the data density is pdata(x)=0.3p_{\text{data}}(\mathbf x)=0.3 and the generator's density is pg(x)=0.1p_g(\mathbf x)=0.1 (in some unit). What does the optimal discriminator output there?

Show the answer

0.75

D∗=0.3/(0.3+0.1)=0.75D^*=0.3/(0.3+0.1)=0.75: three times as many real images as fakes land near x\mathbf x, so the calibrated probability of "real" is 3/43/4. 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 D(G(z))≈0D(G(\mathbf z))\approx0. Write D=σ(l)D=\sigma(l) with logit ll and look at the gradient the generator receives through ll under each candidate loss:

DerivationGradients with respect to the discriminator logit
  1. ∂∂llog⁡(1−σ(l))=−σ(l) → l→−∞  0\frac{\partial}{\partial l}\log\big(1-\sigma(l)\big)=-\sigma(l)\ \xrightarrow{\ l\to-\infty\ }\ 0

    The minimax generator minimizes log⁡(1−σ(l))\log(1-\sigma(l)). Since σ′(l)=σ(l)(1−σ(l))\sigma'(l)=\sigma(l)(1-\sigma(l)):

  2. ∂∂l(−log⁡σ(l))=−(1−σ(l)) → l→−∞  −1\frac{\partial}{\partial l}\big(-\log\sigma(l)\big)=-\big(1-\sigma(l)\big)\ \xrightarrow{\ l\to-\infty\ }\ -1

    The non-saturating generator instead minimizes −log⁡σ(l)-\log\sigma(l), that is, it maximizes log⁡D(G(z))\log D(G(\mathbf z)):

  3. 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, D=12D=\tfrac12 with pg=pdatap_g=p_{\text{data}}, 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 JS\mathrm{JS}; its expected gradient follows DKL(pg ∥ pdata)−2 JS\KL(p_g\,\|\,p_{\text{data}})-2\,\mathrm{JS}, 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).

Check your understanding

Early in training the discriminator outputs D(G(z))=0.001D(G(\mathbf z))=0.001 for most fakes. Which statement is right?

  1. Both generator losses give the same gradient, since they share a fixed point
  2. The minimax loss gives a near-zero gradient through the logit, about −0.001-0.001, while the non-saturating loss gives about −1-1
  3. The non-saturating loss gives a near-zero gradient, so the minimax loss is preferred early on
  4. 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 −0.001-0.001, while the non-saturating loss gives about −1-1

Through the logit, ∂log⁡(1−σ(l))/∂l=−σ(l)=−0.001\partial\log(1-\sigma(l))/\partial l=-\sigma(l)=-0.001 and ∂(−log⁡σ(l))/∂l=−(1−σ(l))=−0.999\partial(-\log\sigma(l))/\partial l=-(1-\sigma(l))=-0.999. A shared fixed point does not mean shared gradients away from it.

Training in practice: cycling and mode collapse

python
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 DD'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 V(x,y)=xyV(x,y)=xy, 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 DD fixed and the generator's best response is degenerate: minimizing Ez[−log⁡D(G(z))]\E_{\mathbf z}[-\log D(G(\mathbf z))] is achieved by sending every z\mathbf z to a maximizer of DD, 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 0.20.2) in the discriminator, and trained with Adam at learning rate 2×10−42\times10^{-4} with β1=0.5\beta_1=0.5, since the default β1=0.9\beta_1=0.9 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 R1R_1 penalty γ2Epdata∥∇xD(x)∥2\frac\gamma2\E_{p_{\text{data}}}\norm{\nabla_{\mathbf x}D(\mathbf x)}^2 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, JS\mathrm{JS} is stuck at its maximum log⁡2\log2 and a perfect discriminator exists, so the generator's loss is flat. Arjovsky, Chintala & Bottou (2017) made this concrete with a one-line example.

W1(pdata,pg)=inf⁡γ∈Π(pdata,pg)E(x,y)∼γ∥x−y∥=sup⁡∥f∥Lip≤1(Epdata[f(x)]−Epg[f(x)])W_1(p_{\text{data}},p_g)=\inf_{\gamma\in\Pi(p_{\text{data}},p_g)}\E_{(\mathbf x,\mathbf y)\sim\gamma}\norm{\mathbf x-\mathbf y}=\sup_{\norm f_{\text{Lip}}\le1}\Big(\E_{p_{\text{data}}}[f(\mathbf x)]-\E_{p_g}[f(\mathbf x)]\Big)
Π\Pi is the set of couplings with the two marginals. The second form is Kantorovich–Rubinstein duality (sketched in the Artificial Intelligence course's Deep Layer lesson on GANs): a 1-Lipschitz critic ff, with no sigmoid, that maximizes the gap between its average score on real and generated data.

A Wasserstein GAN trains a critic network to approximate the supremum and the generator to minimize −Ez[f(G(z))]-\E_{\mathbf z}[f(G(\mathbf z))]. Everything hinges on keeping the critic Lipschitz. The original WGAN clipped every weight to [−0.01,0.01][-0.01,0.01] 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 λ Ex^(∥∇x^f(x^)∥−1)2\lambda\,\E_{\hat{\mathbf x}}\big(\norm{\nabla_{\hat{\mathbf x}}f(\hat{\mathbf x})}-1\big)^2 at random interpolates x^=ϵx+(1−ϵ)G(z)\hat{\mathbf x}=\epsilon\mathbf x+(1-\epsilon)G(\mathbf z), ϵ∼U[0,1]\epsilon\sim U[0,1], with λ=10\lambda=10, five critic steps, Adam with β1=0\beta_1=0, β2=0.9\beta_2=0.9, 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 σ(W)\sigma(W), 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, ∥f∥Lip≤∏l∥Wl/σ(Wl)∥2=1\norm f_{\text{Lip}}\le\prod_l\norm{W_l/\sigma(W_l)}_2=1. 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 (R1R_1, above), favored in later high-resolution GANs.
python
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.

Check your understanding

In the parallel-lines example, the data is the segment at x=0x=0 and the model's segment sits at x=θ=0.5x=\theta=0.5. What happens if you move the model to θ=0.1\theta=0.1?

  1. JS\mathrm{JS} drops from log⁡2\log2 to about 0.1log⁡20.1\log2
  2. JS\mathrm{JS} stays at log⁡2\log2 while W1W_1 drops from 0.50.5 to 0.10.1
  3. Both JS\mathrm{JS} and W1W_1 stay constant until the segments overlap
  4. W1W_1 becomes infinite
Show the answer

B. JS\mathrm{JS} stays at log⁡2\log2 while W1W_1 drops from 0.50.5 to 0.10.1

The supports are still disjoint, so JS\mathrm{JS} is still log⁡2\log2: it cannot tell a near miss from a far one. W1=∣θ∣W_1=\abs\theta measures how far the mass must move, so it falls from 0.50.5 to 0.10.1 and its gradient points toward the data.

Conditioning. A conditional GAN (Mirza & Osindero, 2014) feeds a condition cc, such as a class label, to both networks: G(z,c)G(\mathbf z,c) generates, and D(x,c)D(\mathbf x,c) judges whether x\mathbf x is a real example of class cc, so that ignoring the condition is punished. Later designs inject cc 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 min⁡Gmax⁡DEpdata[log⁡D]+Ez[log⁡(1−D(G(z)))]\min_G\max_D\E_{p_{\text{data}}}[\log D]+\E_{\mathbf z}[\log(1-D(G(\mathbf z)))]: the discriminator is a real-versus-fake classifier and the generator learns to fool it, with no likelihood involved.
  • For fixed GG, D∗=pdata/(pdata+pg)D^*=p_{\text{data}}/(p_{\text{data}}+p_g), and the generator then minimizes 2 JS(pdata ∥ pg)−log⁡42\,\mathrm{JS}(p_{\text{data}}\,\|\,p_g)-\log4, which is minimized only at pg=pdatap_g=p_{\text{data}} (in function space).
  • The minimax generator loss saturates when D(G(z))→0D(G(\mathbf z))\to0; the non-saturating loss −log⁡D(G(z))-\log D(G(\mathbf z)) 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 R1R_1 penalties made training practical.
  • With disjoint supports JS is flat at log⁡2\log2 while W1W_1 stays informative; WGANs estimate W1W_1 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.

Question 1

For a fixed generator, what is the optimal discriminator in the original GAN game?

  1. D∗(x)=pdata(x)D^*(\mathbf x)=p_{\text{data}}(\mathbf x)
  2. D∗(x)=12D^*(\mathbf x)=\tfrac12 everywhere
  3. D∗(x)=pg(x)/(pdata(x)+pg(x))D^*(\mathbf x)=p_g(\mathbf x)/\big(p_{\text{data}}(\mathbf x)+p_g(\mathbf x)\big)
  4. D∗(x)=pdata(x)/(pdata(x)+pg(x))D^*(\mathbf x)=p_{\text{data}}(\mathbf x)/\big(p_{\text{data}}(\mathbf x)+p_g(\mathbf x)\big)
Show the answer

D. D∗(x)=pdata(x)/(pdata(x)+pg(x))D^*(\mathbf x)=p_{\text{data}}(\mathbf x)/\big(p_{\text{data}}(\mathbf x)+p_g(\mathbf x)\big)

Maximizing pdatalog⁡D+pglog⁡(1−D)p_{\text{data}}\log D+p_g\log(1-D) pointwise gives D∗=pdata/(pdata+pg)D^*=p_{\text{data}}/(p_{\text{data}}+p_g): the posterior probability of "real" when real and fake are mixed half and half.

Question 2

Why do practitioners train the generator to maximize log⁡D(G(z))\log D(G(\mathbf z)) instead of minimizing log⁡(1−D(G(z)))\log(1-D(G(\mathbf z)))?

  1. It strengthens the generator's gradient exactly when the discriminator confidently rejects the fakes, where the minimax loss saturates
  2. It makes the game have a different optimum, closer to the data
  3. It turns the GAN into a maximum-likelihood method
  4. 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 −σ(l)-\sigma(l), which vanishes as D(G(z))→0D(G(\mathbf z))\to0, while the non-saturating gradient is −(1−σ(l))-(1-\sigma(l)), which stays near −1-1. The fixed point is the same.

Question 3

Freeze the discriminator and let the generator train to convergence against it. What does the generator converge to?

  1. The data distribution, since the discriminator was trained on real data
  2. A distribution concentrated where DD is largest, ideally a single point: the seed of mode collapse
  3. The uniform distribution over the image space
  4. It cannot converge, because the loss has no minimum
Show the answer

B. A distribution concentrated where DD is largest, ideally a single point: the seed of mode collapse

For fixed DD, Ez[−log⁡D(G(z))]\E_{\mathbf z}[-\log D(G(\mathbf z))] is minimized by sending every z\mathbf z to a maximizer of DD. Only the discriminator's subsequent updates punish the pile-up, which is why alternating training can chase modes instead of covering them.

Question 4

Where does WGAN-GP evaluate its gradient penalty, and what does it push toward?

  1. At the real data points only, pushing the critic's gradient toward zero
  2. At the generated samples only, pushing the critic's output toward zero
  3. At random points on straight lines between real and generated samples, pushing the critic's input-gradient norm toward 1
  4. On the weights, pushing every weight into [−0.01,0.01][-0.01,0.01]
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 (∥∇f(x^)∥−1)2(\norm{\nabla f(\hat{\mathbf x})}-1)^2 at interpolates x^=ϵx+(1−ϵ)G(z)\hat{\mathbf x}=\epsilon\mathbf x+(1-\epsilon)G(\mathbf z), with weight λ=10\lambda=10.

Go deeper

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).