A Rigorous Mathematical Exploration of Variational Autoencoders
Introduction
Variational Autoencoders (VAEs) represent a fascinating fusion of deep learning and probabilistic modeling. This post aims to provide a comprehensive exploration of VAEs, balancing rigorous mathematics with practical examples and applications. We'll journey from foundational concepts to advanced theoretical insights, making this exploration accessible to both theoretically inclined beginners, regular readers and practitioners. We will certainly try our best to make you understand how to use VAE in generating an image using a toy example.
Probabilistic Foundations
Measure-Theoretic Probability
Let be a probability space, where:
- is the sample space
- is a -algebra on
- is a probability measure
Toy Example: Imagine we're modeling the process of generating handwritten digits. Here, could be all possible 28x28 pixel images, would be sets of these images (e.g., all images of the digit "7"), and would assign probabilities to these sets.
Random Variables and Distributions
Let and be random variables representing observed and latent data respectively.
The core of VAE theory lies in the following decomposition:
where is the prior over latent variables and is the likelihood.
Proof: This follows directly from the definition of conditional probability:
Practical Example: In our handwritten digit VAE:
- could be a 28x28 image of a digit
- could be a 10-dimensional vector encoding factors like stroke width, tilt, etc.
- might be a standard normal distribution
- would be our decoder network, generating an image given a latent code
The Variational Inference Framework
The Evidence Lower Bound (ELBO)
Theorem (Evidence Lower Bound): For any distributions and ,
Proof:
Practical Implementation: In PyTorch, we might implement the ELBO loss as:
def elbo_loss(x, x_recon, mu, logvar):
recon_loss = F.mse_loss(x_recon, x, reduction='sum')
kl_div = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())
return recon_loss + kl_div
ELBO Decomposition
We can further decompose the ELBO:
Proof:
Application: In image generation, this decomposition shows us we're balancing two objectives:
- Reconstruction accuracy: How well can we reconstruct the input image?
- Latent space regularity: How close is our encoded distribution to the prior?
The Reparameterization Trick
Theorem (Reparameterization Trick): Let be a differentiable transformation. Then,
where is drawn from some fixed distribution .
Proof: Let where . Then,
PyTorch Implementation:
class VAE(nn.Module):
def __init__(self):
super(VAE, self).__init__()
self.encoder = Encoder()
self.decoder = Decoder()
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)
return self.decoder(z), mu, logvar
Advanced ELBO Analysis
Theorem (Information-Theoretic ELBO Decomposition): The ELBO can be expressed as:
where is the mutual information between and under , and is the entropy of the data distribution.
Proof:
Application: This decomposition reveals insights for disentangled representation learning. By explicitly controlling , we can encourage the model to learn more interpretable latent factors.
Normalizing Flows and VAEs
Theorem (Change of Variables Formula for Normalizing Flows): Let be a normalizing flow. Then,
Proof: By the change of variables formula and the chain rule:
Practical Example: Implementing a simple planar flow in PyTorch:
class PlanarFlow(nn.Module):
def __init__(self, dim):
super(PlanarFlow, self).__init__()
self.w = nn.Parameter(torch.randn(dim))
self.b = nn.Parameter(torch.randn(1))
self.u = nn.Parameter(torch.randn(dim))
def forward(self, z):
linear_term = torch.sum(self.w * z, dim=1, keepdim=True) + self.b
return z + self.u * torch.tanh(linear_term)
def log_det_jacobian(self, z):
linear_term = torch.sum(self.w * z, dim=1, keepdim=True) + self.b
psi = (1 - torch.tanh(linear_term)**2) * self.w
return torch.log(torch.abs(1 + torch.sum(psi * self.u, dim=1, keepdim=True)))
Tighter Variational Bounds
Theorem (IWAE Bound): For any number of samples ,
Proof: By Jensen's inequality and the concavity of log:
PyTorch Implementation:
def iwae_loss(x, model, K=10):
x_expanded = x.unsqueeze(0).expand(K, *x.shape)
x_recon, mu, logvar = model(x_expanded)
z = model.reparameterize(mu, logvar)
log_p_x_given_z = -F.mse_loss(x_recon, x_expanded, reduction='none').sum(dim=(1,2,3))
log_p_z = -0.5 * z.pow(2).sum(dim=1)
log_q_z_given_x = -0.5 * (logvar + (z - mu).pow(2) / logvar.exp()).sum(dim=1)
log_w = log_p_x_given_z + log_p_z - log_q_z_given_x
return -torch.logsumexp(log_w, dim=0) + np.log(K)
Mathematical Model of a VAE for Image Generation
Let's develop a rigorous mathematical model for a VAE designed to generate images, accompanied by a toy example to illustrate the concepts.
Data and Latent Space
Let be our data space, representing all possible grayscale images. Each is a flattened vector of pixel intensities.
Let be our latent space, where is the dimensionality of the latent representation.
Toy Example: Let's consider a very simple case where:
- Our images are 3x3 grayscale (n = 3)
- Our latent space is 2-dimensional (d = 2)
So, and
A sample image might look like:
[0.1, 0.5, 0.9]
[0.2, 0.6, 0.8]
[0.3, 0.7, 0.4]
Which we'd flatten to: x = [0.1, 0.5, 0.9, 0.2, 0.6, 0.8, 0.3, 0.7, 0.4]
Generative Model
We define our generative model as follows:
Prior: , where is the -dimensional identity matrix.
Decoder: , where:
- is a neural network with parameters
- is a fixed variance for simplicity (though this could also be learned)
Toy Example: Let's define a simple decoder network:
Where:
Let
Inference Model
Our inference model (encoder) is defined as:
where:
- is a neural network with parameters
- is a neural network outputting a diagonal covariance matrix
Toy Example: Let's define a simple encoder network:
Where:
The output is split into and (diagonal elements of the covariance matrix in log space).
7.4 ELBO for Image Generation
The Evidence Lower Bound (ELBO) for our image generation VAE is:
Let's expand each term:
- Reconstruction term:
where we've used a single sample approximation for the expectation.
- KL divergence term:
Toy Example Calculation: Let's calculate the ELBO for our sample image x = [0.1, 0.5, 0.9, 0.2, 0.6, 0.8, 0.3, 0.7, 0.4]
Encode: Suppose and
Sample z: (sampled from )
Decode: Suppose
Reconstruction term:
KL divergence term:
ELBO:
Optimization Objective
Our final optimization objective is to maximize the ELBO:
which is equivalent to minimizing the negative ELBO:
Toy Example: In practice, we would use stochastic gradient descent to optimize this objective over a dataset of images. For our single image example, one step of gradient descent might look like:
Where is the learning rate.
Image Generation Process
To generate a new image:
- Sample
- Compute
- Sample
- Reshape the resulting vector into an image
Toy Example:
- Sample from
- Compute
- Sample from , say we get:
- Reshape into a 3x3 image:
[0.25, 0.35, 0.55] [0.35, 0.45, 0.75] [0.15, 0.85, 0.95]
Theoretical Properties
Consistency: As the number of training samples approaches infinity and with sufficient model capacity, the VAE converges to the true data distribution.
Manifold Learning: The VAE learns a low-dimensional manifold in that captures the structure of the image data.
Disentanglement: Under certain conditions (e.g., using a β-VAE formulation), the latent space can capture disentangled factors of variation in the images.
Sample Quality vs. Reconstruction Quality Trade-off: There's an inherent tension between generating high-quality samples and accurately reconstructing inputs, controlled by the weight of the KL divergence term.
Toy Example Illustration: In our 2D latent space, we might find that:
- One dimension controls the overall brightness of the image
- The other dimension controls the contrast between the center and edges
This would be an example of learning a disentangled representation, where each latent dimension corresponds to a meaningful factor of variation in the data.
Conclusion
Through this detailed exploration of VAEs for image generation, complete with a toy example, we've seen how these models bridge the gap between deep learning and probabilistic modeling. The mathematical formulation provides a rigorous foundation, while the toy example offers concrete insights into how VAEs operate in practice.
This combination of theory and example illustrates the power of VAEs in learning compact, meaningful representations of complex data like images. As we continue to advance both the theory and application of VAEs, we open up new possibilities in generative modeling, representation learning, and beyond.