AI Logic

Architectures

Generative Adversarial Network (GAN)

Updated:

Structure of a GAN. Left: noise z passes through the generator G to make fake data, which the discriminator D receives along with real data x and outputs the probability that its input came from the training data. Right: alternating training that updates the discriminator k times and the generator once, and the end point where p_g = p_data and D(x) = 1/2.

Background and Overview

A GAN (Generative Adversarial Network) is a generative model trained by having two networks compete: a "generator" that creates data and a "discriminator" that tells real data from fake. The generator creates data from random noise, and the discriminator distinguishes training data from the generator's output. As the generator learns to fool the discriminator and the discriminator learns not to be fooled, the generator becomes able to produce data that resembles the training data.

Goodfellow et al. proposed it in 2014 in the paper "Generative Adversarial Nets." The paper compares the two networks to counterfeiters and the police. The counterfeiters (the generator) try to produce fake currency that goes undetected, while the police (the discriminator) try to detect it. Competition drives both to improve until the counterfeits are indistinguishable from the genuine article.

Earlier deep generative models ran into intractable integrals when computing probabilities and needed heavy computation such as Markov chain Monte Carlo (MCMC) to approximate them. GANs have the following properties.

  • Training uses backpropagation only: Neither training nor generation needs Markov chains or approximate inference.
  • Generation is a single forward pass: Passing noise through the generator produces one sample.
  • No explicit probability formula is needed: The generator can be any differentiable function; the data probability pg(x)p_g(\boldsymbol{x}) does not have to be computable.

GANs spawned many derivatives, starting with DCGAN, which generates images with convolutional networks, and including WGAN, StyleGAN, and HiFi-GAN.

Theory

A GAN consists of two networks (left of the figure at the top of the article).

  • Generator G(z;ΞΈg)G(\boldsymbol{z}; \theta_g): Draws noise z\boldsymbol{z} from a prior pz(z)p_{\boldsymbol{z}}(\boldsymbol{z}) and maps it to G(z)G(\boldsymbol{z}), which has the same shape as the data. The distribution of G(z)G(\boldsymbol{z}) is written pgp_g.
  • Discriminator D(x;ΞΈd)D(\boldsymbol{x}; \theta_d): Takes an input x\boldsymbol{x} and outputs a single number between 0 and 1: the probability that it came from the training data rather than from pgp_g.

In the paper's experiments, both are multilayer perceptrons.

The minimax game

The discriminator learns to assign 1 to training data and 0 to generator outputs. The generator learns to raise the probability that the discriminator makes a mistake. Written as a two-player game, this becomes the following (Eq. 1).

min⁑Gmax⁑DV(D,G)=Ex∼pdata[log⁑D(x)]+Ez∼pz[log⁑(1βˆ’D(G(z)))]\min_G \max_D V(D, G) = \mathbb{E}_{\boldsymbol{x} \sim p_{\mathrm{data}}}\big[\log D(\boldsymbol{x})\big] + \mathbb{E}_{\boldsymbol{z} \sim p_{\boldsymbol{z}}}\big[\log\big(1 - D(G(\boldsymbol{z}))\big)\big]

For the discriminator, this is the log-likelihood of binary classification between real (label 1) and fake (label 0). In other words, the discriminator trains as an ordinary classifier that minimizes binary cross-entropy.

Training procedure

