Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

~8 min readNeurIPS 2014

GANs,
explained.

Teaching a machine to recognize a cat is one thing. Teaching it to imagine a new cat that never existed is another entirely. In 2014, a single, almost mischievous idea cracked it open: pit two networks against each other — a forger and a fraud detective — and let their arms race do the teaching. Neither is ever told what a good image looks like. They discover it by trying to beat each other.

The delta

What changes against the VAE: the loss function is learned

Rung 1's blurriness comes from a hand-written loss — a per-pixel comparison that does not know what makes an image look real, so it rewards the average. This rung's change is to stop writing the loss and train a network to be the loss.

Two networks play a game. A generator maps noise to images; a discriminator tries to tell its output from real data. The generator's objective is to fool the discriminator, and the discriminator's is not to be fooled, so as the generator improves the critic sharpens, and the target keeps moving. Nothing here computes a likelihood or a pixel distance at all.

The consequence, stated in rung 1's units, is sharpness. There is no averaging of plausible outputs, because a blurred image is trivially identifiable as fake and the discriminator punishes it hard — the generator is pushed toward images that live on the data manifold rather than toward the mean of several. That was a large, visible jump in sample quality, and it is why this family dominated image generation for years despite everything in the next block.

01

The generation problem

Discriminative models — "is this a cat or a dog?" — had a clear training signal: a label to match. Generative models face a harder question with no obvious signal. To create a realistic face, the model must capture the entire probability distribution of faces. But how do you write a loss for "looks like a plausible human"? Pixel-by-pixel error famously produces blurry averages, not crisp, convincing images.

Before GANs, generative models leaned on tractable-but-limited math or heavy approximations, and their samples looked it. The field needed a training signal for realism that didn't require anyone to hand-define what "realistic" means. GANs supplied exactly that — by learning the critic.

02

The adversarial idea

The paper's analogy is perfect: a counterfeiter and a detective. The counterfeiter prints fake money and tries to pass it; the detective inspects bills and tries to spot fakes. Each pushes the other to improve. As the detective sharpens, the counterfeiter must forge better; as the forgeries improve, the detective must look closer. Run this arms race long enough and the fakes become indistinguishable from real currency.

GANs make both roles neural networks and let them co-train. Nobody hands the forger a rule for "realistic." The realism signal comes entirely from a second network that is simultaneously learning to detect fakes. The critic is not fixed — it's an adversary that evolves.

03

The two players

The Generator (G) takes a vector of random noise and transforms it into a sample — say, an image. The noise is its source of variety; different noise vectors should yield different outputs. The Discriminator (D) takes a sample and outputs a probability: how likely is this real rather than generated?

The forger vs. the detective
Generator Gnoise → fake sample
vs
Discriminator Dsample → real? fake?

Their goals are exactly opposed. G wants D to label its fakes as real; D wants to correctly flag them as fake. This direct opposition is the engine of learning — one network's success is the other's failure, so both are relentlessly pressured to improve.

04

The minimax game

Formally, it's a two-player minimax game with one value function they fight over:

minG maxD  𝔼x∼data[log D(x)] + 𝔼z∼noise[log(1 − D(G(z)))]

Read it as a tug of war. D wants to maximize this: push D(x) toward 1 for real data and D(G(z)) toward 0 for fakes. G wants to minimize it: make D(G(z)) close to 1 so the fakes are believed. The theoretical sweet spot — the equilibrium — is when G's samples perfectly match the real data distribution and D is reduced to a coin flip, outputting 0.5 everywhere because it genuinely can't tell.

This isn't just intuition — it's a closed form. For any fixed generator, the best possible discriminator is a simple function of the density ratio, p_data/(p_data + p_g), and plugging it back in pins down the game's value at its lowest point when the two distributions coincide:

−log 4 ≈ −1.386 is the number a perfectly-fooled game settles on — you can compute it below.

Worth knowing

