Skip to main content

Someone wanted to learn this too, so Grasp built them a personal learning path.

You can keep exploring this one or create your own

Understanding Variational Autoencoders: ELBO and the Reparameterization Trick

Introduction

In our last lesson, we explored the standard autoencoder, establishing its function as a deterministic model for dimensionality reduction through a reconstruction objective. We saw that while excellent for data compression, its poorly structured latent space makes it unsuitable for generating new, meaningful data. Today, we advance to the Variational Autoencoder (VAE), a powerful generative model that addresses this limitation by introducing a probabilistic framework.

This lesson will guide you through the theoretical underpinnings of the VAE. You will learn how it transforms the deterministic encoder of a standard autoencoder into a probabilistic one, mapping inputs not to single points but to distributions in the latent space. We will derive its objective function, the Evidence Lower Bound (ELBO), from first principles of variational inference. Finally, we will dissect the ingenious reparameterization trick, the key that unlocks our ability to train these complex probabilistic models using standard gradient-based optimization.

From Deterministic to Generative

The core failing of a standard autoencoder as a generative model is its irregular latent space. The encoder learns to place encodings in arbitrary locations, and there's no guarantee that points sampled from the gaps between these encodings will decode into anything sensible.

VAEs solve this by imposing a structure on the latent space. Instead of learning a direct mapping , a VAE's encoder learns a mapping to a probability distribution.

Variational Autoencoders | Generative AI Animated

This animated video from Deepia provides a clear, conceptual introduction to why standard autoencoders fall short for generation and how VAEs propose a solution.

Please watch the section that explains the limitations of autoencoders for generation. This will set the stage for understanding the VAE's more sophisticated approach.

The VAE architecture reframes the encoding process:

  1. Probabilistic Encoder: For an input , the encoder does not produce a single latent vector . Instead, it outputs the parameters of a probability distribution, typically the mean and the log of the variance of a Gaussian distribution. This distribution, , is our learned approximation of the "true" posterior.
  2. Sampling: A latent vector is then sampled from this distribution: .
  3. Probabilistic Decoder: The decoder, , takes the sampled latent vector and reconstructs the original input, .

This probabilistic sampling is the essence of the VAE's generative power. It ensures that the latent space is continuous and structured, allowing us to later sample from it to generate novel data.

This diagram illustrates the full VAE architecture. The input `x` is passed to a probabilistic encoder `q(z|x)` which outputs parameters `μ` and `σ`. The reparameterization trick is used to sample a latent vector `z`, which is then passed to a probabilistic decoder `P(x|z)` to produce the reconstructed input `x̂`. The entire model is optimized by minimizing the ELBO loss.

The Generative Goal and Variational Inference

To understand the VAE's objective function, we must first frame it in the language of probabilistic modeling. Our ultimate goal is to model the underlying distribution of our data, . To do this, we introduce a latent variable and model the joint distribution .

  • is the prior distribution over the latent space. We choose this to be a simple, well-behaved distribution, typically a standard multivariate Gaussian, .
  • is the likelihood, parameterized by a neural network (the decoder) with weights . It defines how to generate data from a latent vector .

To find the probability of our data, we would need to compute the marginal likelihood:

This integral is intractable. It requires integrating over all possible values of the high-dimensional latent space , with being a complex, non-linear function defined by the decoder network.

Because this is intractable, we also cannot compute the true posterior distribution , which tells us the distribution of latent variables that could have generated a given data point .

This is where variational inference comes in. Since we cannot compute the true posterior , we approximate it with a simpler, tractable distribution , which is our encoder network parameterized by . Our goal is to make as close as possible to the true posterior .

Deriving the Evidence Lower Bound (ELBO)

We measure the "closeness" between our approximation and the true posterior using the Kullback-Leibler (KL) divergence. Our goal is to minimize . A beautiful mathematical relationship arises when we expand this KL divergence, which leads us to our final objective function.

The following video provides an exceptionally clear, step-by-step derivation of the VAE's objective function, known as the Evidence Lower Bound (ELBO).

Variational Autoencoder - Model, ELBO, loss function and maths explained easily!

This video by Umar Jamil walks through the complete mathematical derivation of the ELBO.

Please watch the section from "let's introduce our model" to the end of the "profit, revenue, and cost" analogy. Pay close attention to how the intractable integral problem leads to the use of an approximation, and how the log-likelihood of the data is decomposed into the ELBO and a KL divergence term.

Let's formalize the derivation shown in the video. We start with the log-likelihood of a data point, , and show that it can be decomposed:

Here, is the Evidence Lower Bound (ELBO). Because the KL divergence is always non-negative (), we have . This means that by maximizing the ELBO, we are pushing up a lower bound on the log-likelihood of our data, which is precisely our goal. Maximizing the ELBO also implicitly minimizes the KL divergence between our approximate posterior and the true (but intractable) posterior .

