In [1]:
%matplotlib inline

import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_moons

import torch
import torch.nn as nn 
import torch.nn.functional as F
from torch.utils.data import TensorDataset, DataLoader

device = 'cuda' if torch.cuda.is_available() else 'cpu'
In [2]:
# ----- data -----
X, y = make_moons(n_samples=2500, noise=0.1, random_state=0)
X = (X - X.mean(0)) / X.std(0) # standardize

def plot_moons(X, title="2D Moons Dataset"):
    # plot
    plt.figure(figsize=(5, 5))
    plt.scatter(X[:,0], X[:,1], s=10, alpha=0.7)
    plt.title(title)
    plt.xlabel("x1")
    plt.ylabel("x2")
    plt.gca().set_aspect('equal', adjustable='box')
    plt.show()

plot_moons(X)

def dataloader(X, y, batch_size=64, shuffle=True):    
    X = torch.tensor(X, dtype=torch.float32)
    y = torch.tensor(y, dtype=torch.int64)
    data = TensorDataset(X, y)
    return DataLoader(data, batch_size=batch_size, shuffle=shuffle)

loader = dataloader(X, y, batch_size=128, shuffle=True)

Semi-supervised and generative models¶

In the lectures the Variational Autoencoder (VAE) was introduced as a specific generative latent variable model. Compared to probabilistic PCA, VAE employs nonlinear functions (neural network) for encoding and decoding, and its learning is achieved by maximizing the evidence lower bound (ELBO).

Exercise 9.1 - Understand and derive the ELBO¶

Given observed data points $\{ x_n \}_{n=1}^N$ distributed according to some unknown data distribution $p_\mathrm{data}(x)$, the goal of generative models is to learn a model $p_\theta(x)$ that we can sample from, such that $p_\theta(x)$ is as similar to $p_\mathrm{data}(x)$ as possible.

Let's consider the following latent variable model:

$$ x \sim p_\theta(x|z), \quad z \sim p(z). $$

where $p(z)$ could be a simple Gaussian and $\theta$ is the parameter of a neural network. Then the marginal likelihood of $x$ can be writen as

$$ p_\theta(x) = \int p_\theta(x | z) p(z) dz, $$

which is the objective we want to maximize. But unfortunately, this integral is usually intractable due to the nonlinar and high-dimensional functions (i.e., neural network) inside $z$! Instead, we try to find a lower bound on $p_\theta(x)$ that is easier to compute, which gives the ELBO objective.

Specifically, we focus on maximizing the log-likelihood $\log p_\theta(x)$ by introducing an approximate posterior $q_\phi(z|x)$, as

$$ \log p_\theta(x) = \log \int p_\theta(x|z) p(z) \, dz = \log \int q_\phi(z|x)\,\frac{p_\theta(x|z) p(z)}{q_\phi(z|x)} dz = \log \mathbb{E}_{q_\phi(z|x)}\left[\frac{p_\theta(x|z) p(z)}{q_\phi(z|x)}\right]. $$

Applying Jensen's Inequality to this equation results in the Evidence Lower BOund (ELBO):

$$ \begin{aligned} \mathcal{L}(x; \theta, \phi) &= \log \mathbb{E}_{q_\phi(z|x)}\left[\frac{p_\theta(x|z) p(z)}{q_\phi(z|x)}\right] \\ &\geq \mathbb{E}_{q_\phi(z|x)}\left[\log \frac{p_\theta(x|z) p(z)}{q_\phi(z|x)}\right] \\ &= \mathbb{E}_{q_\phi(z|x)}\left[\log p_\theta(x|z)\right] - D_{KL}(q_\phi(z|x) \| p(z)). \end{aligned} $$

The first term $\mathbb{E}_{q_\phi(z|x)}\left[\log p_\theta(x|z)\right]$ is called the reconstruction loss maximizing the log-likelihood and the second term $-D_{KL}(q_\phi(z|x) \| p(z))$ is a regularizer minimizing the distance between $q_\phi(z|x)$ and $p(z)$.

So, optimizing the ELBO means learning an encoder ($\phi$) and a decoder ($\theta$) that fits the dataset while ensuring the encoded latent variable $z$ remains close to the prior $p(z)$.

Exercise 9.2 - Implement the VAE¶

