Generative adversarial networks¶
A GAN learns to generate by playing a game: a generator turns noise into samples, a discriminator tries to tell those samples from real data, and each network trains against the other. There is no likelihood anywhere, only a learned critic. The one idea to walk away with is that the discriminator is a learned, moving loss function, which is why GANs make the sharpest samples of any classical method and also why they are so hard to train.
10,000 ft
Every generative model must answer one question: how do you tell the model that its samples are wrong? VAEs and autoregressive models answer with a likelihood, which forces them to cover every mode and blurs what they cannot model. GANs (Goodfellow et al., 2014) answer with a second network that is trained to spot the difference between real and generated data. That idea dominated image synthesis from 2015 to 2021 (DCGAN, StyleGAN, BigGAN) before diffusion models overtook it on diversity and stability. It did not disappear. Adversarial losses are what make the autoencoders inside latent diffusion reconstruct sharply, what make neural vocoders and audio codecs sound natural (speech and audio), and what lets distilled diffusion models generate in one to four steps. The game-theoretic view also recurs in RLHF, where a policy is trained against a learned reward model that it can exploit, and in adversarial robustness.
2,000 ft
Two networks, one value function, opposite goals:
- The generator \(G_\theta\) maps a noise vector \(\mathbf z\) to a sample. It never sees real data.
- The discriminator \(D_\psi\) outputs the probability that its input is real.
- Train \(D\) as an ordinary binary classifier on a batch of real and a batch of fake samples.
- Train \(G\) by backpropagating through \(D\): change \(\theta\) so that \(D\) scores the fakes as more real.
- Alternate. If both had unlimited capacity and reached equilibrium, \(p_G = p_\text{data}\) and \(D = \tfrac12\) everywhere.
- In practice the equilibrium is hard to reach. Most of the GAN literature is about the losses, regularisers and architectures that make the game converge.
Ground level¶
The idea: replace the likelihood with a critic¶
Suppose you want a network that maps noise to photographs of faces. You can sample from it easily, but you cannot evaluate the density it defines: \(G\) pushes a Gaussian through a deep non-invertible network, and the resulting \(p_G(\mathbf x)\) has no formula. This is an implicit generative model: a sampler with no likelihood. Maximum likelihood is out.
What you can do is compare samples. If you had a perfect judge of "does this look like it came from the data?", you could train \(G\) to fool it. Goodfellow's insight was that the judge can be learned at the same time, by a classifier trained on the cheapest possible labelled dataset: real examples labelled 1, the generator's current outputs labelled 0. The classifier's errors are exactly the places where the generator is already good; its confident rejections are where it is bad, and its gradient with respect to the input says which way to move a fake to make it look more real.
The picture to keep
The discriminator is a loss function that is itself being learned. A fixed loss such as pixel MSE says "be close to the average". A discriminator says "be indistinguishable from real", and it keeps raising the bar as the generator improves. That is why GAN samples are sharp, and also why training is a moving-target game rather than a descent on a fixed surface.
The minimax game¶
Goodfellow et al. (2014) wrote the game as one value function that \(D\) maximises and \(G\) minimises:
For \(D\) this is the log-likelihood of a binary classifier, the negative of binary cross-entropy. For \(G\) only the second term matters.
What does the best discriminator look like? Fix \(G\), so its samples have some density \(p_g\). \(V\) is an integral over \(\mathbf x\) of \(p_\text{data}(\mathbf x)\log D(\mathbf x) + p_g(\mathbf x)\log(1-D(\mathbf x))\), and each \(\mathbf x\) can be optimised separately. The function \(a\log y + b\log(1-y)\) peaks at \(y = a/(a+b)\), so
The optimal discriminator is a density-ratio estimator: \(D^*/(1-D^*) = p_\text{data}/p_g\). This is the deep reason GANs work at all. A classifier trained to separate two sample sets learns the ratio of their densities, which is exactly the information a generator needs to know where it puts too much or too little mass.
What is the generator then minimising? Substitute \(D^*\) back into \(V\). After rearranging (see The maths):
where \(\mathrm{JS}\) is the Jensen–Shannon divergence, the average KL divergence of each distribution to their mixture \(m = \tfrac12(p_\text{data}+p_g)\). JS is zero exactly when the two distributions are equal, so the global optimum of the game is \(p_g = p_\text{data}\), with \(D^* = \tfrac12\) everywhere and \(V = -\log 4 \approx -1.386\). The GAN is, in the idealised limit, a divergence minimiser that never needs to evaluate a density, because the discriminator estimates the divergence from samples.
Worked example. Take data \(\mathcal N(0,1)\) and generator \(\mathcal N(\mu, 1)\). The code in Build it integrates everything on a grid:
| \(\mu\) | \(V(D^*, G)\) | \(-\log 4 + 2\,\mathrm{JS}\) | JS (nats) | \(d\mathrm{JS}/d\mu\) | \(W_1\) | \(dW_1/d\mu\) |
|---|---|---|---|---|---|---|
| 0 | −1.3863 | −1.3863 | 0.0000 | 0 | 0 | 0 |
| 1 | −1.1635 | −1.1635 | 0.1114 | 0.199 | 1 | 1 |
| 3 | −0.3327 | −0.3327 | 0.5268 | 0.148 | 3 | 1 |
| 6 | −0.0077 | −0.0077 | 0.6893 | 0.0062 | 6 | 1 |
| 10 | −0.0000 | −0.0000 | 0.6931 | 0.0000022 | 10 | 1 |
The identity holds to four decimals. Now read the slope column. When the generator is far from the data, JS saturates at \(\log 2 = 0.6931\) and its gradient vanishes: at \(\mu = 10\) it is \(2\times10^{-6}\), so a generator that starts in the wrong place gets almost no signal about which way to move. The last two columns show the alternative the Wasserstein GAN uses (below): the earth mover's distance grows linearly with the gap and its slope never vanishes.
Two generator losses, and why practitioners use the "wrong" one¶
Early in training the generator is bad, \(D\) rejects its samples confidently, and \(D(G(\mathbf z)) \approx 0\). Write \(D = \sigma(\ell)\) with logit \(\ell\). The minimax generator loss \(\log(1 - \sigma(\ell))\) has gradient \(-\sigma(\ell)\) with respect to the logit, which goes to zero exactly when the fake is obviously fake. With \(D(G(\mathbf z)) = 0.01\) the logit is \(-4.6\) and the gradient is \(-0.01\).
Goodfellow et al. therefore proposed the non-saturating loss: instead of minimising \(\log(1 - D(G(\mathbf z)))\), maximise \(\log D(G(\mathbf z))\). Its gradient with respect to the logit is \(1 - \sigma(\ell) = 0.99\) at the same point, 99 times stronger, and it has the same fixed point. Almost every GAN since has used it.
It is not the same objective, though. Arjovsky and Bottou (2017, Theorem 2.5) showed that, against an optimal discriminator, the non-saturating generator follows the gradient of \(\mathrm{KL}(p_g\,\|\,p_\text{data}) - 2\,\mathrm{JS}(p_g\,\|\,p_\text{data})\). The first term is the reverse KL, which is mode-seeking: it punishes the generator heavily for putting mass where there is no data, and only lightly for missing parts of the data. Contrast the forward KL that maximum likelihood minimises, which punishes missing mass. That asymmetry is one reason GAN samples are sharp and VAE samples are blurry, and also one reason GANs drop modes.
How GANs fail¶
GAN training is not gradient descent on one loss; it is two players taking gradient steps on opposing losses. Three failure modes follow from that.
Mode collapse. The generator maps many different \(\mathbf z\) to the same few outputs. If \(D\) is held fixed, the best response of \(G\) is to put all its mass on the single point \(D\) likes most. \(D\) then learns to reject that point, \(G\) jumps to the next favourite, and the pair can cycle without ever covering the data. Goodfellow's 2014 paper already warned against training \(G\) too long without updating \(D\), calling the collapsed outcome "the Helvetica scenario". Partial collapse (missing some modes, low diversity within others) is much more common than total collapse and much harder to see by eye. Arora and Zhang (2017) proposed a birthday-paradox test: if a batch of \(s\) samples usually contains a near-duplicate pair, the support size is roughly \(s^2\), and their experiments suggested that well-known GANs of the time learned distributions of fairly low support.
Vanishing gradients. Real images lie near a low-dimensional manifold in pixel space, and so do a generator's outputs (they are the image of a low-dimensional \(\mathbf z\)). Two low-dimensional manifolds in a high-dimensional space almost never overlap. Arjovsky and Bottou (2017) showed that in that case a perfect discriminator exists, JS is stuck at \(\log 2\) and, as the worked example showed, the minimax generator's gradient vanishes as \(D\) approaches optimality. Train \(D\) too well and \(G\) stops learning; train it too little and its gradients are meaningless.
Non-convergence. Even near the equilibrium, simultaneous gradient steps on a game need not converge. The cleanest demonstration is Mescheder, Geiger and Nowozin's (2018) Dirac-GAN: data is a point at 0, the generator is a point at \(\theta\), and the discriminator is the one-parameter \(D(x) = \sigma(\psi x)\). The equilibrium is \((\theta, \psi) = (0, 0)\), and the vector field of the game rotates around it.
The picture explains a lot of GAN folklore. The generator's update depends on \(\psi\) and the discriminator's on \(\theta\), so each player chases the other around the equilibrium. Simultaneous gradient steps are a forward-Euler discretisation of a rotation, which always spirals outwards; alternating steps roughly preserve the orbit. What converges is a game with damping: a penalty that pulls the discriminator back towards "no opinion" when the generator is right.
The fixes that made GANs work¶
Five years of work turned GANs from fragile demos into StyleGAN. The fixes fall into three groups.
DCGAN (Radford, Metz and Chintala, 2015) gave the first architecture recipe that trained reliably on images: replace pooling with strided convolutions (transposed convolutions in the generator), use batch normalisation in both networks except the generator's output and the discriminator's input, drop fully connected hidden layers, use ReLU in the generator with a tanh output and LeakyReLU in the discriminator, and train with Adam at learning rate 0.0002 and \(\beta_1 = 0.5\). DCGAN also showed that the generator's latent space is meaningful: vector arithmetic on \(\mathbf z\) ("smiling woman − neutral woman + neutral man") produced smiling men.
Wasserstein GAN (Arjovsky, Chintala and Bottou, 2017) changed the divergence. The earth mover's (Wasserstein-1) distance is the minimum cost of transporting one distribution's mass onto the other, moving mass \(m\) a distance \(d\) at cost \(md\). Unlike JS, it is continuous in the generator's parameters even when the supports do not overlap: the paper's example is two parallel line segments a distance \(\theta\) apart, where \(W_1 = |\theta|\) while JS jumps to \(\log 2\) for any \(\theta\neq0\) and KL is infinite. By Kantorovich–Rubinstein duality,
so the discriminator becomes a critic \(f\) with no sigmoid that must be 1-Lipschitz. The original paper enforced that crudely by clipping every weight to \([-0.01, 0.01]\) and training the critic five times per generator step. Its lasting contribution was a loss curve that actually tracked sample quality.
WGAN-GP (Gulrajani et al., 2017) replaced clipping, which wastes capacity and causes exploding or vanishing gradients, with a soft constraint: penalise \(\lambda(\lVert\nabla_{\hat{\mathbf x}} f(\hat{\mathbf x})\rVert - 1)^2\) at random points \(\hat{\mathbf x}\) on lines between real and fake samples, with \(\lambda = 10\).
Spectral normalisation (Miyato et al., 2018) enforces the Lipschitz bound by construction. A network's Lipschitz constant is at most the product of its layers' spectral norms when the activations are 1-Lipschitz, so dividing every weight matrix by its largest singular value (estimated with one step of power iteration per update) bounds the whole discriminator. It costs almost nothing and became a default, including in BigGAN.
R1 regularisation (Mescheder et al., 2018) penalises the discriminator's gradient on real data only: \(\tfrac{\gamma}{2}\mathbb E_{p_\text{data}}\lVert\nabla_{\mathbf x}D(\mathbf x)\rVert^2\). At equilibrium the discriminator should be flat on the data, and this penalty pulls it there. It is the damping term from the Dirac-GAN picture, and Mescheder et al. proved that it (and instance noise) gives local convergence, while unregularised GANs and, with finite critic steps, WGAN and WGAN-GP need not converge. StyleGAN and most later GANs use R1.
The Build it section shows the whole story in two parameters: a plain GAN learning \(\mathcal N(4, 1.25^2)\) gets the mean right but its spread oscillates between 0.17 and 2.4 for thousands of steps; the same GAN with R1 (\(\gamma = 10\)) settles at mean 4.00, spread 1.24.
The architecture era: from DCGAN to StyleGAN¶
With stable training, progress came from architecture and scale, mostly from NVIDIA's group led by Tero Karras.
- Progressive GAN (Karras et al., 2017) trains at 4×4, then fades in layers for 8×8, 16×16 and so on up to 1024×1024. Early stages learn global structure cheaply; later stages add detail. It produced the first convincing megapixel faces (CelebA-HQ).
- StyleGAN (Karras, Laine and Aila, 2018) redesigned the generator. Noise \(\mathbf z\) goes through an 8-layer MLP mapping network to an intermediate latent \(\mathbf w\); the synthesis network starts from a learned constant tensor, and at every resolution \(\mathbf w\) controls the feature statistics through adaptive instance normalisation (a per-channel scale and bias, the "style"). Per-pixel noise inputs add stochastic detail (hair strands, freckles). Coarse layers control pose and face shape, fine layers colour and texture, so you can mix styles from two latents at different scales. It also introduced the FFHQ dataset of 70,000 high-quality face images at 1024×1024.
- StyleGAN2 (2019) replaced instance normalisation with weight demodulation to remove "droplet" artefacts, dropped progressive growing, and added path-length regularisation so equal steps in \(\mathbf w\) give equal changes in the image. StyleGAN2-ADA (2020) added adaptive discriminator augmentation, which made GANs trainable on a few thousand images. StyleGAN3 (2021) removed aliasing so that details move with the surface instead of sticking to pixel coordinates.
- BigGAN (Brock, Donahue and Simonyan, 2018) showed that GANs scale: class-conditional ImageNet at 128×128 with batch size 2,048, spectral norm, orthogonal regularisation and shared class embeddings. It reached Inception Score 166.5 and FID 7.4, against a previous best of 52.52 and 18.6. Its truncation trick samples \(\mathbf z\) from a truncated normal: shrinking the range trades diversity for fidelity, a dial that guidance would later provide for diffusion models.
Conditional GANs turned the method into a tool. pix2pix (Isola et al., 2016) trained a generator to translate paired images (edges to photos, maps to aerial images) with an L1 loss plus a "PatchGAN" discriminator that judges local patches. CycleGAN (Zhu et al., 2017) dropped the pairing: two generators, \(A\to B\) and \(B\to A\), and a cycle-consistency loss requiring \(F(G(a)) \approx a\), which is how horses became zebras without a single paired example.
Measuring what you cannot evaluate¶
A GAN has no likelihood, so you cannot report test log-likelihood. The field settled on metrics computed on features of a pretrained ImageNet classifier (Inception-v3):
- Inception Score (Salimans et al., 2016): \(\exp\big(\mathbb E_{\mathbf x}\,\mathrm{KL}(p(y\mid\mathbf x)\,\|\,p(y))\big)\). High when each image is confidently one class and the classes are diverse. It never looks at real data, so it cannot detect a generator that makes the wrong kind of images well.
- Fréchet Inception Distance (Heusel et al., 2017): fit a Gaussian to the 2,048-dimensional pool features of real images and another to generated ones, and compute the Fréchet (Wasserstein-2) distance between the Gaussians:
Lower is better. FID penalises both wrong content (mean shift) and lost diversity (covariance shrinkage): in 64 dimensions, shrinking every standard deviation from 1 to 0.7 costs \(64\times(1 + 0.49 - 1.4) = 5.76\). It is also biased upward with few samples. Two sets drawn from the same 64-dimensional Gaussian give FID 4.44 at 500 samples and 0.04 at 50,000 (Build it), which is why FIDs are only comparable at the same sample count, conventionally 50,000.
- Precision and recall (Sajjadi et al., 2018; Kynkäänniemi et al., 2019) split quality into two numbers: what fraction of generated samples fall within the real data's feature manifold (fidelity), and what fraction of real samples fall within the generated manifold (coverage). A mode-collapsed GAN has high precision and low recall; that is the trade the truncation trick moves along.
FID is not a perceptual ground truth
FID depends on an ImageNet classifier's features, so it is sensitive to ImageNet class content: Kynkäänniemi et al. (2022) showed it can be improved by matching the top-1 class histogram without improving images. It also depends on resizing and JPEG details in the implementation. Use the same implementation and sample count when comparing, and look at samples.
Where GANs stand in 2026¶
Diffusion models overtook GANs on class-conditional ImageNet in 2021 (Dhariwal and Nichol's paper is titled Diffusion Models Beat GANs on Image Synthesis) and on text-to-image completely. The reasons are the ones above: diffusion trains with a plain regression loss, never collapses modes and scales without adversarial instability. But "GANs are dead" is wrong in three ways:
- As a loss, the adversarial idea is everywhere. The autoencoders of latent diffusion and VQGAN are trained with a patch discriminator so that their reconstructions are sharp (latent diffusion). Neural vocoders such as HiFi-GAN (Kong, Kim and Bae, 2020) and neural audio codecs use multi-scale discriminators (speech and audio).
- As a distillation tool. Few-step diffusion models are often trained with an adversarial term. Adversarial Diffusion Distillation (Sauer et al., 2023), behind SDXL Turbo, combines score distillation with a GAN loss and generates in one to four steps.
- As generators, GANs still scale. GigaGAN (Kang et al., 2023) showed a text-to-image GAN that renders a 512-pixel image in 0.13 seconds. R3GAN (Huang et al., NeurIPS 2024) derived a regularised relativistic loss with local convergence guarantees, discarded the bag of tricks, and beat StyleGAN2 with a modern backbone.
History¶
Who found it
Ian Goodfellow, then a PhD student in Yoshua Bengio's lab in Montréal, conceived the adversarial game in 2014, and the paper with Pouget-Abadie, Mirza, Xu, Warde-Farley, Ozair, Courville and Bengio appeared at NIPS 2014. Its ingredients had precursors: Schmidhuber's "predictability minimisation" (1992) pitted networks against each other, and noise-contrastive estimation (Gutmann and Hyvärinen, 2010) learned a density by classifying data against noise, which is a GAN with a fixed generator. Mirza and Osindero's conditional GAN followed in 2014, DCGAN in late 2015, and Goodfellow's NIPS 2016 tutorial organised the field. 2017 was the year of losses (WGAN, WGAN-GP, the TTUR paper that introduced FID), 2018 of regularisation and scale (spectral normalisation, R1, BigGAN), and 2018–2021 of StyleGAN. The website "This Person Does Not Exist" (2019), serving StyleGAN faces, made the technology public, and with it the first wave of "deepfake" concern.
First principles¶
Strip GANs to their assumptions and three things are forced.
1. If you can only sample, you can only compare samples. An implicit model gives you \(\mathbf x = G(\mathbf z)\) and nothing else. Any training signal must be a statistic of samples: a two-sample test. Classical two-sample tests (comparing means, or kernel statistics such as the maximum mean discrepancy) use a fixed test. A GAN learns the most powerful test it can find, and the generator then removes whatever difference that test exploits. That is the whole method.
2. A classifier between two sample sets estimates their density ratio. This is the density-ratio trick behind \(D^*\) above, and behind noise-contrastive estimation, contrastive representation learning and, for that matter, the reward models of RLHF. Any proper scoring rule gives you the ratio; the log-loss gives JS. Swap the loss and you get a different divergence: f-GAN (Nowozin et al., 2016) showed that every f-divergence has a variational lower bound \(\mathrm D_f(p\,\|\,q)\ge \sup_T\,\mathbb E_p[T] - \mathbb E_q[f^*(T)]\), with \(f^*\) the convex conjugate, so each choice of \(f\) is a GAN. The Wasserstein critic is the corresponding move for an integral probability metric rather than an f-divergence.
3. Two players means a game, not an optimisation. The equilibrium is a saddle point, and gradient descent–ascent is attracted to minima, not saddles. Linearise the dynamics near equilibrium and the Jacobian has a large antisymmetric part (the "rotation"), whose eigenvalues are imaginary. Without a symmetric, damping part, discrete gradient steps spiral. Everything in "the fixes" either changes what is measured so gradients exist far from equilibrium (WGAN, non-saturating loss) or adds damping near equilibrium (gradient penalties, R1, instance noise, two time-scale learning rates).
What breaks if you change things? Make \(D\) unboundedly powerful and train it to optimality: the generator gets no gradient (disjoint supports). Make \(D\) too weak: Arora et al. (2017) showed that a discriminator with finite capacity can be fooled by a generator whose support is small, so "\(D\) cannot tell" does not imply "\(p_g = p_\text{data}\)". The useful regime is in between, which is exactly why GANs need tuning.
The maths¶
Setup. Data \(\mathbf x\in\mathbb R^D\) with density \(p_\text{data}\); noise \(\mathbf z\in\mathbb R^K\), \(\mathbf z\sim\mathcal N(\mathbf 0, I)\); generator \(G_\theta:\mathbb R^K\to\mathbb R^D\), inducing the distribution \(p_g\); discriminator \(D_\psi:\mathbb R^D\to(0,1)\), \(D = \sigma(\ell_\psi(\mathbf x))\). A training step uses a real batch of shape \((B, D)\) and a noise batch of shape \((B, K)\).
Derivation: the optimal discriminator and the Jensen–Shannon identity
Write the value as an integral (assuming densities exist):
For fixed \(a, b > 0\) the function \(y\mapsto a\log y + b\log(1-y)\) on \((0,1)\) has derivative \(a/y - b/(1-y)\), zero at \(y = a/(a+b)\), and is concave, so pointwise maximisation gives \(D^*(\mathbf x) = p_\text{data}/(p_\text{data}+p_g)\). Substitute, and multiply and divide by 2 inside each log, with \(m = \tfrac12(p_\text{data} + p_g)\):
\(\mathrm{JS}\ge 0\) with equality iff \(p_g = p_\text{data}\), so the minimum over \(G\) is \(-\log 4\). Since \(0\le\mathrm{JS}\le\log 2\), \(V(D^*, G)\) lies in \([-\log 4, 0]\); the worked example's \(\mu=10\) row sits at the top of that range.
Training as alternating stochastic gradients. With mini-batches \(\{\mathbf x_i\}\) and \(\{\mathbf z_i\}\):
The generator's gradient is a vector–Jacobian product through two networks: \(\nabla_\theta\log D(G(\mathbf z)) = J_G(\mathbf z)^\top\,\nabla_{\mathbf x}\log D(\mathbf x)\big|_{\mathbf x = G(\mathbf z)}\). The discriminator's input gradient \(\nabla_{\mathbf x}\log D\), shape \((B, D)\), is the only thing the generator ever learns from. That is why its quality (smooth, non-zero, pointing towards the data) matters more than the discriminator's accuracy.
The regulariser \(R\) is one of:
Derivation: why simultaneous gradient steps spiral in the Dirac-GAN
With \(f(t) = -\log(1+e^{-t})\), the Dirac-GAN value is \(L(\theta,\psi) = f(\psi\theta) + f(0)\). \(D\) ascends in \(\psi\), \(G\) descends in \(\theta\), so the continuous-time dynamics are \(\dot\theta = -\psi f'(\psi\theta)\) and \(\dot\psi = \theta f'(\psi\theta)\). At \((0,0)\), \(f'(0) = \tfrac12\), and the linearisation is
a pure rotation with eigenvalues \(\pm\tfrac i2\). The continuous flow orbits the equilibrium at constant radius. A simultaneous gradient step is forward Euler, \(\mathbf v\leftarrow(I + \eta A)\mathbf v\), whose eigenvalues \(1\pm\tfrac{i\eta}{2}\) have modulus \(\sqrt{1+\eta^2/4} > 1\): every step multiplies the distance to equilibrium by that factor, so the iterates spiral out. The R1 penalty adds \(-\gamma\psi\) to \(\dot\psi\), making the matrix \(\begin{pmatrix}0 & -\frac12\\ \frac12 & -\gamma\end{pmatrix}\), whose eigenvalues have real parts \(-\gamma/2 < 0\) (for \(\gamma < 1\); both are real and negative for larger \(\gamma\)), and for small enough \(\eta\) the discrete iterates converge. With \(\eta = 0.1\) the outward factor per step near the equilibrium is \(1.00125\); farther out \(f'\) shrinks as the sigmoid saturates, so the simulated spiral grows sub-exponentially, from radius 1.41 to 3.35 in 3,000 steps.
Wasserstein distance. For distributions \(p, q\) on \(\mathbb R^D\), \(W_1(p, q) = \inf_{\pi\in\Pi(p,q)}\mathbb E_{(\mathbf x,\mathbf y)\sim\pi}\lVert\mathbf x - \mathbf y\rVert\), where \(\Pi(p,q)\) is the set of joint distributions (couplings, "transport plans") with marginals \(p\) and \(q\). Kantorovich–Rubinstein duality turns the infimum over couplings into a supremum over 1-Lipschitz functions, which is the form a neural critic can approximate. For the 1-D example \(p = \mathcal N(0,1)\), \(q=\mathcal N(\mu,1)\), the optimal plan shifts every point by \(\mu\), so \(W_1 = |\mu|\). The same optimal-transport ideas return in flow matching, where straight transport paths make sampling fast.
FID. Between Gaussians the squared Wasserstein-2 distance has the closed form above. The matrix square root of \(\Sigma_r\Sigma_g\) (not symmetric in general) has the same eigenvalues as \(\Sigma_r^{1/2}\Sigma_g\Sigma_r^{1/2}\) (symmetric positive semi-definite), so \(\operatorname{tr}(\Sigma_r\Sigma_g)^{1/2} = \sum_i\sqrt{\lambda_i(\Sigma_r^{1/2}\Sigma_g\Sigma_r^{1/2})}\), which is how the code computes it stably.
Build it¶
1. The optimal discriminator, the JS identity and vanishing gradients (NumPy):
import numpy as np
# Data p = N(0, 1); generator q = N(mu, 1). Integrate on a fine grid.
x = np.linspace(-30, 40, 400_001); dx = x[1] - x[0]
def normal(x, m): return np.exp(-0.5 * (x - m)**2) / np.sqrt(2 * np.pi)
def js(mu):
p, q = normal(x, 0), normal(x, mu)
m = 0.5 * (p + q)
kl = lambda a, b: np.sum(np.where(a > 0, a * np.log(np.maximum(a, 1e-300) / np.maximum(b, 1e-300)), 0)) * dx
return 0.5 * kl(p, m) + 0.5 * kl(q, m)
def value_at_optimal_D(mu):
p, q = normal(x, 0), normal(x, mu)
D = p / (p + q + 1e-300) # the optimal discriminator
f = lambda a, b: np.where(a > 0, a * np.log(np.maximum(b, 1e-300)), 0)
return np.sum(f(p, D) + f(q, 1 - D)) * dx # E_p[log D] + E_q[log(1 - D)]
print(" mu V(D*,G) -log4+2JS JS dJS/dmu W1 dW1/dmu")
for mu in [0.0, 1.0, 3.0, 6.0, 10.0]:
h = 1e-3
g = (js(mu + h) - js(mu - h)) / (2 * h) if mu > 0 else 0.0
print(f"{mu:4.1f} {value_at_optimal_D(mu):8.4f} {-np.log(4) + 2*js(mu):9.4f} "
f"{js(mu):.4f} {g:9.2e} {mu:4.1f} {1.0 if mu > 0 else 0.0}")
print(f"log 2 = {np.log(2):.4f}")
mu V(D*,G) -log4+2JS JS dJS/dmu W1 dW1/dmu
0.0 -1.3863 -1.3863 0.0000 0.00e+00 0.0 0.0
1.0 -1.1635 -1.1635 0.1114 1.99e-01 1.0 1.0
3.0 -0.3327 -0.3327 0.5268 1.48e-01 3.0 1.0
6.0 -0.0077 -0.0077 0.6893 6.23e-03 6.0 1.0
10.0 -0.0000 -0.0000 0.6931 2.23e-06 10.0 1.0
log 2 = 0.6931
2. The Dirac-GAN: why games spiral (NumPy):
import numpy as np
# Dirac-GAN (Mescheder et al., 2018): data is a point mass at 0, the generator is a
# point mass at theta, the discriminator is D(x) = sigmoid(psi * x).
# Non-saturating-style value: L(theta, psi) = f(psi*theta) + f(0), f(t) = -log(1 + e^-t).
# D ascends L in psi; G descends it in theta. The unique equilibrium is (0, 0).
sig = lambda t: 1 / (1 + np.exp(-t))
fprime = lambda t: sig(-t) # d/dt of -log(1 + e^-t)
def run(mode, gamma=0.0, lr=0.1, steps=3000):
th, ps = 1.0, 1.0
out = []
for k in range(steps + 1):
if k % 1000 == 0: out.append(np.hypot(th, ps))
g_th = ps * fprime(ps * th) # dL/dtheta
g_ps = th * fprime(ps * th) - gamma * ps # dL/dpsi minus the R1 penalty gradient
if mode == "simultaneous":
th, ps = th - lr * g_th, ps + lr * g_ps
else: # alternating: D first, then G sees new D
ps = ps + lr * g_ps
th = th - lr * ps * fprime(ps * th)
return out
print("distance from equilibrium after 0, 1000, 2000, 3000 steps")
for mode, gamma in [("simultaneous", 0.0), ("alternating", 0.0),
("simultaneous", 0.3), ("alternating", 0.3)]:
d = run(mode, gamma)
print(f"{mode:12s} R1 gamma={gamma:.1f}: " + " ".join(f"{v:7.3f}" for v in d))
distance from equilibrium after 0, 1000, 2000, 3000 steps
simultaneous R1 gamma=0.0: 1.414 2.651 3.101 3.354
alternating R1 gamma=0.0: 1.414 1.414 1.414 1.415
simultaneous R1 gamma=0.3: 1.414 0.000 0.000 0.000
alternating R1 gamma=0.3: 1.414 0.000 0.000 0.000
3. A complete GAN in two parameters, with and without R1 (NumPy). The generator is \(G(z) = az + b\); the discriminator is logistic regression on \((u, u^2)\) with \(u = x/4\), so it can detect a wrong mean and a wrong spread. All gradients are written out by hand:
import numpy as np
# Learn x ~ N(4, 1.25^2) with a two-parameter generator G(z) = a*z + b, z ~ N(0, 1).
# Discriminator logit: w1*u + w2*u^2 + c with u = x/4, so it can "see" mean and spread.
# Non-saturating GAN loss, Adam(beta1=0.5), gradients derived by hand.
sig = lambda t: 1 / (1 + np.exp(-t))
feats = lambda x: np.stack([x / 4, (x / 4) ** 2, np.ones_like(x)], 1)
def train(gamma, iters=8000, B=256, lr=2e-3, seed=0):
rng = np.random.default_rng(seed)
G, D = np.array([1.0, 0.0]), np.zeros(3)
state = {k: [0.0, 0.0, 0] for k in "GD"}
def adam_ascent(k, p, g):
m, v, t = state[k]; t += 1
m, v = 0.5 * m + 0.5 * g, 0.999 * v + 0.001 * g * g
state[k] = [m, v, t]
return p + lr * (m / (1 - 0.5**t)) / (np.sqrt(v / (1 - 0.999**t)) + 1e-8)
trace = []
for it in range(iters + 1):
xr = 4 + 1.25 * rng.standard_normal(B)
z = rng.standard_normal(B); xf = G[0] * z + G[1]
# D ascends E[log D(real)] + E[log(1 - D(fake))] - gamma/2 E_real[(dlogit/dx)^2]
gD = feats(xr).T @ (1 - sig(feats(xr) @ D)) / B - feats(xf).T @ sig(feats(xf) @ D) / B
slope = D[0] / 4 + D[1] * xr / 8 # dlogit/dx on real data
gR1 = np.array([np.mean(slope) / 4, np.mean(slope * xr / 8), 0.0])
D = adam_ascent("D", D, gD - gamma * gR1)
# G ascends E[log D(G(z))]: chain rule through the logit and x = a z + b
gx = (1 - sig(feats(xf) @ D)) * (D[0] / 4 + D[1] * xf / 8)
G = adam_ascent("G", G, np.array([np.mean(gx * z), np.mean(gx)]))
if it % 1000 == 0: trace.append(f"{G[1]:.2f}/{abs(G[0]):.2f}")
return trace
print("generator mean/std every 1000 iterations (target 4.00/1.25)")
for gamma in [0.0, 10.0]:
print(f"R1 gamma={gamma:4.1f}: " + " ".join(train(gamma)))
generator mean/std every 1000 iterations (target 4.00/1.25)
R1 gamma= 0.0: 0.00/1.00 2.86/2.86 4.11/0.92 4.16/0.20 4.13/0.17 3.58/2.40 4.11/0.60 3.94/1.52 4.14/0.73
R1 gamma=10.0: 0.00/1.00 2.65/0.17 3.74/0.03 3.94/1.50 4.01/1.24 3.99/1.27 4.00/1.24 4.01/1.24 4.04/1.24
Without the penalty the generator finds the mean within 2,000 steps but its spread swings from 0.17 (nearly collapsed) to 2.40 and back: the Dirac-GAN rotation, now in the spread parameter. At those moments the discriminator's average output on real and fake samples is close to 0.5, which is why "D is at 0.5" is not evidence of convergence. With R1 the spread settles at 1.24.
4. FID, and its small-sample bias (NumPy):
import numpy as np
rng = np.random.default_rng(0)
def frechet(mu1, S1, mu2, S2):
"""||mu1-mu2||^2 + Tr(S1 + S2 - 2 (S1 S2)^{1/2}); the trace of the matrix square
root equals the sum of sqrt-eigenvalues of S1^{1/2} S2 S1^{1/2} (symmetric PSD)."""
w, V = np.linalg.eigh(S1)
r1 = V @ np.diag(np.sqrt(np.maximum(w, 0))) @ V.T
ev = np.linalg.eigvalsh(r1 @ S2 @ r1)
return np.sum((mu1 - mu2) ** 2) + np.trace(S1) + np.trace(S2) - 2 * np.sum(np.sqrt(np.maximum(ev, 0)))
def fid(a, b): # "features" a, b: (N, d) arrays standing in for Inception-v3 pool features
return frechet(a.mean(0), np.cov(a, rowvar=False), b.mean(0), np.cov(b, rowvar=False))
d = 64
# Worked example in closed form: same covariance, means 0.5 apart in every coordinate
print("mean shift only :", round(frechet(np.zeros(d), np.eye(d), 0.5 * np.ones(d), np.eye(d)), 3))
# Generator with the right mean but too little spread (std 0.7 instead of 1): "mode dropping"
print("spread 0.7 vs 1.0:", round(frechet(np.zeros(d), np.eye(d), np.zeros(d), 0.49 * np.eye(d)), 3))
# FID between two sample sets drawn from the SAME distribution is not zero: it is biased
for n in [500, 2_000, 10_000, 50_000]:
a, b = rng.standard_normal((n, d)), rng.standard_normal((n, d))
print(f"same distribution, N={n:6d}: FID = {fid(a, b):.3f}")
mean shift only : 16.0
spread 0.7 vs 1.0: 5.76
same distribution, N= 500: FID = 4.438
same distribution, N= 2000: FID = 1.087
same distribution, N= 10000: FID = 0.222
same distribution, N= 50000: FID = 0.043
5. A DCGAN training step (PyTorch; standard code, not run here):
import torch, torch.nn as nn, torch.nn.functional as F
K = 100
G = nn.Sequential( # z (B, 100, 1, 1) -> image (B, 3, 32, 32)
nn.ConvTranspose2d(K, 256, 4, 1, 0), nn.BatchNorm2d(256), nn.ReLU(),
nn.ConvTranspose2d(256, 128, 4, 2, 1), nn.BatchNorm2d(128), nn.ReLU(),
nn.ConvTranspose2d(128, 64, 4, 2, 1), nn.BatchNorm2d(64), nn.ReLU(),
nn.ConvTranspose2d(64, 3, 4, 2, 1), nn.Tanh())
D = nn.Sequential( # image -> one logit
nn.Conv2d(3, 64, 4, 2, 1), nn.LeakyReLU(0.2),
nn.Conv2d(64, 128, 4, 2, 1), nn.BatchNorm2d(128), nn.LeakyReLU(0.2),
nn.Conv2d(128, 256, 4, 2, 1), nn.BatchNorm2d(256), nn.LeakyReLU(0.2),
nn.Conv2d(256, 1, 4, 1, 0), nn.Flatten())
optG = torch.optim.Adam(G.parameters(), 2e-4, betas=(0.5, 0.999))
optD = torch.optim.Adam(D.parameters(), 2e-4, betas=(0.5, 0.999))
def step(real): # real: (B, 3, 32, 32) scaled to [-1, 1]
z = torch.randn(real.size(0), K, 1, 1)
fake = G(z)
# discriminator: real -> 1, fake -> 0 (detach so G gets no gradient here)
lossD = F.softplus(-D(real)).mean() + F.softplus(D(fake.detach())).mean()
optD.zero_grad(); lossD.backward(); optD.step()
# generator, non-saturating: maximise log D(G(z)) = minimise softplus(-logit)
lossG = F.softplus(-D(fake)).mean()
optG.zero_grad(); lossG.backward(); optG.step()
return lossD.item(), lossG.item()
softplus(-l) is \(-\log\sigma(l)\) and softplus(l) is \(-\log(1-\sigma(l))\), written that way for
numerical stability (log-sum-exp).
Things to try
- In snippet 1, compute the KL of generator to data, \(\mathrm{KL}(q\,\|\,p) = \mu^2/2\), alongside JS. It never saturates either; the problem is specific to JS and to disjoint supports.
- In snippet 2, set
lr=0.01. The simultaneous spiral grows far more slowly (the outward factor is \(\sqrt{1+\eta^2/4}\)), but it still diverges. - In snippet 3, give the discriminator only the linear feature (drop \(u^2\)). The generator now matches the mean and has no reason to match the spread: a discriminator can only enforce the statistics it can see. This is the finite-capacity argument of Arora et al. in miniature.
- In snippet 3, try \(\gamma = 0.1\), \(1\) and \(100\). Too small does not damp; too large flattens the discriminator so much that learning slows.
- Train the DCGAN on CIFAR-10, then compute FID with pytorch-fid on 10,000 and 50,000 samples and compare the two numbers.
In practice¶
- Defaults that work: non-saturating loss or hinge loss; Adam with \(\beta_1 = 0\) or \(0.5\), \(\beta_2 = 0.99\); spectral normalisation in the discriminator, or R1 on real data; an exponential moving average of the generator's weights for evaluation (BigGAN and StyleGAN both sample from the EMA generator).
- Watch samples, not losses. Except for WGAN, GAN losses do not decrease as quality improves. Log a fixed grid of \(\mathbf z\) every few thousand steps and track FID on a held-out set.
- Diagnose collapse with recall, a birthday-paradox duplicate check, or by counting modes on a dataset with known modes (Stacked MNIST has 1,000).
- Small data: the discriminator memorises the training set and its feedback becomes useless. Use differentiable augmentation applied to both real and fake images (StyleGAN2-ADA).
- Reach for a GAN loss when you need sharp outputs from a model that otherwise regresses to the mean: autoencoder decoders, super-resolution, vocoders, few-step distillation. Reach for diffusion or flow matching when you need a full generative model of diverse data.
Common misconceptions¶
\"The discriminator's loss tells you how good the generator is.\"
In the standard GAN it does not: both losses hover around a constant while the generator improves, and a discriminator at 0.5 can coexist with a collapsed generator (snippet 3 shows exactly that). Only the Wasserstein critic's estimate correlates with quality, and even that only within one run.
\"Mode collapse means the generator outputs one image.\"
Total collapse is rare in modern GANs. The common form is partial: missing classes, low diversity in poses or backgrounds. It shows up as low recall, not as identical samples.
\"GANs minimise the Jensen–Shannon divergence.\"
Only at the idealised optimum with an optimal discriminator and the minimax loss. Real GANs use the non-saturating loss (a different divergence), a discriminator far from optimal, and regularisers. The divergence view explains the equilibrium; it does not describe the training dynamics.
Check yourself¶
Derive the optimal discriminator for fixed G. What does it estimate?
Maximise \(p_\text{data}(\mathbf x)\log D + p_g(\mathbf x)\log(1-D)\) pointwise: \(D^* = p_\text{data}/(p_\text{data}+p_g)\). It is a density-ratio estimator, \(D^*/(1-D^*) = p_\text{data}/p_g\), which tells the generator where it over- or under-produces.
At D(G(z)) = 0.05, compare the gradient of the minimax and non-saturating generator losses with respect to the discriminator's logit.
Minimax: \(\partial\log(1-\sigma(\ell))/\partial\ell = -\sigma(\ell) = -0.05\). Non-saturating: \(\partial\log\sigma(\ell)/\partial\ell = 1-\sigma(\ell) = 0.95\), nineteen times larger. Both vanish only at the opposite ends, so the non-saturating loss is strong exactly when the generator is bad.
Why does the JS divergence give no useful gradient when real and generated data lie on disjoint low-dimensional manifolds, and how does WGAN fix it?
If the supports do not overlap, \(m\) puts half its mass on each, both KL terms equal \(\log 2\), and JS is the constant \(\log 2\) for every small change of the generator, so its gradient is zero (and a perfect discriminator exists, so \(D\)'s gradients vanish too). The Wasserstein-1 distance measures how far mass must move, so it changes smoothly as the generator moves and its gradient is non-zero. In the parallel-lines example, \(W_1 = |\theta|\).
Compute FID between N(0, I) and N(0, 0.25 I) in 10 dimensions.
The means agree. \(\operatorname{tr}(I + 0.25I - 2(0.25I)^{1/2}) = 10\times(1 + 0.25 - 1) = 2.5\).
In the Dirac-GAN, why do simultaneous gradient steps diverge while the continuous dynamics only orbit?
The linearised game is a rotation with eigenvalues \(\pm i/2\). Forward Euler multiplies the state by \(I + \eta A\), with eigenvalue modulus \(\sqrt{1+\eta^2/4} > 1\), so each step moves outward. The continuous flow has eigenvalues on the imaginary axis and preserves the radius. Damping (R1) moves the eigenvalues into the left half-plane.
Why is the non-saturating GAN prone to dropping modes, in terms of divergences?
Against an optimal discriminator its generator gradient is that of \(\mathrm{KL}(p_g\,\|\,p_\text{data}) - 2\,\mathrm{JS}\). Reverse KL heavily penalises putting mass where the data has none but barely penalises ignoring regions of the data, so concentrating on a subset of modes is cheap.
Hard: a discriminator with limited capacity reports D = 0.5 on everything. Does that mean the generator has learned the data distribution?
No. It means no function in the discriminator's class separates the two distributions. Arora et al. (2017, Corollary 3.2) showed that a discriminator with \(p\) parameters cannot distinguish the data from some distribution supported on only \(\tilde O(p/\epsilon^2)\) points, however diverse the data is. Snippet 3's "Things to try" shows the 1-D version: a linear discriminator is satisfied by any generator with the right mean.
Hard: StyleGAN feeds the latent through an 8-layer mapping network before using it. Why not use z directly?
\(\mathbf z\) is forced to be Gaussian, but the factors of variation in faces are not distributed that way; mapping a fixed Gaussian directly to images forces the generator to warp the space, entangling factors. Learning \(\mathbf w = f(\mathbf z)\) lets the intermediate space take whatever shape makes the factors easy to control linearly. The paper measured smoother interpolation (perceptual path length) in \(\mathcal W\) than in \(\mathcal Z\).
Go deeper¶
Papers
- Generative Adversarial Networks — Goodfellow et al., 2014. The original. Section 4 has the D* and JS proofs; Figure 1 is the picture above.
- NIPS 2016 Tutorial: Generative Adversarial Networks — Goodfellow, 2016. The inventor's own long-form overview: why implicit models, the taxonomy of generative models, tips and open problems.
- Unsupervised Representation Learning with Deep Convolutional GANs — Radford, Metz and Chintala, 2015. The DCGAN recipe and latent arithmetic.
- Towards Principled Methods for Training GANs — Arjovsky and Bottou, 2017. Why GANs fail: disjoint supports, vanishing gradients, and Theorem 2.5 on the non-saturating loss.
- Wasserstein GAN — Arjovsky, Chintala and Bottou, 2017. Read Section 2 (the parallel-lines example) and Section 3 (the dual).
- Improved Training of Wasserstein GANs — Gulrajani et al., 2017. The gradient penalty.
- Spectral Normalization for GANs — Miyato et al., 2018. A one-line change that made discriminators Lipschitz.
- Which Training Methods for GANs do actually Converge? — Mescheder, Geiger and Nowozin, 2018. The Dirac-GAN and R1; the clearest analysis of GAN dynamics.
- A Style-Based Generator Architecture for GANs — Karras, Laine and Aila, 2018. StyleGAN; then read StyleGAN2 for weight demodulation.
- Large Scale GAN Training for High Fidelity Natural Image Synthesis — Brock, Donahue and Simonyan, 2018. BigGAN: scale, truncation and the failure modes of large GANs.
- GANs Trained by a Two Time-Scale Update Rule Converge to a Local Nash Equilibrium — Heusel et al., 2017. Where FID comes from.
- Improved Precision and Recall Metric for Assessing Generative Models — Kynkäänniemi et al., 2019. Fidelity and coverage as separate numbers.
- The GAN is dead; long live the GAN! A Modern GAN Baseline — Huang et al., NeurIPS 2024. R3GAN: a principled loss and a trick-free modern GAN.
Videos and lectures
- Stanford CS236: Deep Generative Models (2023) — Stefano Ermon. The GAN, f-GAN and Wasserstein lectures place adversarial training among likelihood-free methods.
- MIT 6.S191: Introduction to Deep Learning — Amini and Amini. The "Deep generative modelling" lecture is a fast, well-illustrated first pass at autoencoders and GANs.
Articles and blog posts
- From GAN to WGAN — Lilian Weng, 2017. The divergence story from JS to Wasserstein in one place.
- ganhacks: How to Train a GAN? — Chintala et al., 2016. The folklore of 2016 GAN training; read it to recognise the tricks later papers made unnecessary.
Courses and books
- Understanding Deep Learning — Simon J. D. Prince, 2023. Chapter 15 covers GANs, Wasserstein distance and StyleGAN with excellent figures.
- Deep Learning: Foundations and Concepts — Bishop and Bishop, 2024. A careful textbook treatment of GANs alongside the other generative families.
Code
- NVlabs/stylegan3 — Official StyleGAN⅔ code; the reference implementation of R1, ADA and FID evaluation.
- eriklindernoren/PyTorch-GAN — Short, readable implementations of dozens of GAN variants.
- brownvc/R3GAN — The modern minimalist baseline.
Where this leads¶
- Diffusion models: the method that replaced GANs for image synthesis, trained with a regression loss instead of a game.
- Latent diffusion and guidance: where an adversarial loss trains the autoencoder, and guidance plays the role of the truncation trick.
- Score matching and flow matching: optimal transport returns, this time as straight paths between noise and data.
- Speech and audio: GAN vocoders and codec discriminators in production.
- RLHF with PPO: another policy trained against a learned critic it can exploit.