HSR Sector 6 · Bangalore +91 96110 27980 Mon–Sat · 09:30–20:30
Chapter 6 of 25 — Generative AI Fundamentals
intermediate Chapter 6 of 25

Variational Autoencoders (VAE): Latent Space, Encoder, Decoder and ELBO

By Vikas Swami, CCIE #22239 | Updated Mar 2026 | Free Course

What Is a VAE (Variational Autoencoder)?

A VAE, or variational autoencoder, is a generative model that encodes each input as a probability distribution over latent variables and learns to decode latent samples into data. It trains by maximising the evidence lower bound (ELBO), which rewards accurate reconstruction and penalises an encoder distribution that strays from a chosen prior. After training, it can generate new examples by sampling that prior and decoding the samples without an input example.

A conventional autoencoder maps an input x to a fixed code z and decodes that code to reconstruct the input. Its reconstruction objective alone gives no rule for drawing useful new codes. A VAE gives the latent variables an explicit probability model. For example, with two latent dimensions and a standard Gaussian prior, you can draw two independent standard normal numbers, pass that pair to the decoder, and obtain a distribution over possible outputs. Whether those outputs look like training data still depends on how well the model learned.

For a digit image, the latent variables may help represent properties such as stroke thickness or slant. The objective does not assign meanings to individual coordinates. A model can spread one property across several coordinates, or use one coordinate for several properties. Think of z as a hidden cause used by the model rather than a list of named features. Compare this with vector embeddings, which are often trained for tasks such as similarity search rather than for sampling new observations.

How Do the VAE Encoder, Latent Space and Decoder Work?

A VAE defines a joint distribution pθ(x, z) = p(z) pθ(x | z). The prior p(z) describes latent draws before seeing data, and the decoder pθ(x | z) describes which observations are likely given a draw. The exact posterior pθ(z | x) would tell us which latent draws could explain a specific observation. Computing it requires the marginal likelihood pθ(x), which integrates over all latent values and is generally intractable for a neural decoder. The encoder qφ(z | x) learns an approximation to that posterior.

A VAE encodes an input into a Gaussian distribution during training and samples directly from the prior during generation.
Training samples from the encoder distribution, while unconditional generation samples from the prior.
  1. Encode: For a latent dimension d, the encoder outputs two length-d vectors: μ and ℓ = log σ². They specify a Gaussian with mean μ and diagonal covariance with entries exp(ℓ). The covariance is diagonal for each input; this assumption does not imply that latent coordinates are semantically independent across the dataset.
  2. Sample: Draw ε ~ N(0, I) and compute z = μ + exp(0.5 × ℓ) ⊙ ε, where ⊙ means elementwise multiplication. The exponent uses half the log variance because sampling requires the standard deviation σ. This construction produces exactly the intended Gaussian sample.
  3. Decode: The decoder turns z into likelihood parameters. For a binary image with 64 pixels, it can output 64 logits, one per pixel. Applying sigmoid yields 64 Bernoulli probabilities. The likelihood treats pixels as conditionally independent given z; shared dependence on z can still make pixels correlated overall.

Step two is the reparameterisation trick. For a particular forward pass, the sampled ε is fixed during backpropagation. The path from the reconstruction loss through z to μ and ℓ is then differentiable. For coordinate j, for instance, ∂zⱼ/∂ℓⱼ = 0.5 × exp(0.5 × ℓⱼ) × εⱼ. This lets the reconstruction term train the encoder to adjust its uncertainty as well as its mean.

At inference time, use the encoder mean for a repeatable preview of an existing input, or sample its posterior approximation to explore variations of that input. For unconditional generation, skip the encoder and use z ~ p(z). Showing decoder probabilities gives a mean image for a given z; drawing pixels from those probabilities gives an actual sample from pθ(x | z). These are three distinct operations: reconstructing an input, varying it, and generating without one.

What Is the ELBO in a Variational Autoencoder?

