Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Deep generative models

Deep generative models learn probability distributions of data so engineers can generate new samples, perform density estimation and use learned representations in tasks such as data augmentation, anomaly detection and unsupervised pretraining.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Deep generative models let an engineer model how data x (images, audio, text) are produced and then use that model to (a) generate new realistic samples, (b) estimate likelihoods for anomaly detection, and (c) learn compact latent representations useful for downstream tasks (transfer learning, semi-supervised learning). These models are core for generative adversarial networks (GANs), variational autoencoders (VAEs) and energy-based models.

Key ideas

Start from first principles and define terms before use.

  • Generative model: a model that defines a probability distribution p(x) over observed data x. It can be explicit (gives p(x)) or implicit (gives a sampling mechanism but not a tractable p(x)).

  • Likelihood: for a parametric model p(x; θ), the likelihood of parameter θ given observed data x is L(θ|x)=p(x; θ). In practice we optimize the log-likelihood log p(x; θ).

  • Latent variable model: a generative model that posits hidden variable z and a joint distribution p(x, z) = p(x|z) p(z). Here latent means z is not observed.

  • Maximum likelihood estimation (MLE): choose θ that maximises the sum of log-likelihoods over data: θ* = argmax_θ ∑_i log p(x_i; θ). Assumes samples are independent and identically distributed (i.i.d.).

  • Kullback–Leibler (KL) divergence: for two distributions q and p, KL(q||p) = ∫ q(u) log (q(u)/p(u)) du. It is non-negative and zero iff q=p almost everywhere (assumes q is absolutely continuous w.r.t. p; otherwise KL(q||p) can be +∞).

  • Variational inference: when p(z|x) is intractable, introduce a tractable family q(z|x; φ) (the variational posterior) and approximate p(z|x) by minimising KL(q||p). This leads to the Evidence Lower Bound (ELBO).

  • Evidence Lower Bound (ELBO): for any approximate q(z|x): log p(x) = ELBO(q) + KL(q(z|x)||p(z|x)), so ELBO(q) ≤ log p(x). Maximising ELBO over q and model parameters approximates maximum likelihood.

    Derivation students are commonly asked to produce step-by-step: start from log p(x), subtract and add q, use Jensen's inequality or algebraic rearrangement to show the decomposition into expected reconstruction term and KL regulariser. See worked example for full derivation.

  • Variational Autoencoder (VAE): a neural-network parameterisation of the generative model p_θ(x|z) (decoder) and variational posterior q_φ(z|x) (encoder). Key trick: the reparameterisation trick writes z = μ_φ(x) + σ_φ(x) ⊙ ε with ε ~ N(0,I) so gradients w.r.t. φ can flow through stochastic sampling.

  • Generative Adversarial Network (GAN): two networks, generator G(z; θ_g) mapping random noise z∼p_z to samples, and discriminator D(x; θ_d) producing probability that x is real. They play a two-player minimax game with value V(G,D). The optimal discriminator given G has a closed form D*(x) = p_data(x) / (p_data(x) + p_g(x)). At optimum of discriminator, training G minimises a statistical divergence related to Jensen–Shannon divergence between p_data and p_g. Students are usually asked to show D* and the JS relation; see brief derivation below.

  • Energy-based models and Boltzmann machines: define an unnormalised probability p(x) ∝ exp(-E(x)), where E is an energy function; normalising constant (partition function) Z = ∫ exp(-E(x)) dx is often intractable, which leads to specialised sampling or learning methods (contrastive divergence). These models are related historically to deep generative modelling but have different practical trade-offs (sampling cost vs explicit density).

  • Autoregressive models: factorise p(x) = ∏i p(x_i | x{<i}); provide explicit likelihoods and straightforward maximum-likelihood training; examples include PixelCNN/PixelRNN and Transformers for text.

  • Normalizing flows: learn an invertible mapping f_θ between a simple prior z and data x; enable exact log-likelihood via change-of-variables with tractable Jacobian determinants; examples: NICE, RealNVP, Glow.

  • Diffusion/score-based models: define a forward noising process and learn a reverse denoising process via score matching or a variational bound; achieve state-of-the-art sample quality with iterative sampling.

