Skip to content
E
Educatum

Explain the core principles of a Variational Autoencoder (VAE) and how it integrates latent variables into its architectural design.

Curated by Educatum AI teamLast updated:
Variational Autoencoders (VAEs)
Direct Answer

A Variational Autoencoder (VAE) is a probabilistic latent-variable generative model whose encoder outputs mean and log-variance parameters of an approximate Gaussian posterior q(z|x), rather than a single deterministic vector. Using the reparameterization trick (z = mu + sigma * epsilon), gradients backpropagate through latent sampling while maximizing the Evidence Lower Bound (ELBO), balancing reconstruction likelihood against KL regularization toward a standard normal prior. Properly scaling reconstruction and KL losses prevents posterior collapse and ensures a smooth, generative latent space.

Study Card: Variational Autoencoders (VAEs)

Direct Answer

A Variational Autoencoder (VAE) (Kingma & Welling, 2013) is a probabilistic generative model that pairs variational inference with neural encoder-decoder networks. Unlike a deterministic autoencoder—which maps inputs to isolated latent points with dead gaps in between—a VAE models each input xx as inducing a distribution qϕ(z∣x)=N(μϕ(x),diag⁡(σϕ2(x)))q_\phi(z \mid x) = \mathcal{N}\big(\mu_\phi(x), \operatorname{diag}(\sigma_\phi^2(x))\big) over latent variables z∈Rdz \in \mathbb{R}^d under a standard Gaussian prior p(z)=N(0,I)p(z) = \mathcal{N}(0, I).

Because the exact marginal log-likelihood log⁡pθ(x)=log⁡∫pθ(x∣z)p(z) dz\log p_\theta(x) = \log \int p_\theta(x \mid z)p(z)\,dz is intractable, VAEs maximize the Evidence Lower Bound (ELBO) (equivalently, minimize −LELBO-\mathcal{L}_{\text{ELBO}}):

log⁡pθ(x)≥LELBO(θ,ϕ;x)=Eqϕ(z∣x)[log⁡pθ(x∣z)]−DKL(qϕ(z∣x) ∥ p(z))\log p_\theta(x) \ge \mathcal{L}_{\text{ELBO}}(\theta, \phi; x) = \mathbb{E}_{q_\phi(z \mid x)}\big[\log p_\theta(x \mid z)\big] - D_{\text{KL}}\big(q_\phi(z \mid x) \,\|\, p(z)\big)

For a diagonal Gaussian posterior and standard normal prior, the KL divergence has an exact closed form:

DKL(qϕ(z∣x) ∥ p(z))=−12∑j=1d(1+log⁡σj2−μj2−σj2)D_{\text{KL}}\big(q_\phi(z \mid x) \,\|\, p(z)\big) = -\frac{1}{2}\sum_{j=1}^d \left(1 + \log \sigma_j^2 - \mu_j^2 - \sigma_j^2\right)

To backpropagate gradients through stochastic latent sampling, VAEs use the reparameterization trick:

z=μ+σ⊙ε,ε∼N(0,I)z = \mu + \sigma \odot \varepsilon, \qquad \varepsilon \sim \mathcal{N}(0, I)

Note a classic implementation pitfall: both reconstruction NLL (∑i=1DBCE(xi,x^i)\sum_{i=1}^D \text{BCE}(x_i, \hat{x}_i)) and KL divergence (∑j=1dKLj\sum_{j=1}^d \text{KL}_j) must be summed over feature/latent dimensions (and averaged over the batch). Using mean BCE over DD pixels while summing KL over dd dims creates a D×D\times KL imbalance and causes posterior collapse (qϕ(z∣x)≈p(z)q_\phi(z \mid x) \approx p(z)).

Key Terms

  • Latent Variables (zz): Continuous hidden factors (z∼N(0,I)z \sim \mathcal{N}(0, I)) capturing underlying variation in data.
  • ELBO (Evidence Lower Bound): Sum of expected reconstruction log-likelihood minus KL divergence toward the prior p(z)p(z).
  • Reparameterization Trick: Expressing z=μ+exp⁡(12log⁡σ2)⊙εz = \mu + \exp(\frac{1}{2}\log \sigma^2) \odot \varepsilon so randomness lives in parameter-free ε\varepsilon, enabling backpropagation into μ\mu and log⁡σ2\log \sigma^2.
  • Posterior Collapse: Failure mode where the KL penalty overpowers reconstruction and the decoder ignores zz.
  • β\beta-VAE: Scales KL divergence by β>1\beta > 1 to encourage disentangled latent factors at the cost of reconstruction fidelity.