The training goal is to assign high marginal likelihood pθ(x) to the data. To see where the lower bound comes from, start with pθ(x) = ∫ pθ(x, z) dz. Multiply and divide the integrand by qφ(z | x). The integral becomes an expectation of pθ(x, z) / qφ(z | x) under the encoder distribution. Since log is concave, Jensen's inequality gives log E[r] ≥ E[log r] for this positive ratio r. Expanding the logarithm yields:

ELBO(x) = E_{z ~ qφ(z | x)}[log pθ(x | z)] − KL(qφ(z | x) || p(z))

The first term rewards a decoder that gives high probability to the observed input. The second term is the Kullback-Leibler (KL) divergence from the encoder distribution to the prior. The bound has an exact gap: log pθ(x) − ELBO(x) = KL(qφ(z | x) || pθ(z | x)) ≥ 0. So the ELBO equals the log likelihood only when the encoder distribution matches the true posterior for that input. A diagonal Gaussian is often convenient, but it cannot express a posterior with multiple separated modes.

When the prior is standard normal and the encoder uses a diagonal Gaussian, the KL term has a closed form: KL = 0.5 × Σⱼ [μⱼ² + exp(ℓⱼ) − 1 − ℓⱼ]. Each summand is zero when μⱼ = 0 and ℓⱼ = 0. A mean far from zero or a variance far from one increases the penalty. The reconstruction expectation usually has no closed form, so a common training setup estimates it with one draw of z per example per step.

Optimisers usually minimise loss = reconstruction negative log likelihood + KL. For binary pixels, the first term is binary cross entropy summed over pixels. For continuous data with a Gaussian decoder of fixed variance s², the negative log likelihood is squared error divided by 2s² plus a constant. The scale matters: averaging the reconstruction term over pixels while summing KL over latent dimensions silently increases the relative weight of KL. Sum over each example's event dimensions first, then average the combined loss over the batch.

Worked Example: Calculate a VAE Loss by Hand

Take a binary input x = [1, 0, 1]. Its encoder predicts μ = [1, 0] and variances [0.25, 1]. The log variances are approximately [-1.3863, 0]. With a noise draw ε = [-1, 0.5], the standard deviations are [0.5, 1] and the reparameterised sample is z = [1 + 0.5 × (-1), 0 + 1 × 0.5] = [0.5, 0.5].

Suppose the decoder returns probabilities [0.8, 0.3, 0.6] for the three entries being 1. The first and third entries are 1, so their observed probabilities are 0.8 and 0.6. The middle entry is 0, so its observed probability is 1 − 0.3 = 0.7. The loss for this latent draw is:

TermCalculationValue in nats
Reconstruction negative log likelihood−log(0.8) − log(0.7) − log(0.6)1.091
KL for latent coordinate 10.5 × [1² + 0.25 − 1 − log(0.25)]0.818
KL for latent coordinate 20.5 × [0² + 1 − 1 − log(1)]0
Estimated negative ELBO1.091 + 0.8181.909

The KL is exact for this encoder distribution. The reconstruction value comes from one random draw, so another ε can change the total while leaving the KL unchanged. The units are nats because the logarithms are natural. A common sign error is to add the positive KL to the log likelihood when maximising the ELBO. Subtract it when maximising the bound and add it when minimising the negative bound.

How to Build and Train a VAE in PyTorch

This CPU example uses the 8 by 8 digit dataset bundled with scikit-learn. The original intensities range from 0 to 16. Thresholding at 8 makes the inputs and targets binary, so a Bernoulli likelihood is a direct match. Digit labels are unused. Two latent dimensions make the code easy to inspect, but the choice is for teaching and can limit reconstruction quality. Run it in an environment with torch and scikit-learn installed.

import torch
from sklearn.datasets import load_digits
from torch import nn
from torch.nn import functional as F
from torch.utils.data import DataLoader