In this exercise, you will learn the key techniques that make VAEs actually trainable and will implement the VAE on a small dataset.

Compute the KL divergence¶

Note that the KL term has a closed-form if both the approximate posterior $q_\phi(z|x)$ and prior $p(z)$ are Gaussian distribution. For example, we define $p(z)$ a standard multivariate Gaussian and $q_\phi(z|x)$ a multivariate Gaussian with a diagonal covariance matrix:

$$ p(z) = \mathcal{N}(0, I), \quad q_\phi(z|x) = \mathcal{N}(\mu_\phi(x), \mathrm{diag}(\sigma^2_\phi(x))). $$

The KL divergence between them has a simple yet analytical solution given by

$$ D_{KL}(q_\phi(z|x) \| p(z)) = -\frac{1}{2} \sum_{n=1}^N (1 + \log (\sigma_\phi^2(x_n)) - \mu_\phi^2(x_n) - \sigma_\phi^2(x_n)), $$

where $N$ is the number of dimensions in the latent space. $\mu_\phi$ and $\sigma_\phi^2$ are the mean and variance generated by the encoder, respectively.

(a) KL Implementation:

In [3]:
def kl_std_normal(mu, logvar):
    # mu and logvar are the outputs of the encoder network, shape (batch_size, latent_dim)
    # returns KL(N(mu, diag(sigma^2)) || N(0, I)) for every data point, shape (batch_size,)
    kl = ...
    kl = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp(), dim=-1)
    return kl

Reparameterization trick¶

The question now turns to how to compute the expectation over posterior i.e., $\mathbb{E}_{z \sim q_\phi(z|x)}\left[\log p_\theta(x|z)\right]$). However, the latent variable $z$ is sampled from $q_\phi(z | x)$, whose parameter $\phi$ is what we want to optimize as well. And the sampling process itself, such as , is not differentiable. Then how can we compute the gradient $\nabla_\phi$ from the random sampling node and make sure it is avaiable in backpropagation? The solution is the Reparameterization Trick.

The trick is to separate the randomness from the parameters. Instead of directly sampling $z \sim q_\phi(z | x)$, we generate $z$ from the following two steps:

  1. Sample a random noise from the standard normal distribution: $\epsilon \sim \mathcal{N}(0, I)$.
  2. Obtain $z$ from a deterministic, differentiable function: $z = \mu_\phi(x) + \sigma_\phi(x) \cdot \epsilon$.

In this way, $z$ is still a random variable with distribution $\mathcal{N}(\mu_\phi(x), \sigma^2_\phi(x))$, but the randomness comes entirely from $\epsilon$ rather than the encoder.

(b) Sampling Implementation:

In [4]:
def reparameterize(mu, logvar):
    # sample z ~ N(mu, diag(exp(logvar))) with the reparameterization trick
    # z = mu + sigma * eps, eps ~ N(0, I)
    z = ...
    std = torch.exp(0.5 * logvar)
    eps = torch.randn_like(std)
    z = mu + std * eps
    return z

(c) The final ELBO loss function:

In [5]:
def elbo_loss(model, x, beta=0.1):
    # encode x, sample z with the reparameterization trick and decode z
    x_hat = ...

    # Reconstruction loss (L1 error summed over the data dimensions), shape (batch_size,)
    recon_loss = ...

    # KL divergence loss, shape (batch_size,)
    kl_loss = ...

    # negative ELBO averaged over the mini-batch
    loss = ...
    mu, logvar = model.encode(x)
    z = reparameterize(mu, logvar)
    x_hat = model.decode(z)

    # Reconstruction loss
    recon_loss = F.l1_loss(x_hat, x, reduction='none').sum(dim=1)
    
    # KL divergence loss
    kl_loss = kl_std_normal(mu, logvar)
    loss = (recon_loss + beta * kl_loss).mean()
    return loss, recon_loss.mean().detach(), kl_loss.mean().detach()

Now we can define the Network architecture and train the VAE model.

Task: Read through and understand the implementation of the training procedure.

