Exercises — Variational Autoencoders (VAE) theory
#ai-ml/generative-models #exercises #self-test
These problems build from recognising the pieces of a VAE up to synthesising whole training objectives. Every solution is hidden inside a collapsible callout — try the problem first, then reveal. Numeric answers are all machine-checked.
Everything you need was built in the parent note. When a prerequisite appears, we link it: Evidence Lower Bound (ELBO), Kullback-Leibler Divergence, Reparameterization Trick, Bayesian Inference, Latent Variable Models.
Level 1 — Recognition
Exercise 1.1 — Name the two terms
The Evidence Lower Bound (ELBO) for one data point is Name term and term , and say which network "owns" each.
Recall Solution
- is the reconstruction term. It asks: after encoding into a and decoding it back, how likely is the original ? Both the encoder (it draws the ) and the decoder (it scores ) participate, but the score is owned by the decoder.
- is the regularization term (a Kullback-Leibler Divergence). It measures how far the encoder's output distribution is from the prior . It is owned by the encoder .
We subtract because we want to maximize : high reconstruction, low divergence from the prior.
Exercise 1.2 — Spot the intractable object
In , which quantity is intractable and why?
Recall Solution
The integral itself (the marginal likelihood, also called the evidence) is intractable. To evaluate it exactly you would sum the decoder's output over every latent code in a high-dimensional space. There is no closed form, and grid-summing an -dimensional space costs exponentially in . This is precisely why we introduce the encoder and the Evidence Lower Bound (ELBO) — we replace an impossible integral with a bound we can optimize by sampling.
Exercise 1.3 — Which is the reparameterization?
Which of these expresses a Gaussian sample so that gradients can flow to ?
Recall Solution
(ii) is the Reparameterization Trick. In (i) the random draw sits inside a node that depends on , so there is no differentiable path from the loss back to . In (ii) the only randomness is , which does not depend on ; and enter through plain differentiable arithmetic (add, multiply), so backprop works.
Level 2 — Application
Exercise 2.1 — Closed-form KL, one dimension
For a 1-D latent with and prior , the closed form is Compute it for . Give a decimal.
Recall Solution
Plug in , , : Numerically , so . Look at figure s01: the wide, off-centre orange curve versus the teal standard prior — the KL penalty is the "cost" of that mismatch.
Exercise 2.2 — Multi-dimensional KL sums up
A 3-D diagonal Gaussian encoder outputs and against prior . Compute the total KL.
Recall Solution
For a diagonal Gaussian the dimensions are independent, so the KL is the sum of per-dimension KLs:
- : (this dim already matches the prior).
- : .
- : , ; . Total .
Exercise 2.3 — One reparameterized sample
Encoder gives for a 1-D latent. A noise draw yields . What is ?
Recall Solution
. The gradient and — both finite, both flowing to . That is the whole point of the Reparameterization Trick.
Level 3 — Analysis
Exercise 3.1 — When is the KL exactly zero?
Under what encoder output does the per-dimension KL vanish, and why is that a warning sign rather than a triumph?
Recall Solution
has its minimum-and-zero at (check: ). So KL is zero exactly when the encoder outputs the prior itself, ignoring . This is the failure mode called Posterior Collapse: if a dimension always returns regardless of the input, it carries no information about . The decoder learns to ignore that latent. A zero KL term is therefore suspicious — it may mean the model found the lazy solution of matching the prior and reconstructing from nothing.
Exercise 3.2 — Why the minus sign, verified
Show that for fixed reconstruction quality, increasing the KL term always lowers the ELBO. Argue from the formula.
Recall Solution
The ELBO is . Hold the reconstruction expectation fixed. Since and enters with a minus, any increase produces . So the KL acts as a pull toward the prior: the optimizer will never inflate KL for free. This is the "regularization vs reconstruction" balance from the parent note made precise — the two terms compete, and maximizing trades them off.
Exercise 3.3 — The bound is tight when...
Recall . When does the ELBO equal the true log-evidence?
Recall Solution
The gap is , which is and equals iff almost everywhere. So the bound is tight exactly when the encoder recovers the true posterior. In practice a diagonal-Gaussian usually cannot match a complex true posterior, so a residual gap remains — motivating richer families like Normalizing Flows. See figure s02: the log-evidence bar splits into the ELBO plus the posterior-approximation gap.
Level 4 — Synthesis
Exercise 4.1 — Write the full single-sample objective
For one image with pixels modelled as independent Bernoulli (values in ) with decoder output , and a diagonal-Gaussian encoder, write the minibatch loss (to minimize) for a -dim latent.
Recall Solution
Minimizing . The reconstruction for independent Bernoulli pixels is the negative binary cross-entropy: The KL has the closed form from L2. With one reparameterized sample : What each piece is doing: first sum = "make the reconstruction match"; second sum = "keep the codes near the prior". We minimize their sum.
Exercise 4.2 — Numeric end-to-end loss
Tiny model, latent dim . Encoder: , . A 2-pixel image is reconstructed as . Compute the total loss from Ex 4.1. (Use natural log.)
Recall Solution
Reconstruction (negative BCE): , ; sum ; negated . KL: both : Total loss .
Exercise 4.3 — Add a weight
The -VAE scales the KL: . Recompute Ex 4.2's total with , and say in one line what encourages.
Recall Solution
Recon unchanged; scaled KL . Total . A larger pushes the codes harder toward the prior, trading reconstruction sharpness for more Disentangled Representations — each latent axis is pressured to independently match .
Level 5 — Mastery
Exercise 5.1 — Diagnose posterior collapse from the loss curve
During training you observe: reconstruction loss stays high and flat, while the KL term drops to ~0 within a few epochs. Diagnose, and propose two fixes.
Recall Solution
Diagnosis: Posterior Collapse. The KL term dominated early, so the encoder took the cheapest route — output (KL , from Ex 3.1) — and the decoder learned to reconstruct from an uninformative code, leaving reconstruction stuck. Fixes:
- KL annealing — start near and ramp it up, so the model first learns to reconstruct before regularizing.
- Free bits / KL floor — allow each latent dim a small "free" nats budget of KL that isn't penalized, so useful dimensions aren't crushed to the prior. A stronger/autoregressive decoder makes this worse (it can reconstruct without ), so weakening the decoder is a third option.
Exercise 5.2 — Degenerate variance:
What happens to (a) the reparameterized sample, (b) the KL term, and (c) the model's generative ability, if the encoder drives for all dimensions?
Recall Solution
- (a) : the sample becomes deterministic — a plain autoencoder.
- (b) KL per dim . As , , so KL . The regularizer explodes, so the optimizer is strongly repelled from .
- (c) With near-zero variance the latent space is a set of isolated points with gaps between them (the very problem VAEs exist to prevent). Sampling a fresh lands in an untrained gap → garbage generations. The infinite KL penalty is precisely nature's guardrail against this collapse to a deterministic autoencoder.
Exercise 5.3 — Why not GANs' trick here?
A classmate says "just make output a single point and match distributions adversarially like a Generative Adversarial Networks (GANs)." Give the principled reason the VAE keeps an explicit distribution and an explicit KL instead.
Recall Solution
The VAE's whole objective is a tractable lower bound on log-likelihood (Bayesian Inference view): . That bound requires to be a genuine distribution so the expectation and the KL are defined and the reparameterized gradient is unbiased. A single deterministic point has no density, so no ELBO, no likelihood interpretation, and no smoothing of the latent space. GANs abandon likelihood entirely for an adversarial game — a different trade-off (sharper samples, no explicit density, harder training). The VAE deliberately keeps the density so it can evaluate and bound .
Recall Self-check summary
One-word for the network approximating the posterior ::: encoder Sign in front of the KL term inside the ELBO ::: minus KL of from ::: 1.30685 Reparameterized with ::: 1.4 Failure mode when KL collapses to zero ::: posterior collapse What happens to KL as ::: it diverges to infinity