In practice, the log(1 − D(G(z))) term gives the generator weak gradients early on when its fakes are obvious. A common fix is the "non-saturating" trick: train G to maximize log D(G(z)) instead — same intent, stronger learning signal.

05

Training the duel

Training alternates. Freeze G and update D: show it a batch of real samples and a batch of G's fakes, and improve its ability to tell them apart. Then freeze D and update G: generate fakes, run them through D, and nudge G's weights so D is more fooled. Repeat, back and forth, for many rounds.

The elegant part is where G's gradient comes from: it flows through the discriminator. G never sees a real image directly or gets told "make this pixel darker." It only receives the signal "D would find this more convincing if you changed in this direction." Realism is taught entirely by an adversary — a genuinely new kind of training signal.

06

Where the duel goes wrong

Because two networks optimize in opposition, GAN training is a balancing act, not a smooth descent. If D gets too good too fast, it rejects everything and G's gradients vanish; if G finds a cheap exploit, D can't keep up. Training can oscillate forever instead of converging.

The signature failure is mode collapse: G discovers one (or a few) outputs that reliably fool D and produces only those — one flawless face, endlessly — ignoring the rest of the data's diversity. It "wins" the game while failing the actual goal. Taming these pathologies spawned a whole research industry (DCGAN, WGAN, spectral normalization, and more).

07

The limits

Beyond instability and mode collapse, vanilla GANs offer no clean number to track — there's no single loss that reliably says "getting better," which makes them hard to monitor and tune. And there's no built-in likelihood, so you can't ask a GAN how probable a given real image is under its model.

For high-fidelity image generation, diffusion models ultimately overtook GANs: they train with a stable regression loss, don't collapse, and cover the data distribution more faithfully — at the cost of slow, multi-step sampling. GANs' single-pass speed keeps them relevant where latency matters, but they are no longer the default for state-of-the-art quality.

08

Why it still matters

GANs proved machines could generate, convincingly, and they defined the modern generative era's ambitions — photorealistic faces (StyleGAN), image-to-image translation (pix2pix, CycleGAN), super-resolution, and the whole cultural moment of "deepfakes." For years, GAN was almost synonymous with AI image generation.

Their deepest contribution is conceptual: adversarial training. The idea that you can learn by pitting networks against each other — one proposing, one critiquing — echoes far beyond images, into robustness research, domain adaptation, and the reward-model critics of RLHF. GANs may have been overtaken for image quality, but adversarial thinking is now part of the field's DNA.

Read next

Contrast with DDPM, the diffusion model that dethroned GANs for image quality by trading the adversarial game for stable, iterative denoising.

How it works

How Goodfellow et al. trained the first GANs, step by step

The paper does three things: it defines a two-player game, proves what the game converges to under idealized conditions, and gives the minibatch training loop it actually ran. The loop departs from the theory in two ways that matter.

noise z ~ pz generator G fake G(z) discriminator D(x) = P(real) data x ~ pdata real x k = 1 in the experiments D step, k times raise log D(x) + log(1 − D(G(z))) D* = pd / (pd + pg) C(G) = 2·JSD − log 4 G step, once raise log D(G(z)) backprop through D the generator's only gradient comes through D
The loop the paper ran. Only the discriminator touches real data; the generator learns entirely from gradients passed back through it. The middle box is the theory, which assumes D is optimal before every generator step, something k = 1 never delivers.
  1. Define the players. A generator G(z; θg) maps a noise vector drawn from a fixed prior pz to a sample. A discriminator D(x; θd) outputs one number, the probability that x came from the data. Both were multilayer perceptrons: the generator used a mix of rectified linear and sigmoid units, the discriminator used maxout units and was trained with dropout. Noise entered only at the generator's bottom layer.
  2. Train the discriminator for k steps. Sample m noise vectors and m real examples, then ascend the gradient of (1/m) Σ [log D(xi) + log(1 − D(G(zi)))]. This is ordinary logistic regression: real examples labeled 1, generated ones labeled 0, binary cross-entropy.
  3. Train the generator for one step. Sample m fresh noise vectors and descend the gradient of (1/m) Σ log(1 − D(G(zi))). The gradient reaches θg only by backpropagating through D, so the generator never sees a training image.
  4. Swap in the non-saturating loss. Early on, D rejects samples easily, D(G(z)) is near zero and log(1 − D(G(z))) is flat there. The paper therefore trains G to maximize log D(G(z)) instead, which keeps the same fixed point and gives much stronger gradients while G is losing.
  5. Repeat, with k = 1. The loop allows several discriminator steps per generator step; the experiments used k = 1, the cheapest option, with momentum-based updates.
  6. Sample. One forward pass of G per sample, with no Markov chain and no inference network, so successive samples are independent.

