GAN Fundamentals
Generative Adversarial Networks (GANs) work like a counterfeiter and a detective locked in an endless game. The Generator creates fake art, while the Discriminator tries to detect forgeries. Through this adversarial competition, both become experts - the Generator learns to create increasingly convincing fakes, and the Discriminator becomes better at spotting them.
GAN Architecture: The Adversarial Game
Reading the Minimax Objective
Generator and discriminator optimise opposite sides of a single binary cross-entropy. The discriminator wants both log D(x) on real images and log(1 - D(G(z))) on fakes to be large. The generator only controls the second term and wants it large too, which means it wants D(G(z)) close to 1. At the theoretical equilibrium the discriminator outputs 0.5 on every input, because it has learned the true distribution and can no longer tell the difference, and the generator loss sits at log(0.5), about -0.693 in natural logs. Nobody trains to that point. Training stops when sample quality peaks, which happens well before equilibrium, and checkpoints are selected by FID rather than by the loss value, since a falling generator loss can equally mean the discriminator has gone weak.
Training Dynamics and Mode Collapse
What the Loss Curves Tell You
GAN losses are not comparable across runs the way cross-entropy is, because two networks are chasing each other. Read the relationship instead of the absolute values. A healthy run shows the discriminator loss oscillating inside a band while the generator loss trends slowly downward over thousands of steps. Three patterns are diagnostic:
- Discriminator loss pinned near zero for a long stretch means it wins too easily and the generator receives almost no gradient. Reduce the discriminator learning rate, add dropout, or take fewer discriminator steps per generator step.
- Generator loss falling while every sample converges on one repeated image is mode collapse: the generator found a single fooling input and stopped exploring the latent space.
- Both losses swinging wildly with no trend usually means the learning rates are too high. The DCGAN setting of 2e-4 with betas of 0.5 and 0.999 is a reliable reset point.
Defeating Mode Collapse
Collapse is a coverage failure: the generator maps too many points of the latent space onto the same output. The fixes all work by penalising that behaviour. Minibatch discrimination lets the discriminator compare samples within a batch, so a hundred near-identical fakes become obvious. Unrolled GANs train the generator against a discriminator that has imagined a few future updates, removing the incentive to exploit a momentary weakness. Feature matching replaces the raw discriminator score with hidden activations, forcing the generator to match statistics rather than a single decision boundary. Two-time-scale updates, where the two networks use different learning rates, cover the remaining instability. One cheap diagnostic is worth automating: draw 64 samples, round each to a perceptual hash, and count distinct results β fewer than 50 unique outputs out of 64 is an early warning.
GAN Zoo: Major Architectures
Choosing a Variant by Constraint
GAN variants exist because each one solved a specific limitation, so pick by what limits you rather than by which paper is newest.
| Constraint | Start with | Why it fits |
|---|---|---|
| One pass per image, real time | DCGAN or a distilled StyleGAN | single forward call, no iterative loop |
| Photoreal faces near 1024 px | StyleGAN3 | alias-free layers and editable style codes |
| Paired translation, edges to photos | Pix2Pix | L1 plus adversarial loss on patches |
| Unpaired translation, horses to zebras | CycleGAN | cycle consistency replaces paired labels |
| Very small labelled set | Conditional GAN with augmentation | augmentation stabilises a weak discriminator |
Two of these choices deserve emphasis. CycleGAN works without paired data because it adds a second constraint: translating to the other domain and back must return the original image, which rules out the degenerate solution where the generator ignores its input. Pix2Pix needs pairs, but its PatchGAN discriminator only judges 70 by 70 regions, which is cheaper and keeps local texture sharp.
Where GANs Still Win
Diffusion models dominate text-to-image, yet GANs keep real deployments where latency or resolution is decisive. Real-time style transfer runs a single-pass network at 30 frames per second, while a diffusion sampler would need 20 to 50 passes per frame. Face editors use StyleGAN latent directions for ageing or expression changes because the latent space is explicit and cheap to traverse. Super-resolution models use an adversarial term to invent plausible high-frequency texture that pure regression losses smooth away. The trade-off is training difficulty: expect restarts, careful discriminator tuning, and weaker text conditioning than diffusion offers in exchange for that speed.
How GANs Learn
Think of GAN training like a poker game between two players. The Generator (bluffer) tries to create convincing fakes, while the Discriminator (detector) tries to spot them. Initially, the bluffer produces obvious fakes that are easily caught. But through thousands of rounds, the bluffer learns subtler tells, and the detector becomes more perceptive. At equilibrium, the bluffer creates art indistinguishable from real pieces, and the detector is reduced to random guessing (50% accuracy).
The adversarial dynamic creates a natural curriculum: as one improves, it forces the other to improve. This self-play mechanism is why GANs can produce remarkably sharp, photorealistic images.
Python Example: Basic GAN
import torch
import torch.nn as nn
class Generator(nn.Module):
def __init__(self, latent_dim=100, img_dim=784):
super().__init__()
self.model = nn.Sequential(
nn.Linear(latent_dim, 256),
nn.LeakyReLU(0.2),
nn.BatchNorm1d(256),
nn.Linear(256, 512),
nn.LeakyReLU(0.2),
nn.BatchNorm1d(512),
nn.Linear(512, img_dim),
nn.Tanh()
)
def forward(self, z):
return self.model(z)
class Discriminator(nn.Module):
def __init__(self, img_dim=784):
super().__init__()
self.model = nn.Sequential(
nn.Linear(img_dim, 512),
nn.LeakyReLU(0.2),
nn.Dropout(0.3),
nn.Linear(512, 256),
nn.LeakyReLU(0.2),
nn.Dropout(0.3),
nn.Linear(256, 1),
nn.Sigmoid()
)
def forward(self, img):
return self.model(img)
# Training loop
criterion = nn.BCELoss()
G = Generator()
D = Discriminator()
opt_G = torch.optim.Adam(G.parameters(), lr=0.0002, betas=(0.5, 0.999))
opt_D = torch.optim.Adam(D.parameters(), lr=0.0002, betas=(0.5, 0.999))
for epoch in range(100):
for real_imgs, _ in dataloader:
batch_size = real_imgs.size(0)
real_labels = torch.ones(batch_size, 1)
fake_labels = torch.zeros(batch_size, 1)
z = torch.randn(batch_size, 100)
fake_imgs = G(z)
D_real = D(real_imgs)
D_fake = D(fake_imgs.detach())
D_loss = criterion(D_real, real_labels) + criterion(D_fake, fake_labels)
opt_D.zero_grad()
D_loss.backward()
opt_D.step()
z = torch.randn(batch_size, 100)
fake_imgs = G(z)
D_fake = D(fake_imgs)
G_loss = criterion(D_fake, real_labels)
opt_G.zero_grad()
G_loss.backward()
opt_G.step()
Hands-on Project: MNIST GAN
import torch
import torch.nn as nn
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize([0.5], [0.5])
])
dataset = datasets.MNIST('./data', train=True, download=True, transform=transform)
dataloader = DataLoader(dataset, batch_size=128, shuffle=True)
latent_dim = 100
G = Generator(latent_dim, 784)
D = Discriminator(784)
# Train for 50 epochs and visualize generated digits
# Save samples every 10 epochs to track improvement
for epoch in range(50):
for batch in dataloader:
imgs = batch[0].view(-1, 784)
# ... (training code from above)
if epoch % 10 == 0:
with torch.no_grad():
z = torch.randn(16, latent_dim)
samples = G(z).view(-1, 1, 28, 28)
save_image(samples, f'generated_epoch_{epoch}.png')
Evaluating GAN Output
Inception Score was the first published metric and is now too easy to game, because it rewards confident classification rather than diversity. FrΓ©chet Inception Distance became the default: extract Inception-v3 features for real and generated sets, fit a Gaussian to each, and measure the FrΓ©chet distance between them. On CIFAR-10 an FID below 3 is strong and on CelebA-HQ mid-single digits is good, but the number only means something next to a fixed reference implementation. Precision and recall for generative models split that single number in two: precision asks whether generated samples look real, recall asks whether they cover the real distribution. Reporting both tells you whether you have a quality problem or a coverage problem, which FID alone cannot distinguish.
Where GAN Training Goes Wrong
Common Mistakes
Stopping when the generator loss looks lowest
Fix: Select checkpoints by FID on a fixed sample set, since a falling generator loss can mean a weak discriminator
Keeping the discriminator far ahead of the generator
Fix: Slow the discriminator, add dropout, or take fewer discriminator steps per generator step
Evaluating a GAN from a handful of cherry-picked seeds
Fix: Score a large fixed sample batch with FID plus precision and recall to separate quality from coverage
Summary
GANs revolutionized generative modeling through adversarial training. The Generator and Discriminator engage in a minimax game that, when balanced, produces remarkably realistic outputs. Key architectures like DCGAN (stable training), StyleGAN (photoreal faces), and CycleGAN (unpaired translation) each address specific challenges. Understanding GAN dynamics is essential for working with modern image generation.
Next: We explore VAEs, which offer a probabilistic approach to generation with smooth, interpretable latent spaces.
Key Takeaways
- The minimax objective is two sides of one cross-entropy: the discriminator separates real from fake while the generator pushes fakes toward the real side
- Losses are only readable as relationships β a pinned discriminator and a falling generator with repeated samples both mean trouble
- Mode collapse is a coverage failure, and minibatch discrimination, feature matching, and unrolled updates each penalise it differently
- Pick the variant by constraint: latency, resolution, paired versus unpaired data, and label budget decide the architecture
- Select checkpoints by FID plus precision and recall rather than by whichever loss happens to look lowest