In [6]:
class VAE(nn.Module):
    def __init__(self, dim=128):
        super(VAE, self).__init__()

        # nonlinear encoder with parameter theta
        self.encoder = nn.Sequential(
            nn.Linear(2, dim), nn.ReLU(),
            nn.Linear(dim, dim), nn.ReLU(),
            nn.Linear(dim, dim), nn.ReLU(),
            nn.Linear(dim, 4)
        )

        # nonlinear decoder with parameter phi
        self.decoder = nn.Sequential(
            nn.Linear(2, dim), nn.ReLU(),
            nn.Linear(dim, dim), nn.ReLU(),
            nn.Linear(dim, dim), nn.ReLU(),
            nn.Linear(dim, 2)
        )

    def encode(self, x):
        """
        Predict mean and log-covariance.
        """
        mu, logvar = self.encoder(x).chunk(2, dim=1)
        return mu, logvar

    def decode(self, z):
        """
        Return reconstructed data.
        """
        return self.decoder(z)
    
    def forward(self, x):
        """
        Encode and decode with the Reparameterization trick
        """
        mu, logvar = self.encode(x)
        z = reparameterize(mu, logvar)
        x_hat = self.decode(z)
        return x_hat, mu, logvar
    
    
def train_vae(epochs=200, lr=0.001, beta=0.1, print_every=20):
    vae = VAE(dim=128).to(device)
    optimizer = torch.optim.Adam(vae.parameters(), lr=lr)
    
    for epoch in range(1, epochs+1):
        for x, _ in loader:
            x = x.to(device)
            loss, recon, kl = elbo_loss(vae, x, beta=beta)
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()
        if epoch % print_every == 0:
            print(f"Epoch: {epoch} | loss: {loss.item():.4f} | recon {recon.item():.4f} | kl {kl.item():.4f}")
    
    return vae

vae = train_vae()
Epoch: 20 | loss: 0.5624 | recon 0.2101 | kl 3.5224
Epoch: 40 | loss: 0.5632 | recon 0.2303 | kl 3.3289
Epoch: 60 | loss: 0.5902 | recon 0.2489 | kl 3.4130
Epoch: 80 | loss: 0.5526 | recon 0.2150 | kl 3.3761
Epoch: 100 | loss: 0.5575 | recon 0.2034 | kl 3.5410
Epoch: 120 | loss: 0.5400 | recon 0.2063 | kl 3.3377
Epoch: 140 | loss: 0.5643 | recon 0.2176 | kl 3.4665
Epoch: 160 | loss: 0.5772 | recon 0.2330 | kl 3.4414
Epoch: 180 | loss: 0.5520 | recon 0.2192 | kl 3.3285
Epoch: 200 | loss: 0.5547 | recon 0.2217 | kl 3.3299

Exercise 9.3 - Model Inference¶

Once trained, we can obtain new data points by sampling from the noise distribution.

In [7]:
with torch.no_grad():
    X_tensor = torch.tensor(X, dtype=torch.float32)
    x_hat, mu, logvar = vae.forward(X_tensor)

x_hat, mu = x_hat.numpy(), mu.numpy()

fig, axes = plt.subplots(1, 3, figsize=(16, 5))
axes[0].scatter(X[:, 0], X[:, 1], c='blue', alpha=0.6)
axes[0].set_title('Original Moons Dataset')
axes[0].set_xlabel('Feature 1')
axes[0].set_ylabel('Feature 2')
axes[0].grid(True, alpha=0.3)

axes[1].scatter(x_hat[:, 0], x_hat[:, 1], c='red', alpha=0.6)
axes[1].set_title('Reconstructed Data')
axes[1].set_xlabel('Feature 1')
axes[1].set_ylabel('Feature 2')
axes[1].grid(True, alpha=0.3)

# Latent space representation
axes[2].scatter(mu[:, 0], mu[:, 1], c='green', alpha=0.6)
axes[2].set_title('Latent Space (μ)')
axes[2].set_xlabel('Latent Dimension 1')
axes[2].set_ylabel('Latent Dimension 2')
axes[2].grid(True, alpha=0.3)

(d) Sampling data from noise:

In [8]:
@torch.no_grad()
def vae_sampling(n_samples=2000):
    # sample n_samples latent variables from the prior p(z) and decode them
    samples = ...
    z = torch.randn(n_samples, 2).to(device)
    samples = vae.decode(z)
    return samples

samples = vae_sampling()
plot_moons(samples, title="Sampled data from noise")

Exercise 9.4 - Challenge Problem: How tight is the ELBO?¶