torch.manual_seed(7)
x = torch.from_numpy((load_digits().data >= 8).astype("float32"))
order = torch.randperm(len(x))
train, test = x[order[300:]], x[order[:300]]
loader = DataLoader(train, batch_size=64, shuffle=True)


class VAE(nn.Module):
    def __init__(self, latent_dim=2):
        super().__init__()
        self.encoder = nn.Sequential(nn.Linear(64, 128), nn.ReLU())
        self.mean = nn.Linear(128, latent_dim)
        self.logvar = nn.Linear(128, latent_dim)
        self.decoder = nn.Sequential(
            nn.Linear(latent_dim, 128), nn.ReLU(), nn.Linear(128, 64)
        )

    def forward(self, x):
        h = self.encoder(x)
        mu, logvar = self.mean(h), self.logvar(h)
        std = torch.exp(0.5 * logvar)
        z = mu + std * torch.randn_like(std)
        return self.decoder(z), mu, logvar


def loss_terms(logits, x, mu, logvar):
    recon = F.binary_cross_entropy_with_logits(
        logits, x, reduction="none"
    ).sum(dim=1)
    kl = 0.5 * (mu.square() + logvar.exp() - 1 - logvar).sum(dim=1)
    return recon, kl


model = VAE()
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)

for epoch in range(1, 31):
    model.train()
    for batch in loader:
        logits, mu, logvar = model(batch)
        recon, kl = loss_terms(logits, batch, mu, logvar)
        optimizer.zero_grad()
        (recon + kl).mean().backward()
        optimizer.step()

    if epoch % 10 == 0:
        model.eval()
        with torch.no_grad():
            logits, mu, logvar = model(test)
            recon, kl = loss_terms(logits, test, mu, logvar)
            print(f"{epoch}: recon={recon.mean():.2f}, "
                  f"KL={kl.mean():.2f}, "
                  f"negative ELBO estimate={(recon + kl).mean():.2f}")

model.eval()
with torch.no_grad():
    z = torch.randn(4, 2)
    pixel_probs = model.decoder(z).sigmoid().reshape(4, 8, 8)
    binary_samples = torch.bernoulli(pixel_probs)

For a batch of size B, the logits have shape [B, 64], while mu, logvar, and z have shape [B, 2]. Each loss term becomes a length-B vector before batch averaging. Pass raw decoder logits to binary_cross_entropy_with_logits; it computes the loss in a numerically stable way without a separate sigmoid. The final pixel_probs tensor holds four mean images. The binary_samples tensor holds four binary draws, useful for seeing the difference between displaying probabilities and sampling the model.

To diagnose training, inspect both held-out loss terms, several reconstructions, and several prior samples. The printed reconstruction term is stochastic because model.eval() does not switch off explicit latent sampling. For a less noisy comparison, average reconstruction losses over several draws per held-out example; the analytic KL only needs to be computed once per example. If using the held-out partition repeatedly to choose hyperparameters, treat it as validation data and reserve a separate test set for final evaluation. This follows the same distinction between training and inference used throughout generative AI.

If KL stays near zero and reconstructions barely change when z changes, suspect posterior collapse: the decoder is relying very little on the latent code. Check KL by coordinate before changing the model; unused coordinates are less concerning than a decoder that ignores all coordinates. If the entire code is unused, try gradually increasing the KL weight from a small value to one during training. While the weight differs from one, the loss is a modified objective. If reconstructions look good but prior samples look poor, inspect the mismatch between the prior and the distribution obtained by pooling encoder samples over many inputs. Good reconstructions alone do not test prior sampling.

How Does a VAE Compare With GANs, Diffusion Models and LLMs?

The types of generative AI models are grouped by different properties. A VAE is defined by latent-variable likelihood modelling with variational inference. A GAN is defined by an adversarial training setup. Autoregression is a factorisation of a data distribution, while LLM refers to a language model at scale. A single system can fall into more than one category.