Example

Consider training a VAE on 28×2828 \times 28 handwritten digit images (D=784D = 784) with a 2D latent space (d=2d = 2):

  • The encoder outputs (μ,log⁡σ2)∈R2×R2(\mu, \log \sigma^2) \in \mathbb{R}^2 \times \mathbb{R}^2 for each digit, overlapping smooth Gaussian clouds in latent space so neighboring latent points decode into coherent transitions (e.g., morphing a "3" smoothly into an "8").
  • After training, sampling any z∼N(0,I)z \sim \mathcal{N}(0, I) and passing it through the decoder alone generates novel digits.
  • In modern Latent Diffusion Models (e.g., Stable Diffusion), a perceptual/KL-regularized VAE compresses high-resolution RGB images into compact spatial latents before diffusion runs in latent space.

Code Implementation

import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim


class VAE(nn.Module):
    def __init__(self, input_dim=784, hidden_dim=256, latent_dim=16):
        super().__init__()
        self.encoder = nn.Sequential(
            nn.Linear(input_dim, hidden_dim),
            nn.ReLU(),
        )
        self.fc_mu = nn.Linear(hidden_dim, latent_dim)
        self.fc_logvar = nn.Linear(hidden_dim, latent_dim)

        self.decoder = nn.Sequential(
            nn.Linear(latent_dim, hidden_dim),
            nn.ReLU(),
            nn.Linear(hidden_dim, input_dim),  # Outputs raw logits for BCE-with-logits
        )

    def encode(self, x):
        h = self.encoder(x)
        return self.fc_mu(h), self.fc_logvar(h)

    def reparameterize(self, mu, logvar):
        std = torch.exp(0.5 * logvar)
        eps = torch.randn_like(std)
        return mu + eps * std

    def forward(self, x):
        mu, logvar = self.encode(x)
        z = self.reparameterize(mu, logvar)
        recon_logits = self.decoder(z)
        return recon_logits, mu, logvar


def vae_elbo_loss(recon_logits, x, mu, logvar):
    """Exact negative ELBO: sum over data & latent dims, then average over batch."""
    recon_loss = F.binary_cross_entropy_with_logits(recon_logits, x, reduction="none").sum(dim=1)
    kl_loss = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp(), dim=1)
    return (recon_loss + kl_loss).mean(), recon_loss.mean(), kl_loss.mean()


torch.manual_seed(0)
input_dim, latent_dim = 128, 8
vae = VAE(input_dim=input_dim, hidden_dim=64, latent_dim=latent_dim)
optimizer = optim.AdamW(vae.parameters(), lr=1e-3)

# Synthetic binary-like probabilities in [0, 1]
x_batch = torch.sigmoid(torch.randn(64, input_dim))

for step in range(1, 21):
    recon_logits, mu, logvar = vae(x_batch)
    loss, recon, kl = vae_elbo_loss(recon_logits, x_batch, mu, logvar)
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

    if step in (1, 10, 20):
        print(f"Step {step:2d} | Neg-ELBO: {loss.item():.2f} (Recon: {recon.item():.2f}, KL: {kl.item():.2f})")

# Sample new synthetic data points directly from the prior p(z) = N(0, I)
vae.eval()
with torch.no_grad():
    z_prior = torch.randn(4, latent_dim)
    generated = torch.sigmoid(vae.decoder(z_prior))
print("Generated samples shape:", generated.shape)
  • Standard Autoencoder vs. VAE: Deterministic autoencoders learn unregularized latent encodings prone to holes; VAEs enforce a continuous probabilistic prior enabling generation.
  • GANs vs. VAEs: VAEs offer stable optimization and explicit lower-bound likelihood estimation; GANs often yield sharper samples without explicit density bounds.
  • VQ-VAE (Vector Quantized VAE): Replaces continuous Gaussian latents with a discrete codebook via straight-through estimation, powering multimodal tokenization.
  • Latent Diffusion Models: Rely on a KL-VAE to compress pixels into perceptual latent grids before denoising.
View all →

Try keywords like RoPE, FlashAttention, DPO, or Blind 75.