Post

Variational Autoencoders (VAEs) - Fundamentals

Variational Autoencoders (VAEs) - Fundamentals

Variational Autoencoders (VAEs) are a powerful class of generative models that learn to encode data into a lower-dimensional latent space and decode it back to reconstruct the original data. VAEs combine the power of neural networks with probabilistic modeling to generate new, realistic data samples.

What are VAEs?

VAEs are generative models that learn a probabilistic mapping between a high-dimensional data space and a lower-dimensional latent space. Unlike traditional autoencoders, VAEs impose a probabilistic structure on the latent space, enabling controlled generation of new data.

Key Components

  1. Encoder (Recognition Model): Maps input data $x$ to latent variables $z$
  2. Decoder (Generative Model): Maps latent variables $z$ back to reconstructed data $\hat{x}$
  3. Latent Space: Lower-dimensional probabilistic representation

Mathematical Foundation

The Probabilistic Framework

VAEs are based on the assumption that data $x$ is generated from a latent variable $z$ through a probabilistic process:

\[p(x) = \int p(x|z) p(z) dz\]

Where:

  • $p(z)$ is the prior distribution over latent variables (typically $\mathcal{N}(0, I)$)
  • $p(xz)$ is the likelihood function (decoder)
  • $p(zx)$ is the posterior distribution (encoder)

The Variational Lower Bound

Since the true posterior $p(zx)$ is intractable, VAEs approximate it with a variational distribution $q_\phi(zx)$ parameterized by $\phi$. The objective is to maximize the Evidence Lower BOund (ELBO):
\[\log p(x) \geq \mathbb{E}_{q_\phi(z|x)}[\log p_\theta(x|z)] - D_{KL}(q_\phi(z|x) \| p(z)) = \mathcal{L}(\theta, \phi; x)\]

Where:

  • $\mathbb{E}{q\phi(zx)}[\log p_\theta(xz)]$ is the reconstruction term
  • $D_{KL}(q_\phi(zx) | p(z))$ is the KL divergence regularization term

Reparameterization Trick

To enable gradient-based optimization, VAEs use the reparameterization trick:

\[z = \mu_\phi(x) + \sigma_\phi(x) \odot \epsilon, \quad \epsilon \sim \mathcal{N}(0, I)\]

This allows gradients to flow through the stochastic sampling process.

Architecture Details

Encoder Network

The encoder outputs parameters of the approximate posterior:

\[q_\phi(z|x) = \mathcal{N}(\mu_\phi(x), \sigma_\phi^2(x) I)\]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Encoder(nn.Module):
    def __init__(self, input_dim, hidden_dim, latent_dim):
        super().__init__()
        self.fc1 = nn.Linear(input_dim, hidden_dim)
        self.fc2 = nn.Linear(hidden_dim, hidden_dim)
        self.fc_mu = nn.Linear(hidden_dim, latent_dim)
        self.fc_logvar = nn.Linear(hidden_dim, latent_dim)
    
    def forward(self, x):
        h = F.relu(self.fc1(x))
        h = F.relu(self.fc2(h))
        mu = self.fc_mu(h)
        logvar = self.fc_logvar(h)
        return mu, logvar

Decoder Network

The decoder reconstructs data from latent samples:

\[p_\theta(x|z) = \mathcal{N}(\mu_\theta(z), \sigma^2 I)\]
1
2
3
4
5
6
7
8
9
10
11
class Decoder(nn.Module):
    def __init__(self, latent_dim, hidden_dim, output_dim):
        super().__init__()
        self.fc1 = nn.Linear(latent_dim, hidden_dim)
        self.fc2 = nn.Linear(hidden_dim, hidden_dim)
        self.fc3 = nn.Linear(hidden_dim, output_dim)
    
    def forward(self, z):
        h = F.relu(self.fc1(z))
        h = F.relu(self.fc2(h))
        return torch.sigmoid(self.fc3(h))

Training Process

Loss Function

The VAE loss combines reconstruction and regularization terms:

