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 GG and a discriminator DD. The generator GG maps random noise to fake data. The discriminator DD tries to distinguish real data from GG'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 pmodel(x)p_{model}(x) 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.

Key takeaways
  • A GAN pits a generator G(z)G(z) against a discriminator D(x)D(x) in a two-player minimax game.
  • DD is trained as a binary classifier: real data → label 1, generated data → label 0.
  • GG is trained to make DD output values close to 1 on its fakes — it never sees real data directly.
  • At the theoretical optimum, D∗(x)=12D^*(x) = \tfrac{1}{2} everywhere and GG'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.
The core insight

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 Gθ:Z→XG_\theta: \mathcal{Z} \to \mathcal{X} maps a latent noise vector z∼pzz \sim p_z (typically z∼N(0,I)z \sim \mathcal{N}(0, I) or Uniform[−1,1]d\text{Uniform}[-1,1]^d) to a synthetic sample Gθ(z)G_\theta(z) in data space. The discriminator Dϕ:X→[0,1]D_\phi: \mathcal{X} \to [0,1] is a binary classifier that outputs the probability that an input xx came from the real data distribution pdatap_{data} rather than from GG. Crucially, GG never sees real training data. It only receives a gradient signal through DD: the derivative of DD's output with respect to DD's input, backpropagated further through GG's parameters. This is what makes generation implicit — there is no explicit formula for pG(x)p_G(x), the distribution induced by pushing pzp_z through GG. We can sample from pGp_G (run GG forward), but we cannot evaluate its density. The training objective is the minimax game:

min⁡Gmax⁡D  V(D,G)=Ex∼pdata[log⁡D(x)]+Ez∼pz[log⁡(1−D(G(z)))]\min_G \max_D \; V(D, G) = \mathbb{E}_{x \sim p_{data}}[\log D(x)] + \mathbb{E}_{z \sim p_z}[\log(1 - D(G(z)))]

Read this as: DD wants to maximize VV by assigning high probability (close to 1) to real samples and low probability (close to 0) to fakes; GG wants to minimize VV, i.e., make D(G(z))D(G(z)) close to 1 so the second term becomes very negative (log of something near 1 is close to 0, undermining DD). This is a zero-sum game: DD's gain is GG'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 GθG_\theta and DϕD_\phi (typically convolutional networks for images). Choose a noise prior pzp_z. Initialize θ,ϕ\theta, \phi randomly.

