Skip to content
AIAI Wranglers

15 Variational Autoencoders

The previous chapters of this book developed two families of generative models. Gaussian mixture models (Chapter 7) introduced latent variable modelling and the expectation–maximisation algorithm for discrete latent spaces. Generative adversarial networks (Chapters 913) showed how to train implicit generators through adversarial games. In this chapter we combine neural networks with variational inference to build the Variational Autoencoder (VAE), a principled framework for learning deep latent variable models.

The journey proceeds in five steps:

  1. We start with deterministic autoencoders and their connection to PCA.

  2. We introduce deep latent variable models and explain why the posterior is intractable.

  3. We derive the Evidence Lower Bound (ELBO) from two complementary perspectives.

  4. We assemble the VAE: an amortised encoder, a neural decoder, and the reparameterisation trick for end-to-end training.

  5. We discuss practical issues: posterior collapse, latent space structure, and generation quality.

Historical Note.

The VAE was independently proposed by Kingma & Welling [1] and Rezende, Mohamed & Wierstra [2] in 2013–2014. The key insight, amortising variational inference with a neural-network encoder and training end-to-end via the reparameterisation trick, unified Bayesian latent-variable modelling with deep learning and opened the door to scalable generative models of images, text, and molecules.

Autoencoders

Before introducing the probabilistic machinery of VAEs, we review their deterministic predecessor: the autoencoder.

Definition 1 (Autoencoder).

An autoencoder consists of

  • an encoder fϕ:dk, and

  • a decoder gθ:kd,

with bottleneck dimension k<d. The pair is trained to minimise a reconstruction loss over a dataset {𝒙1,,𝒙N}: (Recon LOSS)rec(ϕ,θ)=1Ni=1N𝒙igθ(fϕ(𝒙i))2.

The encoder compresses each input 𝒙d into a latent code 𝒛=fϕ(𝒙)k; the decoder attempts to reconstruct 𝒙 from 𝒛. Because k<d, the bottleneck forces the network to discover a compact representation that captures the most important structure of the data.

Architecture of a deterministic autoencoder. The bottleneck dimension k is smaller than the input dimension d, forcing the network to learn a compressed representation.

Autoencoders find applications in dimensionality reduction, denoising (by training on corrupted inputs), feature learning, and anomaly detection (by flagging inputs with high reconstruction error). However, they suffer from a fundamental limitation for generative modelling.

Key Idea.

A deterministic autoencoder learns to compress and reconstruct, but its latent space has no guaranteed structure. Sampling a random 𝒛k and decoding it may produce nonsense, because nothing forces the encoder's outputs to fill the latent space in a regular way. The VAE solves this by imposing a probabilistic prior on the latent space.

Linear Autoencoders and PCA

We now make precise the connection between autoencoders and the classical technique of Principal Component Analysis (PCA). Recall that PCA projects data onto the top k eigenvectors of the covariance matrix Σ=1Ni=1N(𝒙i𝒙)(𝒙i𝒙), thereby minimising the reconstruction error among all linear projections.

Definition 2 (Linear Autoencoder).

A linear autoencoder is an autoencoder whose encoder and decoder use only linear transformations (no activation functions): fϕ(𝒙)=Wenc𝒙 with Wenck×d, and gθ(𝒛)=Wdec𝒛 with Wdecd×k.

Theorem 1 (Linear Autoencoder – PCA Equivalence).

Let Wenck×d and Wdecd×k minimise the reconstruction loss 1Ni=1N𝒙iWdecWenc𝒙i2 over centred data (𝒙=0). Then at any global minimum, colspan(Wdec)=colspan(Vk), where Vkd×k contains the top k eigenvectors of the data covariance matrix Σ.

Proof.

Let XN×d be the centred data matrix (rows are data points). The reconstruction loss equals 1NXXMF2 where M=WdecWencd×d has rank at most k. Minimising over all rank-k matrices M is precisely the Eckart–Young problem. Let X=USV be the (thin) SVD. The Eckart–Young theorem gives M=VkVk, where Vk consists of the top k right singular vectors of X. Since Σ=1NXX=VS2NV, the right singular vectors of X are precisely the eigenvectors of Σ (ordered by eigenvalue). Any factorisation M=WdecWenc of rank k satisfies colspan(Wdec)=colspan(Vk).

