🖊️ ing down my thoughts here

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 (Ω,,P) be a probability space, where:

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 P would assign probabilities to these sets.

Random Variables and Distributions

Let X:Ω𝒳 and Z:Ω𝒵 be random variables representing observed and latent data respectively.

The core of VAE theory lies in the following decomposition:

p(x,z)=p(x|z)p(z)

where p(z) is the prior over latent variables and p(x|z) is the likelihood.

Proof: This follows directly from the definition of conditional probability:

p(x,z)=p(x|z)p(z)(by definition of conditional probability)=p(z|x)p(x)(alternative factorization)

Practical Example: In our handwritten digit VAE:

The Variational Inference Framework

The Evidence Lower Bound (ELBO)

Theorem (Evidence Lower Bound): For any distributions q(z|x) and p(x,z),

logp(x)𝔼q(z|x)[logp(x,z)logq(z|x)]ELBO(x)

Proof:

logp(x)=logp(x,z)dz=logp(x,z)q(z|x)q(z|x)dz=log𝔼q(z|x)[p(x,z)q(z|x)]𝔼q(z|x)[logp(x,z)q(z|x)](by Jensen's inequality)

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:

ELBO(x)=𝔼q(z|x)[logp(x|z)]KL(q(z|x)||p(z))

Proof:

ELBO(x)=𝔼q(z|x)[logp(x,z)logq(z|x)]=𝔼q(z|x)[logp(x|z)+logp(z)logq(z|x)]=𝔼q(z|x)[logp(x|z)]+𝔼q(z|x)[logp(z)logq(z|x)]=𝔼q(z|x)[logp(x|z)]KL(q(z|x)||p(z))

Application: In image generation, this decomposition shows us we're balancing two objectives:

  1. Reconstruction accuracy: How well can we reconstruct the input image?
  2. Latent space regularity: How close is our encoded distribution to the prior?

The Reparameterization Trick

Theorem (Reparameterization Trick): Let gϕ(ϵ,x) be a differentiable transformation. Then,

𝔼qϕ(z|x)[f(z)]=𝔼ϵ~p(ϵ)[f(gϕ(ϵ,x))]

where ϵ is drawn from some fixed distribution p(ϵ).

Proof: Let z=gϕ(ϵ,x) where ϵ~p(ϵ). Then,

𝔼qϕ(z|x)[f(z)]=f(z)qϕ(z|x)dz=f(gϕ(ϵ,x))p(ϵ)dϵ(by change of variables)=𝔼ϵ~p(ϵ)[f(gϕ(ϵ,x))]

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:

ELBO=𝔼pdata(x)[𝔼qϕ(z|x)[logpθ(x|z)]]Iq(x;z)+H(x)

where Iq(x;z) is the mutual information between x and z under qϕ(x,z)=pdata(x)qϕ(z|x), and H(x) is the entropy of the data distribution.

Proof:

ELBO=𝔼pdata(x)[𝔼qϕ(z|x)[logpθ(x|z)]KL(qϕ(z|x)||p(z))]=𝔼pdata(x)[𝔼qϕ(z|x)[logpθ(x|z)]]𝔼pdata(x)[KL(qϕ(z|x)||p(z))]=𝔼pdata(x)[𝔼qϕ(z|x)[logpθ(x|z)]](Iq(x;z)+𝔼pdata(x)[KL(qϕ(z|x)||qϕ(z))])=𝔼pdata(x)[𝔼qϕ(z|x)[logpθ(x|z)]]Iq(x;z)+H(x)

Application: This decomposition reveals insights for disentangled representation learning. By explicitly controlling Iq(x;z), we can encourage the model to learn more interpretable latent factors.

Normalizing Flows and VAEs

Theorem (Change of Variables Formula for Normalizing Flows): Let zK=fK...f1(z0) be a normalizing flow. Then,

logqK(zK)=logq0(z0)k=1Klog|detfkzk1|

Proof: By the change of variables formula and the chain rule:

qK(zK)=q0(z0)k=1K|detfk1zk|logqK(zK)=logq0(z0)+k=1Klog|detfk1zk|=logq0(z0)k=1Klog|detfkzk1|

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 K,

logp(x)𝔼z1,...,zK~qϕ(z|x)[log1Kk=1Kpθ(x,zk)qϕ(zk|x)]K

Proof: By Jensen's inequality and the concavity of log:

logp(x)=log𝔼z~qϕ(z|x)[pθ(x,z)qϕ(z|x)]=log𝔼z1,...,zK~qϕ(z|x)[1Kk=1Kpθ(x,zk)qϕ(zk|x)]𝔼z1,...,zK~qϕ(z|x)[log1Kk=1Kpθ(x,zk)qϕ(zk|x)]

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 𝒳=[0,1]n2 be our data space, representing all possible n×n grayscale images. Each x𝒳 is a flattened vector of pixel intensities.

Let 𝒵=d be our latent space, where d is the dimensionality of the latent representation.

Toy Example: Let's consider a very simple case where:

So, 𝒳=[0,1]9 and 𝒵=2

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:

  1. Prior: p(z)=𝒩(0,Id), where Id is the d-dimensional identity matrix.

  2. Decoder: pθ(x|z)=𝒩(μθ(z),σ2In2), where:

    • μθ:d[0,1]n2 is a neural network with parameters θ
    • σ2 is a fixed variance for simplicity (though this could also be learned)

Toy Example: Let's define a simple decoder network:

μθ(z)=sigmoid(W2·ReLU(W1z+b1)+b2)

Where: W14×2,b14,W29×4,b29

Let σ2=0.1

Inference Model

Our inference model (encoder) is defined as:

qϕ(z|x)=𝒩(μϕ(x),Σϕ(x))

where:

Toy Example: Let's define a simple encoder network:

[μϕ(x),logΣϕ(x)]=W4·ReLU(W3x+b3)+b4

Where: W36×9,b36,W44×6,b44

The output is split into μϕ(x)2 and logΣϕ(x)2 (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:

ELBO(x)=𝔼qϕ(z|x)[logpθ(x|z)]KL(qϕ(z|x)||p(z))

Let's expand each term:

  1. Reconstruction term:
𝔼qϕ(z|x)[logpθ(x|z)]&=𝔼qϕ(z|x)[n22log(2πσ2)12σ2||xμθ(z)||2]&n22log(2πσ2)12σ2||xμθ(μϕ(x))||2

where we've used a single sample approximation for the expectation.

  1. KL divergence term:
KL(qϕ(z|x)||p(z))=12(tr(Σϕ(x))+μϕ(x)Tμϕ(x)dlogdet(Σϕ(x)))

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]

  1. Encode: Suppose μϕ(x)=[0.5,0.3] and logΣϕ(x)=[1.2,0.8]

  2. Sample z: z=[0.4,0.5] (sampled from 𝒩(μϕ(x),Σϕ(x)))

  3. Decode: Suppose μθ(z)=[0.15,0.45,0.85,0.25,0.55,0.75,0.35,0.65,0.45]

  4. Reconstruction term: 92log(2π·0.1)12·0.1(0.10.15)2+...+(0.40.45)210.5

  5. KL divergence term: 12(e1.2+e0.8+0.52+(0.3)22+1.2+0.8)0.3

  6. ELBO: ELBO(x)10.50.3=10.8

Optimization Objective

Our final optimization objective is to maximize the ELBO:

maxθ,ϕ𝔼pdata(x)[ELBO(x)]

which is equivalent to minimizing the negative ELBO:

minθ,ϕ𝔼pdata(x)[12σ2||xμθ(μϕ(x))||2+12(tr(Σϕ(x))+μϕ(x)Tμϕ(x)dlogdet(Σϕ(x)))]

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:

θθ+αθELBO(x)ϕϕ+αϕELBO(x)

Where α is the learning rate.

Image Generation Process

To generate a new image:

  1. Sample z~𝒩(0,Id)
  2. Compute μθ(z)
  3. Sample x~𝒩(μθ(z),σ2In2)
  4. Reshape the resulting vector into an n×n image

Toy Example:

  1. Sample z=[0.1,0.7] from 𝒩(0,I2)
  2. Compute μθ(z)=[0.2,0.4,0.6,0.3,0.5,0.7,0.1,0.8,0.9]
  3. Sample x from 𝒩(μθ(z),0.1I9), say we get: x=[0.25,0.35,0.55,0.35,0.45,0.75,0.15,0.85,0.95]
  4. 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

  1. Consistency: As the number of training samples approaches infinity and with sufficient model capacity, the VAE converges to the true data distribution.

  2. Manifold Learning: The VAE learns a low-dimensional manifold in 𝒵 that captures the structure of the image data.

  3. Disentanglement: Under certain conditions (e.g., using a β-VAE formulation), the latent space can capture disentangled factors of variation in the images.

  4. 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:

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.