Training the discriminator to completion before each generator update would be too expensive, and with finite data the discriminator would overfit. Instead, the two are updated alternately in small steps (Algorithm 1, right of the figure at the top of the article).

  1. Sample a minibatch of noise z(1),…,z(m)\boldsymbol{z}^{(1)}, \dots, \boldsymbol{z}^{(m)} and a minibatch of training data x(1),…,x(m)\boldsymbol{x}^{(1)}, \dots, \boldsymbol{x}^{(m)}.
  2. Update the discriminator in the direction that increases the quantity below, using its gradient.
  3. Repeat steps 1–2 kk times (the paper's experiments use k=1k = 1, the cheapest option).
  4. Sample a new minibatch of noise and update the generator in the direction that decreases 1mβˆ‘ilog⁑(1βˆ’D(G(z(i))))\frac{1}{m}\sum_i \log\big(1 - D(G(\boldsymbol{z}^{(i)}))\big).
  5. Repeat steps 1–4.

The quantity increased in step 2 is:

1mβˆ‘i=1m[log⁑D(x(i))+log⁑(1βˆ’D(G(z(i))))]\frac{1}{m} \sum_{i=1}^{m} \Big[\log D\big(\boldsymbol{x}^{(i)}\big) + \log\Big(1 - D\big(G(\boldsymbol{z}^{(i)})\big)\Big)\Big]

When updating the generator, gradients flow through the discriminator back to the generator via backpropagation, but only the generator's weights are updated. The paper's experiments used gradient descent with momentum.

Minimizing log⁑(1βˆ’D(G(z)))\log(1 - D(G(\boldsymbol{z}))) as written in Eq. 1 does not work well early in training. While the generator is still poor, the discriminator rejects fakes with high confidence, so D(G(z))D(G(\boldsymbol{z})) is close to 0, this term saturates, and almost no gradient comes through. The paper instead recommends training the generator to maximize log⁑D(G(z))\log D(G(\boldsymbol{z})). The fixed point is the same, and the gradients early in training are much stronger.

Why It Can Learn the Data Distribution

Assuming the generator and discriminator have enough capacity (the idealized case in which the probability distributions themselves can be adjusted freely), the paper shows that GAN training recovers the data distribution.

The optimal discriminator

For a fixed generator, the discriminator that maximizes V(D,G)V(D, G) is (Proposition 1):

DGβˆ—(x)=pdata(x)pdata(x)+pg(x)D^*_G(\boldsymbol{x}) = \frac{p_{\mathrm{data}}(\boldsymbol{x})}{p_{\mathrm{data}}(\boldsymbol{x}) + p_g(\boldsymbol{x})}

This is a natural form: it compares the density of real data with that of fake data and reports the share that is real.

What the generator aims for

Substituting this optimal discriminator into Eq. 1, the quantity the generator minimizes becomes (Eq. 6):

C(G)=βˆ’log⁑4+2β‹…JSD(pdata βˆ₯ pg)C(G) = -\log 4 + 2 \cdot \mathrm{JSD}\big(p_{\mathrm{data}} \,\|\, p_g\big)

JSD is the Jensen–Shannon divergence, which measures the difference between two distributions (a symmetrized KL divergence). It is non-negative and equals 0 only when the two distributions are identical. Therefore C(G)C(G) reaches its minimum (βˆ’log⁑4-\log 4) only when pg=pdatap_g = p_{\mathrm{data}} (Theorem 1). At that point the discriminator outputs D(x)=1/2D(\boldsymbol{x}) = 1/2 for every input and can no longer tell real from fake.

The paper further shows that if the discriminator reaches its optimum at each step and the generator's distribution is improved little by little, pgp_g converges to pdatap_{\mathrm{data}} (Proposition 2).

These results assume the distributions themselves can be adjusted freely. In practice, the generator can only represent distributions expressible through the multilayer perceptron's weights ΞΈg\theta_g, and the parameter space has multiple critical points. The paper's position is that, despite the lack of theoretical guarantees, multilayer perceptrons work well in practice and are a reasonable choice.

Advantages over other generative models

The paper lists the following advantages.

  • The generator is updated only with gradients that pass through the discriminator, not directly with data examples. As a result, parts of the input are never copied directly into the generator's parameters.
  • Methods based on Markov chains need the distribution to be somewhat blurry so the chain can mix between modes. GANs can represent very sharp distributions.

Experimental Results

The paper trained GANs on MNIST, the Toronto Face Database (TFD, face images), and CIFAR-10. The generator combined ReLU and sigmoid activations, the discriminator used Maxout, and dropout was applied when training the discriminator. Noise was fed only as input to the bottom layer of the generator.

Because a GAN cannot compute pg(x)p_g(\boldsymbol{x}), the test-set log-likelihood was estimated by fitting Gaussian windows to generated samples (Parzen windows); higher is better.

ModelMNISTTFD
DBN138 Β± 21909 Β± 66
Stacked CAE121 Β± 1.62110 Β± 50
Deep GSN214 Β± 1.11890 Β± 29
GAN225 Β± 22057 Β± 26

On MNIST it scored the highest of the compared models, and on TFD it was second to Stacked CAE. The paper itself cautions, however, that this estimator has somewhat high variance and does not work well in high dimensions.

For the sample images (Figure 2 of the paper), the authors do not claim superiority over existing methods, only that the samples are "at least competitive with the better generative models." They show the nearest training example next to each sample to demonstrate that the model has not memorized the training set. Interpolating along a straight line between two points in the noise space z\boldsymbol{z} also changes the generated digit smoothly (Figure 3).

Research on evaluating generative models continued after this paper. Image GANs today are commonly evaluated with the Inception Score and FID.

Practical Considerations

Keep the following points in mind when using GANs.

  • Keep the generator and discriminator balanced: The paper warns that training the generator too much without updating the discriminator causes the generator to map many values of z\boldsymbol{z} to the same x\boldsymbol{x}, losing diversity (the paper calls this "the Helvetica scenario"; it is generally known as mode collapse. The later DCGAN paper also lists the collapse of all samples to a single point as a common GAN failure). Match the update speeds of the two with kk and the learning rates.
  • Use a non-saturating generator loss: Instead of log⁑(1βˆ’D(G(z)))\log(1 - D(G(\boldsymbol{z}))), maximize log⁑D(G(z))\log D(G(\boldsymbol{z})) (cross-entropy with fake samples labeled "real").
  • The loss value is a poor indicator of progress: Because the two networks compete, the loss does not keep decreasing as in ordinary training. Inspect generated samples by eye or evaluate them with metrics such as FID.
  • The likelihood cannot be computed: Since pg(x)p_g(\boldsymbol{x}) has no explicit form, GANs are unsuitable when data probabilities must be evaluated.

In PyTorch, when updating the discriminator, use G(z).detach() for the generator output so that gradients do not flow into the generator. When updating the generator, gradients flow through the discriminator without detach(), but this also accumulates gradients in the discriminator's weights. Always call zero_grad() on the discriminator's optimizer before its next update.

Comparison with Other Methods

The table compares GANs with other deep generative models along the same dimensions (based on Table 2 of the paper).

MethodTrainingInference (latent variables from data)SamplingEvaluating p(x)p(\boldsymbol{x})
Directed graphical models (e.g., VAE)Inference needed during trainingLearned approximate inferenceNo difficultiesIntractable (approximation possible)
Undirected graphical models (e.g., Boltzmann machines)Partition-function gradient approximated with MCMCVariational inferenceRequires Markov chainIntractable (approximation possible)
Generative autoencoders (e.g., denoising)Must balance mixing against reconstruction strengthMCMC-based inferenceRequires Markov chainNo explicit form (Parzen-window approximation possible)
GANGenerator and discriminator must be synchronizedLearned approximate inference (train a separate network)No difficultiesNo explicit form (Parzen-window approximation possible)

Rough guidelines for choosing:

  • Fast generation of sharp, good-looking samples: GANs fit well; generation is a single forward pass. For images, use convolutional architectures from DCGAN onward.
  • A mapping into latent space (an encoder) or a likelihood lower bound is also needed: VAE fits well.
  • Training stability is a priority: Combine techniques such as Spectral Normalization, which normalizes the discriminator's weights, or WGAN, which changes the loss. Diffusion models (e.g., DDPM) are also candidates.
  • Conditional generation: As noted at the end of the paper, adding a condition c\boldsymbol{c} to the inputs of both the generator and the discriminator yields a conditional generative model p(x∣c)p(\boldsymbol{x} \mid \boldsymbol{c}).

PyTorch example

Show code
python
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from torchvision import datasets, transforms

"""
Example: training the GAN of Goodfellow et al. (2014) on MNIST with fully connected networks
- The discriminator maximizes log D(x) + log(1 - D(G(z))) (= minimizes binary cross-entropy)
- The generator uses the non-saturating form: maximize log D(G(z)) (cross-entropy with fakes labeled "real")
- k = 1 as in the paper (update the discriminator once, then the generator once)
"""

device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
z_dim = 100

transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))])  # scale pixels to [-1, 1]
loader = DataLoader(datasets.MNIST("./data", train=True, download=True, transform=transform),
                    batch_size=128, shuffle=True, drop_last=True)