In Exercise 9.1 we showed that the ELBO is a lower bound on the log-likelihood $\log p_\theta(x)$, and in Exercise 9.2 we trained the VAE by maximizing this bound. But how far below $\log p_\theta(x)$ is the bound? In general we can not answer this question, since $p_\theta(x) = \int p_\theta(x|z) p(z) dz$ is intractable. Our VAE, however, has a two-dimensional latent space, so we can compute the integral accurately by numerical integration on a grid. We use this to measure the gap between the ELBO and the log-likelihood, and to study a tighter bound, the importance weighted ELBO (Burda et al., 2016).

Throughout, we use the model vae that was trained in Exercise 9.2. Its loss elbo_loss is, up to a constant and a factor $\beta$, the negative ELBO (estimated with a single sample) for the likelihood $$ p_\theta(x|z) = \prod_{d=1}^{2} \frac{1}{2b} \exp\left(-\frac{|x_d - f_\theta(z)_d|}{b}\right), \qquad b = \beta = 0.1, $$ i.e., each coordinate of $x$ follows a Laplace distribution with location given by the decoder output $f_\theta(z)$ (model.decode(z)) and scale $b$. The log-densities of the model are implemented below.

In [9]:
b = 0.1 # scale of the Laplace likelihood (equal to beta in Exercise 9.2)

def log_prior(z):
    # log N(z; 0, I)
    return -0.5 * (z**2 + np.log(2 * np.pi)).sum(dim=-1)

def log_q(z, mu, logvar):
    # log N(z; mu, diag(exp(logvar)))
    return -0.5 * ((z - mu)**2 / logvar.exp() + logvar + np.log(2 * np.pi)).sum(dim=-1)

def log_likelihood_laplace(x, x_hat, b):
    # log p(x | z) where x_hat = decode(z)
    return (-np.log(2 * b) - (x - x_hat).abs() / b).sum(dim=-1)

(a) The gap between the ELBO and the log-likelihood¶

(Pen and paper exercise) Show that for every $x$ $$ \log p_\theta(x) - \mathcal{L}(x; \theta, \phi) = D_{KL}(q_\phi(z|x) \| p_\theta(z|x)), $$ where $p_\theta(z|x) = p_\theta(x|z) p(z) / p_\theta(x)$ is the true posterior of the model. When is the ELBO tight?

We now compute $\log p_\theta(x)$ numerically. For a grid of $G \times G$ points $z_{ij} = (g_i, g_j)$, where $g_1, \ldots, g_G$ are equally spaced in $[-L, L]$ with spacing $\Delta$, we approximate $$ p_\theta(x) \approx \Delta^2 \sum_{i=1}^G \sum_{j=1}^G p_\theta(x|z_{ij}) p(z_{ij}). $$ Implement the function log_marginal_quadrature that returns $\log p_\theta(x_n)$ for every row $x_n$ of x. Why do we have to compute the sum in log-space with torch.logsumexp?

Hint: The grid only needs to be decoded once. To save memory, the data points are processed in batches.

In [11]:
@torch.no_grad()
def log_marginal_quadrature(model, x, b, L=5.0, G=300, batch_size=100):
    # grid of G x G points in [-L, L]^2 and the log of the area of a grid cell
    grid = torch.linspace(-L, L, G, device=x.device)
    z_grid = torch.cartesian_prod(grid, grid) # shape (G*G, 2)
    log_dz = 2 * torch.log(grid[1] - grid[0])
    x_hat_grid = model.decode(z_grid) # shape (G*G, 2)

    log_px = []
    for x_batch in x.split(batch_size):
        # log p(x_n) for all data points in the batch, shape (batch_size,)
        log_px_batch = ...
        log_joint = log_likelihood_laplace(x_batch[:, None, :], x_hat_grid, b) + log_prior(z_grid)
        log_px_batch = torch.logsumexp(log_joint, dim=1) + log_dz
        log_px.append(log_px_batch)
    return torch.cat(log_px)

The following code compares the average log-likelihood with the average ELBO, estimated with 100 samples from $q_\phi(z|x)$ for every data point, and shows the gap for every data point.

In [12]:
X_tensor = torch.tensor(X, dtype=torch.float32, device=device)

