Generative Adversarial Networks (GANs) - Fundamentals
Generative Adversarial Networks (GANs) - Fundamentals
Generative Adversarial Networks (GANs) are a family of generative models trained via a two-player game between a generator (G) and a discriminator/critic (D). GANs learn to synthesize realistic samples by matching the data distribution through adversarial training.
What are GANs?
- Generator (G): Maps random noise $z \sim p(z)$ to a synthetic sample $x_g = G(z)$.
- Discriminator/Critic (D): Scores inputs as real vs. fake (probability for vanilla GANs, real-valued score for WGAN).
- Goal: Learn $p_g$ such that $p_g \approx p_{data}$.
Vanilla GAN Objective (JS-divergence view)
Minimax value function (Goodfellow et al., 2014):
\[\min_G \max_D \; \mathbb{E}_{x \sim p_{data}}[\log D(x)] + \mathbb{E}_{z \sim p(z)}[\log(1 - D(G(z)))] .\]In practice, use the non-saturating generator loss to avoid vanishing gradients:
\[\max_D \; \mathbb{E}_{x}[\log D(x)] + \mathbb{E}_{z}[\log(1 - D(G(z)))], \quad \min_G \; \mathbb{E}_{z}[ -\log D(G(z)) ].\]At the optimum $D^*(x) = \tfrac{p_{data}(x)}{p_{data}(x) + p_g(x)}$, the game minimizes the Jensen–Shannon divergence between $p_{data}$ and $p_g$.
Core Architectures
- DCGAN: Convolutional G/D, strided convs and transposed convs, batch norm in G, avoid fully-connected bottlenecks, use ReLU in G (tanh output), LeakyReLU in D.
- Conditional GAN (cGAN/AC-GAN): Condition on class labels or attributes (concatenate/embed labels to inputs; D may also predict class).
- Image-to-Image (Pix2Pix/CycleGAN): Paired (Pix2Pix) or unpaired (CycleGAN) domain translation using adversarial + reconstruction/cycle losses.
- StyleGAN/StyleGAN2/3: Style-based generator with per-layer noise, adaptive instance norm; state-of-the-art image synthesis and ADA for limited data.
Stabilization Techniques (Practical Tips)
- Non-saturating loss for G; batch norm in G, spectral norm in D.
- TTUR: Different LRs (e.g., D: 2–4x G), Adam $\beta_1=0.0$ or 0.5, $\beta_2=0.9$ or 0.999.
- Label smoothing (one-sided): Real labels 0.9 instead of 1.0; occasional label flips can regularize.
- Feature matching / gradient penalty / instance noise: Reduce overfitting and sharpen gradients.
- Balanced updates: Often 1–5 D steps per G step; monitor for discriminator overpowering.
- Data augmentation: ADA (adaptive discriminator augmentation) for small datasets; flips, crops, color jitter.
Wasserstein GAN (WGAN, WGAN-GP)
Replace the JS objective with an approximation of the Earth Mover (Wasserstein-1) distance. Use a 1-Lipschitz critic (no sigmoid):
\[\max_D \; \mathbb{E}_{x \sim p_{data}}[D(x)] - \mathbb{E}_{z \sim p(z)}[D(G(z))], \quad \min_G \; -\mathbb{E}_{z}[D(G(z))].\]- Lipschitz constraint: Weight clipping (WGAN) or gradient penalty (WGAN-GP):
- Advantages: More stable training and meaningful loss curves that correlate with sample quality.
Common Failure Modes and Fixes
- Mode collapse: Generator produces limited variety.
- Fixes: Mini-batch discrimination, unrolled GANs, gradient penalties, stronger augmentations, WGAN-GP, feature matching.
- Vanishing/exploding gradients:
- Fixes: Non-saturating loss, spectral normalization, gradient clipping, balanced updates.
- Discriminator overpowering:
- Fixes: Reduce D steps/LR, increase G capacity, apply label smoothing/noise.
Evaluation Metrics
- Inception Score (IS): Measures image quality and diversity (can be gamed by artifacts).
- Fréchet Inception Distance (FID): Distance between real/fake feature distributions (lower is better; widely used).
- KID: Polynomial MMD; unbiased alternative to FID.
- Precision & Recall (PRD): Separately assess fidelity and diversity.
- PPL (Perceptual Path Length): Latent smoothness (StyleGAN).
Minimal PyTorch Training Sketch (Non-saturating GAN)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import torch
from torch import nn, optim
class Generator(nn.Module):
def __init__(self, z_dim=128, img_dim=3*64*64):
super().__init__()
self.net = nn.Sequential(
nn.Linear(z_dim, 1024), nn.ReLU(True),
nn.Linear(1024, 4*4*256), nn.ReLU(True),
# Replace with ConvTranspose blocks for images in practice
nn.Linear(4*4*256, img_dim), nn.Tanh()
)
def forward(self, z):
return self.net(z)
class Discriminator(nn.Module):
def __init__(self, img_dim=3*64*64):
super().__init__()
self.net = nn.Sequential(
nn.Linear(img_dim, 1024), nn.LeakyReLU(0.2, True),
nn.Linear(1024, 256), nn.LeakyReLU(0.2, True),
nn.Linear(256, 1), nn.Sigmoid()
)
def forward(self, x):
return self.net(x).view(-1)
z_dim, img_dim = 128, 3*64*64
G, D = Generator(z_dim, img_dim), Discriminator(img_dim)
opt_G = optim.Adam(G.parameters(), lr=2e-4, betas=(0.5, 0.999))
opt_D = optim.Adam(D.parameters(), lr=2e-4, betas=(0.5, 0.999))
bce = nn.BCELoss()
def train_step(real):
B = real.size(0)
real = real.view(B, -1)
valid = torch.ones(B)
fake_lbl = torch.zeros(B)
# 1) Update D
z = torch.randn(B, z_dim)
with torch.no_grad():
fake = G(z)
d_real = D(real)
d_fake = D(fake)
loss_D = bce(d_real, valid) + bce(d_fake, fake_lbl)
opt_D.zero_grad(); loss_D.backward(); opt_D.step()
# 2) Update G (non-saturating)
z = torch.randn(B, z_dim)
fake = G(z)
d_fake = D(fake)
loss_G = bce(d_fake, valid)
opt_G.zero_grad(); loss_G.backward(); opt_G.step()
return loss_D.item(), loss_G.item()
Notes:
- Replace MLPs with DCGAN-style conv blocks for images.
- Consider spectral norm on D and instance/batch norm on G.
- For WGAN-GP, remove sigmoid, use linear critic and gradient penalty.
Practical Recipe
- Start with DCGAN on 64×64 images, z_dim=128, Adam (2e-4, betas 0.5/0.999).
- Use non-saturating loss for G, 1–2 D steps per G step.
- Add augmentations (ADA) for small datasets.
- Track FID over a validation set; keep checkpoints with best FID.
Further Reading
- Generative Adversarial Nets (Goodfellow et al., 2014)
- Improved Techniques for Training GANs (Salimans et al., 2016)
- Wasserstein GAN (Arjovsky et al., 2017) & WGAN-GP (Gulrajani et al., 2017)
- Spectral Normalization for GANs (Miyato et al., 2018)
- StyleGAN/StyleGAN2/StyleGAN3 (Karras et al., 2019–2021)
This post is licensed under CC BY 4.0 by the author.