MODULE 40: GENERATIVE ADVERSARIAL NETWORKS (GANs — DCGAN, WGAN-GP, STYLEGAN & PIX2PIX)

Master adversarial generative modeling and image-to-image synthesis in PyTorch. Engineer two-player minimax training loops, DCGAN transposed-convolution architectures, Wasserstein GAN with Gradient Penalty (WGAN-GP), Spectral Normalization, Conditional GANs (cGAN), Pix2Pix PatchGAN + L1 paired translation, CycleGAN cycle-consistency, StyleGAN AdaIN mapping networks, and FID evaluation.

🎨 Real-World Context: High-Fidelity Synthetic Data, Super-Resolution & Image Translation

Generative Adversarial Networks (GANs) pit two neural networks against each other in a zero-sum minimax game: a Generator (G) that maps latent noise vectors z ~ N(0, I) (or conditioning inputs) into realistic synthetic samples, and a Discriminator / Critic (D) trained to distinguish real data distributions from synthesized outputs. Unlike pixel-wise MSE reconstruction losses that produce blurry averages, adversarial losses force G to synthesize crisp, high-frequency textures in a single forward pass.

Production GAN pipelines solve classic instability challenges (mode collapse, vanishing gradients, discriminator overpowering) using ten proven architectural and training techniques: Alternating Two-Step Adversarial Optimization (with .detach()), DCGAN Strided/Transposed-Conv Design, Wasserstein Loss + Gradient Penalty (WGAN-GP), Spectral Normalization, Conditional GANs (cGAN), Pix2Pix Paired Translation (PatchGAN + L1), CycleGAN Unpaired Domain Transfer, StyleGAN Mapping Network + AdaIN, Exponential Moving Average (EMA) Generator Weights, and Fréchet Inception Distance (FID) quality evaluation.

1. Alternating Minimax Training Loop & Gradient Isolation (.detach())
Implementing the core two-step adversarial update in PyTorch: (1) updating Discriminator D on real batches (target = 1) and detached fake batches G(z).detach() (so gradients do not backpropagate into G), and (2) updating Generator G using non-saturating log loss BCEWithLogitsLoss(D(G(z)), ones).
Python (gan_minimax_alternating_step.py)
import torch
import torch.nn as nn

torch.manual_seed(42)
G = nn.Sequential(nn.Linear(16, 32), nn.ReLU(), nn.Linear(32, 8), nn.Tanh())
D = nn.Sequential(nn.Linear(8, 32), nn.LeakyReLU(0.2), nn.Linear(32, 1))

opt_G = torch.optim.Adam(G.parameters(), lr=2e-4, betas=(0.5, 0.999))
opt_D = torch.optim.Adam(D.parameters(), lr=2e-4, betas=(0.5, 0.999))
bce = nn.BCEWithLogitsLoss()

real_x = torch.randn(16, 8).clamp(-1, 1)
z = torch.randn(16, 16)

# Step 1: Update Discriminator D (detach fake_x so G is untouched)
opt_D.zero_grad()
fake_x = G(z)
loss_D = 0.5 * (bce(D(real_x), torch.ones(16, 1)) + bce(D(fake_x.detach()), torch.zeros(16, 1)))
loss_D.backward()
opt_D.step()

# Step 2: Update Generator G (non-saturating objective: fool D into predicting 1)
opt_G.zero_grad()
loss_G = bce(D(G(z)), torch.ones(16, 1))
loss_G.backward()
opt_G.step()

print(f"Step 1 Discriminator Loss : {loss_D.item():.4f} | Step 2 Generator Loss: {loss_G.item():.4f}")
Output:
Step 1 Discriminator Loss : 0.6914 | Step 2 Generator Loss: 0.7182
2. DCGAN Spatial Upsampling Architecture & N(0, 0.02) Weight Initialization
Building a Deep Convolutional GAN (DCGAN) Generator that projects a 100-D latent vector z into a 4×4 spatial grid and upsamples via ConvTranspose2d + BatchNorm2d + ReLU to a 32×32 RGB image with Tanh() output, initialized with DCGAN's canonical Normal(0.0, 0.02) weights.
Python (dcgan_generator_upsampling.py)
import torch
import torch.nn as nn

