Skip to content
E
Educatum

Describe the fundamental components of a Generative Adversarial Network (GAN) and elaborate on the dynamic interplay between its generator and discriminator during the training phase.

Curated by Educatum AI teamLast updated:
Generative Adversarial Networks (GANs)
Direct Answer

A Generative Adversarial Network (GAN) pairs a generator network that maps latent noise z to synthetic samples with a discriminator network that distinguishes real data from generated fakes. Theoretically formulated as a two-player minimax game minimizing Jensen-Shannon divergence, practical GANs typically train the generator with a non-saturating log-likelihood loss to prevent vanishing gradients early in training. Iterative alternating updates drive the generator toward realistic samples while challenging the discriminator to refine its decision boundary.

Study Card: Generative Adversarial Networks (GANs)

Direct Answer

A Generative Adversarial Network (GAN) (Goodfellow et al., 2014) consists of two neural networks trained via adversarial competition:

  • Generator (GG): Maps random latent vectors z∼pz(z)z \sim p_z(z) (e.g., N(0,I)\mathcal{N}(0, I)) to synthetic samples G(z)G(z) approximating the real data distribution pdatap_{\text{data}}.
  • Discriminator (DD): Classifies whether a given sample xx came from pdatap_{\text{data}} (D(x)→1D(x) \to 1) or from the generator pgp_g (D(G(z))→0D(G(z)) \to 0).

In the theoretical two-player zero-sum minimax formulation, DD maximizes classification log-likelihood while GG minimizes it:

min⁡Gmax⁡DV(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_{\text{data}}}[\log D(x)] + \mathbb{E}_{z \sim p_z}[\log(1 - D(G(z)))]

For a fixed generator GG, the Bayes-optimal discriminator is D∗(x)=pdata(x)pdata(x)+pg(x)D^*(x) = \frac{p_{\text{data}}(x)}{p_{\text{data}}(x) + p_g(x)}, reducing the outer objective to 2 DJS(pdata ∥ pg)−log⁡42\,D_{\text{JS}}(p_{\text{data}} \,\|\, p_g) - \log 4. Thus, at equilibrium (pg=pdatap_g = p_{\text{data}}), D∗(x)=12D^*(x) = \frac{1}{2} everywhere.

In practice, minimizing log⁡(1−D(G(z)))\log(1 - D(G(z))) suffers from vanishing gradients early in training when DD easily rejects poor samples (D(G(z))≈0D(G(z)) \approx 0). Consequently, practitioners train GG with the non-saturating objective max⁡GEz[log⁡D(G(z))]\max_G \mathbb{E}_z[\log D(G(z))] (making practical training non-zero-sum while preserving the same fixed point).

Key Terms

  • Generator (GG): Differentiable decoder mapping latent noise z∼pzz \sim p_z to synthetic data G(z)G(z) without requiring an explicit density formula.
  • Discriminator (DD): Binary classifier (or critic in WGANs) estimating whether inputs are real or generated, providing gradients ∇G\nabla_G back through G(z)G(z).
  • Minimax / Non-Saturating Loss: Theoretical zero-sum objective versus practical −log⁡D(G(z))-\log D(G(z)) generator loss that maintains strong gradients early in training.
  • Alternating Optimization: Fixing GG while updating DD for kk steps (freezing gradient flow into GG via .detach()), then fixing DD while updating GG.
  • Jensen-Shannon Divergence (DJSD_{\text{JS}}): Symmetric divergence between pdatap_{\text{data}} and pgp_g minimized at the global minimax equilibrium.

Example

Consider an art forger (GG) and an art authenticator (DD):

  • Early on, GG produces obvious noise, so DD immediately outputs D(G(z))≈0D(G(z)) \approx 0. Under the non-saturating loss −log⁡D(G(z))-\log D(G(z)), GG receives large gradients telling it which pixel/feature adjustments make DD slightly less confident.
  • As GG improves, DD must inspect finer local details (edges, textures, global geometry), which in turn forces GG to match those finer statistics.
  • Because the two players optimize simultaneous non-convex objectives rather than a single static loss, training can oscillate or suffer mode collapse if DD overpowers GG or GG exploits a single blind spot of DD.

Code Implementation

import torch
import torch.nn as nn
import torch.optim as optim


class Generator(nn.Module):
    def __init__(self, latent_dim=16, hidden_dim=64, data_dim=2):
        super().__init__()
        self.net = nn.Sequential(
            nn.Linear(latent_dim, hidden_dim),
            nn.LeakyReLU(0.2, inplace=True),
            nn.Linear(hidden_dim, hidden_dim),
            nn.LeakyReLU(0.2, inplace=True),
            nn.Linear(hidden_dim, data_dim),
        )

    def forward(self, z):
        return self.net(z)


class Discriminator(nn.Module):
    def __init__(self, data_dim=2, hidden_dim=64):
        super().__init__()
        self.net = nn.Sequential(
            nn.Linear(data_dim, hidden_dim),
            nn.LeakyReLU(0.2, inplace=True),
            nn.Linear(hidden_dim, hidden_dim),
            nn.LeakyReLU(0.2, inplace=True),
            nn.Linear(hidden_dim, 1),  # Outputs raw logit for BCEWithLogitsLoss
        )

    def forward(self, x):
        return self.net(x)


def sample_real_bimodal(batch_size):
    centers = torch.tensor([[-2.0, 0.0], [2.0, 0.0]])
    idx = torch.randint(0, 2, (batch_size,))
    return centers[idx] + 0.25 * torch.randn(batch_size, 2)


torch.manual_seed(42)
latent_dim, batch_size = 16, 64
G = Generator(latent_dim=latent_dim)
D = Discriminator()

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_logits = nn.BCEWithLogitsLoss()

for step in range(1, 201):
    real = sample_real_bimodal(batch_size)
    real_labels = torch.ones(batch_size, 1)
    fake_labels = torch.zeros(batch_size, 1)

    # 1. Update Discriminator: detach fake samples so gradients do not flow to G
    z = torch.randn(batch_size, latent_dim)
    fake = G(z).detach()
    d_loss = bce_logits(D(real), real_labels) + bce_logits(D(fake), fake_labels)

    opt_D.zero_grad()
    d_loss.backward()
    opt_D.step()

    # 2. Update Generator using non-saturating loss: -log D(G(z))
    z = torch.randn(batch_size, latent_dim)
    g_loss = bce_logits(D(G(z)), real_labels)

    opt_G.zero_grad()
    g_loss.backward()
    opt_G.step()

    if step in (1, 100, 200):
        print(f"Step {step:3d} | D loss: {d_loss.item():.4f} | G loss: {g_loss.item():.4f}")
  • Variational Autoencoders (VAEs): Likelihood-based latent variable models optimizing an ELBO rather than an adversarial game—more stable to train, though prone to blurrier reconstructions without perceptual/adversarial losses.
  • Mode Collapse: Failure mode where GG maps many zz inputs to a small subset of real modes, sacrificing sample diversity.
  • Evaluation Metrics (FID & IS): Fréchet Inception Distance (FID) and Inception Score (IS) evaluate sample fidelity and diversity in deep feature space.
  • Conditional GANs (cGANs): Condition both G(z,c)G(z, c) and D(x,c)D(x, c) on class labels, text embeddings, or source images (e.g., Pix2Pix).
  • WGAN & Spectral Normalization: Wasserstein distance (WGAN-GP) and spectral normalization constrain DD‘s Lipschitz constant to eliminate gradient vanishing when pdatap_{\text{data}} and pgp_g have disjoint supports.
View all →

Try keywords like RoPE, FlashAttention, DPO, or Blind 75.