The ELBO itself is further decomposed into two meaningful terms:

  1. Reconstruction Term: This is the expected log-likelihood of the data, given a latent vector sampled from our encoder's distribution. It encourages the decoder to learn to reconstruct the input faithfully. For real-valued data (like images), this term often becomes a Mean Squared Error loss. For binary data, it becomes a Binary Cross-Entropy loss.

  2. Regularization Term: This is the KL divergence between our approximate posterior and the prior . This term acts as a regularizer, forcing the distributions learned by the encoder to stay close to the simple prior (e.g., a standard normal distribution). This is the crucial component that structures the latent space, making it dense and continuous, which is exactly what we need for generation.

For a rigorous, in-depth derivation from a primary source, the original VAE paper and its subsequent tutorials are invaluable.

An Introduction to Variational Autoencoders

This paper provides a formal and comprehensive introduction to VAEs. We will focus on the section that derives and explains the ELBO.

Please read Section 2.2, titled Evidence Lower Bound (ELBO). This text offers an alternative derivation to the one in the video, starting from log p(x) and arriving at the same decomposition. Pay attention to how it articulates the dual role of maximizing the ELBO: improving the generative model and making the posterior approximation more accurate.

The Reparameterization Trick

We now have a loss function, the negative ELBO, that we want to minimize. However, there's a major technical hurdle. The reconstruction term, , involves an expectation over samples from the encoder . In practice, we approximate this expectation with Monte Carlo sampling (i.e., we take one sample of for each ).

The problem is that the sampling operation, , is stochastic. We cannot backpropagate gradients through a random sampling node. This would prevent us from learning the parameters of the encoder. How can we differentiate with respect to if the path to the loss involves a random step?

Variational Autoencoder - Model, ELBO, loss function and maths explained easily!

The same video by Umar Jamil also provides an excellent explanation of this gradient problem and its solution.

Please watch the segment from "Now the problem is". It clearly explains why taking gradients of stochastic quantities can have high variance and why the sampling operation blocks backpropagation, before introducing the reparameterization trick.

The solution is the elegant reparameterization trick. Instead of sampling directly from the distribution defined by the encoder, we externalize the randomness.

If our encoder outputs the mean and standard deviation for a Gaussian posterior, we can reparameterize the sampling of as follows:

  1. Sample a random noise vector from a simple, fixed distribution: .
  2. Compute the latent vector deterministically: .

The randomness now comes from , which is outside the computational graph of our network. The path from the encoder parameters (which produce and ) to the final loss is now fully deterministic and differentiable. This allows us to use standard backpropagation to train the entire VAE, including the encoder.

This diagram contrasts the original formulation with the reparameterized one. On the left, the gradient flow to φ is blocked by the random node z. On the right, the randomness is externalized into ε, creating a deterministic path from φ to z, which allows gradients to flow back through the network.

For the complete formal explanation, we return to the introductory paper.

An Introduction to Variational Autoencoders

This part of the paper details the mathematics of the reparameterization trick and its application to the most common VAE variant.

Please read Section 2.4, Reparameterization Trick, which formalizes the change of variables. Then, continue to Section 2.5, Factorized Gaussian posteriors, which shows exactly how the trick is applied for the common case where the encoder models a diagonal Gaussian distribution.

Conclusion

In this lesson, we have constructed the Variational Autoencoder from its theoretical foundations. By shifting from a deterministic to a probabilistic encoder, the VAE learns not just to compress data, but to model its underlying distribution in a structured, continuous latent space suitable for generation.

Here are the key takeaways:

  • Generative Goal: VAEs are generative models that aim to maximize the likelihood of the observed data, , by introducing a latent variable .
  • The ELBO: Due to the intractability of the true data likelihood, we instead maximize a lower bound called the Evidence Lower Bound (ELBO). The ELBO consists of a reconstruction term (ensuring good reconstructions) and a regularization term (structuring the latent space).
  • The Reparameterization Trick: This crucial technique makes training VAEs possible. By externalizing the stochastic sampling process, it creates a differentiable path for gradients to flow through the entire network, allowing for end-to-end training with standard optimizers.

You now understand the "variational" in VAEs refers to the use of variational inference to approximate an intractable posterior, and the "autoencoder" part refers to its characteristic encoder-decoder structure.

In our next lesson, we will explore a completely different and highly influential family of generative models: Generative Adversarial Networks (GANs). You will see how GANs approach the problem of generation not through probabilistic inference and likelihoods, but through a game-theoretic, adversarial competition between two neural networks.

Can't find a good explanation? Sign up and we'll make it for you

Sign up