What the theory guarantees, and what it assumes

The analysis works in the space of distributions, not network weights. For a fixed G the best discriminator has a closed form, and substituting it turns the game into minimizing a Jensen–Shannon divergence between the data and the generator's distribution pg, whose only minimum is pg = pdata. A second result says that if D reaches its optimum after every change to G, and pg is improved against it, pg converges to pdata, because the criterion is convex in pg.

The loop breaks both assumptions. With k = 1 the discriminator is never optimal, only one step closer. And θg parameterizes a neural network, where the objective is not convex even though it is convex in pg. The authors say the guarantee does not carry over and argue that multilayer perceptrons work well enough in practice to use anyway.

The failure the paper already names

Among its listed disadvantages, the paper warns that G must not be trained too much without updating D, or it can map many values of z to the same x and lose the diversity needed to model the data. The authors called this the Helvetica scenario; the field later named it mode collapse.

Why the divergence itself causes trouble

Arjovsky and Bottou (2017) showed that when the data and generator distributions lie on low-dimensional sets that barely overlap, as natural images and early samples do, a near-perfect discriminator exists, the Jensen–Shannon divergence sits at its maximum and the original generator loss gives vanishing gradients. That analysis motivated Wasserstein GAN, which swaps the divergence for an earth-mover distance whose gradient stays informative when the two distributions do not overlap.

The math

The optimal discriminator and where 2·JSD − log 4 comes from

V(D, G) = ∫ [ pdata(x) log D(x) + pg(x) log(1 − D(x)) ] dx
a log y + b log(1 − y) peaks at y = a / (a + b) ⟹ D*G(x) = pdata(x) / ( pdata(x) + pg(x) )
C(G) = maxD V(D, G) = −log 4 + KL(pdata ‖ m) + KL(pg ‖ m) = −log 4 + 2 · JSD(pdata ‖ pg), with m = (pdata + pg) / 2
  • pg — the distribution of G(z). Rewriting the noise expectation as one over x is what lets D be optimized separately at every point.
  • D*G — a function of the density ratio r = pdata/pg, namely r/(1 + r), always between 0 and 1.
  • m — the 50/50 mixture of data and generator. Turning each denominator into 2m pulls out a factor of ½ twice, which is the −log 4.
  • JSD — symmetric, bounded between 0 and log 2.

At the good extreme, pg = pdata gives D* = ½ everywhere, JSD = 0 and C(G) = −log 4, the global minimum. At the bad extreme, disjoint supports give JSD = log 2 and C(G) = 0 for every such generator, with D* equal to 1 on real data and 0 on samples. Small moves of G leave the criterion unchanged, so it offers no direction toward the data.

The evidence

What the 2014 experiments measured, and how

Three datasets: MNIST, the Toronto Face Database (TFD) and CIFAR-10. A GAN has no likelihood to report, so the paper estimated one indirectly: draw samples from G, fit a Gaussian Parzen window (a kernel density estimate) to them, choose the kernel width by cross-validation on a validation set, and report the mean log-likelihood of test data under that density. Higher is better.

ModelMNISTTFD
Deep belief network138 ± 21909 ± 66
Stacked contractive autoencoder121 ± 1.62110 ± 50
Deep generative stochastic network214 ± 1.11890 ± 29
Adversarial nets225 ± 22057 ± 26