@torch.no_grad()
def elbo_estimate(model, x, b, n_samples=100):
    # Monte Carlo estimate of the ELBO of each data point
    mu, logvar = model.encode(x)
    z = mu + torch.exp(0.5 * logvar) * torch.randn(n_samples, *mu.shape, device=x.device)
    log_w = log_likelihood_laplace(x, model.decode(z), b) + log_prior(z) - log_q(z, mu, logvar)
    return log_w.mean(dim=0)

torch.manual_seed(0)
log_px_vae = log_marginal_quadrature(vae, X_tensor, b)
elbo_vae = elbo_estimate(vae, X_tensor, b)
print(f"log-likelihood: {log_px_vae.mean().item():.4f}")
print(f"ELBO:           {elbo_vae.mean().item():.4f}")

gap = (log_px_vae - elbo_vae).cpu().numpy()
plt.figure(figsize=(6, 5))
plt.scatter(X[:, 0], X[:, 1], c=gap, s=10, cmap="viridis")
plt.colorbar(label="log-likelihood - ELBO")
plt.gca().set_aspect("equal", adjustable="box")
plt.title("Gap between log-likelihood and ELBO")
plt.show()
log-likelihood: -1.9718
ELBO:           -2.2557

We can also compare the approximate posterior $q_\phi(z|x)$ with the true posterior $p_\theta(z|x) \propto p_\theta(x|z) p(z)$, evaluated on a grid, for some data points. The red lines are the contours of $q_\phi(z|x)$ (corresponding to one and two standard deviations), and the filled contours show the true posterior.

Is the true posterior Gaussian? How does $q_\phi(z|x)$ differ from it? Explain your observation using the KL divergence in the gap.

In [13]:
# selected data points: both ends and the top of the moons
idx = [np.argmin(X[:, 0]), np.argmax(X[:, 1]), np.argmax(X[:, 0]), np.argmin(X[:, 1])]

@torch.no_grad()
def plot_posteriors(model, idx, title, L=4.0, G=250):
    grid = torch.linspace(-L, L, G, device=device)
    z_grid = torch.cartesian_prod(grid, grid)
    x_hat_grid = model.decode(z_grid)
    mu, logvar = model.encode(X_tensor[idx])
    grid = grid.cpu().numpy()

    fig, axes = plt.subplots(1, len(idx) + 1, figsize=(4 * (len(idx) + 1), 4))
    axes[0].scatter(X[:, 0], X[:, 1], s=5, alpha=0.3)
    axes[0].set_aspect("equal", adjustable="box")
    axes[0].set_title("data")
    for k, (n, ax) in enumerate(zip(idx, axes[1:])):
        axes[0].scatter(*X[n], color=f"C{k+1}", s=100, marker="x", linewidths=3)
        log_post = log_likelihood_laplace(X_tensor[n], x_hat_grid, b) + log_prior(z_grid)
        post = torch.exp(log_post - log_post.max()).reshape(G, G).T.cpu().numpy()
        log_q_grid = log_q(z_grid, mu[k], logvar[k])
        q_grid = torch.exp(log_q_grid - log_q_grid.max()).reshape(G, G).T.cpu().numpy()
        ax.contourf(grid, grid, post, levels=np.linspace(0.02, 1, 10), cmap="Blues", extend="neither")
        ax.contour(grid, grid, q_grid, levels=np.exp([-2, -0.5]), colors="red")
        ax.set_aspect("equal", adjustable="box")
        ax.set_xlabel("$z_1$")
        ax.set_ylabel("$z_2$")
        ax.set_title(f"x = ({X[n, 0]:.2f}, {X[n, 1]:.2f})", color=f"C{k+1}")
    fig.suptitle(title)
    plt.tight_layout()
    plt.show()

plot_posteriors(vae, idx, "VAE: true posterior (blue) and $q_\\phi(z|x)$ (red)")

Solution:

Using $p_\theta(x|z) p(z) = p_\theta(z|x) p_\theta(x)$, $$ \mathcal{L}(x; \theta, \phi) = \mathbb{E}_{q_\phi(z|x)}\left[\log \frac{p_\theta(z|x) p_\theta(x)}{q_\phi(z|x)}\right] = \log p_\theta(x) - \mathbb{E}_{q_\phi(z|x)}\left[\log \frac{q_\phi(z|x)}{p_\theta(z|x)}\right] = \log p_\theta(x) - D_{KL}(q_\phi(z|x) \| p_\theta(z|x)). $$ Hence the ELBO is tight if and only if $q_\phi(z|x) = p_\theta(z|x)$ (almost everywhere). Maximizing the ELBO with respect to $\phi$ is therefore the same as making $q_\phi(z|x)$ a good approximation of the true posterior, and maximizing it with respect to $\theta$ increases the log-likelihood or makes the true posterior easier to approximate by $q_\phi$.

The densities $p_\theta(x|z) p(z)$ are tiny for most grid points, e.g., $p(z) \approx 10^{-6}$ at the corners of the grid and $p_\theta(x|z)$ decays exponentially with rate $1/b = 10$ in the reconstruction error. Summing the densities directly underflows (in particular in single precision), whereas logsumexp subtracts the largest term before exponentiating.

The gap is a few tenths of a nat on average (between about $0.3$ and $0.4$ in our runs; the exact numbers depend on the training run), and it varies considerably between data points, from about $0.1$ to more than $1$ nat. The true posteriors are clearly not Gaussian: they are skewed, have sharp edges, and are elongated along directions in latent space in which the decoder output changes slowly. The approximate posterior $q_\phi(z|x)$ has a diagonal covariance matrix and thus can only represent axis-aligned ellipses, which can not follow tilted, elongated posteriors. Since the gap is the reverse KL divergence $D_{KL}(q_\phi \| p_\theta)$, which is large if $q_\phi$ puts mass where $p_\theta(z|x)$ is small, $q_\phi(z|x)$ concentrates on the high-density core of the true posterior and is too narrow to cover its tails (mode-seeking behaviour).

(b) A tighter bound: importance weighting¶

For $K \geq 1$ we define the importance weighted ELBO $$ \mathcal{L}_K(x) = \mathbb{E}_{z_1, \ldots, z_K \sim q_\phi(z|x)}\left[\log \frac{1}{K} \sum_{k=1}^K w_k \right], \qquad w_k = \frac{p_\theta(x|z_k) p(z_k)}{q_\phi(z_k|x)}, $$ where $z_1, \ldots, z_K$ are sampled independently.

(Pen and paper exercise) Show that $\mathcal{L}_1(x)$ is the ELBO $\mathcal{L}(x; \theta, \phi)$ and that $\mathcal{L}_K(x) \leq \log p_\theta(x)$ for all $K$. (One can also show that $\mathcal{L}_K(x)$ increases monotonically with $K$ and converges to $\log p_\theta(x)$ as $K \to \infty$ under mild conditions, see Burda et al.)

Implement the function iwae_bound(model, x, b, K) that returns a Monte Carlo estimate of $\mathcal{L}_K(x_n)$ for every row $x_n$ of x, based on one set of $K$ samples $z_1, \ldots, z_K \sim q_\phi(z|x_n)$ (sampled with the reparameterization trick). Do not use torch.no_grad() inside the function, since we will train with it in (c).

Plot the average $\mathcal{L}_K$ for $K = 1, 2, 4, \ldots, 1024$ together with the average log-likelihood from (a). How many samples are needed to close half of the gap between the ELBO and the log-likelihood?

Hint: Use that $\log \frac{1}{K} \sum_{k=1}^K w_k = \operatorname{logsumexp}(\log w_1, \ldots, \log w_K) - \log K$.

In [14]:
def iwae_bound(model, x, b, K):
    # estimate of the importance weighted ELBO L_K(x_n) for every data point, shape (N,)
    L_K = ...
    mu, logvar = model.encode(x)
    z = mu + torch.exp(0.5 * logvar) * torch.randn(K, *mu.shape, device=x.device) # shape (K, N, 2)
    log_w = log_likelihood_laplace(x, model.decode(z), b) + log_prior(z) - log_q(z, mu, logvar) # shape (K, N)
    L_K = torch.logsumexp(log_w, dim=0) - np.log(K)
    return L_K
In [15]:
@torch.no_grad()
def average_iwae_bound(model, x, b, K, repetitions=5, batch_size=100):
    # average of L_K over the data set (and over several repetitions to reduce the Monte Carlo error)
    return np.mean([
        torch.cat([iwae_bound(model, x_batch, b, K) for x_batch in x.split(batch_size)]).mean().item()
        for _ in range(repetitions)
    ])