G = nn.Sequential(                       # generator: noise z -> image
  nn.Linear(z_dim, 256), nn.ReLU(),
  nn.Linear(256, 512), nn.ReLU(),
  nn.Linear(512, 784), nn.Tanh(),        # output in [-1, 1] (matches the data range)
).to(device)

D = nn.Sequential(                       # discriminator: image -> logit of being real
  # The paper's discriminator uses Maxout; LeakyReLU is used here for simplicity. Dropout is applied to the discriminator as in the paper
  nn.Linear(784, 512), nn.LeakyReLU(0.2), nn.Dropout(0.3),
  nn.Linear(512, 256), nn.LeakyReLU(0.2), nn.Dropout(0.3),
  nn.Linear(256, 1),                     # the sigmoid is computed inside the loss
).to(device)

bce = nn.BCEWithLogitsLoss()
# The paper used gradient descent with momentum (the learning rate and momentum values are chosen for this example)
opt_d = torch.optim.SGD(D.parameters(), lr=0.01, momentum=0.5)
opt_g = torch.optim.SGD(G.parameters(), lr=0.01, momentum=0.5)

for epoch in range(30):
  G.train(); D.train()
  for x, _ in loader:
    x = x.to(device).flatten(1)
    m = x.size(0)
    ones = torch.ones(m, 1, device=device)
    zeros = torch.zeros(m, 1, device=device)

    # (1) update the discriminator: 1 for real, 0 for fake
    z = torch.randn(m, z_dim, device=device)
    fake = G(z).detach()                 # do not backpropagate into the generator
    loss_d = bce(D(x), ones) + bce(D(fake), zeros)
    opt_d.zero_grad()
    loss_d.backward()
    opt_d.step()

    # (2) update the generator: make the discriminator say "real (1)" = maximize log D(G(z))
    z = torch.randn(m, z_dim, device=device)
    loss_g = bce(D(G(z)), ones)
    opt_g.zero_grad()                    # gradients accumulated in D are cleared by opt_d.zero_grad() next time
    loss_g.backward()
    opt_g.step()                         # only the generator is updated

  print(f"epoch {epoch + 1}: loss_D {loss_d.item():.3f}  loss_G {loss_g.item():.3f}")

