Generative Models for Vision
🎯 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.
- 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.
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.
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.
3. Generative Adversarial Networks (GANs)
Introduced by Goodfellow et al. (2014). Two networks compete in a minimax game:
- 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).
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
- Train D: Sample real batch x and fake batch G(z). Update D to maximise log D(x) + log(1 − D(G(z))).
- Train G: Sample noise z. Update G to maximise log D(G(z)) [or equivalently minimise log(1 − D(G(z)))].
- Repeat steps 1–2 (often k = 1 D step per G step).
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).
Intuitively: the minimum cost to transport mass from distribution pr to pg.
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
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.
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).
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.
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.
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.
- A pre-trained autoencoder compresses images x to latent z = E(x)
- Diffusion is performed in latent space (much smaller than pixel space)
- Text conditioning via cross-attention with CLIP text embeddings
- Decoded back to pixel space: x̂ = D(ẑ)
| Property | VAE | GAN | Diffusion |
|---|---|---|---|
| Training stability | Stable | Unstable | Stable |
| Sample quality | Blurry | Sharp | Very sharp |
| Diversity | Good | Mode collapse risk | Excellent |
| Sampling speed | Fast (1 pass) | Fast (1 pass) | Slow (T steps) |
| Likelihood | Tractable (ELBO) | Intractable | Tractable (VLB) |
| Latent space | Smooth, structured | Unstructured | N/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.