The table does not show a clean sweep. On TFD the stacked contractive autoencoder scores higher than the adversarial net. The authors also describe the Parzen estimator as high-variance and weak in high-dimensional spaces, the best available method rather than a good one, and Theis, van den Oord and Bethge (2016) later showed such estimates can be badly misleading about true likelihood. These numbers say little about visual quality.

The stronger evidence was qualitative. The samples shown are fair random draws, not hand-picked, and independent because no Markov chain is involved. CIFAR-10 got samples from a fully connected model and from one with a convolutional discriminator and a deconvolutional generator, but no number.

The evaluation that replaced Parzen windows came later: the Inception Score (Salimans and colleagues, 2016), then the Fréchet Inception Distance (Heusel and colleagues, 2017), which compares the mean and covariance of Inception-network features of real and generated images. Architecture caught up too. DCGAN (Radford, Metz and Chintala, 2015) made convolutional GANs train reliably, and StyleGAN (Karras and colleagues, 2019) pushed face synthesis to photographic quality as measured by FID.

Trade-offs

What a GAN costs to train and run, against diffusion and VAEs

The running cost is the selling point: a sample is one generator forward pass, where pixel diffusion needs tens to a thousand sequential denoiser passes. The training cost is where it is paid back. Every step runs two networks, the generator's update backpropagates through the discriminator as well, and both carry optimizer state. The larger cost is engineering time: with no loss that tracks progress, choosing learning rates, the balance between the two players and when to stop takes many runs judged by eye or by FID.

GANDiffusionVAE
Passes per sample1Tens to 1,0001
Networks trained2, against each other12, jointly on one loss
Coverage of the dataCan drop modesCovers itCovers it, softly
Progress signalNone reliableFalling regression lossFalling bound
Encoder for real imagesNone; needs inversionApproximate, via deterministic samplingBuilt in

The trade in one line: a GAN buys sharpness and single-pass latency with instability and incomplete coverage. That makes its loss attractive as a component where latency or texture matters, and makes it a poor default for a broad, diverse generator.

In the wild

Where this shows up in production

The standalone image GAN is rarely the default now; the adversarial loss is everywhere as a part.

  • Inside autoencoders and codecs

    The autoencoder behind latent diffusion is trained with a patch-based adversarial loss, as VQGAN was, so decoded images stay sharp. Neural audio codecs such as SoundStream and EnCodec also train against discriminators.

  • Speech vocoders and super-resolution

    HiFi-GAN turns spectrograms into waveforms in one fast pass, the latency profile a GAN is good at. ESRGAN and Real-ESRGAN are GAN-trained image upscalers.

  • Few-step diffusion

    Adversarial Diffusion Distillation, the method behind SDXL Turbo, adds a discriminator to distil a diffusion model into one to four steps: the critic restores the sharpness that aggressive step-cutting loses.

  • In interviews

    Expect to derive the optimal discriminator, explain why the generator's gradient vanishes and how the non-saturating loss helps, describe mode collapse, and say why FID replaced likelihood estimates for evaluation.

Since then

What the authors admit, and what happened next

The instability is intrinsic and acknowledged. The training target is a saddle point of a two-player game, not the minimum of a function — so there is no loss curve that reliably goes down and no reliable signal that training is progressing or finished. Practitioners learned to judge by looking at samples, which is a real statement about the state of the art.

Mode collapse is the second failure and it follows from the objective rather than from a bug: fooling the discriminator does not require covering the data distribution, so a generator that finds one convincing output and produces variations of it is doing well by its own loss while ignoring most of the data. And because no likelihood is computed, there is no principled way to evaluate the result — the metrics the field settled on are proxies with known pathologies, which made progress hard to measure.