What to draw (diagrams):

  • For a VAE: draw an input x on left, arrow to encoder box q_φ(z|x) that outputs μ and σ, sample z (annotate reparameterisation z = μ + σ·ε), arrow to decoder p_θ(x|z) that reconstructs x̂. Label loss terms: reconstruction E_q[log p(x|z)] and KL(q||p(z)).
  • For a GAN: draw noise z feeding generator G(z) producing x_fake; real data x_real and x_fake both feed into discriminator D(x) outputting probability. Mark adversarial loss arrows (D maximises, G minimises).
  • For an autoregressive model: show masked convolution or causal self-attention unrolled over positions x_1,…,x_D with arrows only from past to future.
  • For a normalizing flow: draw z ~ p(z) passed through invertible blocks f_k with Jacobian determinant annotations, output x; annotate change-of-variables.

Assumptions usually stated in exam answers: i.i.d. data, chosen forms for prior p(z) (commonly standard normal), decoder likelihood family (Gaussian for continuous data, Bernoulli for binary pixels), and differentiability of networks for gradient-based optimisation.

Formulas

p(x; θ) = ∫ p_θ(x|z) p(z) dz — p(x; θ) is the marginal likelihood (dimensionless), applies to latent-variable models where z is integrated out. Symbols: x = observed data (unitless), θ = model parameters, z = latent variable (unitless), p_θ(x|z) = conditional density (unitless), p(z) = prior density (unitless).

log p(x) = ELBO(q) + KL(q(z|x) || p(z|x)) — decomposition of log evidence; all terms are unitless (nats). Applies for any q with support where p(z|x)>0.

ELBO(q) = E_{z∼q(z|x)} [log p_θ(x|z)] - KL(q(z|x) || p(z)) — the objective maximised in VAEs. Symbols: E = expectation, log p_θ(x|z) = reconstruction log-likelihood, KL = Kullback–Leibler divergence.

KL(q||p) = ∫ q(u) log (q(u)/p(u)) du — definition of KL divergence; unitless (nats if ln used).

z = μ_φ(x) + σ_φ(x) ⊙ ε , ε ∼ N(0,I) — reparameterisation trick; μ_φ(x), σ_φ(x) outputs of encoder; ⊙ is element-wise multiply.

V(G,D) = E_{x∼p_data} [log D(x)] + E_{z∼p_z} [log (1 - D(G(z)))] — minimax GAN value function; unitless.

D*(x) = p_data(x) / (p_data(x) + p_g(x)) — optimal discriminator (pointwise), assumes densities exist at x.

max_D V(G,D) = -log 4 + 2 · JS(p_data || p_g) — for fixed G, the discriminator-optimal value equals a constant plus twice the Jensen–Shannon divergence; JS measured in nats when log is natural. Consequently, min_G max_D V(G,D) = -log 4 is attained when p_g = p_data.

KL(N(μ_q, σ_q^2) || N(μ_p, σ_p^2)) = ln(σ_p/σ_q) + (σ_q^2 + (μ_q - μ_p)^2) / (2 σ_p^2) - 1/2 — closed form for KL between univariate Gaussians; unitless. Applies when σ_p, σ_q > 0.

p(x) = ∏_{i=1}^D p(x_i | x_{<i}) — autoregressive factorization of a D-dimensional joint; yields exact log-likelihood ∑i log p(x_i | x{<i}).

log p_X(x) = log p_Z(f^{-1}(x)) + log |det ∂ f^{-1}(x)/∂ x| — change-of-variables formula for normalizing flows with invertible x = f(z).

q(x_t | x_0) = N(√ᾱ_t x_0, (1 − ᾱ_t) I) and train ε_θ via E_{t, x_0, ε}[||ε − ε_θ(x_t, t)||^2] — common DDPM parameterisation; logs in nats.

Worked examples

  1. Derive the ELBO decomposition (model exam answer).

Start from log p(x). Introduce any q(z|x) with support where p>0.

log p(x) = log ∫ p(x,z) dz = log ∫ q(z|x) p(x,z) / q(z|x) dz = log E_{z∼q} [p(x,z) / q(z|x)].

Apply log to an expectation -> use algebraic rearrangement (no Jensen step required here to get decomposition):

log p(x) = E_{z∼q} [log p(x,z) - log q(z|x)] + KL(q(z|x) || p(z|x)).

To see this, start from KL(q(z|x) || p(z|x)) = E_{z∼q}[log q(z|x) − log p(z|x)], substitute p(z|x) = p(x,z)/p(x), which yields KL = E_{z∼q}[log q(z|x) − log p(x,z)] + log p(x); rearrange to obtain log p(x) = E_{z∼q}[log p(x,z) − log q(z|x)] + KL(q(z|x) || p(z|x)). Then note

E_{z∼q} [log p(x,z) - log q(z|x)] = E_{z∼q} [log p(x|z)] + E_{z∼q}[log p(z)] - E_{z∼q}[log q(z|x)] = E_{z∼q}[log p(x|z)] - KL(q(z|x) || p(z)).