Alternating optimization. In each iteration: 1. Sample a minibatch of real data and a minibatch of noise; update DD to increase VV (a few steps, often just one). 2. Sample a fresh minibatch of noise; update GG to decrease VV (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 log⁡(1−D(G(z)))\log(1 - D(G(z))) (whose gradient vanishes when DD is confidently correct, i.e., D(G(z))≈0D(G(z)) \approx 0, early in training), the generator instead maximizes log⁡D(G(z))\log D(G(z)). Both losses share the same fixed point but the non-saturating version supplies much stronger gradients when GG 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:

  • DD's gradient step is ascent on V(D,G)V(D,G), implemented as descent on −V-V, i.e. the standard binary cross-entropy loss with real samples labeled 1 and fake samples labeled 0.
  • During the DD update, gradients must not flow into θ\theta (the fake batch is treated as a constant input to DD); during the GG update, ϕ\phi is held fixed and gradients flow through Dϕ(Gθ(z))D_\phi(G_\theta(z)) back into θ\theta only.
  • The base case is the random initialization: at iteration 0, DD is a coin flip and GG produces noise-like output; the invariant maintained across iterations is that DD is always trained to (approximately) reach its optimum for the current GG before GG is updated — this is what the inner loop of kk steps approximates.
Figure
The adversarial game as a computational loop
noise z ~ p(z) Generator G(z; θ) Discriminator D(x; φ) real data x ~ p_data fake x̂ D(x) ∈ [0,1] real vs fake ∇_θ via backprop through D — updates G to raise D(G(z)) ∇_φ — updates D to separate real from fake

Complexity & correctness

Time complexity per iteration. Let CGC_G and CDC_D be the cost of one forward+backward pass through GG and DD respectively, on a batch of size mm. One full iteration costs O(k⋅(CD))+O(CG+CD)O(k \cdot (C_D)) + O(C_G + C_D) — the discriminator phase runs kk forward/backward passes through DD (plus kk forward passes through GG to generate fakes, though these can be cheap if θ\theta is frozen and reused), and the generator phase runs one forward/backward through both networks. In practice k=1k=1 is common, giving a per-iteration cost of the same order as training an ordinary classifier plus an ordinary regressor jointly: O(CG+CD)O(C_G + C_D) 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. O(∣θ∣+∣ϕ∣+m⋅d)O(|\theta| + |\phi| + m \cdot d) for parameters and the activations of the current minibatch (dimension dd), 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 GG. For any fixed generator, the inner maximization over DD has a clean closed form. Writing pgp_g for the density induced by GG, the value function is

V(D,G)=∫x[pdata(x)log⁡D(x)+pg(x)log⁡(1−D(x))] dx.V(D,G) = \int_x \Big[ p_{data}(x)\log D(x) + p_g(x)\log(1-D(x)) \Big]\, dx.

For each fixed xx, this integrand is of the form alog⁡y+blog⁡(1−y)a \log y + b \log(1-y) with a=pdata(x),b=pg(x)a = p_{data}(x), b = p_g(x), maximized over y∈(0,1)y \in (0,1). Taking the derivative and setting it to zero:

ay−b1−y=0  ⇒  y∗=aa+b.\frac{a}{y} - \frac{b}{1-y} = 0 \;\Rightarrow\; y^* = \frac{a}{a+b}.

So the optimal discriminator for a fixed GG is

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

This matches intuition: where pdatap_{data} dominates pgp_g, D∗D^* is close to 1; where pgp_g dominates, D∗D^* is close to 0; where they're equal, D∗=1/2D^* = 1/2. Substituting DG∗D^*_G back into VV gives the effective generator objective, which algebra shows equals

C(G)=max⁡DV(D,G)=−log⁡4+2⋅JSD(pdata ∥ pg),C(G) = \max_D V(D,G) = -\log 4 + 2\cdot JSD(p_{data} \,\|\, p_g),

where JSDJSD is the Jensen–Shannon divergence, a symmetric, bounded (∈[0,log⁡2]\in [0, \log 2]) divergence between distributions. Since JSD(p∥q)≥0JSD(p\|q) \ge 0 with equality iff p=qp = q, we get C(G)≥−log⁡4C(G) \ge -\log 4 with equality iff pg=pdatap_g = p_{data}. This is the correctness argument: the global minimum of the outer minimization over GG is achieved exactly when the generator's distribution matches the true data distribution, and at that point the optimal discriminator is D∗(x)=1/2D^*(x) = 1/2 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 DD and GG have unlimited capacity and that at every outer step DD is trained fully to its optimum DG∗D^*_G — 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 DD is too strong) is exactly what GAN Training Dynamics and Failure Modes addresses.
  • Because pgp_g is never written explicitly, we cannot directly evaluate JSD(pdata∥pg)JSD(p_{data}\|p_g) 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 pdata=N(5,1)p_{data} = \mathcal{N}(5, 1), and at the current training iteration the generator produces pg=N(3,1)p_g = \mathcal{N}(3, 1) (it has not yet converged). DD is a simple logistic model D(x)=σ(wx+b)D(x) = \sigma(w x + b), currently at w=1.0,b=−4.0w=1.0, b=-4.0. Draw a minibatch (m = 4) — 2 real samples, 2 fake samples:

SampleSourceValue xxD(x)=σ(x−4)D(x) = \sigma(x - 4)Target label
x1x_1real5.20σ(1.20)=0.769\sigma(1.20) = 0.7691
x2x_2real4.80σ(0.80)=0.690\sigma(0.80) = 0.6901
x^1\hat x_1fake (z1z_1)2.90σ(−1.10)=0.250\sigma(-1.10) = 0.2500
x^2\hat x_2fake (z2z_2)3.10σ(−0.90)=0.289\sigma(-0.90) = 0.2890

Discriminator loss (binary cross-entropy, matching −V/m-V/m):

LD=−14[log⁡(0.769)+log⁡(0.690)+log⁡(1−0.250)+log⁡(1−0.289)]L_D = -\tfrac{1}{4}\Big[\log(0.769) + \log(0.690) + \log(1-0.250) + \log(1-0.289)\Big]
=−14[(−0.263)+(−0.371)+(−0.288)+(−0.341)]=1.2634=0.316.= -\tfrac{1}{4}\big[(-0.263) + (-0.371) + (-0.288) + (-0.341)\big] = \tfrac{1.263}{4} = 0.316.

This is much better than the initial coin-flip loss of log⁡2≈0.693\log 2 \approx 0.693, telling us DD has already learned to separate the two clusters (centered at 3 vs 5) reasonably well. Backpropagating ∂LD/∂w,∂LD/∂b\partial L_D/\partial w, \partial L_D/\partial b and taking a gradient step increases ww and adjusts bb so the decision boundary sharpens around x≈4x \approx 4.

Generator loss (non-saturating). Using the same DD (now momentarily frozen) on the fake batch only:

LG=−12[log⁡(0.250)+log⁡(0.289)]=−12[(−1.386)+(−1.241)]=1.314.L_G = -\tfrac{1}{2}\big[\log(0.250) + \log(0.289)\big] = -\tfrac{1}{2}\big[(-1.386) + (-1.241)\big] = 1.314.

The gradient ∂LG/∂θ\partial L_G/\partial \theta flows backward through DD's logit at x^1,x^2\hat x_1, \hat x_2 (pushing D(x^)D(\hat x) toward 1, i.e., pushing the logit x^−4\hat x - 4 upward) and then through Gθ(z)G_\theta(z), nudging θ\theta so that future samples land further to the right — directly toward the real cluster at mean 5. Repeating this alternation over many iterations moves pgp_g's mean from 3 toward 5 and shrinks the gap the discriminator can exploit, exactly as the JSD argument predicts: as pg→pdatap_g \to p_{data}, DD's achievable accuracy collapses toward 50%.

Contrast with a trivial case. Note this example is deliberately non-symmetric: pg≠pdatap_g \ne p_{data} initially, DD is not at 50% accuracy, and the two loss values (0.3160.316 vs 1.3141.314) 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

PitfallWhy it happensFix / mitigation
Vanishing generator gradientUsing log⁡(1−D(G(z)))\log(1-D(G(z))) when DD is confidently correct saturates the log near 0 slopeUse the non-saturating loss −log⁡D(G(z))-\log D(G(z))
Mode collapseGG finds one mode of pdatap_{data} that fools DD and stops exploring; the minimax game has no incentive for diversity per seMinibatch discrimination, unrolled GANs, diversity-promoting losses (previewed in failure-modes article)
Discriminator too strong, too earlyIf kk is large or DD overfits, D(G(z))≈0D(G(z)) \approx 0 everywhere, gradient to GG vanishesBalance DD/GG capacity and steps; label smoothing; instance noise
Treating DD's loss as a progress metricDD's loss does not monotonically indicate sample quality since both networks moveUse held-out sample quality metrics (FID, human eval), not just the loss curve
Non-convergent oscillationSimultaneous or alternating gradient descent on a minimax objective can cycle indefinitely, even near equilibriumTwo-timescale update rules, gradient penalty, spectral normalization
Forgetting to detach fake samples during DD's updateBackpropagating LDL_D naively can also update θ\theta if the fake batch graph isn't cutStop gradients into GG during the discriminator phase

Pioneers & history

Origins · 1 minIan J. Goodfellow and how this was discovered
IJ
Ian J. Goodfellow
1985–present · Deep learning, Google Brain / OpenAI / Apple, formulated the GAN minimax framework in 2014

History
2014
— Goodfellow et al. introduce Generative Adversarial Networks, proving the JSD equivalence at equilibrium.
2015
— DCGAN (Radford, Metz, Chintala) stabilizes training with convolutional architectural guidelines.
2016
— Conditional and auxiliary-classifier GANs extend the framework to controllable, labeled generation.
2017
— Wasserstein GAN reframes the objective around Earth-Mover distance to address vanishing-gradient instability.
2018–2019
— StyleGAN and BigGAN scale GANs to high-resolution, high-fidelity photorealistic image synthesis.

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 pgp_g, the distribution induced by pushing noise through the generator, is never available in closed form — we can only sample from it by running GG 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 pdata/(pdata+pg)p_{data}/(p_{data}+p_g) 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 DD loss can mean DD is improving, or that GG 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 zz is the source of randomness that lets a deterministic function GθG_\theta produce a whole distribution of outputs rather than a single point. Without stochastic input, GθG_\theta would be a fixed deterministic map and could only ever produce one output per training configuration — useless for modeling a diverse data distribution. Sampling zz 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 pgp_g comes entirely from the nonlinearity of GθG_\theta, 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 V(D,G)V(D,G): DD maximizes it, GG 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 DD steps (small kk) means DD is far from its optimum for the current GG, so the generator's gradient (which depends on DD) is a poor approximation of the theoretically justified gradient. Too many DD steps (large kk) risks DD overfitting or becoming near-perfect, which saturates the generator's gradient toward zero, especially with the original saturating loss. In practice k=1k=1 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 GG requires the sampling step from GG's output to DD'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.

Before this

Where this leads