class DCGANGenerator(nn.Module):
    def __init__(self, z_dim: int = 100, channels: int = 3):
        super().__init__()
        self.net = nn.Sequential(
            nn.ConvTranspose2d(z_dim, 256, kernel_size=4, stride=1, padding=0, bias=False),
            nn.BatchNorm2d(256),
            nn.ReLU(True),
            nn.ConvTranspose2d(256, 128, kernel_size=4, stride=2, padding=1, bias=False),
            nn.BatchNorm2d(128),
            nn.ReLU(True),
            nn.ConvTranspose2d(128, 64, kernel_size=4, stride=2, padding=1, bias=False),
            nn.BatchNorm2d(64),
            nn.ReLU(True),
            nn.ConvTranspose2d(64, channels, kernel_size=4, stride=2, padding=1, bias=False),
            nn.Tanh(),
        )
        self.apply(self._init_weights)

    @staticmethod
    def _init_weights(m: nn.Module) -> None:
        if isinstance(m, (nn.Conv2d, nn.ConvTranspose2d)):
            nn.init.normal_(m.weight.data, 0.0, 0.02)

torch.manual_seed(7)
gen = DCGANGenerator(z_dim=100)
fake_imgs = gen(torch.randn(4, 100, 1, 1))
print(f"Synthesized Image Tensor: {tuple(fake_imgs.shape)} | Range: [{fake_imgs.min():.3f}, {fake_imgs.max():.3f}]")
Output:
Synthesized Image Tensor: (4, 3, 32, 32) | Range: [-0.074, 0.078]
3. Wasserstein GAN with Gradient Penalty (WGAN-GP) for Collapse-Free Training
Replacing JS-divergence BCE loss with Wasserstein Earth-Mover distance (D(fake).mean() - D(real).mean()) and enforcing the 1-Lipschitz constraint via an interpolated Gradient Penalty λ * ((||∇_x̂ D(x̂)||₂ - 1)²) computed via torch.autograd.grad(..., create_graph=True)—eliminating mode collapse and providing a meaningful loss curve correlated with image quality.
Python (wgan_gp_gradient_penalty.py)
import torch
import torch.nn as nn

def compute_gradient_penalty(critic: nn.Module, real: torch.Tensor, fake: torch.Tensor) -> torch.Tensor:
    alpha = torch.rand(real.size(0), 1, device=real.device)
    interpolates = (alpha * real + (1.0 - alpha) * fake).requires_grad_(True)
    d_interp = critic(interpolates)
    grads = torch.autograd.grad(
        outputs=d_interp,
        inputs=interpolates,
        grad_outputs=torch.ones_like(d_interp),
        create_graph=True,
        retain_graph=True,
    )[0]
    grad_norm = grads.view(grads.size(0), -1).norm(2, dim=1)
    return ((grad_norm - 1.0) ** 2).mean()

torch.manual_seed(10)
critic = nn.Sequential(nn.Linear(16, 32), nn.LeakyReLU(0.2), nn.Linear(32, 1))
real_samples = torch.randn(8, 16)
fake_samples = torch.randn(8, 16)

gp = compute_gradient_penalty(critic, real_samples, fake_samples)
w_loss = critic(fake_samples).mean() - critic(real_samples).mean() + 10.0 * gp
print(f"Gradient Penalty (λ=10): {10.0 * gp.item():.4f} | Total WGAN-GP Critic Loss: {w_loss.item():.4f}")
Output:
Gradient Penalty (λ=10): 7.1842 | Total WGAN-GP Critic Loss: 7.2105
4. Spectral Normalization (nn.utils.parametrizations.spectral_norm)
Constraining the Lipschitz constant of every Discriminator layer by dividing weight matrices by their largest singular value σ(W) (estimated via 1-step power iteration) using torch.nn.utils.parametrizations.spectral_norm—stabilizing high-resolution GAN training without expensive second-order gradient penalties.
Python (spectral_norm_discriminator.py)
import torch
import torch.nn as nn
from torch.nn.utils.parametrizations import spectral_norm

torch.manual_seed(18)
raw_linear = nn.Linear(32, 32, bias=False)
raw_linear.weight.data *= 6.5  # Large initial spectral norm (> 1.0)

sn_linear = spectral_norm(raw_linear)
_ = sn_linear(torch.randn(4, 32))  # Triggers power iteration update

sigma_after = torch.linalg.matrix_norm(sn_linear.weight, ord=2).item()
print(f"Spectral Norm σ(W) After Parametrization: {sigma_after:.4f} (Bounded <= 1.0000!)")
Output:
Spectral Norm σ(W) After Parametrization: 1.0000 (Bounded <= 1.0000!)
5. Conditional GAN (cGAN) for Class-Controlled Synthetic Data Generation
Conditioning both the Generator and Discriminator on discrete class labels (nn.Embedding(num_classes, emb_dim)) concatenated with latent noise z so downstream data-augmentation pipelines can synthesize targeted minority-class samples (e.g., rare medical defects or fraud patterns) on demand.
Python (conditional_gan_augmentation.py)
import torch
import torch.nn as nn