torch.manual_seed(0)
Ks = 2 ** np.arange(11)
L_Ks = [average_iwae_bound(vae, X_tensor, b, K) for K in Ks]
for K, L_K in zip(Ks, L_Ks):
    print(f"K = {K:4d}: {L_K:.4f}")

plt.figure()
plt.semilogx(Ks, L_Ks, "o-", base=2, label="$\\mathcal{L}_K$")
plt.axhline(log_px_vae.mean().item(), color="k", linestyle="--", label="log-likelihood (quadrature)")
plt.xlabel("number of samples $K$")
plt.ylabel("average over data set")
plt.legend()
plt.show()
K =    1: -2.2629
K =    2: -2.1214
K =    4: -2.0571
K =    8: -2.0249
K =   16: -2.0079
K =   32: -1.9993
K =   64: -1.9881
K =  128: -1.9863
K =  256: -1.9810
K =  512: -1.9800
K = 1024: -1.9794

Solution:

  1. For $K = 1$, $\mathcal{L}_1(x) = \mathbb{E}_{q_\phi(z|x)}[\log w_1] = \mathbb{E}_{q_\phi(z|x)}\left[\log \frac{p_\theta(x|z) p(z)}{q_\phi(z|x)}\right] = \mathcal{L}(x; \theta, \phi)$.

  2. Every weight is an unbiased estimate of the marginal likelihood, $$ \mathbb{E}_{q_\phi(z|x)}[w_k] = \int q_\phi(z|x) \frac{p_\theta(x|z) p(z)}{q_\phi(z|x)} dz = p_\theta(x), $$ and hence so is their average. Since $\log$ is concave, Jensen's inequality gives $$ \mathcal{L}_K(x) = \mathbb{E}\left[\log \frac{1}{K} \sum_{k=1}^K w_k \right] \leq \log \mathbb{E}\left[\frac{1}{K} \sum_{k=1}^K w_k \right] = \log p_\theta(x). $$

Monotonicity in $K$ and convergence to $\log p_\theta(x)$ are shown in Burda et al., 2016.

In the plot, $\mathcal{L}_K$ increases monotonically with $K$ and approaches the log-likelihood computed by quadrature, which confirms both our implementation of the quadrature and the theory. Already $K \approx 2$ to $4$ samples close half of the gap, but the convergence is slow afterwards: even with $K = 1024$ samples there is a small but visible gap. Note that for the closely related importance sampling estimate of $p_\theta(x)$ the variance of the weights matters - the narrower $q_\phi(z|x)$ is compared to the true posterior, the more samples are needed.

(c) Training with the tighter bound¶

Since $\mathcal{L}_K$ is a tighter bound on the log-likelihood than the ELBO, it is natural to train the model by maximizing $\mathcal{L}_K$ instead. This model is called the importance weighted autoencoder (IWAE). Note that it has exactly the same generative model and encoder as the VAE - only the training objective differs.

Implement the loss function iwae_loss(model, x), the negative average of $\mathcal{L}_K$ with $K = 16$ over a mini-batch, and train a model with it (this takes a bit longer than in Exercise 9.2). Then compare the VAE and the IWAE: which one is the better generative model (larger $\log p_\theta(x)$), which one has the larger ELBO, and which encoder better approximates the true posterior?

(Pen and paper exercise) Explain your observations. Hint: What kind of distribution $q_\phi(z|x)$ makes the weights $w_k$ have low variance?

In [16]:
def train_with_objective(loss_fn, epochs=200, lr=0.001, print_every=20, seed=0):
    torch.manual_seed(seed)
    model = VAE(dim=128).to(device)
    optimizer = torch.optim.Adam(model.parameters(), lr=lr)

    for epoch in range(1, epochs+1):
        for x, _ in loader:
            loss = loss_fn(model, x.to(device))
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()
        if epoch % print_every == 0:
            print(f"Epoch: {epoch} | loss: {loss.item():.4f}")

    return model
In [17]:
def iwae_loss(model, x):
    # negative average of the importance weighted ELBO with K = 16
    loss = ...
    loss = -iwae_bound(model, x, b, K=16).mean()
    return loss