Insight.

PCA is the best that any linear model can do. A nonlinear autoencoder (with ReLU or other activations) can capture curved manifolds that PCA misses entirely. The VAE goes further: it adds probabilistic structure on top of this nonlinear capability, enabling principled generation and density estimation.

Latent Variable Models

We now shift from deterministic compression to probabilistic generative modelling. The central idea is to posit a latent (unobserved) variable 𝒛 that explains the observed data 𝒙 through a generative process: first sample 𝒛 from a simple prior, then generate 𝒙 conditioned on 𝒛.

Definition 3 (Deep Latent Variable Model).

A deep latent variable model defines a joint distribution (Joint)pθ(𝒙,𝒛)=p(𝒛)pθ(𝒙|𝒛), where

  • p(𝒛)=𝒩(0,I) is the prior over latent variables 𝒛d, and

  • pθ(𝒙|𝒛) is the likelihood (decoder), parameterised by a neural network with parameters θ.

The marginal likelihood (evidence) is (Marginal)pθ(𝒙)=p(𝒛)pθ(𝒙|𝒛)d𝒛.

This framework generalises the Gaussian mixture model studied in Exercise 14: in a GMM the latent variable is discrete (the cluster label) and the decoder is a simple Gaussian 𝒩(𝝁k,Σk). The deep LVM replaces the discrete 𝒛 with a continuous Gaussian and the simple decoder with a neural network, vastly increasing expressiveness.

The goal is to find parameters θ that maximise the log-likelihood of the observed data: (MLE)θ=arg maxθ𝔼pdata(𝒙)[logpθ(𝒙)]. This is equivalent to minimising the KL divergence 𝖣KL(pdatapθ) (cf. Definition 3).

Proposition 1 (Intractable Posterior).

For a deep latent variable model with a nonlinear neural-network decoder, the posterior (Posterior)pθ(𝒛|𝒙)=pθ(𝒙|𝒛)p(𝒛)pθ(𝒙) is intractable: computing the denominator pθ(𝒙)=p(𝒛)pθ(𝒙|𝒛)d𝒛 requires evaluating the decoder network at every point in the latent space, an integral that has no closed-form solution in general.

Proof.

Evaluating pθ(𝒙) requires integrating the product of a standard Gaussian density and the nonlinear function pθ(𝒙|𝒛) over 𝒛d. When the decoder is a multi-layer neural network, this product is a highly multimodal function of 𝒛 for which no analytic antiderivative exists. Moreover, naïve Monte Carlo estimation (sampling 𝒛p(𝒛)) suffers from exponentially high variance in high dimensions, since most samples from the prior land in regions where pθ(𝒙|𝒛) is negligible.

Caution.

The intractability of pθ(𝒙) means we cannot directly compute the log-likelihood, its gradients, or the posterior. Every technique in the rest of this chapter (the ELBO, amortised inference, the reparameterisation trick) is a creative response to this fundamental barrier.

The Evidence Lower Bound

Since maximising logpθ(𝒙) directly is intractable, we introduce an approximate posterior q(𝒛) and derive a tractable lower bound on the log-evidence. We present two derivations that reveal complementary insights.

Jensen Derivation

Theorem 2 (Evidence Lower Bound - Jensen).

For any distribution q(𝒛) with q(𝒛)>0 wherever p(𝒛)pθ(𝒙|𝒛)>0, (ELBO Jensen)logpθ(𝒙)𝔼q(𝒛)[logpθ(𝒙|𝒛)p(𝒛)q(𝒛)]=def(𝒙,q,θ). The quantity is called the evidence lower bound (ELBO).

Proof.

Starting from the marginal likelihood: logpθ(𝒙)=logp(𝒛)pθ(𝒙|𝒛)d𝒛=logq(𝒛)pθ(𝒙|𝒛)p(𝒛)q(𝒛)d𝒛=log𝔼q(𝒛)[pθ(𝒙|𝒛)p(𝒛)q(𝒛)]𝔼q(𝒛)[logpθ(𝒙|𝒛)p(𝒛)q(𝒛)], where the last step applies Jensen's inequality (log is concave).

The ELBO decomposes naturally into two interpretable terms.

Proposition 2 (ELBO Decomposition).