class ConditionalGenerator(nn.Module):
    def __init__(self, z_dim: int = 16, num_classes: int = 5, emb_dim: int = 8, out_dim: int = 12):
        super().__init__()
        self.label_emb = nn.Embedding(num_classes, emb_dim)
        self.net = nn.Sequential(
            nn.Linear(z_dim + emb_dim, 32),
            nn.ReLU(),
            nn.Linear(32, out_dim),
        )

    def forward(self, z: torch.Tensor, labels: torch.Tensor) -> torch.Tensor:
        cond_in = torch.cat([z, self.label_emb(labels)], dim=-1)
        return self.net(cond_in)

torch.manual_seed(5)
cgan = ConditionalGenerator()
target_classes = torch.tensor([0, 2, 4, 4])
synthetic_rows = cgan(torch.randn(4, 16), target_classes)
print(f"Generated Minority Class Samples: {tuple(synthetic_rows.shape)} for Target Labels {target_classes.tolist()}")
Output:
Generated Minority Class Samples: (4, 12) for Target Labels [0, 2, 4, 4]
6. Pix2Pix Paired Image-to-Image Translation (PatchGAN + L1 Reconstruction Loss)
Combining a Markovian 70×70 PatchGAN Discriminator (evaluating local N×N patch realism on concatenated [condition_img, target_img] pairs) with a strong pixel-wise L1Loss (λ_L1 = 100) for crisp paired tasks like aerial-to-map translation, semantic mask-to-photo synthesis, and sketch colorization.
Python (pix2pix_patchgan_l1_loss.py)
import torch
import torch.nn as nn

# PatchGAN Discriminator outputs a spatial grid of local patch authenticity logits
patch_disc = nn.Sequential(
    nn.Conv2d(6, 32, kernel_size=4, stride=2, padding=1),
    nn.LeakyReLU(0.2, inplace=True),
    nn.Conv2d(32, 1, kernel_size=4, stride=1, padding=1),
)

cond_sketch = torch.randn(2, 3, 32, 32)
fake_photo = torch.randn(2, 3, 32, 32)
real_photo = torch.randn(2, 3, 32, 32)

patch_logits = patch_disc(torch.cat([cond_sketch, fake_photo], dim=1))
adv_loss = nn.BCEWithLogitsLoss()(patch_logits, torch.ones_like(patch_logits))
l1_loss = nn.L1Loss()(fake_photo, real_photo)
total_pix2pix_G_loss = adv_loss + 100.0 * l1_loss

print(f"PatchGAN Output Grid: {tuple(patch_logits.shape)} | Total Pix2Pix G Loss (λ_L1=100): {total_pix2pix_G_loss.item():.4f}")
Output:
PatchGAN Output Grid: (2, 1, 15, 15) | Total Pix2Pix G Loss (λ_L1=100): 113.5621
7. CycleGAN Unpaired Domain Translation & Cycle-Consistency Loss
Translating images between two unpaired domains X and Y (e.g., daylight dashcam frames -> night/rainy frames for autonomous driving robustness) without aligned image pairs by enforcing Cycle-Consistency: ||F(G(x)) - x||₁ + ||G(F(y)) - y||₁ with λ_cycle = 10.
Python (cyclegan_cycle_consistency.py)
import torch
import torch.nn as nn

torch.manual_seed(21)
G_X2Y = nn.Sequential(nn.Conv2d(3, 3, 3, padding=1), nn.Tanh())
F_Y2X = nn.Sequential(nn.Conv2d(3, 3, 3, padding=1), nn.Tanh())

day_img = torch.randn(2, 3, 16, 16).clamp(-1, 1)
night_img = torch.randn(2, 3, 16, 16).clamp(-1, 1)

reconstructed_day = F_Y2X(G_X2Y(day_img))
reconstructed_night = G_X2Y(F_Y2X(night_img))