\[\mathcal{L} = \mathbb{E}_{q_\phi(z|x)}[\log p_\theta(x|z)] - \beta \cdot D_{KL}(q_\phi(z|x) \| p(z))\]

Where $\beta$ controls the trade-off between reconstruction quality and latent space regularization.

Training Algorithm

  1. Forward Pass: Encode input $x$ to get $\mu$ and $\sigma$
  2. Sampling: Sample $z \sim q_\phi(zx)$ using reparameterization trick
  3. Reconstruction: Decode $z$ to get $\hat{x}$
  4. Loss Computation: Calculate reconstruction + KL divergence loss
  5. Backpropagation: Update encoder and decoder parameters

Applications

Data Generation

VAEs can generate new samples by sampling from the prior:

\(z \sim p(z) = \mathcal{N}(0, I)\) \(\hat{x} \sim p_\theta(x|z)\)

Data Compression

The latent representation provides a compressed version of the data while preserving essential information.

Anomaly Detection

VAEs can identify anomalies by measuring reconstruction error - normal data should have low reconstruction error.

Representation Learning

The learned latent space often captures meaningful semantic features of the data.

Advantages and Limitations

Advantages

  • Probabilistic Framework: Provides uncertainty estimates
  • Controllable Generation: Can interpolate in latent space
  • End-to-End Training: Joint optimization of encoder and decoder
  • Theoretical Foundation: Well-grounded in variational inference

Limitations

  • Blurry Reconstructions: Often produces smooth, averaged outputs
  • Posterior Collapse: Encoder may ignore latent variables
  • Mode Collapse: May generate limited variety of samples
  • KL Vanishing: KL term may become too small during training

Variants and Improvements

$\beta$-VAE

Introduces a hyperparameter $\beta$ to control the trade-off between reconstruction and regularization:

\[\mathcal{L} = \mathbb{E}[\log p_\theta(x|z)] - \beta \cdot D_{KL}(q_\phi(z|x) \| p(z))\]

Conditional VAE (C-VAE)

Incorporates additional conditioning information:

\[p(x|c) = \int p(x|z,c) p(z|c) dz\]

VAE-GAN

Combines VAE with GAN discriminator for sharper reconstructions.

Hierarchical VAE

Uses multiple levels of latent variables for more complex representations.

Practical Tips

Architecture Design

  • Use batch normalization for stable training
  • Start with simple architectures (2-3 hidden layers)
  • Choose appropriate latent dimension (typically 2-512)

Training Considerations

  • Monitor KL divergence to avoid posterior collapse
  • Use warm-up schedules for $\beta$ parameter
  • Apply gradient clipping for stability

Evaluation Metrics

  • Reconstruction Loss: MSE or BCE depending on data type
  • KL Divergence: Should be non-zero but not too large
  • Perceptual Metrics: FID, IS for image generation
  • Latent Space Quality: Interpolation smoothness

Implementation Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class VAE(nn.Module):
    def __init__(self, input_dim, hidden_dim, latent_dim):
        super().__init__()
        self.encoder = Encoder(input_dim, hidden_dim, latent_dim)
        self.decoder = Decoder(latent_dim, hidden_dim, input_dim)
    
    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.encoder(x)
        z = self.reparameterize(mu, logvar)
        recon = self.decoder(z)
        return recon, mu, logvar
    
    def loss_function(self, recon_x, x, mu, logvar, beta=1.0):
        BCE = F.binary_cross_entropy(recon_x, x, reduction='sum')
        KLD = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())
        return BCE + beta * KLD

Conclusion

VAEs provide a principled approach to generative modeling with strong theoretical foundations. While they may produce blurrier outputs compared to GANs, their probabilistic nature and controllable generation make them valuable for many applications. Understanding VAEs is essential for anyone working in generative AI, as they form the basis for many advanced models and techniques.

Further Reading


This post covers the fundamentals of Variational Autoencoders. Future posts will explore advanced VAE variants and applications.

This post is licensed under CC BY 4.0 by the author.