(ELBO Decompose)(𝒙,q,θ)=𝔼q(𝒛)[logpθ(𝒙|𝒛)]reconstruction term𝖣KL(q(𝒛)p(𝒛))regularisation term.

Proof.

Expanding the log ratio inside the ELBO: =𝔼q(𝒛)[logpθ(𝒙|𝒛)+logp(𝒛)logq(𝒛)]=𝔼q(𝒛)[logpθ(𝒙|𝒛)]𝔼q(𝒛)[logq(𝒛)p(𝒛)]=𝔼q(𝒛)[logpθ(𝒙|𝒛)]𝖣KL(q(𝒛)p(𝒛)).

The reconstruction term encourages q and θ to explain the data well; the KL term penalises q for deviating from the prior. This tension between fidelity and regularity is the defining feature of variational methods.

Bayes Derivation

The second derivation reveals the gap between the ELBO and the true log-evidence.

Theorem 3 (ELBO Gap Identity).

(ELBO GAP)logpθ(𝒙)=(𝒙,q,θ)+𝖣KL(q(𝒛)pθ(𝒛|𝒙)). The gap between the ELBO and the log-evidence is precisely the KL divergence between the approximate posterior q and the true posterior pθ(𝒛|𝒙).

Proof.

We start from the KL divergence between q(𝒛) and the true posterior: 𝖣KL(q(𝒛)pθ(𝒛|𝒙))=𝔼q(𝒛)[logq(𝒛)pθ(𝒛|𝒙)]=𝔼q(𝒛)[logq(𝒛)pθ(𝒙)pθ(𝒙|𝒛)p(𝒛)](Bayes’ rule)=logpθ(𝒙)+𝔼q(𝒛)[logq(𝒛)pθ(𝒙|𝒛)p(𝒛)]=logpθ(𝒙)(𝒙,q,θ). Rearranging gives logpθ(𝒙)=+𝖣KL(qpθ(|𝒙)).

Since 𝖣KL0, we immediately recover the lower-bound property logpθ(𝒙). More importantly, the gap identity tells us exactly when the bound is tight.

Key Idea.

The two ELBO derivations reveal complementary insights:

  • The Jensen derivation shows that is a lower bound on logpθ(𝒙).

  • The Bayes derivation shows that maximising over q simultaneously pushes q towards the true posterior and increases the log-evidence.

When q(𝒛)=pθ(𝒛|𝒙), the bound is tight: =logpθ(𝒙).

Remark 1 (Connection to GMM ELBO).

The ELBO was first encountered in the context of Gaussian mixture models (EM as Coordinate Ascent on the ELBO), where q assigns each data point to a mixture component. The EM algorithm alternates between tightening the bound (E-step) and maximising it (M-step). The VAE replaces these discrete updates with gradient-based optimisation of continuous encoder and decoder parameters.

The VAE Architecture

Classical variational inference optimises a separate q(𝒛) for each data point 𝒙, which is computationally expensive for large datasets. The VAE introduces amortised inference: a single neural network, called the encoder or inference network, maps any 𝒙 to the parameters of an approximate posterior qϕ(𝒛|𝒙).

Definition 4 (Variational Autoencoder).

A variational autoencoder consists of three components:

  1. An encoder (inference network) qϕ(𝒛|𝒙)=𝒩(𝒛;𝝁ϕ(𝒙),diag(σϕ2(𝒙))), where 𝝁ϕ and logσϕ are outputs of a neural network with parameters ϕ.

  2. A decoder (generative network) pθ(𝒙|𝒛), parameterised by a neural network with parameters θ.

  3. A prior p(𝒛)=𝒩(0,I).

The VAE is trained by maximising the ELBO summed (or averaged) over the dataset. Using the amortised posterior qϕ in place of a generic q, the VAE objective becomes:

(Objective)(ϕ,θ)=𝔼pdata(𝒙)[𝔼qϕ(𝒛|𝒙)[logpθ(𝒙|𝒛)]𝖣KL(qϕ(𝒛|𝒙)p(𝒛))].(VAE)

Remark 2 (Amortised Inference).

In classical variational inference, one optimises a separate variational distribution qi(𝒛) for each data point 𝒙i, requiring an inner optimisation loop. The VAE amortises this cost: the encoder qϕ(𝒛|𝒙) shares parameters ϕ across all data points, so the cost of inference is a single forward pass through the network. This makes the VAE scalable to millions of data points.