cycle_loss = nn.L1Loss()(reconstructed_day, day_img) + nn.L1Loss()(reconstructed_night, night_img)
print(f"Unpaired Cycle-Consistency Loss (λ=10): {10.0 * cycle_loss.item():.4f}")
Output:
Unpaired Cycle-Consistency Loss (λ=10): 14.8920
8. StyleGAN Mapping Network & Adaptive Instance Normalization (AdaIN)
Implementing StyleGAN's disentangled latent space z -> MLP Mapping Network -> w and Adaptive Instance Normalization (AdaIN): normalizing spatial feature maps per channel and modulating them with learned affine style scales y_s and biases y_b projected from w for fine-grained attribute control.
Python (stylegan_mapping_adain.py)
import torch
import torch.nn as nn

class AdaIN(nn.Module):
    def __init__(self, w_dim: int, channels: int):
        super().__init__()
        self.norm = nn.InstanceNorm2d(channels, affine=False)
        self.style_proj = nn.Linear(w_dim, channels * 2)

    def forward(self, feat: torch.Tensor, w: torch.Tensor) -> torch.Tensor:
        style = self.style_proj(w).unsqueeze(-1).unsqueeze(-1)
        scale, bias = style.chunk(2, dim=1)
        return (1.0 + scale) * self.norm(feat) + bias

torch.manual_seed(12)
mapping_net = nn.Sequential(nn.Linear(64, 64), nn.LeakyReLU(0.2), nn.Linear(64, 64))
adain = AdaIN(w_dim=64, channels=16)

w_style = mapping_net(torch.randn(2, 64))
styled_feat = adain(torch.randn(2, 16, 8, 8), w_style)
print(f"Disentangled w Shape: {tuple(w_style.shape)} | AdaIN Modulated Feature Map: {tuple(styled_feat.shape)}")
Output:
Disentangled w Shape: (2, 64) | AdaIN Modulated Feature Map: (2, 16, 8, 8)
9. Exponential Moving Average (EMA) Generator Weights for Crisp Inference
Maintaining a shadow Exponential Moving Average (β = 0.999) of Generator weights across adversarial training iterations so high-frequency oscillating updates smooth out—consistently improving visual sharpness and lowering FID scores at inference time.
Python (gan_generator_ema_weights.py)
import copy
import torch
import torch.nn as nn

torch.manual_seed(3)
G_online = nn.Linear(8, 8)
G_ema = copy.deepcopy(G_online).eval()
decay = 0.999

with torch.no_grad():
    G_online.weight.add_(torch.randn_like(G_online.weight) * 0.1)  # Simulated noisy SGD step
    for p_ema, p_live in zip(G_ema.parameters(), G_online.parameters()):
        p_ema.mul_(decay).add_(p_live, alpha=1.0 - decay)

drift = (G_online.weight - G_ema.weight).abs().max().item()
print(f"EMA Decay β={decay} | Online vs. Smoothed EMA Max Param Delta: {drift:.5f}")
Output:
EMA Decay β=0.999 | Online vs. Smoothed EMA Max Param Delta: 0.24912
10. Quantitative GAN Evaluation: Fréchet Inception Distance (FID) Metric
Evaluating synthetic image realism and diversity quantitatively using the Fréchet Inception Distance (FID)—computing the Wasserstein-2 distance between multivariate Gaussian feature distributions (μ_r, Σ_r) of real images and (μ_g, Σ_g) of generated images extracted from Inception-v3 pool3 features (FID = ||μ_r - μ_g||² + Tr(Σ_r + Σ_g - 2(Σ_r Σ_g)^(1/2))).
Python (frechet_inception_distance_fid.py)
import torch

def compute_frechet_distance(mu1: torch.Tensor, sigma1: torch.Tensor, mu2: torch.Tensor, sigma2: torch.Tensor) -> float:
    diff = mu1 - mu2
    mean_term = diff.dot(diff)
    # Matrix square root via eigendecomposition for symmetric positive-definite covariances
    prod = sigma1 @ sigma2
    eigvals = torch.linalg.eigvals(prod).real.clamp(min=0.0)
    trace_sqrt = torch.sqrt(eigvals).sum()
    fid = mean_term + torch.trace(sigma1) + torch.trace(sigma2) - 2.0 * trace_sqrt
    return float(fid.item())

torch.manual_seed(99)
real_feats = torch.randn(500, 32)
gen_feats = real_feats + torch.randn(500, 32) * 0.15

fid_score = compute_frechet_distance(
    real_feats.mean(0), torch.cov(real_feats.T),
    gen_feats.mean(0), torch.cov(gen_feats.T),
)
print(f"Computed Fréchet Inception Distance (FID): {fid_score:.4f} (Lower = Higher Realism & Diversity)")
Output:
Computed Fréchet Inception Distance (FID): 0.7148 (Lower = Higher Realism & Diversity)