Modern machine learning models—from autoencoders to large language models—rely on the idea of latent representations. These are compact, abstract encodings of data that capture structure, meaning, or features without directly mirroring the raw input. A latent representation is a vector (or set of vectors) in a hidden space learned from data, which encodes the input in a way that makes downstream tasks easier. Latent spaces often have meaningful geometric properties like clustering of similar items together, meaningful semantic linearity (in case of word embeddings king - man + woman ≈ queen), or the manifold hypothesis which suggests that data lies on a much lower dimensional manifold embedded in latent space.
To learn such representations in an unsupervised way, we need models that can compress data into these lower-dimensional manifolds while still preserving its essential information. This is precisely where autoencoders come into play. They are designed to learn efficient latent encodings by training a neural network to reconstruct its own input.
Autoencoders (AE)
Let’s assume that our data is represented by , and latent variable is denoted as , where . A standard autoencoder (AE) consists of two neural network modules:
Encoder: Learns the parametrized function , which maps the high-dimensional input data to a low-dimensional latent representation:
Decoder: Learns the parametrized function , which reconstructs the input from the latent code:
The network is trained to minimize the reconstruction error, i.e., how close the reconstructed is to the original . A common choice of loss function is the Mean Squared Error (MSE):

Variational Autoencoders (VAE)
The vanilla autoencoder maps an input to a deterministic point in the latent space. As a result, the latent space learnt is discontinuous, patchy and not semantically meaninful. A deterministic mapping means you cannot simply sample a random point from the latent space and expect the decoder to produce a realistic, new sample that resembles the training data. The decoder only works well for the specific points that came from the encoder.
A variational encoder solves the above autoencoder issues, learns a meaningful latent space by imposing a prior on the latent , and doing variational inference for the posterior, encouraging the latent representations to be continuous, smooth, and generative.
Evidence Lower Bound (using Jensen’s inequality)
Let represent the true data distribution, and we have samples . We would like to model to approximate . Formally, we would like to solve:
Since our underlying assumption that the data has been generated from a latent variable , we express the data likelihood as marginalization over all possible latent codes (Luo, 2022):
Computing the above integral is intractable, especially when is a complex neural network, therefore we introduce an approximate posterior (the encoder) and optimize the Evidence Lower Bound (ELBO).
By Jensen’s inequality (since log is concave, ):
Thus, we have:
The above derivation of ELBO shows that it’s a lower bound on the likelihood, but it doesn’t give insight on the tightness of bound, and why maximizing it will maximize likelihood . That’s where an alternate derivation is more helpful.
Evidence Lower Bound (alternate derivation)
Starting with the log-likelihood , we can decompose it as (Kingma, 2017):
Since second term , the first term (ELBO) is a lower bound on the likelihood, or evidence, that is, . Interesting, the KL divergence determines the two distances:
- KL divergence of the approximate posterior from the true posterior .
- Gap between ELBO and likelihood , known as the tightness of bound. The better approximate posterior is closer to true posterior, lower the KL divergence, the tigher the bound.
There’s another equivalent way of writing ELBO as:
VAE Optimization
For VAEs, the optimization objective is ELBO. Maximization of ELBO w.r.t. the paramters and will concurrently optimize the two things we are interested in:
- Maximizing ELBO w.r.t. approximately maximizes . Since if , where represents the gradient w.r.t. . If becomes 0, then its gradient will vanish.
- Maximizing ELBO w.r.t. minimizes the KL divergence , because the likelihood is a constant w.r.t. .
Since ELBO allows joint optimization w.r.t. all parameters ( and ) using stochastic gradient descent, we can randomly initialize and , and optimize till convergence (Kingma, 2017).
Good unbiased gradient estimators exist, such that we can perform minibatch SGD.
Gradients w.r.t. : Unbiased gradients of the ELBO w.r.t. the generative model parameters are simple to obtain:
where is sampled from .
Gradients w.r.t. : Unbiased gradients w.r.t. the variational parameters are more difficult to obtain, since the ELBO’s expectation is taken w.r.t. the distribution , which is a function of . In general:
The key challenge is that we cannot simply move the gradient inside the expectation when the distribution itself depends on .
Reparameterization trick
The key idea is to express the random variable as a differentiable (and invertible) transformation of another random variable :
where the distribution of is independent of or .
In the original form (left in Figure 2), we cannot differentiate w.r.t. because we cannot directly backpropagate gradients through the random variable . By ‘externalizing’ the randomness through the reparameterization, we can compute gradients (Kingma, 2017).

