Generative Models for Vision

GATE Relevance: Medium

🎯 Learning Objectives

  • Understand autoencoders and their bottleneck design
  • Derive the VAE loss function (reconstruction + KL divergence)
  • Explain GANs: generator, discriminator, and the minimax objective
  • Recognise common GAN variants (DCGAN, CGAN, WGAN)
  • Understand mode collapse and training instability in GANs
  • Describe the forward and reverse processes in diffusion models

1. Autoencoders

An autoencoder learns to compress input x into a low-dimensional latent code z and then reconstruct x from z. The bottleneck forces the network to learn a compact representation.

Autoencoder Components:
  • Encoder fθ: x → z (maps input to latent space)
  • Decoder gφ: z → x̂ (reconstructs input from latent code)
  • Loss: L = ‖x − x̂‖² (mean squared error) or binary cross-entropy for pixel values in [0, 1]

Applications: Dimensionality reduction, denoising (denoising autoencoder adds noise to input, trains to recover clean output), anomaly detection (high reconstruction error = anomaly), feature learning.

Limitation: Standard autoencoders learn a mapping but their latent space may not be continuous or structured. You cannot easily sample new z values and get meaningful outputs. This motivates Variational Autoencoders.

2. Variational Autoencoders (VAE)

VAEs impose a probabilistic structure on the latent space. The encoder outputs parameters of a distribution (not a point), and training regularises the latent space to be smooth and continuous.

VAE Encoder Output: Instead of z = f(x), the encoder outputs μ and σ (mean and standard deviation of a Gaussian). The latent code is sampled: z = μ + σ ⊙ ε, where ε ∼ N(0, I). This is the reparameterisation trick that allows backpropagation through the sampling operation.
VAE Loss Function (ELBO):
LVAE = Lrecon + LKL

Reconstruction loss: −Ez∼q(z|x)[log p(x|z)] ≈ ‖x − x̂‖² (or BCE)

KL divergence: DKL(q(z|x) ‖ p(z)) where p(z) = N(0, I)
= −½ ∑j=1d (1 + log σj² − μj² − σj²)

The KL term regularises the latent space to be close to a standard normal, enabling smooth sampling and interpolation.

Example — VAE Latent Interpolation

Given two images x1 and x2 with latent codes z1 and z2:

Interpolated latent: zα = (1 − α) · z1 + α · z2,   α ∈ [0, 1]

Decoding zα produces a smooth transition between x1 and x2. This works because the KL regularisation ensures the latent space is continuous.

⚠ VAE Trade-off: The reconstruction loss and KL divergence are in tension. Too much weight on KL produces blurry outputs (latent space is smooth but limited capacity). Too little KL weight produces sharp images but a poorly structured latent space. The β-VAE framework uses a coefficient β to control this balance.

3. Generative Adversarial Networks (GANs)

Introduced by Goodfellow et al. (2014). Two networks compete in a minimax game:

GAN Components:
  • Generator G(z): Takes random noise z ∼ N(0, I) and generates a synthetic sample x̂ = G(z).
  • Discriminator D(x): Outputs the probability that input x is real (from the data) vs. fake (from G).
GAN Minimax Objective:
minG maxD V(D, G) = Ex∼pdata[log D(x)] + Ez∼pz[log(1 − D(G(z)))]

D wants to maximise: D(real) → 1, D(fake) → 0 (high V).
G wants to minimise: D(G(z)) → 1 (make fakes indistinguishable from real).

At Nash equilibrium (in theory): D(x) = ½ for all x, and pG = pdata.

GAN Training Loop

Algorithm — GAN Training

  1. Train D: Sample real batch x and fake batch G(z). Update D to maximise log D(x) + log(1 − D(G(z))).
  2. Train G: Sample noise z. Update G to maximise log D(G(z)) [or equivalently minimise log(1 − D(G(z)))].
  3. Repeat steps 1–2 (often k = 1 D step per G step).
Practical Tip: In practice, G is trained to maximise log D(G(z)) rather than minimise log(1 − D(G(z))) to avoid vanishing gradients early in training when the generator is poor.

4. DCGAN (Deep Convolutional GAN)

Established architectural guidelines for stable GAN training with convolutional networks:

  • Replace pooling layers with strided convolutions (D) and transposed convolutions (G)
  • Use batch normalisation in both G and D (except D input layer and G output layer)
  • Remove all fully connected layers (fully convolutional)
  • Use ReLU in G (except output: tanh) and LeakyReLU in D

5. Conditional GAN (cGAN)

Both G and D receive additional conditioning information y (e.g., class label, text description, another image):

  • Generator: x̂ = G(z, y) — generates images conditioned on y
  • Discriminator: D(x, y) — judges if x is real AND matches condition y

