Generative Adversarial Networks for Images
Suppose you want a computer to invent a face that has never existed. No dataset contains it. No lookup table can return it. Yet the output must look as plausible as a photograph from a camera. This is the problem of image synthesis. For most of the history of computer vision, it was intractable at high resolution. Nobody could write down an explicit probability density over natural images. Nobody could even sample from it. Generative Adversarial Networks (GANs) solved this by refusing to model the density explicitly at all. Instead, they train two neural networks against each other in a game. The idea, introduced in 2014, reframed generative modeling as a competition. A generator network tries to manufacture images that look real. Meanwhile, a discriminator network tries to catch it in the act of faking them. Neither network is told directly what a "realistic image" looks like in mathematical terms. Realism emerges as the equilibrium point of an adversarial game. This equilibrium is enforced purely through gradients flowing between the two competing networks. This sidesteps the need for an explicit likelihood function, which had stalled earlier generative approaches. GANs matter because they produce sharp, high-fidelity samples. This contrasts with the blurry averages typical of earlier pixel-wise regression losses. This sharpness comes precisely from the adversarial loss. A discriminator that can distinguish blur from texture punishes the generator for hedging its bets. That single mechanism powers deepfake detection research and synthetic data generation for training other vision models. It also drives photo restoration, super-resolution, and the entire family of conditional image translation systems that followed. This article builds the GAN framework from first principles. It covers the minimax game, the practical training loop, and the reasons the naive objective misbehaves. It also covers the specific failure mode called mode collapse that every practitioner must learn to recognize. It assumes familiarity with Backpropagation and general Image Generation Fundamentals. It sets up the machinery later needed for Image-to-Image Translation and Neural Style Transfer.
- A GAN pairs a generator that maps noise to images with a discriminator that classifies real vs. fake.
- Training is a two-player minimax game; at the theoretical optimum matches the true data distribution exactly.
- The original loss saturates early, so practitioners use the non-saturating loss for the generator instead.
- Training alternates and updates via stochastic gradient methods, with no shared global objective being minimized.
- Mode collapse — where produces only a few distinct outputs — is the signature failure mode of adversarial training.
- Losses like Wasserstein GAN and architectural fixes (batch norm, spectral normalization) were developed specifically to stabilize this game.
A GAN turns image generation into a two-player game where a generator and discriminator improve each other through competing gradients, with photorealism emerging as the Nash equilibrium rather than being explicitly modeled.
The idea
A Generative Adversarial Network consists of two differentiable functions, both usually convolutional neural networks. The generator maps a latent noise vector (typically Gaussian or uniform) to a synthetic image . The discriminator takes an image and outputs the probability that the image came from the real data distribution rather than from . The two networks are trained jointly but with opposing objectives, which is what makes this "adversarial." Formally, the training objective is the minimax game
The discriminator wants to push for real images and for fakes, maximizing . The generator wants the opposite: it wants , i.e., it wants to fool the discriminator, which corresponds to minimizing . Crucially there is no single loss function being jointly minimized by both networks — this is a game with a Nash equilibrium, not an optimization problem with a global minimum, and that distinction explains much of the instability discussed later. The key theoretical result, due to the original 2014 formulation, is that if is trained to optimality for a fixed , the optimal discriminator has a closed form,
where is the distribution induced by . Substituting this back into reduces the generator's objective to (up to a constant) the Jensen–Shannon divergence between and . Since the JS divergence is minimized (equal to zero) exactly when , the global optimum of the game is a generator that perfectly reproduces the true data distribution, with the discriminator reduced to outputting everywhere, unable to do better than a coin flip.
How it works
Training proceeds by alternating gradient updates: several (often one) step(s) updating with fixed, followed by one step updating with fixed, repeated until convergence or a fixed number of iterations. Each network only ever sees gradients through its own parameters, backpropagated through the other network's forward pass when needed (the generator's gradient must flow through the frozen discriminator). A critical practical modification is the non-saturating generator loss. Early in training, is poor and correctly rejects its samples with high confidence, so . The original generator loss has near-zero gradient in this regime (it saturates), starving the generator of learning signal exactly when it needs it most. The fix is to instead train to maximize directly. This has the same fixed point (both are minimized/maximized when ) but provides much stronger gradients when is weak, because is steep near while is nearly flat there. ```
# GAN training loop (non-saturating generator loss, minibatch SGD) initialize generator parameters theta initialize discriminator parameters phi for iteration = 1 to N_iterations:
# ---- Discriminator step(s) ---- for k = 1 to k_disc_steps: sample minibatch of m real images {x_1, ..., x_m} from data sample minibatch of m noise vectors {z_1, ..., z_m} from p_z fake_images <- G(z_i; theta) for i = 1..m # no gradient needed yet
# discriminator loss: maximize log D(real) + log(1 - D(fake)) L_D <- -(1/m) sum_i [ log D(x_i; phi) + log(1 - D(fake_images_i; phi)) ] phi <- phi - lr_D gradient(L_D, phi) # gradient ASCENT on V == descent on -V
# ---- Generator step ---- sample minibatch of m noise vectors {z_1, ..., z_m} from p_z fake_images <- G(z_i; theta) for i = 1..m # gradient must flow through here
# non-saturating loss: minimize -log D(fake) instead of maximize log(1 - D(fake)) L_G <- -(1/m) sum_i [ log D(fake_images_i; phi) ] theta <- theta - lr_G gradient(L_G, theta) return G, D ``` Two implementation details matter for correctness. First, when computing `L_D`, the fake images are treated as constants with respect to (gradients do not need to flow into ), which is why many implementations detach 's output from the computation graph during the discriminator step — this saves memory and avoids accidentally updating with the wrong loss. Second, when computing `L_G`, the discriminator's parameters must be held fixed (no update to from this loss); only gradients with respect to are taken, using purely as a frozen scoring function.
Complexity & correctness
Time complexity per iteration. A single training iteration costs one forward and backward pass through (cost where is the number of FLOPs in 's architecture, dominated by convolution operations scaling with image resolution and channel width) plus forward/backward passes through for the discriminator sub-steps (cost ). For a convolutional architecture operating on an image with feature channels and layers, per-layer cost is roughly for a kernel, so total cost per iteration is linear in the number of pixels processed and quadratic in channel width — identical asymptotic scaling to a standard CNN classifier or Image Generation Fundamentals autoencoder, since a GAN is architecturally just two CNNs. There is no additional algorithmic complexity beyond ordinary Backpropagation through each network; the added cost relative to a single supervised network is roughly a constant factor of .
Space complexity is for parameters plus the usual activation memory for backpropagation through both networks, proportional to batch size times the sum of feature-map sizes at every layer. Because gradients for 's step do not need to be stored through (fake images can be detached), peak memory during the discriminator step only needs 's activation graph, not 's.
Correctness argument (why equilibrium implies matching distributions). The proof sketch has two parts, matching the derivation in "The idea" section. 1. Optimal discriminator for fixed . For a fixed generator distribution , is, pointwise in , of the form with , , . Differentiating with respect to and setting to zero gives , recovering . This is a maximum because the second derivative of is negative for . 2. Global minimum over . Substituting back in,
using the definition of Jensen–Shannon divergence in terms of KL divergences to the mixture . Since with equality iff the two distributions are identical, is minimized exactly at , achieving the global minimum value .
Honest caveats. This proof assumes and have unbounded capacity (they range over all possible functions, not just those representable by a fixed neural architecture), that is trained to full convergence at every step (not just a few gradient steps, as done in practice), and that the alternating gradient procedure actually converges to this equilibrium. None of these hold exactly in practice: real networks have finite capacity, is never trained to optimality, and simultaneous gradient descent on a non-convex-non-concave minimax game has no general convergence guarantee — the dynamics can cycle or diverge even when a Nash equilibrium exists. This gap between the elegant theory and the messy practice is exactly why GAN training is known to be finicky, and why the specific failure mode below is so important to understand.
Worked example
Consider training a GAN on a toy 2D dataset that is not images but is easy to trace by hand: is a mixture of four 2D Gaussians arranged at the corners of a square (a common diagnostic used because it is easy to visualize whether covers all four modes or only some). Assume Gaussian noise, and are small MLPs, and we track qualitative behavior over training epochs.
| Epoch | Discriminator behavior | Generator output | Diagnosis |
|---|---|---|---|
| 0 | outputs ~0.5 everywhere (untrained) | Random scattered points, no structure | Both networks near initialization |
| 50 | learns a rough boundary separating real clusters from the diffuse fake cloud | output starts clustering loosely near the real modes | Early co-adaptation, gradients informative |
| 200 | sharply rejects points outside all 4 real clusters | places mass on one of the four corners very confidently | Mode collapse beginning: has found one "safe" region that reliably fools the current |
| 210 | adapts, learns to penalize that one corner specifically | 's output jumps to a different single corner | Oscillation: chases 's blind spot rather than covering the full distribution |
| 500 (with fix: minibatch discrimination / unrolled updates) | maintains balanced rejection across all corners | produces samples near all four modes with roughly correct proportions | Converged behavior close to the theoretical equilibrium |
This trace illustrates the central practical failure: between epochs 200 and 210, never learns to cover the whole distribution — it learns to win locally against whatever currently penalizes least, then catches up, and relocates its entire probability mass to a different single mode rather than spreading across all four. This oscillating, mode-hopping behavior is mode collapse, and it is a direct consequence of 's objective only requiring it to fool on some subset of the space, not to match the full density at every training step (recall the JS-divergence equivalence only holds when is trained to full optimality, which never happens with a handful of gradient steps). Fixes demonstrated in row 5 of the table are real techniques used in practice: minibatch discrimination lets compare examples within a batch, so it can detect when a whole batch of "fakes" is suspiciously identical (real batches from a mixture of four Gaussians should show diversity; a mode-collapsed fake batch will not), giving a gradient signal to diversify. Unrolled GANs let 's update account for several future steps of 's optimization, discouraging from exploiting a discriminator that is about to be corrected.
Common pitfalls & traps
| Pitfall | Why it happens | Consequence | Mitigation |
|---|---|---|---|
| Using the original saturating loss | Gradient is near zero when confidently rejects early fakes | Generator receives almost no learning signal at the start of training | Use the non-saturating loss |
| Discriminator overpowers generator | is a simpler classification task and converges much faster than 's generation task | permanently; 's gradients vanish | Balance update ratios, lower 's learning rate, add label smoothing or noise to 's inputs |
| Treating mode collapse as "just needs more epochs" | Mode collapse is a dynamical equilibrium of the game, not undertraining | Training runs indefinitely producing low-diversity samples | Minibatch discrimination, unrolled updates, or switch to Wasserstein-style losses with stronger convergence properties |
| Forgetting to detach fake images before the discriminator step | Autograd graphs accidentally connect 's loss to | Silent incorrect gradient updates to during the "-only" step | Explicitly stop gradients on 's output before computing |
| Evaluating GAN quality only by eyeballing samples | No explicit likelihood exists to compute perplexity or held-out log-likelihood | Overestimating diversity; missing subtle mode collapse | Use quantitative diversity metrics (e.g., counting distinct modes recovered, Inception-based diversity scores) alongside visual inspection |
| Assuming convergence is guaranteed because a Nash equilibrium exists | Existence of an equilibrium says nothing about whether alternating gradient descent finds it | Training can oscillate or diverge even on toy problems | Use techniques with better-understood dynamics (gradient penalty, spectral normalization, two-timescale update rules) |
Pioneers & history
Origins · 1 minIan J. Goodfellow and how this was discovered
The GAN framework arrived at a moment when explicit generative models — density estimators, variational autoencoders' precursors, and Boltzmann machines — struggled to produce sharp, high-resolution samples because they optimized likelihood-based objectives that reward covering probability mass everywhere, including blurry averages between modes. Casting generation as a game between a forger and a detective, rather than as direct density estimation, allowed sharpness to emerge naturally: the discriminator specifically punishes blur once it learns that blurry images are a giveaway of forgery. This reframing, simple in hindsight, unlocked a decade of rapid progress in photorealistic image synthesis.
Origins · 1 minhow this was discovered
Where this matters
GANs underpin a wide range of production and research systems in computer vision. Photo-realistic face synthesis systems (used for avatar generation, synthetic training data, and — controversially — deepfakes) are built directly on the generator-discriminator architecture described here. Super-resolution systems that upscale low-resolution images use adversarial losses layered on top of pixel-wise losses specifically because a purely pixel-wise objective produces blurry upscaling, while the discriminator's texture-sensitivity forces sharp, plausible high-frequency detail. Data augmentation pipelines in domains with scarce labeled data (medical imaging, rare-defect industrial inspection) use trained generators to synthesize additional realistic training examples for downstream classifiers. The conditional variant of the adversarial game, where both and are given an additional input (a class label, a sketch, a semantic map, or a source-domain image), is the direct foundation of Image-to-Image Translation systems that convert sketches to photos or day scenes to night scenes. The same discriminator-driven notion of a learned perceptual loss — punishing outputs that "look wrong" according to a trained critic rather than according to a fixed pixel distance — reappears as a key ingredient in Neural Style Transfer pipelines and in perceptual loss functions used throughout modern Image Generation Fundamentals research, including diffusion-model guidance and autoencoder-based compression systems.
Ask the tutor: How does the Wasserstein GAN loss change the training dynamics and specifically help mitigate mode collapse compared to the original minimax formulation?
Why can't a GAN's generator loss and discriminator loss be minimized simultaneously like a normal neural network's training loss?
Because a GAN is not solving a single optimization problem — it is playing a two-player zero-sum game where maximizes and minimizes the same value function . There is no scalar objective whose gradient descent, applied to both parameter sets jointly, is guaranteed to converge, unlike ordinary supervised learning where a single loss is minimized over one set of parameters. The equilibrium concept that applies is a Nash equilibrium: a point where neither player can improve unilaterally. Standard convergence guarantees from convex optimization simply do not apply to this non-convex, non-concave minimax setting, which is precisely why alternating gradient descent on GANs can oscillate, cycle, or diverge even when a good equilibrium exists.
What causes mode collapse mechanistically, beyond "the generator gets lazy"?
Mode collapse arises because the generator's non-saturating loss only asks it to fool the current discriminator, not to match the full data density at every step. If finds a small region of image space that currently fools , gradient descent will happily push all of 's probability mass there, since doing so directly minimizes the current-step loss. The discriminator then adapts and learns to reject that region, but by the time it does, may simply relocate its entire mass to a different narrow region rather than spreading out — because spreading out was never explicitly rewarded, only "not being currently caught" was. This chase-and-relocate dynamic can repeat indefinitely without ever converging to full-distribution coverage.
Is the Jensen-Shannon divergence result still considered the "correct" explanation for why GANs work?
It is the correct explanation for the idealized game — with unbounded-capacity networks and a discriminator trained to full optimality at every generator step — but it is widely understood to be a poor description of the actual training dynamics used in practice. Real discriminators are updated with only a few gradient steps between generator updates, never reach the closed-form optimum, and have finite capacity. This gap is exactly why alternative formulations such as the Wasserstein distance were introduced: they provide better-behaved gradients under the finite-step, finite-capacity conditions that actually hold during training, even though the original JS-divergence argument remains the cleanest way to understand why the game has the right answer at its ideal equilibrium.
How is a conditional GAN different from the vanilla GAN described here, and why does it matter for later topics?
A conditional GAN gives both the generator and discriminator access to extra side information (a class label, a segmentation map, or a source image), so the generator learns and the discriminator learns , judging whether is a real image consistent with rather than just realistic in general. This single change transforms unconditional image synthesis into controllable synthesis, which is the direct mechanism behind Image-to-Image Translation (where is a source-domain image and must produce a plausible target-domain counterpart) and behind style-conditioned generation used in Neural Style Transfer pipelines that blend adversarial and perceptual losses.
Why do GANs typically produce sharper images than autoencoder-style generative models trained with pixel-wise losses?
A pixel-wise loss like mean squared error rewards the generator for being close to some plausible real image on average, and because multiple plausible outputs exist for any given latent code or condition, the loss-minimizing strategy is often to output the average of those plausible images, which looks blurry. A discriminator, in contrast, is explicitly trained to detect exactly this kind of blur and texture inconsistency, since real images have sharp high-frequency statistics that averaged images lack. The generator is therefore penalized specifically for hedging, pushing it toward committing to one sharp, plausible mode rather than averaging over many.
What role does the discriminator's capacity play in training stability?
If the discriminator is too powerful relative to the generator (e.g., it converges to near-perfect real/fake classification quickly), it produces almost everywhere, which — even with the non-saturating loss — leaves very little useful gradient signal for , since the discriminator's decision boundary can become extremely sharp with vanishing gradient outside a thin margin. Conversely, if is too weak, it gives poor, noisy feedback that does not meaningfully guide toward realism. Practical stabilization techniques—spectral normalization, gradient penalties, label smoothing, and careful learning-rate balancing—exist specifically to keep the discriminator's power in a productive middle range relative to the generator throughout training.
Can GAN training be said to "converge" in the same sense as supervised learning?
Not in the same well-defined sense. Supervised learning minimizes a single loss and convergence means the loss (and typically validation metrics) stabilizes at a low value. GAN training instead tracks a moving target: as improves, 's task changes, and vice versa, so neither loss curve alone indicates progress — a discriminator loss near (its value when outputs 1/2 everywhere) can indicate either a converged equilibrium or a stuck, uninformative discriminator. Practitioners instead rely on periodic qualitative sample inspection and quantitative diversity/fidelity metrics computed on generated samples, since no single scalar reliably summarizes adversarial convergence the way training loss does for ordinary networks.