Architecture of a Variational Autoencoder. The encoder maps input 𝒙 to the mean 𝝁ϕ and standard deviation σϕ of the approximate posterior. A latent code 𝒛 is sampled using the reparameterisation trick (𝒛=𝝁ϕ+σϕϵ). The decoder reconstructs 𝒙^ from 𝒛. The loss consists of a reconstruction term and a KL regularisation term.

Remark 3 (Reconstruction Loss).

The form of pθ(𝒙|𝒛) determines the reconstruction loss:

  • Gaussian decoder: pθ(𝒙|𝒛)=𝒩(𝒙;𝝁θ(𝒛),σ2I) yields MSE loss: logpθ(𝒙|𝒛)𝒙𝝁θ(𝒛)2.

  • Bernoulli decoder: pθ(𝒙|𝒛)=jBernoulli(xj;πθ,j(𝒛)) yields binary cross-entropy loss (suitable for binary or normalised images).

Gaussian VAE: Closed-Form KL Divergence

A major computational advantage of the Gaussian VAE is that the KL term in the ELBO can be evaluated in closed form. The general KL divergence between multivariate Gaussians was derived in Proposition 2; here we specialise to the diagonal-covariance case that arises in the standard VAE.

Theorem 4 (Closed-Form KL for Gaussian VAE).

Let qϕ(𝒛|𝒙)=𝒩(𝝁,diag(σ2)) with 𝝁=𝝁ϕ(𝒙)d and σ=σϕ(𝒙)>0d, and let p(𝒛)=𝒩(0,I). Then (KL Gaussian)𝖣KL(qϕ(𝒛|𝒙)p(𝒛))=12j=1d[μj2+σj2logσj21].

Proof.

Step 1 (Factorisation). Because both q and p factorise across dimensions (q(𝒛)=j=1dq(zj) and p(𝒛)=j=1dp(zj)), the KL divergence decomposes: (KL Factorise)𝖣KL(qp)=j=1d𝖣KL(q(zj)p(zj)).

Step 2 (Per-dimension KL). For a single dimension, q(zj)=𝒩(μj,σj2) and p(zj)=𝒩(0,1): (KL 1D)𝖣KL(q(zj)p(zj))=𝔼q(zj)[logq(zj)p(zj)]=𝔼q(zj)[logσj(zjμj)22σj2+zj22]=logσj12σj2𝔼q[(zjμj)2]=σj2+12𝔼q[zj2]=σj2+μj2=logσj12+12(σj2+μj2).

Step 3 (Combine). Summing over dimensions and writing logσj=12logσj2: 𝖣KL(qp)=12j=1d[μj2+σj2logσj21].

Insight.

The closed-form KL term is the reason VAEs almost universally use Gaussian encoders with a standard normal prior. No Monte Carlo estimation is needed for the regularisation term; only the reconstruction term requires sampling, making training significantly more stable.

Substituting the closed-form KL and a single-sample Monte Carlo estimate for the reconstruction term, the practical VAE loss for a minibatch {𝒙1,,𝒙M} becomes:

(FULL LOSS)^(ϕ,θ)=1Mm=1M[logpθ(𝒙m|𝒛m)12j=1d(μϕ,j2(𝒙m)+σϕ,j2(𝒙m)logσϕ,j2(𝒙m)1)], where 𝒛m=𝝁ϕ(𝒙m)+σϕ(𝒙m)ϵm with ϵm𝒩(0,I).

The Reparameterisation Trick in VAEs

The ELBO involves the expectation 𝔼qϕ(𝒛|𝒙)[logpθ(𝒙|𝒛)]. To maximise with gradient-based optimisation, we need ϕ of this expectation. However, naïvely sampling 𝒛qϕ(𝒛|𝒙) creates a stochastic node that blocks gradient flow: the sample depends on ϕ, but the sampling operation is not differentiable.

The solution is the reparameterisation trick, introduced in Definition 5 (Chapter 3). Here we show how it applies specifically to the VAE.

Proposition 3 (Reparameterised ELBO Gradient).