iwae = train_with_objective(iwae_loss)
Epoch: 20 | loss: 2.2710
Epoch: 40 | loss: 2.0482
Epoch: 60 | loss: 2.2899
Epoch: 80 | loss: 1.9190
Epoch: 100 | loss: 2.1398
Epoch: 120 | loss: 2.0304
Epoch: 140 | loss: 1.9861
Epoch: 160 | loss: 2.2305
Epoch: 180 | loss: 1.8800
Epoch: 200 | loss: 2.0542
In [18]:
torch.manual_seed(0)
for name, model in [("VAE", vae), ("IWAE", iwae)]:
    print(f"{name:4s} | log-likelihood: {log_marginal_quadrature(model, X_tensor, b).mean().item():.4f}"
          f" | L_16: {average_iwae_bound(model, X_tensor, b, K=16):.4f}"
          f" | ELBO: {elbo_estimate(model, X_tensor, b).mean().item():.4f}")

plot_posteriors(iwae, idx, "IWAE: true posterior (blue) and $q_\\phi(z|x)$ (red)")

# compare samples (decoder outputs for z ~ N(0, I)) of both models
with torch.no_grad():
    z = torch.randn(2000, 2, device=device)
    samples_vae = vae.decode(z).cpu().numpy()
    samples_iwae = iwae.decode(z).cpu().numpy()
fig, axes = plt.subplots(1, 3, figsize=(15, 5), sharex=True, sharey=True)
for ax, data, title in zip(axes, [X, samples_vae, samples_iwae], ["data", "VAE samples", "IWAE samples"]):
    ax.scatter(data[:, 0], data[:, 1], s=5, alpha=0.5)
    ax.set_aspect("equal", adjustable="box")
    ax.set_title(title)
plt.show()
VAE  | log-likelihood: -1.9718 | L_16: -2.0045 | ELBO: -2.2569
IWAE | log-likelihood: -1.8895 | L_16: -1.9587 | ELBO: -3.7687

Solution:

The IWAE achieves a (slightly) larger log-likelihood than the VAE, and a $\mathcal{L}_{16}$ that is as large or larger, i.e., training with the tighter bound gives a (slightly) better generative model. However, the ELBO of the IWAE is much smaller than that of the VAE (in our runs about $-3.8$ compared to $-2.3$, while the log-likelihoods are about $-1.89$ and $-1.97$). By (a), the gap between log-likelihood and ELBO is $D_{KL}(q_\phi(z|x) \| p_\theta(z|x))$, so the encoder of the IWAE is a much worse approximation of the true posterior in the sense of this KL divergence. The posterior plots show why: the approximate posteriors of the IWAE are considerably wider than the true posteriors (and not even centered on them), whereas the approximate posteriors of the VAE are too narrow and concentrate on the core of the true posteriors. The samples of the IWAE also follow the moons more closely (note that we plot the decoder outputs $f_\theta(z)$ without the Laplace noise).

Explanation: For large $K$, $\mathcal{L}_K$ approaches $\log p_\theta(x)$ for any $q_\phi$ (with bounded weights), so the objective puts less and less pressure on $q_\phi$ to approximate the true posterior. Instead, $q_\phi$ only serves as a proposal distribution for importance sampling: the bound is tight if the average $\frac{1}{K} \sum_k w_k$ has small variance. If $q_\phi(z|x)$ is narrower than the posterior, some regions with large posterior density are rarely sampled and produce huge weights $w_k = p_\theta(x|z_k)p(z_k)/q_\phi(z_k|x)$ when they are sampled, which leads to a large variance. A $q_\phi(z|x)$ that is somewhat wider than the posterior (mass-covering) only wastes a few samples in regions with small weights, which is harmless for $K = 16$ samples. This is the opposite of the mode-seeking behaviour of the reverse KL divergence in the ELBO, which heavily penalizes any $q_\phi$ mass outside of the posterior. For the decoder, the IWAE objective is less restrictive: it does not force the true posterior to be well approximated by a single Gaussian, which leaves more flexibility to fit the data and explains the larger log-likelihood.

Remark: a larger $K$ is not always better for training. Rainforth et al. (2018) showed that the signal-to-noise ratio of the gradient estimates of the encoder parameters $\phi$ decreases as $K$ grows, which is another manifestation of the reduced pressure on the encoder.