Applications: Image-to-image translation (pix2pix), text-to-image generation, class-conditional image synthesis, super-resolution.

6. Wasserstein GAN (WGAN)

Addresses training instability by replacing the JS divergence with the Wasserstein distance (Earth Mover’s Distance).

Wasserstein Distance: W(pr, pg) = infγ ∈ Π(pr, pg) E(x,y)∼γ[‖x − y‖]
Intuitively: the minimum cost to transport mass from distribution pr to pg.
WGAN Objective (using Kantorovich-Rubinstein duality):
minG maxD∈1-Lipschitz Ex∼pdata[D(x)] − Ez∼pz[D(G(z))]

The discriminator (called “critic” in WGAN) must be 1-Lipschitz continuous. Originally enforced by weight clipping; WGAN-GP uses a gradient penalty instead.

Benefits: Meaningful loss curves that correlate with image quality, more stable training, reduced mode collapse.

7. Mode Collapse

Mode Collapse: The generator learns to produce only a few types of outputs (modes) that fool the discriminator, ignoring the full diversity of the data distribution. For example, a GAN trained on digits might only generate “1”s and “7”s while ignoring all other digits.

Causes: The generator finds a “safe” output that consistently fools D, and gradient updates reinforce this narrow strategy.

Mitigations:

  • Mini-batch discrimination: D looks at statistics across a batch, penalising lack of diversity
  • Unrolled GANs: G optimises against future D states, not just current D
  • Wasserstein loss: More stable gradients reduce collapse tendency
  • Feature matching: G minimises difference in intermediate D feature statistics

8. Diffusion Models

A class of generative models that learn to reverse a gradual noising process. Currently state-of-the-art for image generation quality.

Forward Process (Diffusion): Gradually add Gaussian noise to data x0 over T timesteps:
q(xt | xt−1) = N(xt; √(1 − βt) xt−1, βt I)
where βt is a noise schedule. After many steps, xT ≈ N(0, I) (pure noise).
Reverse Process (Denoising): A neural network learns to reverse the forward process step by step:
pθ(xt−1 | xt) = N(xt−1; μθ(xt, t), Σθ(xt, t))
The model is trained to predict the noise ε added at each step. At generation time, start from xT ∼ N(0, I) and iteratively denoise.
Diffusion Training Loss (simplified):
L = Et, x0, ε [‖ε − εθ(xt, t)‖²]

The model εθ predicts the noise ε that was added to create xt from x0. This is equivalent to a variational bound on the data log-likelihood.
Key property: Due to the Gaussian noise schedule, xt can be computed directly from x0 without iterating through all steps:
xt = √ᾱt x0 + √(1 − ᾱt) ε,   ε ∼ N(0, I)
where ᾱt = ∏s=1t(1 − βs). This enables efficient training.

9. DALL-E & Stable Diffusion

9.1 DALL-E / DALL-E 2

Text-to-image generation by OpenAI. DALL-E 2 uses a two-stage process: a text encoder (CLIP) produces text embeddings, a prior model maps text embeddings to image embeddings, and a diffusion decoder generates the image from image embeddings.

9.2 Stable Diffusion

Performs diffusion in a compressed latent space rather than pixel space (Latent Diffusion Model). This dramatically reduces computational cost.

Latent Diffusion Model (LDM):
  1. A pre-trained autoencoder compresses images x to latent z = E(x)
  2. Diffusion is performed in latent space (much smaller than pixel space)
  3. Text conditioning via cross-attention with CLIP text embeddings
  4. Decoded back to pixel space: x̂ = D(ẑ)
PropertyVAEGANDiffusion
Training stabilityStableUnstableStable
Sample qualityBlurrySharpVery sharp
DiversityGoodMode collapse riskExcellent
Sampling speedFast (1 pass)Fast (1 pass)Slow (T steps)
LikelihoodTractable (ELBO)IntractableTractable (VLB)
Latent spaceSmooth, structuredUnstructuredN/A (iterative)

10. Summary

  • Autoencoders: Encoder-decoder for reconstruction; bottleneck forces compression.
  • VAE: Probabilistic latent space; loss = reconstruction + KL divergence. Enables smooth sampling.
  • GAN: Generator vs. discriminator in a minimax game. Produces sharp images but training is unstable.
  • DCGAN: Architectural guidelines for convolutional GANs (strided conv, batch norm, no FC).
  • cGAN: Conditions generation on auxiliary information (class labels, text, images).
  • WGAN: Uses Wasserstein distance for more stable training and meaningful loss.
  • Mode collapse: G produces limited variety; mitigated by WGAN, mini-batch discrimination, etc.
  • Diffusion models: Forward process adds noise; reverse process denoises. State-of-the-art quality.
  • Stable Diffusion: Latent diffusion model for efficient text-to-image generation.