How it held up: it lost the main event. Rung 4 matched and exceeded it on quality while training stably and covering the distribution, and the family stopped being the default. What survived is the adversarial loss as a component: it is still the best available tool for "make this look real rather than plausible on average", which is why it appears inside the decoder of the autoencoder at rung 7 and in super-resolution. The idea of a learned loss outlived the architecture that introduced it.

SOLVE IT YOURSELF

Find the equilibrium — and catch mode collapse

The minimax game has a closed-form answer, and you can compute it over a tiny 4-mode "image" distribution. This builds the optimal discriminator D* for three generators — a bad one, the perfect one, and a mode-collapsed one — and evaluates the game. Watch the matched generator drive D* to 0.5 everywhere and the value to exactly −log 4 (the theorem), while the collapsed generator gets caught red-handed: D* = 1 on every mode it abandoned. Change the distributions and re-run.

YOUR TASK

Write the body of value. Everything else in the file is already written; this is the function the paper is about. Press ▶ Run to check it against the 5 assertions below — they start red.

WHAT IT HAS TO SATISFY — 5 ASSERTIONS
  1. The optimal discriminator is p_data / (p_data + p_g)
  2. A perfect generator makes D a coin flip everywhere
  3. The equilibrium value equals -log 4
  4. A matched generator gives the discriminator its worst (lowest) value
  5. Mode collapse is caught: D* = 1 on an abandoned mode
CPython · WebAssembly
Questions

Questions people ask about GANs

How do you prove that the GAN objective minimizes the Jensen–Shannon divergence?

Fix the generator and write the value function as an integral over x of p_data(x) log D(x) + p_g(x) log(1 − D(x)), using the fact that G(z) has distribution p_g. For each x, a log y + b log(1 − y) peaks at y = a/(a+b), so the optimal discriminator is p_data/(p_data + p_g). Substitute it back. Each term becomes a log-ratio against the mixture m = (p_data + p_g)/2 once a factor of one half is pulled out of each, which contributes −log 2 twice. What remains is KL(p_data ‖ m) + KL(p_g ‖ m), which is twice the Jensen–Shannon divergence. So a generator facing an optimal discriminator minimizes 2·JSD − log 4, whose minimum of −log 4 occurs exactly when p_g = p_data.

Why do GAN generator gradients vanish when the discriminator gets too good?

With the original minimax loss the generator minimizes log(1 − D(G(z))). If D confidently rejects samples, D(G(z)) is near zero and that function is nearly flat, so the gradient through the discriminator's sigmoid is roughly D(G(z)) itself, close to zero. There is a deeper version: real images and early generator samples occupy thin, low-dimensional sets that barely overlap, so a near-perfect discriminator exists, the Jensen–Shannon divergence sits at its maximum of log 2, and small changes to G do not change it. Arjovsky and Bottou analyzed this in 2017. The paper's non-saturating loss, maximizing log D(G(z)), fixes the first problem but not the second, which is what motivated Wasserstein GAN.

What is the difference between a GAN and a WGAN?

Both train a generator against a learned critic, but they minimize different distances. The original GAN, with an optimal discriminator, minimizes a Jensen–Shannon divergence, which saturates when the data and generated distributions do not overlap. Wasserstein GAN, from Arjovsky, Chintala and Bottou in 2017, minimizes the earth-mover (Wasserstein-1) distance, written in a dual form as the largest difference in a critic's average score between real and generated samples, over critics that are 1-Lipschitz. That distance keeps shrinking smoothly as the distributions approach each other, even without overlap, so the critic can be trained hard without starving the generator, and its value tracks sample quality better. The original WGAN clipped weights to enforce the constraint; WGAN-GP replaced clipping with a gradient penalty.

How many discriminator steps per generator step did the original GAN paper use?

The training loop allows k discriminator updates for each generator update, because the convergence argument wants the discriminator near its optimum whenever the generator moves. In the experiments the authors used k = 1, the least expensive choice, with momentum-based minibatch updates. So the theory's assumption of an optimal discriminator never holds in practice: each discriminator is one step from the previous one, chasing a moving generator. Later practice varied. WGAN used five critic steps per generator step because its critic is meant to approximate a distance well, while many standard GAN recipes stayed at one step each and balanced the two networks through separate learning rates instead.