Therefore

log p(x) = ELBO(q) + KL(q(z|x) || p(z|x)),

ELBO(q) = E_{z∼q}[log p(x|z)] - KL(q(z|x) || p(z)).

Maximising ELBO wrt φ, θ (encoder and decoder) therefore increases a lower bound on log p(x). End of derivation.

  1. Numerical KL between q = N(μ_q=0.5, σ_q=0.8) and p = N(0,1). Compute KL(q||p).

Formula: KL = ln(σ_p/σ_q) + (σ_q^2 + (μ_q - μ_p)^2) / (2 σ_p^2) - 1/2.

Substitute σ_p = 1, σ_q = 0.8, μ_p = 0, μ_q = 0.5.

ln(1 / 0.8) = ln(1.25) = 0.22314355 (nats) (σ_q^2 + (μ_q - μ_p)^2) / 2 = (0.64 + 0.25) / 2 = 0.89 / 2 = 0.445 So KL = 0.22314355 + 0.445 - 0.5 = 0.16814355 nats.

Final answer: KL(q||p) ≈ 0.1681 nats (dimensionless). If you need bits, divide by ln 2.

  1. Short model answer: show optimal discriminator D*(x) in GAN.

Start from V(G,D) = E_{x∼p_data} [log D(x)] + E_{x∼p_g} [log(1 - D(x))]. This is a pointwise optimization for each x: for fixed p_data(x) and p_g(x) choose D(x) ∈ (0,1) to maximise p_data(x) log D(x) + p_g(x) log(1 - D(x)). Take derivative wrt D(x) and set to zero -> p_data(x)/D(x) - p_g(x)/(1 - D(x)) = 0. Solve -> D*(x) = p_data(x) / (p_data(x) + p_g(x)). Insert D* back into V gives expression related to JS divergence and constant -log 4; students should show algebra or reference the standard proof.

Common mistakes

  • Using discrete formulas for continuous variables (or vice versa) without noting densities vs probabilities.
  • Forgetting to reparameterise z when implementing VAEs, which prevents gradients flowing to encoder parameters.
  • Thinking GAN discriminator outputs a density; D(x) is a classifier probability, not a density.
  • Dropping constant terms improperly when reporting likelihood-related values (e.g., forgetting the -1/2 term in Gaussian KL closed form).
  • Confusing implicit models (GANs) with explicit density models (VAEs): GAN training does not maximise likelihood directly.

For your exam

Types of questions you will see and what full-mark answers include:

  • Definitions: give concise definitions and a one-line mathematical form (e.g., define ELBO and write formula).
  • Derivations: step-by-step algebra with assumptions stated (e.g., derive ELBO from log p(x); derive D*(x) for GAN). Write each algebra step and label where you use Jensen or properties of KL.
  • Short notes: contrast VAEs vs GANs (explicit likelihood + reconstruction + KL regulariser vs adversarial training, sample quality trade-offs). Mention typical priors and likelihoods used.
  • Numericals: compute KL between Gaussians, compute ELBO for a simple toy model; show all arithmetic and units (nats).
  • Diagrams: draw the encoder–latent–decoder pipeline for VAE and the generator–discriminator loop for GAN, label losses, sample flows and reparameterisation.
  • Implementation/programming: pseudo-code or short Python outline for VAE training loop; state the reparameterisation step. For full marks include loss expressions, optimisation step, and mention batch estimates of expectations.
  • Autoregressive/flow/diffusion: for autoregressive, write the factorization and masked architecture; for flows, derive the change-of-variables log-likelihood and log-det term for a coupling layer; for diffusion, write the forward noising q(x_t|x_0) and the ε-prediction loss used in DDPMs.

Quick check

  1. Give the ELBO expression for latent-variable model p(x,z).
  2. What is the reparameterisation trick for a Gaussian encoder? Write the formula.
  3. Write the optimal discriminator D*(x) for a fixed generator.

Answers: ELBO = E_{q(z|x)}[log p(x|z)] - KL(q(z|x) || p(z)); z = μ_φ(x) + σ_φ(x) ⊙ ε, ε∼N(0,I); D*(x) = p_data(x) / (p_data(x) + p_g(x)).

Note on uncertainty: I am confident about the ELBO derivation, the VAE reparameterisation, the Gaussian KL closed form, and the standard GAN D* and its relation to Jensen–Shannon divergence. Please verify the sign/constant convention in the GAN value-to-JS relation and any factor of 2 or -log 4 if your course uses log base 2 or different normalisation (see verify list).

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?