A generative AI family map shows VAEs, GANs, diffusion models, autoregressive models and the overlap between LLMs and autoregressive models.
The categories overlap: for example, GPT-style LLMs generate autoregressively.
FamilyHow it generatesPractical distinction
VAESamples a latent variable and decodes it into an observation distribution.The encoder gives a direct route from data to a latent distribution. The observation likelihood must suit the data.
GANMaps random noise to a sample using a generator trained against a discriminator.A basic GAN has no learned inverse encoder. GANs can generate images or video, but training can miss parts of the data distribution.
Diffusion modelStarts with noise and applies a learned reverse process, commonly over multiple steps.Used for images, audio and video. Latent diffusion systems such as Stable Diffusion perform this process in a compressed space, then decode the result.
Autoregressive modelSamples each element conditioned on the elements already generated, using p(x) = ∏ᵢ p(xᵢ | x₁, …, xᵢ₋₁).Works for text, audio and other ordered representations. Standard sampling has a sequential dependency.
LLMGPT-style LLMs sample a next token given the prompt and the generated prefix.GPT illustrates the overlap: it is both a large language model and an autoregressive model.

Start with a VAE when your project needs an encoder, a compact probabilistic representation, and the ability to reconstruct and generate. For example, if you are exploring handwritten digit variation, you can encode examples, decode intermediate latent points, and compare them with prior samples. Smooth interpolation is an empirical result to check, since points between encoded examples are not necessarily well supported by the training data. If your main goal is high-fidelity image generation, compare with diffusion. A simple pixel likelihood can yield blurry mean reconstructions when several plausible fine details correspond to the same latent code.

Key Takeaways

  • A VAE learns an approximate posterior over latent variables for each input.
  • The encoder outputs a mean and log variance; the decoder outputs observation likelihood parameters.
  • Reparameterisation puts the random draw in a separate noise variable so gradients can reach the encoder parameters.
  • Minimising the negative ELBO balances reconstruction negative log likelihood against KL divergence to the prior.
  • Use the approximate posterior for input-conditioned reconstructions and the prior for unconditional generation.
  • Compare held-out losses, reconstructions, and prior samples to check whether the model uses its latent space productively.

Frequently Asked Questions

What is the main difference between a VAE and an autoencoder?

A standard autoencoder returns a fixed latent code and usually trains on reconstruction error alone. A VAE returns parameters of a distribution over codes and trains with an objective that includes a prior penalty. This gives the VAE a defined procedure for generating new examples: draw a latent code from the prior and decode it.

Why does a VAE predict log variance instead of variance?

A network can freely output any real number as a log variance. Exponentiating that number yields a positive variance without a separate positivity constraint on the output layer. If the output is log variance, exponentiating half of it gives the standard deviation required to scale a standard normal noise sample.

Is ELBO the same as reconstruction loss?

The ELBO includes expected reconstruction log likelihood and subtracts a KL penalty that compares the approximate posterior with the prior. When training by minimisation, the signs flip: the reconstruction negative log likelihood and the KL are added. Tracking both terms helps reveal cases where the total improves while one component deteriorates.

Why do some VAE images look blurry?

When a latent code leaves fine details uncertain, a decoder with a simple pixel likelihood may predict averages across plausible details. Displaying those averages can blur edges. Sampling from the likelihood can replace smooth averages with noisy pixels, so sampling alone may not recover coherent details that the decoder cannot represent.

How do I choose the latent dimension of a VAE?

Start with a small dimension you can inspect, then compare several sizes under the same likelihood and training setup. Evaluate held-out reconstructions, prior samples, and KL per coordinate. A larger latent space may preserve more detail, but extra coordinates can remain unused. Choose the size that meets the needs of the downstream task.

Ready to Master Generative AI Fundamentals?

Join 45,000+ students at Networkers Home. CCIE-certified trainers, 24x7 real lab access, and Placement Guarantee* — structured interview support until placed.

Explore Course