How did the original GAN paper evaluate its samples, and why did the field switch to FID?

It fitted a Gaussian Parzen window to samples from the generator and reported the log-likelihood of held-out test data under that kernel density, with the kernel width chosen on a validation set. On MNIST that gave 225 ± 2, ahead of the deep belief network and stacked contractive autoencoder baselines; on the Toronto Face Database it gave 2057 ± 26, behind the stacked contractive autoencoder's 2110. The authors themselves called the estimator high-variance and weak in high dimensions. Fréchet Inception Distance, introduced in 2017, instead fits Gaussians to Inception-network features of real and generated images and measures the distance between them, which tracks visual quality and diversity far better, although it has biases of its own.

Does the non-saturating GAN loss still minimize the Jensen–Shannon divergence?

No, although it keeps the same fixed point. The paper introduced maximizing log D(G(z)) purely for stronger early gradients and noted that the equilibrium is unchanged. Arjovsky and Bottou later worked out what the generator then follows when the discriminator is optimal: a reverse KL divergence from the generator to the data, minus twice the Jensen–Shannon divergence. Reverse KL heavily penalizes putting mass where the data has none but barely penalizes missing whole modes, and the negative JSD term pushes the two distributions apart, which helps explain why practical GANs drop modes rather than cover the data. The loss most people train is therefore not the one the convergence proof describes.

Check yourself

4 questions to test what you just read

Work each one out before you open it — a number, a prediction or a reason, not a definition. Producing the answer is what makes it stick. Your progress is kept on this device.

At a point where p_data(x) = 0.3 and p_g(x) = 0.1, what does the optimal discriminator output, and what does it output once the generator has matched the data there?

Show answer

D* = 0.3 / (0.3 + 0.1) = 0.75, which is the density ratio 3 mapped through r/(1 + r). Once pg = pdata at that point the ratio is 1 and D* = 0.5, a coin flip.

If the data and generator distributions have disjoint supports, what is C(G), and why does the generator get no learning signal from it?

Show answer

For disjoint supports JSD = log 2, so C(G) = −log 4 + 2 log 2 = 0, the same for every generator in that situation. The optimal D is 1 on real data and 0 on samples, and C(G) does not change as G moves, so the criterion points nowhere.

With D(G(z)) = 0.01, how do the saturating loss log(1 − D) and the non-saturating loss −log D compare in their gradient with respect to the discriminator’s logit?

Show answer

With D = σ(a): ∂/∂a log(1 − σ(a)) = −σ(a) = −0.01, while ∂/∂a [−log σ(a)] = −(1 − σ(a)) = −0.99. Both push the logit up when minimized, but the non-saturating loss is about 99× stronger exactly when the generator is losing badly.

Why does the training loop with k = 1 fall outside the paper’s convergence guarantee?

Show answer

The guarantee assumes D reaches D*G after every change to G, and that pg itself is updated, where the criterion is convex. With k = 1, D takes one gradient step toward a moving target, and G changes network weights θg, where the objective is not convex. Neither condition holds, so the result says nothing about whether this loop converges.

Where this sits

Generating pixels

Ten papers from the first latent-variable generator to video and real-time 3D. The diffusion half is strictly cumulative — each rung removes a cost the last one paid.

  1. 1VAE2014
  2. 2GANs2014
  3. 3VQ-VAE2017
  4. 4DDPM2020
  5. 5DDIM2021
  6. 6Classifier-Free Guidance2021
  7. 7Latent Diffusion2022
  8. 8Sora2024
  9. 9NeRF2020
  10. 103D Gaussian Splatting2023

All 110 papers, in 19 ladders →

Finished this one? 0 / 110 Paper Breakdowns done
NextVQ-VAE Next on the “Generating pixels” ladder · rung 3 of 10

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Paper Breakdowns