With the reparameterization trick, we can now compute gradients w.r.t. both and . The ELBO gradient becomes:
where and . The key insight is that since is independent of , we can move the gradient inside the expectation, enabling efficient gradient computation via Monte Carlo sampling.
Special Case: Gaussian Posterior and Fixed Prior
In practice, we assume a Gaussian approximate posterior and a Gaussian prior .
The reparameterization of is:
where and are predicted from the encoder.
Recall that the ELBO is:
For this scenario, the KL divergence has a closed-form solution:
The reconstruction term depends on the data likelihood. For continuous data, we often use:
where is the decoder output.
Training Loss: The final VAE training loss for a single datapoint is:

Training Procedure
- Initialize: Randomly initialize encoder parameters and decoder parameters
- Repeat until convergence:
- Sample a minibatch of data from the dataset
- For each in the minibatch:
- Encode: Compute and using the encoder network
- Sample: Draw
- Reparameterize: Compute
- Decode: Compute reconstruction using the decoder network
- Compute loss:
- Compute minibatch loss:
- Update parameters: , where is the learning rate.
Training VAE on MNIST
For the MNIST dataset (LeCun et al., 1998), we train both an AE and VAE, using a convolutional architecture for both encoder and decoder, and compare the differences in the latent space.
Visualization of Latent Space: In Figure 4, we visualize the latent space for the trained models after running inference for 10k images in the testset, applying PCA (Wikipedia, 2025) on the latents, and plotting the first two principal components. We can see that VAE latent space lies uniformly in [-3, 3] while AE latent space is discontinous and patchy, as expected. We had hoped to see clearer clusters w.r.t. digits, but it’s possible that we don’t see them due to projecting to lower 2-dims via PCA in both AE and VAE.

Interpolation Quality: To evaluate the smoothness of the latent space, we perform linear interpolation between two encoded points in the latent space and decode the intermediate points. Figure 5 shows that VAE produces smooth transitions between digits when interpolating between two points representing digits 7 and 2, with intermediate points resembling digits 3 and 8, while AE generates unrealistic intermediate reconstructions due to its discontinuous latent space.

Generative Sampling: To show that latent space of VAE is semantically meaningful, and allows the model to be generative, we sample random points from the latent space and decode them. We sample from the prior, and then pass them through the decoder for both AE and VAE. Figure 6 demonstrates that VAE generates realistic digit samples from random latent codes, while AE fails to produce meaningful outputs since its latent space is not designed for random sampling.

Check out the Colab notebook for the implementation.
References
- Kingma, D. P. (2017). Variational Inference & Deep Learning: A New Synthesis [Ph.D. thesis, University of Amsterdam]. https://pure.uva.nl/ws/files/17891313/Thesis.pdf
- LeCun, Y., Cortes, C., & Burges, C. J. C. (1998). The MNIST Database of Handwritten Digits. https://huggingface.co/datasets/ylecun/mnist
- Luo, C. (2022). Understanding Diffusion Models: A Unified Perspective. CoRR, abs/2208.11970. https://doi.org/10.48550/arXiv.2208.11970
- Wikipedia. (2025). Principal component analysis — Wikipedia, The Free Encyclopedia. https://en.wikipedia.org/wiki/Principal_component_analysis