Generative Adversarial Networks
Imagine trying to forge a painting so convincing that even a world-class art critic cannot tell it from an original. Now imagine the critic getting better at detecting fakes every time you improve your forgery. Imagine also that you improve your forgery every time the critic gets sharper. This escalating contest is the entire idea behind Generative Adversarial Networks (GANs). Two neural networks are locked in a game, each pushing the other to improve. No explicit density is ever written down. Before GANs, Generative Modeling: Learning Data Distributions typically required an explicit likelihood. This meant a formula for how probable each data point is. This made models like variational autoencoders tractable but often blurry. They optimize a bound on likelihood rather than sample sharpness directly. GANs sidestep the likelihood entirely. Instead of asking "how probable is this image under my model?", a GAN asks "can a classifier catch this image being fake?" That shift in objective turned out to produce dramatically sharper, more realistic samples. It launched an entire subfield: image synthesis, super-resolution, image-to-image translation, deepfakes, data augmentation. It also inspired the early architectural ancestors of some diffusion-adjacent generative pipelines. The core mechanism is a minimax game between a generator and a discriminator . The generator maps random noise to fake data. The discriminator tries to distinguish real data from 's output. Training alternates between the two. The discriminator learns to classify better. The generator learns to fool the discriminator better. Ideally, the generator's samples become indistinguishable from real data. This is called implicit generation. The model never computes explicitly; it only produces samples. This article builds the GAN objective from first principles. It walks through the training algorithm with full pseudocode. It proves what the optimal discriminator and optimal generator look like at equilibrium. It traces a concrete numeric example of one training step. It also previews the instability issues that motivate GAN Training Dynamics and Failure Modes.
- A GAN pits a generator against a discriminator in a two-player minimax game.
- is trained as a binary classifier: real data → label 1, generated data → label 0.
- is trained to make output values close to 1 on its fakes — it never sees real data directly.
- At the theoretical optimum, everywhere and 's distribution equals the data distribution.
- The objective is equivalent to minimizing the Jensen–Shannon divergence between real and generated distributions.
- Training is notoriously unstable in practice — a preview of the failure modes covered next.
A GAN trains a generator implicitly, by making it win an adversarial classification game against a discriminator, rather than by maximizing an explicit data likelihood.
The idea
A GAN consists of two neural networks with opposing objectives, trained jointly via Gradient Descent and Backpropagation-style optimization. The generator maps a latent noise vector (typically or ) to a synthetic sample in data space. The discriminator is a binary classifier that outputs the probability that an input came from the real data distribution rather than from . Crucially, never sees real training data. It only receives a gradient signal through : the derivative of 's output with respect to 's input, backpropagated further through 's parameters. This is what makes generation implicit — there is no explicit formula for , the distribution induced by pushing through . We can sample from (run forward), but we cannot evaluate its density. The training objective is the minimax game:
Read this as: wants to maximize by assigning high probability (close to 1) to real samples and low probability (close to 0) to fakes; wants to minimize , i.e., make close to 1 so the second term becomes very negative (log of something near 1 is close to 0, undermining ). This is a zero-sum game: 's gain is 's loss. Formally it is a Nash-equilibrium-seeking process over two function classes (neural network parameter spaces), not a single joint optimization — this distinction is exactly why training a GAN behaves very differently from training an ordinary supervised classifier.
How it works
Setup. Choose architectures for and (typically convolutional networks for images). Choose a noise prior . Initialize randomly.
Alternating optimization. In each iteration: 1. Sample a minibatch of real data and a minibatch of noise; update to increase (a few steps, often just one). 2. Sample a fresh minibatch of noise; update to decrease (one step). A crucial practical fix, introduced in the original 1963 minimax formulation's neural instantiation, is the non-saturating generator loss: instead of minimizing (whose gradient vanishes when is confidently correct, i.e., , early in training), the generator instead maximizes . Both losses share the same fixed point but the non-saturating version supplies much stronger gradients when is weak. ``` Algorithm: GAN Training (non-saturating variant) Input: real dataset X, noise prior p_z, learning rates η_D, η_G, discriminator steps per generator step k Initialize discriminator parameters φ, generator parameters θ for iteration = 1, 2, ... do
# ---- Discriminator phase: k steps ---- for step = 1 to k do sample minibatch {x_1, ..., x_m} from X sample minibatch {z_1, ..., z_m} from p_z
# fake samples via current generator (no grad needed into θ here) x̂_i ← G_θ(z_i) for i = 1..m L_D ← -(1/m) Σ_i [ log D_φ(x_i) + log(1 - D_φ(x̂_i)) ] φ ← φ - η_D ∇_φ L_D # gradient DESCENT on the negative of V end for
# ---- Generator phase: 1 step ---- sample minibatch {z_1, ..., z_m} from p_z x̂_i ← G_θ(z_i) for i = 1..m L_G ← -(1/m) Σ_i log D_φ(x̂_i) # non-saturating loss θ ← θ - η_G ∇_θ L_G end for return θ, φ ``` Notes on correctness of the pseudocode:
- 's gradient step is ascent on , implemented as descent on , i.e. the standard binary cross-entropy loss with real samples labeled 1 and fake samples labeled 0.
- During the update, gradients must not flow into (the fake batch is treated as a constant input to ); during the update, is held fixed and gradients flow through back into only.
- The base case is the random initialization: at iteration 0, is a coin flip and produces noise-like output; the invariant maintained across iterations is that is always trained to (approximately) reach its optimum for the current before is updated — this is what the inner loop of steps approximates.
Complexity & correctness
Time complexity per iteration. Let and be the cost of one forward+backward pass through and respectively, on a batch of size . One full iteration costs — the discriminator phase runs forward/backward passes through (plus forward passes through to generate fakes, though these can be cheap if is frozen and reused), and the generator phase runs one forward/backward through both networks. In practice is common, giving a per-iteration cost of the same order as training an ordinary classifier plus an ordinary regressor jointly: per iteration, i.e. linear in network size and batch size, identical in order to standard supervised training — GANs do not introduce a big-O overhead over ordinary deep network training. The overhead is entirely in how many iterations are needed to reach a usable equilibrium, which is not captured by per-step complexity and is empirically much larger and less predictable than for supervised classifiers.
Space complexity. for parameters and the activations of the current minibatch (dimension ), same order as training two separate feedforward-style networks — no additional asymptotic memory cost is inherent to the adversarial framing itself.
Correctness — what is being optimized, and what is the fixed point? Fix . For any fixed generator, the inner maximization over has a clean closed form. Writing for the density induced by , the value function is
For each fixed , this integrand is of the form with , maximized over . Taking the derivative and setting it to zero:
So the optimal discriminator for a fixed is
This matches intuition: where dominates , is close to 1; where dominates, is close to 0; where they're equal, . Substituting back into gives the effective generator objective, which algebra shows equals
where is the Jensen–Shannon divergence, a symmetric, bounded () divergence between distributions. Since with equality iff , we get with equality iff . This is the correctness argument: the global minimum of the outer minimization over is achieved exactly when the generator's distribution matches the true data distribution, and at that point the optimal discriminator is everywhere — it cannot do better than a coin flip because the two distributions are literally identical.
Caveats on the proof (be honest about the gap between theory and practice).
- The argument assumes and have unlimited capacity and that at every outer step is trained fully to its optimum — neither holds for finite neural networks trained with a few gradient steps.
- The proof establishes existence and uniqueness of the global equilibrium in distribution space, but says nothing about whether gradient-based alternating optimization actually converges to it — alternating gradient descent on a minimax objective is not guaranteed to converge even in simple bilinear games, and can cycle or oscillate. This gap between theory and observed training instability (mode collapse, non-convergence, vanishing gradients when is too strong) is exactly what GAN Training Dynamics and Failure Modes addresses.
- Because is never written explicitly, we cannot directly evaluate during training; it is only a theoretical tool for the proof, not a quantity monitored in practice.
Worked example
Consider a toy 1-D setting to make the abstract game concrete. Suppose the true data distribution is , and at the current training iteration the generator produces (it has not yet converged). is a simple logistic model , currently at . Draw a minibatch (m = 4) — 2 real samples, 2 fake samples:
| Sample | Source | Value | Target label | |
|---|---|---|---|---|
| real | 5.20 | 1 | ||
| real | 4.80 | 1 | ||
| fake () | 2.90 | 0 | ||
| fake () | 3.10 | 0 |
Discriminator loss (binary cross-entropy, matching ):
This is much better than the initial coin-flip loss of , telling us has already learned to separate the two clusters (centered at 3 vs 5) reasonably well. Backpropagating and taking a gradient step increases and adjusts so the decision boundary sharpens around .
Generator loss (non-saturating). Using the same (now momentarily frozen) on the fake batch only:
The gradient flows backward through 's logit at (pushing toward 1, i.e., pushing the logit upward) and then through , nudging so that future samples land further to the right — directly toward the real cluster at mean 5. Repeating this alternation over many iterations moves 's mean from 3 toward 5 and shrinks the gap the discriminator can exploit, exactly as the JSD argument predicts: as , 's achievable accuracy collapses toward 50%.
Contrast with a trivial case. Note this example is deliberately non-symmetric: initially, is not at 50% accuracy, and the two loss values ( vs ) are meaningfully different — showing the asymmetric, adversarial pull of the game, rather than an already-converged or symmetric toy case that would hide how the gradients actually behave early in training.
Common pitfalls & traps
| Pitfall | Why it happens | Fix / mitigation |
|---|---|---|
| Vanishing generator gradient | Using when is confidently correct saturates the log near 0 slope | Use the non-saturating loss |
| Mode collapse | finds one mode of that fools and stops exploring; the minimax game has no incentive for diversity per se | Minibatch discrimination, unrolled GANs, diversity-promoting losses (previewed in failure-modes article) |
| Discriminator too strong, too early | If is large or overfits, everywhere, gradient to vanishes | Balance / capacity and steps; label smoothing; instance noise |
| Treating 's loss as a progress metric | 's loss does not monotonically indicate sample quality since both networks move | Use held-out sample quality metrics (FID, human eval), not just the loss curve |
| Non-convergent oscillation | Simultaneous or alternating gradient descent on a minimax objective can cycle indefinitely, even near equilibrium | Two-timescale update rules, gradient penalty, spectral normalization |
| Forgetting to detach fake samples during 's update | Backpropagating naively can also update if the fake batch graph isn't cut | Stop gradients into during the discriminator phase |
Pioneers & history
Origins · 1 minIan J. Goodfellow and how this was discovered
The GAN idea emerged from a now-famous account: Goodfellow reportedly sketched the minimax formulation after a late-night bar conversation about whether adversarial competition between two networks could substitute for an explicit likelihood model, and implemented the first version within the same night. The paper's clean two-player game framing borrowed intuition from Game Theory and Minimax Reasoning, while its practical machinery — backpropagation through two coupled networks — rests entirely on ordinary Gradient Descent and Backpropagation applied to each player in turn. Within a year, the field split into a flurry of architectural stabilizations (DCGAN), theoretical reformulations of the divergence being minimized (Wasserstein GAN, f-GANs), and applied variants (pix2pix, CycleGAN, StyleGAN) that made GANs a dominant tool for realistic image and video synthesis before diffusion models later became competitive on sample quality and training stability.
Where this matters
GANs (and their descendants) underlie a wide swath of production and research systems: StyleGAN-family models for photorealistic face and asset synthesis in gaming and film pre-visualization; pix2pix and CycleGAN for image-to-image translation (sketches-to-photos, satellite-to-map imagery, medical image domain adaptation); super-resolution GANs (SRGAN, ESRGAN) used in photo restoration and upscaling pipelines; data augmentation for training classifiers when labeled real data is scarce, especially in medical imaging; and speech synthesis vocoders (e.g., adversarial components in some neural vocoders) that produce more natural-sounding audio than purely regression-trained models. The adversarial training principle — pit a learned critic against a generator — also seeds ideas beyond raw image synthesis, including adversarial robustness testing, domain adaptation, and some reinforcement-learning-adjacent imitation learning setups (e.g., GAIL). Understanding the basic minimax game here is the prerequisite for understanding why these systems are hard to train reliably, which is the subject taken up directly in GAN Training Dynamics and Failure Modes.
Ask the tutor: Why does alternating gradient descent on the GAN minimax objective fail to guarantee convergence, even though the theoretical global equilibrium is unique?
Why can't a GAN just directly minimize a distance between p_data and p_g?
Because , the distribution induced by pushing noise through the generator, is never available in closed form — we can only sample from it by running forward, not evaluate its density at a point. Most classical distances (KL divergence, MLE) require evaluating densities. The adversarial trick sidesteps this: the discriminator, trained as a classifier, implicitly estimates a density ratio at every point, without either network ever writing down an explicit formula for either density. That density-ratio estimation, done via ordinary binary classification, is precisely what makes the objective computable using only samples from both distributions.
Is a GAN's discriminator loss a reliable way to monitor training progress?
Not reliably. Because both networks are moving simultaneously, a decreasing loss can mean is improving, or that is momentarily weaker, or that the game has entered an unstable oscillation. Unlike supervised learning, where a falling validation loss usually tracks real progress, GAN losses do not have a monotone relationship with sample quality. In practice, practitioners track separate, sample-based quality metrics such as the Fréchet Inception Distance (FID) or Inception Score, and visually inspect generated samples, rather than trusting the adversarial loss curves alone.
What role does the noise vector z play, and why is it needed?
The noise is the source of randomness that lets a deterministic function produce a whole distribution of outputs rather than a single point. Without stochastic input, would be a fixed deterministic map and could only ever produce one output per training configuration — useless for modeling a diverse data distribution. Sampling from a simple prior (Gaussian or uniform) and letting a deep network transform it into a complex, structured sample is the mechanism of implicit generation: complexity in comes entirely from the nonlinearity of , not from complexity in the noise itself.
How does a GAN differ from a variational autoencoder in what it optimizes?
A variational autoencoder maximizes a tractable lower bound on the data log-likelihood (the ELBO), which involves an explicit reconstruction term and a KL regularizer against a prior — it directly touches an approximate density. A GAN never computes or bounds a likelihood; it instead minimizes the Jensen–Shannon divergence implicitly, via an adversarial classification game, and only ever produces samples. This is why GAN samples are often sharper (no averaging induced by an explicit reconstruction loss) but training is less stable and there's no natural likelihood-based metric to monitor convergence, unlike VAEs.
Why is GAN training described as a Nash equilibrium problem rather than ordinary optimization?
Ordinary supervised training optimizes a single objective for a single set of parameters, and gradient descent provably decreases that objective (under standard smoothness assumptions). A GAN instead has two players with opposing objectives over the same value function : maximizes it, minimizes it. There is no single scalar loss that both networks jointly descend, so classical convergence guarantees for gradient descent do not directly apply. The desired solution concept is a Nash equilibrium — a point where neither player can improve unilaterally — and alternating or simultaneous gradient updates are only a heuristic, not a guaranteed algorithm, for finding one.
What determines how many discriminator steps k to take per generator step?
There is a tradeoff: too few steps (small ) means is far from its optimum for the current , so the generator's gradient (which depends on ) is a poor approximation of the theoretically justified gradient. Too many steps (large ) risks overfitting or becoming near-perfect, which saturates the generator's gradient toward zero, especially with the original saturating loss. In practice with the non-saturating loss, combined with careful learning-rate balancing (or techniques like the two-timescale update rule), is the most common practical compromise.
Can GANs model discrete data, like text, directly?
Not cleanly, because backpropagation through requires the sampling step from 's output to 's input to be differentiable, and standard discrete sampling (e.g., argmax over a vocabulary) is not differentiable. Workarounds include the Gumbel-softmax relaxation, reinforcement-learning-style policy gradients (as in SeqGAN), or applying GANs at the level of continuous embeddings rather than raw discrete tokens. This is a genuine structural limitation compared to likelihood-based sequence models, and it's a large part of why GANs dominate image generation far more than text generation.