Using the reparameterisation 𝒛=𝝁ϕ(𝒙)+σϕ(𝒙)ϵ with ϵ𝒩(0,I), the gradient of the reconstruction term can be computed as: (Reparam Gradient)ϕ𝔼qϕ(𝒛|𝒙)[logpθ(𝒙|𝒛)]=𝔼ϵ𝒩(0,I)[ϕlogpθ(𝒙|𝝁ϕ(𝒙)+σϕ(𝒙)ϵ)].

Proof.

Define the deterministic function Fϕ(𝒙,ϵ)=𝝁ϕ(𝒙)+σϕ(𝒙)ϵ. By the law of the unconscious statistician (LOTUS), if 𝒛=Fϕ(𝒙,ϵ) with ϵπ(ϵ)=𝒩(0,I), then 𝔼qϕ(𝒛|𝒙)[h(𝒛)]=𝔼π(ϵ)[h(Fϕ(𝒙,ϵ))] for any measurable h. Applying this with h(𝒛)=logpθ(𝒙|𝒛) and noting that π does not depend on ϕ: ϕ𝔼π(ϵ)[logpθ(𝒙|Fϕ(𝒙,ϵ))]=𝔼π(ϵ)[ϕlogpθ(𝒙|Fϕ(𝒙,ϵ))], where the interchange of gradient and expectation is justified because π is independent of ϕ (Leibniz's rule).

The reparameterisation trick. Left: sampling 𝒛qϕ directly creates a non-differentiable node (dashed red arrow), blocking gradients with respect to ϕ. Right: reparameterising as 𝒛=𝝁ϕ+σϕϵ makes 𝒛 a deterministic function of ϕ, allowing gradients to flow (solid green arrows).

Remark 4 (Single-Sample Estimator).

In practice, a single Monte Carlo sample (L=1) per data point suffices when using large minibatches. This is the approach used in the original VAE paper [1]: the variance from using L=1 is offset by averaging over many data points in the minibatch.

VAE Training Algorithm

We now consolidate the preceding results into complete training and sampling algorithms.

Algorithm 1 (VAE Training).

Input: Dataset {𝒙1,,𝒙N}, latent dimension d, learning rate η, epochs E, minibatch size M. Output: Trained parameters ϕ,θ.

  1. Initialise encoder parameters ϕ and decoder parameters θ randomly.

  2. for e=1,,E do

  3. Randomly shuffle the dataset into minibatches of size M.

  4. for each minibatch {𝒙1,,𝒙M} do

  5. for m=1,,M do

  6. Compute 𝝁ϕ(𝒙m) and σϕ(𝒙m) via the encoder.

  7. Sample ϵm𝒩(0,I).

  8. Set 𝒛m𝝁ϕ(𝒙m)+σϕ(𝒙m)ϵm.

  9. end for

  10. Evaluate the minibatch ELBO: ^=1Mm=1M[logpθ(𝒙m|𝒛m)𝖣KL(qϕ(𝒛|𝒙m)p(𝒛))].

  11. Update ϕϕ+ηϕ^; θθ+ηθ^.

  12. end for

  13. end for

Algorithm 2 (Sampling from a Trained VAE).

Input: Trained decoder pθ, number of samples S. Output: Generated samples {𝒙^1,,𝒙^S}.

  1. for s=1,,S do

  2. Sample 𝒛s𝒩(0,I).

  3. Compute 𝒙^s=𝝁θ(𝒛s) (or sample 𝒙^spθ(𝒙|𝒛s)).

  4. end for

Remark 5 (Implementation Details).

Several practical considerations arise when implementing VAEs:

  • Log-variance parameterisation. The encoder should output logσϕ2(𝒙) rather than σϕ(𝒙) directly. This avoids the need for a positivity constraint and is numerically more stable.

  • Optimiser. Adam [3] is the standard choice, typically with learning rate η[104,103].

  • Latent dimension. Common choices range from d=2 (for visualisation) to d=256 or higher (for complex image generation).

  • Architecture. Convolutional encoders/decoders are standard for images; fully connected networks suffice for low-dimensional tabular data.

Posterior Collapse

One of the most common failure modes in VAE training occurs when the encoder learns to ignore the input, making the approximate posterior match the prior on some or all latent dimensions.

Definition 5 (Posterior Collapse).

Posterior collapse occurs when, for some latent dimension j, the approximate posterior matches the prior for all data points: qϕ(zj|𝒙)p(zj)=𝒩(0,1)for all 𝒙. In this regime, the encoder ignores the input along dimension j (μϕ,j(𝒙)0, σϕ,j(𝒙)1), and the decoder receives no useful information from zj.

Posterior collapse arises from the tension between the two ELBO terms. The KL term 𝖣KL(qϕ(𝒛|𝒙)p(𝒛)) is minimised when qϕ=p (yielding 𝖣KL=0), while the reconstruction term 𝔼qϕ[logpθ(𝒙|𝒛)] benefits from an informative posterior. If the decoder is powerful enough to model the data distribution without relying on 𝒛 (for example, an autoregressive decoder such as PixelCNN), then the “easiest” solution is to set qϕp and let the decoder do all the work.

Caution.

Posterior collapse is not merely a theoretical curiosity; it is one of the most common failure modes when training VAEs in practice. Especially with powerful autoregressive decoders (PixelCNN, Transformer), the model can learn to ignore the latent variable entirely, reducing the VAE to a standard autoregressive model with wasted latent dimensions.

Several mitigation strategies have been proposed:

  • KL annealing (warm-up): During early training, weight the KL term by a factor βt that increases from 0 to 1 over the first several epochs. This gives the encoder time to learn useful representations before the full regularisation pressure is applied [4].

  • Free bits: Replace 𝖣KL(qp) with max(𝖣KL(qp),λ) per dimension, ensuring that each latent dimension carries at least λ nats of information [5].

  • β-VAE weighting: Use β𝖣KL with β<1 to reduce the regularisation pressure, at the cost of less structured latent spaces.

Remark 6 (β-VAE).

The β-VAE [6] introduces a hyperparameter β>0 before the KL term: β=𝔼qϕ[logpθ(𝒙|𝒛)]β𝖣KL(qϕp). When β>1, the stronger regularisation encourages disentangled representations where each latent dimension captures a single generative factor. A full treatment of the β-VAE and its variants appears in the next chapter.

Latent Space Structure and Generation Quality

The KL regularisation term in the ELBO endows the VAE's latent space with useful geometric properties that deterministic autoencoders lack.

Comparison of latent spaces. Left: Deterministic Autoencoder - may produce irregular, disconnected clusters with large gaps; decoding a random point from a gap produces meaningless output. Right: Variational Autoencoder - the KL regularisation pushes the encoded distributions toward the prior (dashed circle), producing a smooth, overlapping latent space where interpolation is meaningful.

Example 1 (Latent Space Interpolation).

Given two data points 𝒙a and 𝒙b, encode them to obtain 𝒛a=𝝁ϕ(𝒙a) and 𝒛b=𝝁ϕ(𝒙b). Decoding the linear interpolation 𝒛t=(1t)𝒛a+t𝒛b for t[0,1] produces a smooth transition between 𝒙^a and 𝒙^b in data space. This property arises because the KL term ensures that the latent space has no “holes” between encoded data points. Deterministic autoencoders do not guarantee this; interpolated points may land in regions where the decoder has never been trained.

Remark 7 (Generation Quality: VAE vs. GAN).

VAE-generated samples are often observed to be blurrier than those produced by GANs (cf. Exercise 9). This can be understood through the lens of forward vs. reverse KL divergence (cf. Forward vs. Reverse KL Divergence):

  • The VAE maximises the ELBO, which corresponds to minimising the forward KL 𝖣KL(pdatapθ). This encourages mode-covering behaviour: the model spreads its density to cover all modes of the data, resulting in blurry samples at intermediate points.

  • GANs implicitly minimise a divergence (e.g. JSD or Wasserstein) that encourages mode-seeking behaviour, producing sharper but potentially less diverse samples.

This trade-off between coverage and sharpness is a fundamental distinction between the two families of generative models.

Exercises

Exercise 1 (Bottleneck as Regulariser).

Consider an autoencoder with encoder fϕ:dk and decoder gθ:kd where k<d. The reconstruction loss is =1Ni=1N𝒙igθ(fϕ(𝒙i))2. Explain why the bottleneck dimension k acts as a regulariser. What happens to the reconstruction loss as kd? Why would this be undesirable for representation learning?

Exercise 2 (Linear Autoencoder PCA Proof).

Prove that for a linear autoencoder with weight matrices Wenck×d and Wdecd×k, the optimal solution (minimising MSE reconstruction loss) satisfies WdecWenc=VkVk, where Vk contains the top k eigenvectors of the data covariance matrix. Hint: Use the Eckart–Young theorem.

Exercise 3 (Denoising Autoencoder).

A denoising autoencoder is trained by corrupting the input 𝒙 with noise to obtain 𝒙~=𝒙+ϵ where ϵ𝒩(0,σ2I), and then minimising 𝒙gθ(fϕ(𝒙~))2. Explain why this forces the autoencoder to learn more robust features compared to a standard autoencoder. How does the noise level σ affect the learned representation?

Exercise 4 (Unstructured Latent Space).

The latent space of a deterministic autoencoder is not guaranteed to have any particular structure. Explain why this makes autoencoders unsuitable for generation: if you sample a random point 𝒛 from the latent space and decode it, why might the result look unrealistic? How does a VAE address this issue through its use of a prior p(𝒛)?

Exercise 5 (Posterior Collapse).

In the VAE objective , the total loss consists of a reconstruction term and a KL term. Discuss the tension between these two terms. What does the model learn if the KL term dominates? What if the reconstruction term dominates? Explain the phenomenon of “posterior collapse” and when it occurs.

Exercise 6 (Swiss Roll).

Suppose the latent dimension of an autoencoder is k=2 and the input data lies on a Swiss roll manifold embedded in 3. Can a linear autoencoder successfully “unroll” the Swiss roll into a flat 2D representation? Why or why not? What does this tell us about the advantage of nonlinear autoencoders for manifold learning?

Exercise 7 (ELBO Tightness).

Using the ELBO gap identity (Theorem 3), show that the ELBO is tight (=logpθ(𝒙)) if and only if q(𝒛)=pθ(𝒛|𝒙). What does this imply about the importance of having a flexible approximate posterior?

Exercise 8 (One-Dimensional KL Divergence).

Derive the KL divergence 𝖣KL(𝒩(μ,σ2)𝒩(0,1)) from scratch by writing out the integral q(z)logq(z)p(z)dz and evaluating each term. Verify that your result matches (KL 1D).

Exercise 9 (Reconstruction Loss Derivation).

  1. Show that a Gaussian decoder pθ(𝒙|𝒛)=𝒩(𝒙;𝝁θ(𝒛),σ2I) with fixed variance σ2 gives rise to MSE reconstruction loss (up to constants independent of θ).

  2. Show that a Bernoulli decoder pθ(𝒙|𝒛)=jBernoulli(xj;πθ,j(𝒛)) gives binary cross-entropy loss.

Exercise 10 (Reparameterising Other Distributions).

The reparameterisation trick extends beyond Gaussians. Suppose the approximate posterior is qϕ(z)=Uniform(aϕ,bϕ) where aϕ and bϕ are outputs of a neural network.

  1. Write the reparameterisation z=h(ϵ;aϕ,bϕ) where ϵUniform(0,1).

  2. Derive the gradient ϕ𝔼qϕ[f(z)] using the reparameterisation.

Exercise 11 (β-VAE Trade-off).

In the β-VAE objective β=𝔼qϕ[logpθ(𝒙|𝒛)]β𝖣KL(qϕp):

  1. Show that increasing β increases the regularisation pressure on the approximate posterior.

  2. Describe qualitatively what happens to the generated samples as β0 and as β.

  3. What value of β recovers the standard VAE?

Exercise 12 (ELBO and KL Minimisation).

Show that maximising the ELBO averaged over the data distribution, 𝔼pdata(𝒙)[(𝒙,qϕ,θ)], is equivalent to minimising 𝖣KL(pdata(𝒙)pθ(𝒙)) plus a constant that does not depend on θ. Hint: expand the forward KL and identify the ELBO inside.

Exercise 13 (Importance-Weighted ELBO).

The importance-weighted autoencoder (IWAE) uses K samples to form a tighter bound: K=𝔼𝒛1,,𝒛Kqϕ[log1Kk=1Kpθ(𝒙,𝒛k)qϕ(𝒛k|𝒙)].

  1. Show that 1 is the standard ELBO.

  2. Using Jensen's inequality applied to the concave function log, show that KK+1logpθ(𝒙).

Exercise 14 (Two-Dimensional VAE).

Implement a VAE with latent dimension d=2 on a dataset sampled from a mixture of four 2D Gaussians. Use fully connected encoder and decoder networks.

  1. Train the model and plot the ELBO as a function of training epoch.

  2. Visualise the learned latent space by encoding the training data and colouring points by their mixture component.

  3. Sample from the prior 𝒛𝒩(0,I), decode, and compare the generated distribution with the true data distribution.

References

  1. Auto-Encoding Variational Bayes

    Diederik P Kingma, Max Welling

    International Conference on Learning Representations · 2014

    BibTeX
    @inproceedings{kingma2013auto,
      title={Auto-Encoding Variational {B}ayes},
      author={Kingma, Diederik P and Welling, Max},
      booktitle={International Conference on Learning Representations},
      year={2014}
    }

    Conference paper

  2. Stochastic Backpropagation and Approximate Inference in Deep Generative Models

    Danilo Jimenez Rezende, Shakir Mohamed, Daan Wierstra

    International Conference on Machine Learning, pp. 1278-1286 · 2014

    BibTeX
    @inproceedings{rezende2014stochastic,
      title={Stochastic Backpropagation and Approximate Inference in Deep Generative Models},
      author={Rezende, Danilo Jimenez and Mohamed, Shakir and Wierstra, Daan},
      booktitle={International Conference on Machine Learning},
      pages={1278--1286},
      year={2014}
    }

    Conference paper

  3. Adam: A Method for Stochastic Optimization

    Diederik P. Kingma, Jimmy Ba

    3rd International Conference on Learning Representations, ICLR 2015 · 2015

    BibTeX
    @InProceedings{ADAM,
      author    = {Diederik P. Kingma and Jimmy Ba},
      title     = {Adam: {A} Method for Stochastic Optimization},
      booktitle = {3rd International Conference on Learning Representations, {ICLR} 2015},
      year      = {2015},
    }

    Conference paper

  4. Generating Sentences from a Continuous Space

    Samuel R Bowman, Luke Vilnis, Oriol Vinyals, Andrew M Dai, Rafal Jozefowicz, Samy Bengio

    Proceedings of the 20th SIGNLL Conference on Computational Natural Language Learning, pp. 10-21 · 2016

    BibTeX
    @inproceedings{bowman2016generating,
      title={Generating Sentences from a Continuous Space},
      author={Bowman, Samuel R and Vilnis, Luke and Vinyals, Oriol and Dai, Andrew M and Jozefowicz, Rafal and Bengio, Samy},
      booktitle={Proceedings of the 20th SIGNLL Conference on Computational Natural Language Learning},
      pages={10--21},
      year={2016}
    }

    Conference paper

  5. Improved Variational Inference with Inverse Autoregressive Flow

    Diederik P. Kingma, Tim Salimans, Rafal Jozefowicz, Xi Chen, Ilya Sutskever, Max Welling

    Advances in Neural Information Processing Systems, pp. 4743-4751 · 2016

    BibTeX
    @inproceedings{kingma2016improved,
      title={Improved Variational Inference with Inverse Autoregressive Flow},
      author={Kingma, Diederik P. and Salimans, Tim and Jozefowicz, Rafal and Chen, Xi and Sutskever, Ilya and Welling, Max},
      booktitle={Advances in Neural Information Processing Systems},
      pages={4743--4751},
      year={2016}
    }

    Conference paper

  6. $eta$-VAE: Learning Basic Visual Concepts with a Constrained Variational Framework

    Irina Higgins, Loic Matthey, Arka Pal, Christopher Burgess, Xavier Glorot, Matthew Botvinick, Shakir Mohamed, Alexander Lerchner

    International Conference on Learning Representations · 2017

    BibTeX
    @inproceedings{higgins2017beta,
      title={$\beta$-{VAE}: Learning Basic Visual Concepts with a Constrained Variational Framework},
      author={Higgins, Irina and Matthey, Loic and Pal, Arka and Burgess, Christopher and Glorot, Xavier and Botvinick, Matthew and Mohamed, Shakir and Lerchner, Alexander},
      booktitle={International Conference on Learning Representations},
      year={2017}
    }

    Conference paper