# generation: just pass noise through the generator (the discriminator with dropout is not used)
G.eval()
with torch.no_grad():
  samples = G(torch.randn(64, z_dim, device=device)).view(64, 1, 28, 28)   # images in [-1, 1]

FAQ

Q. Why does the GAN generator maximize $\log D(G(\boldsymbol{z}))$ instead of minimizing $\log(1 - D(G(\boldsymbol{z})))$?
A.

Early in training the generator is poor, so the discriminator easily rejects fakes and D(G(z))D(G(\boldsymbol{z})) is close to 0. At that point log⁑(1βˆ’D(G(z)))\log(1 - D(G(\boldsymbol{z}))) saturates and almost no gradient reaches the generator. Maximizing log⁑D(G(z))\log D(G(\boldsymbol{z})) keeps the same fixed point (pg=pdatap_g = p_{\mathrm{data}}) while giving much stronger gradients early in training. The paper recommends this form as well.

Q. How should I choose between a GAN and a VAE?
A.

A GAN produces sharp samples in a single forward pass, but it cannot compute data probabilities and has no encoder. A VAE can map data into latent space with its encoder and can compute a lower bound on the log-likelihood. Choose a GAN when the visual quality of samples matters most, and consider a VAE when you want to use the latent space as a representation or need more stable training.

Q. What is mode collapse?
A.

Mode collapse is a phenomenon in which the generator maps many noise values z\boldsymbol{z} to similar outputs and fails to reproduce the diversity of the data. The original paper calls it "the Helvetica scenario" and explains that it occurs when the generator is trained too much without updating the discriminator. The basic remedy is to keep the generator and discriminator updates balanced.

References

  1. Goodfellow, I. J., Pouget-Abadie, J., Mirza, M., Xu, B., Warde-Farley, D., Ozair, S., Courville, A., & Bengio, Y. (2014). Generative Adversarial Nets. NeurIPS 2014. arXiv:1406.2661.