TExcelTAD

Variational Autoencoders

The previous lesson ended with a failure. Codes drawn at random and passed through a plain autoencoder's decoder gave blurred blends that a classifier was unsure about, because nothing in the training loss defined a distribution over codes. A variational autoencoder (VAE, Kingma and Welling, 2013) fixes that with two changes. The encoder outputs a distribution for each input instead of a point, and a penalty pulls all of those distributions towards one fixed prior p(z)=N(0,I)p(\mathbf{z}) = \mathcal{N}(\mathbf{0}, I). After training, generating is easy: draw z\mathbf{z} from the prior and decode it.

This lesson builds the pieces: the loss (the ELBO), the KL term in closed form, checked by Monte Carlo, and the reparameterisation trick that lets gradients pass through a random sample. Then a VAE is written and trained in NumPy, a PyTorch version is recorded, and the lesson ends with β\beta-VAE and posterior collapse. The data is the course's Digits split (1077 training, 360 validation images). Every reported number is a validation number.

The model

x encoder mu log var eps ~ N(0, I) z = mu +sigma * eps decoder x-hat reconstruction: -log p(x | z) KL( N(mu, sigma^2) || N(0, I) ) gradients flowthrough mu, sigma

The encoder qϕ(z∣x)=N(μϕ(x),diag⁡(σϕ2(x)))q_\phi(\mathbf{z} \mid \mathbf{x}) = \mathcal{N}(\boldsymbol{\mu}_\phi(\mathbf{x}), \operatorname{diag}(\boldsymbol{\sigma}^2_\phi(\mathbf{x}))) outputs a mean and a log-variance per latent dimension. The log-variance is used because it can take any real value, while a variance must stay positive. The decoder pθ(x∣z)p_\theta(\mathbf{x} \mid \mathbf{z}) gives a distribution over images. For pixels in [0,1][0, 1], the usual choice is an independent Bernoulli per pixel, with the decoder outputting logits, so −log⁡pθ(x∣z)-\log p_\theta(\mathbf{x} \mid \mathbf{z}) is the binary cross-entropy summed over the 64 pixels.

The ELBO

Training maximises a lower bound on the log-likelihood of each image, the evidence lower bound:

log⁡pθ(x)≥Eqϕ(z∣x)[log⁡pθ(x∣z)]⏟reconstruction−DKL(qϕ(z∣x) ∥ p(z))⏟regulariser=ELBO⁡(x)\log p_\theta(\mathbf{x}) \ge \underbrace{\mathbb{E}_{q_\phi(\mathbf{z} \mid \mathbf{x})}\left[\log p_\theta(\mathbf{x} \mid \mathbf{z})\right]}_{\text{reconstruction}} - \underbrace{D_{\mathrm{KL}}\left(q_\phi(\mathbf{z} \mid \mathbf{x}) \,\Vert\, p(\mathbf{z})\right)}_{\text{regulariser}} = \operatorname{ELBO}(\mathbf{x})

The gap between the two sides is DKL(qϕ(z∣x)∥pθ(z∣x))D_{\mathrm{KL}}(q_\phi(\mathbf{z} \mid \mathbf{x}) \Vert p_\theta(\mathbf{z} \mid \mathbf{x})), the KL divergence from the encoder to the true posterior, which is never negative. So the loss you minimise is the negative ELBO: a reconstruction term plus a KL term. The KL term keeps each image's code distribution close to the prior. Codes therefore overlap and fill the region around the origin, and that region is exactly where prior samples land. KL divergence and its asymmetry are covered in Entropy, Cross-Entropy and KL Divergence.

For a diagonal Gaussian against N(0,I)\mathcal{N}(\mathbf{0}, I), the KL term has a closed form, summed over the latent dimensions jj:

DKL(N(μ,diag⁡σ2) ∥ N(0,I))=12∑j(μj2+σj2−1−log⁡σj2)D_{\mathrm{KL}}\left(\mathcal{N}(\boldsymbol{\mu}, \operatorname{diag}\boldsymbol{\sigma}^2) \,\Vert\, \mathcal{N}(\mathbf{0}, I)\right) = \frac{1}{2} \sum_{j} \left(\mu_j^2 + \sigma_j^2 - 1 - \log \sigma_j^2\right)

Each term is zero exactly when μj=0\mu_j = 0 and σj=1\sigma_j = 1. A dimension whose KL is zero for every input carries no information about the input.

The reparameterisation trick

The reconstruction term is an expectation over z∼qϕ\mathbf{z} \sim q_\phi, and you cannot backpropagate through "draw a random number". The trick moves the randomness into an input that has no parameters:

z=μϕ(x)+σϕ(x)⊙ϵ,ϵ∼N(0,I)\mathbf{z} = \boldsymbol{\mu}_\phi(\mathbf{x}) + \boldsymbol{\sigma}_\phi(\mathbf{x}) \odot \boldsymbol{\epsilon}, \qquad \boldsymbol{\epsilon} \sim \mathcal{N}(\mathbf{0}, I)

Now z\mathbf{z} is a differentiable function of μ\boldsymbol{\mu} and σ\boldsymbol{\sigma}, with ∂zj/∂μj=1\partial z_j / \partial \mu_j = 1 and ∂zj/∂log⁡σj2=12σjϵj\partial z_j / \partial \log \sigma^2_j = \tfrac{1}{2} \sigma_j \epsilon_j. A single sample per image gives an unbiased gradient. The alternative that works for any distribution, the score-function (REINFORCE) estimator E[f(z)∇log⁡q(z)]\mathbb{E}[f(\mathbf{z}) \nabla \log q(\mathbf{z})], is also unbiased but much noisier. The code below checks the closed-form KL against a Monte Carlo average of log⁡q(z)−log⁡p(z)\log q(\mathbf{z}) - \log p(\mathbf{z}), then compares the two gradient estimators on f(z)=z2f(z) = z^2, where the exact gradient of E[z2]=μ2+σ2\mathbb{E}[z^2] = \mu^2 + \sigma^2 with respect to μ\mu is 2μ2\mu.

python · try it yourself
import numpy as np

rng = np.random.default_rng(0)
mu = np.array([0.5, -1.0, 0.0])                    # an encoder's output for one image
logvar = np.array([-1.0, 0.3, 0.0])
sigma = np.exp(0.5 * logvar)

# closed form: KL( N(mu, sigma^2) || N(0, 1) ), summed over the 3 latent dimensions
kl_dims = 0.5 * (mu ** 2 + np.exp(logvar) - 1 - logvar)
print("closed-form KL per dimension:", np.round(kl_dims, 4).tolist(), " total", round(float(kl_dims.sum()), 4))

# Monte Carlo: average of log q(z) - log p(z) over samples z ~ q
def log_normal(z, m, s):
    return -0.5 * np.log(2 * np.pi) - np.log(s) - 0.5 * ((z - m) / s) ** 2
for n in (100, 10_000, 1_000_000):
    z = mu + sigma * rng.standard_normal((n, 3))   # reparameterised samples
    kl_mc = (log_normal(z, mu, sigma) - log_normal(z, 0, 1)).sum(axis=1)
    print(f"Monte Carlo, {n:>9,} samples: {kl_mc.mean():.4f}  (standard error {kl_mc.std() / np.sqrt(n):.4f})")

# Gradient of E_q[f(z)] with respect to mu for f(z) = z^2 in one dimension; the exact answer is 2 mu
m, s, n = 0.5, np.exp(-0.5), 1000
eps = rng.standard_normal((200, n))                # 200 repeated estimates of n samples each
z = m + s * eps
reparam = (2 * z).mean(axis=1)                     # d f(m + s eps) / dm = f'(z)
score = (z ** 2 * (z - m) / s ** 2).mean(axis=1)   # f(z) * d log q(z) / dm
print(f"exact gradient {2 * m:.3f}")
print(f"reparameterisation: mean {reparam.mean():.3f}  std over repeats {reparam.std():.4f}")
print(f"score function:     mean {score.mean():.3f}  std over repeats {score.std():.4f}")
closed-form KL per dimension: [0.3089, 0.5249, 0.0]  total 0.8339
Monte Carlo,       100 samples: 0.7388  (standard error 0.1378)
Monte Carlo,    10,000 samples: 0.8306  (standard error 0.0129)
Monte Carlo, 1,000,000 samples: 0.8338  (standard error 0.0013)
exact gradient 1.000
reparameterisation: mean 0.998  std over repeats 0.0375
score function:     mean 0.992  std over repeats 0.0974

The closed form gives 0.8339 nats. Monte Carlo estimates approach it at the rate 1/n1/\sqrt{n}: with 100 samples, 0.7388 is off by less than its standard error of 0.1378, and with a million samples it gives 0.8338. The third dimension has μ=0\mu = 0 and log⁡σ2=0\log \sigma^2 = 0, so it matches the prior and its KL is exactly 0. Both gradient estimators are unbiased (0.998 and 0.992 against 1). The reparameterised one has a spread of 0.0375 over repeats, against 0.0974 for the score function, 2.6 times less. In a network with many latent dimensions the gap is usually much larger, which is why VAEs train with one sample per image.

A VAE in NumPy

The encoder is 64-64 with ReLU, then a layer that outputs 8 means and 8 log-variances. The decoder is 8-64-64 and outputs logits. The backward pass is ordinary backpropagation with two additions. At z\mathbf{z}, the gradient splits into μ\boldsymbol{\mu} and log⁡σ2\log \boldsymbol{\sigma}^2 by the derivatives above, and the KL term adds its own gradients, μj\mu_j and 12(σj2−1)\tfrac{1}{2}(\sigma_j^2 - 1), divided by the batch size. After training, 360 codes are drawn from the prior and decoded, and a logistic regression trained on real training pixels says what it sees.

python · try it yourself
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression

X, y = load_digits(return_X_y=True)
X = X / 16.0
X_tmp, X_te, y_tmp, y_te = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)
X_tr, X_va, y_tr, y_va = train_test_split(X_tmp, y_tmp, test_size=0.25, random_state=0, stratify=y_tmp)

rng = np.random.default_rng(0)
L, H = 8, 64                                        # latent size, hidden size
def init(a, b): return [rng.normal(0, np.sqrt(2 / a), (a, b)), np.zeros(b)]
P = init(64, H) + init(H, 2 * L) + init(L, H) + init(H, 64)   # enc1, enc2 (mu|logvar), dec1, dec2
sig = lambda t: 1 / (1 + np.exp(-t))

def step(x, eps):
    W1, b1, W2, b2, W3, b3, W4, b4 = P
    h = np.maximum(x @ W1 + b1, 0)
    out = h @ W2 + b2
    mu, logvar = out[:, :L], out[:, L:]
    std = np.exp(0.5 * logvar)
    z = mu + std * eps                              # the reparameterisation trick
    g = np.maximum(z @ W3 + b3, 0)
    logits = g @ W4 + b4
    p = sig(logits)
    n = len(x)
    rec = -np.sum(x * np.log(p + 1e-9) + (1 - x) * np.log(1 - p + 1e-9)) / n   # Bernoulli NLL per image
    kl = 0.5 * np.sum(mu ** 2 + np.exp(logvar) - 1 - logvar, axis=0) / n         # per latent dimension
    # backward pass of rec + kl.sum()
    dlog = (p - x) / n
    dg = dlog @ W4.T * (g > 0)
    dz = dg @ W3.T
    dmu = dz + mu / n
    dlv = dz * eps * 0.5 * std + 0.5 * (np.exp(logvar) - 1) / n
    dout = np.hstack([dmu, dlv])
    dh = dout @ W2.T * (h > 0)
    grads = [x.T @ dh, dh.sum(0), h.T @ dout, dout.sum(0), z.T @ dg, dg.sum(0), g.T @ dlog, dlog.sum(0)]
    return rec, kl, grads

m = [0 * p for p in P]; v = [0 * p for p in P]; t = 0
for epoch in range(1, 151):
    for idx in np.array_split(rng.permutation(len(X_tr)), 17):
        _, _, grads = step(X_tr[idx], rng.standard_normal((len(idx), L)))
        t += 1
        for k, gk in enumerate(grads):              # Adam, lr 2e-3
            m[k] = 0.9 * m[k] + 0.1 * gk; v[k] = 0.999 * v[k] + 0.001 * gk * gk
            P[k] -= 2e-3 * (m[k] / (1 - 0.9 ** t)) / (np.sqrt(v[k] / (1 - 0.999 ** t)) + 1e-8)
    if epoch in (1, 30, 150):
        rec, kl, _ = step(X_va, rng.standard_normal((len(X_va), L)))
        print(f"epoch {epoch:3d}  validation: reconstruction {rec:6.2f}  KL {kl.sum():5.2f}  negative ELBO {rec + kl.sum():6.2f}")
print("KL per latent dimension (validation):", np.round(kl, 2).tolist())

# generate: z from the prior N(0, I), decode, and ask a pixel classifier what it sees
clf = LogisticRegression(max_iter=2000).fit(X_tr, y_tr)
z = rng.standard_normal((360, L))
samples = sig(np.maximum(z @ P[4] + P[5], 0) @ P[6] + P[7])
proba = clf.predict_proba(samples)
print("predicted classes of 360 samples:", np.bincount(proba.argmax(1), minlength=10).tolist())
print(f"classifier confidence: samples {proba.max(1).mean():.3f}, real validation images {clf.predict_proba(X_va).max(1).mean():.3f}")
epoch   1  validation: reconstruction  37.44  KL  2.05  negative ELBO  39.49
epoch  30  validation: reconstruction  22.73  KL  2.67  negative ELBO  25.40
epoch 150  validation: reconstruction  21.28  KL  3.38  negative ELBO  24.67
KL per latent dimension (validation): [0.35, 0.86, 0.0, 0.5, 0.01, 0.07, 0.84, 0.75]
predicted classes of 360 samples: [25, 42, 35, 36, 31, 29, 50, 48, 28, 36]
classifier confidence: samples 0.675, real validation images 0.899

On validation data, the negative ELBO falls from 39.49 to 24.67 nats per image. Most of that is reconstruction (21.28), and the KL is only 3.38 nats. That KL is the information the codes carry about each image beyond the prior. It is small here because 8×88 \times 8 grey digits have little detail, and the Bernoulli likelihood on grey pixel values is flat around the right answer. The KL per dimension shows the model's choice. Five dimensions carry between 0.35 and 0.86 nats, and three (0.0, 0.01, 0.07) are close to the prior and almost unused. This is normal VAE behaviour, not a bug: a dimension the decoder does not need costs KL, so the optimiser switches it off.

The 360 prior samples are spread over all ten classes (between 25 and 50 per class). That is what a generator should do, and an unregularised code space does not guarantee it. The classifier's mean confidence on the samples is 0.675, only slightly above the 0.656 for random codes of the plain autoencoder in the previous lesson, and well below the 0.899 for real digits. A Bernoulli decoder outputs mean images, which are blurry, and a small NumPy model trained for 150 epochs on 1077 images is a modest generator.

The same in PyTorch (recorded), with β\beta

A β\beta-VAE (Higgins et al., 2017) multiplies the KL term by β\beta. With β>1\beta > 1, codes are pulled harder towards the prior, which can give more disentangled dimensions but blurrier reconstructions. With β<1\beta < 1, the model keeps more information. The example trains a slightly deeper VAE (two hidden layers of 128) for β=0.5,1,4\beta = 0.5, 1, 4 and reports the KL per dimension, the classes of 360 prior samples and, for β=1\beta = 1, the classifier's reading of 7 images decoded along a straight line between the codes of a validation 0 and a validation 6. It is recorded and ran on the CPU.

python · try it yourself
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression

X, y = load_digits(return_X_y=True)
X = (X / 16.0).astype(np.float32)
X_tmp, X_te, y_tmp, y_te = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)
X_tr, X_va, y_tr, y_va = train_test_split(X_tmp, y_tmp, test_size=0.25, random_state=0, stratify=y_tmp)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

class VAE(nn.Module):
    def __init__(self, latent=8, hidden=128):
        super().__init__()
        self.enc = nn.Sequential(nn.Linear(64, hidden), nn.ReLU(), nn.Linear(hidden, hidden), nn.ReLU())
        self.mu, self.logvar = nn.Linear(hidden, latent), nn.Linear(hidden, latent)
        self.dec = nn.Sequential(nn.Linear(latent, hidden), nn.ReLU(), nn.Linear(hidden, hidden), nn.ReLU(),
                                 nn.Linear(hidden, 64))          # logits of 64 Bernoulli pixels
    def forward(self, x):
        h = self.enc(x)
        mu, logvar = self.mu(h), self.logvar(h)
        z = mu + torch.exp(0.5 * logvar) * torch.randn_like(mu)   # reparameterisation
        return self.dec(z), mu, logvar

def losses(model, x):
    logits, mu, logvar = model(x)
    rec = F.binary_cross_entropy_with_logits(logits, x, reduction="sum") / len(x)
    kl = 0.5 * (mu ** 2 + logvar.exp() - 1 - logvar).sum(0) / len(x)   # per latent dimension
    return rec, kl

def train(beta, epochs=150):
    torch.manual_seed(0)
    model = VAE().to(device)
    opt = torch.optim.Adam(model.parameters(), lr=1e-3)
    xs = torch.from_numpy(X_tr).to(device)
    for _ in range(epochs):
        model.train()
        for idx in torch.randperm(len(xs)).split(64):
            rec, kl = losses(model, xs[idx])
            loss = rec + beta * kl.sum()
            opt.zero_grad(); loss.backward(); opt.step()
    return model.eval()

clf = LogisticRegression(max_iter=2000).fit(X_tr, y_tr)        # judge for generated digits
xv = torch.from_numpy(X_va)
print("device:", device)
for beta in (0.5, 1.0, 4.0):
    model = train(beta)
    torch.manual_seed(1)
    with torch.no_grad():
        rec, kl = losses(model, xv)
        samples = torch.sigmoid(model.dec(torch.randn(360, 8))).numpy()
    proba = clf.predict_proba(samples)
    print(f"beta {beta:.1f}: val reconstruction {rec.item():.2f}  KL {kl.sum().item():.2f}  "
          f"active dims (KL > 0.1) {int((kl > 0.1).sum())}")
    print("   KL per dim:", [round(k, 2) for k in kl.tolist()])
    print("   classes of 360 prior samples:", np.bincount(proba.argmax(1), minlength=10).tolist(),
          f" confidence {proba.max(1).mean():.3f}")
    if beta == 1.0:
        with torch.no_grad():   # interpolate between the codes (means) of a validation 0 and a validation 6
            a, b = model.mu(model.enc(xv[y_va == 0][:1])), model.mu(model.enc(xv[y_va == 6][:1]))
            path = torch.stack([(1 - t) * a[0] + t * b[0] for t in np.linspace(0, 1, 7)])
            imgs = torch.sigmoid(model.dec(path)).numpy()
        print("   interpolation 0 -> 6, predicted classes:", clf.predict(imgs).tolist())
device: cpu
beta 0.5: val reconstruction 19.38  KL 5.22  active dims (KL > 0.1) 4
   KL per dim: [0.0, 1.27, 0.0, 0.0, 1.38, 0.0, 1.35, 1.2]
   classes of 360 prior samples: [21, 39, 27, 36, 34, 37, 36, 38, 50, 42]  confidence 0.766
beta 1.0: val reconstruction 21.08  KL 3.26  active dims (KL > 0.1) 4
   KL per dim: [0.0, 0.86, 0.0, 0.0, 0.98, 0.0, 0.35, 1.06]
   classes of 360 prior samples: [31, 20, 37, 42, 39, 35, 51, 37, 37, 31]  confidence 0.742
   interpolation 0 -> 6, predicted classes: [0, 0, 0, 0, 0, 6, 6]
beta 4.0: val reconstruction 27.22  KL 0.00  active dims (KL > 0.1) 0
   KL per dim: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
   classes of 360 prior samples: [0, 0, 0, 0, 0, 0, 0, 0, 360, 0]  confidence 0.289

Three findings:

  • The trade-off. Lowering β\beta from 1 to 0.5 raises the KL from 3.26 to 5.22 nats and lowers the reconstruction loss from 21.08 to 19.38. With β=0.5\beta = 0.5 the prior samples are also judged a little more confidently (0.766 against 0.742). The PyTorch model at β=1\beta = 1 gives clearer samples than the NumPy one (0.742 against 0.675): it is deeper and trains with a lower learning rate.
  • Posterior collapse. At β=4\beta = 4 the KL of every dimension is 0.00. The encoder outputs the prior for every image, the decoder ignores z\mathbf{z} and learns to draw one average image, and all 360 samples are classified as 8 with a confidence of only 0.289. The reconstruction loss of 27.22 is the cost of drawing that average image for every input. Collapse also happens at β=1\beta = 1 with a decoder strong enough to model the data without z\mathbf{z}, such as an autoregressive decoder for text. Common remedies are KL annealing (start with β=0\beta = 0 and raise it to 1 during training), free bits (no KL penalty below a minimum number of nats per dimension) and a weaker decoder.
  • Interpolation. Decoding 7 evenly spaced points between the code of a 0 and the code of a 6 gives images classified as [0, 0, 0, 0, 0, 6, 6]. The path stays on digit-like images and switches class once, instead of passing through noise. Linear interpolation is common in practice. Because most of a high-dimensional Gaussian's mass lies on a shell, spherical interpolation is sometimes used instead.

Pitfalls

  • Summing versus averaging. The ELBO sums over pixels and latent dimensions. If you average the reconstruction over 64 pixels but sum the KL, β\beta is effectively multiplied by 64 and the model collapses. Keep the two terms on the same scale (both per image, here).
  • Using sigma instead of logvar as the output. A raw variance can go negative. Predict log⁡σ2\log \sigma^2 and exponentiate.
  • Sampling at evaluation. For reconstructions and features, use μ\boldsymbol{\mu}. For generation, sample z\mathbf{z} from the prior, not from one image's posterior.
  • Reading the negative ELBO as a likelihood. It is an upper bound on −log⁡p(x)-\log p(\mathbf{x}). Comparing models by it is fair only with the same likelihood model, and a Bernoulli likelihood on grey pixels is a convenient approximation, not a true density for those values.
  • Blurry samples blamed on the architecture. Independent per-pixel likelihoods average over plausible images. Sharper generation needs a different likelihood, an adversarial loss (GANs) or a diffusion model (Diffusion Models: The Noising Process).

Practice

  1. Compute the KL for one dimension with μ=0.5\mu = 0.5 and log⁡σ2=−1\log \sigma^2 = -1 by hand and check it against the first value in the NumPy output.
Answer

12(0.25+e−1−1+1)=12(0.25+0.3679)=0.3089\frac{1}{2}(0.25 + e^{-1} - 1 + 1) = \frac{1}{2}(0.25 + 0.3679) = 0.3089, the first value of the per-dimension list.

  1. Derive ∂L/∂log⁡σj2\partial \mathcal{L} / \partial \log \sigma_j^2 for the reparameterised sample, where L\mathcal{L} is the loss and gj=∂L/∂zjg_j = \partial \mathcal{L} / \partial z_j comes from the decoder, and compare it with the line dlv = dz * eps * 0.5 * std + 0.5 * (np.exp(logvar) - 1) / n.
Answer

With zj=μj+e12log⁡σj2ϵjz_j = \mu_j + e^{\frac{1}{2} \log \sigma_j^2} \epsilon_j, the chain rule gives gj⋅12σjϵjg_j \cdot \tfrac{1}{2} \sigma_j \epsilon_j. The KL term 12(μj2+elog⁡σj2−1−log⁡σj2)\tfrac{1}{2}(\mu_j^2 + e^{\log \sigma_j^2} - 1 - \log \sigma_j^2) adds 12(σj2−1)\tfrac{1}{2}(\sigma_j^2 - 1). In the code, dz already holds gjg_j divided by the batch size, and the KL gradient is divided by n because the loss is a batch mean.

  1. The β=4\beta = 4 model reports reconstruction 27.22 and KL 0.00. What would its samples look like, and what change would you try first to get a useful model with a strong KL weight?
Answer

All samples decode to the same average image, since the decoder ignores z\mathbf{z} (all 360 were classified as 8). Try KL annealing: train with β\beta rising from 0 to its final value over the first epochs, so the decoder learns to use z\mathbf{z} before the penalty grows. Free bits are another option.

Test yourself

What does the reparameterisation z=μ+σ⊙ϵ\mathbf{z} = \boldsymbol{\mu} + \boldsymbol{\sigma} \odot \boldsymbol{\epsilon} achieve?

  1. It makes the KL term zero
  2. It moves the randomness into a parameter-free input, so gradients flow to μ\boldsymbol{\mu} and σ\boldsymbol{\sigma} through the sample
  3. It removes the need for a decoder
  4. It makes sampling deterministic at training time

What is the KL divergence from N(0,1)\mathcal{N}(0, 1) to the prior N(0,1)\mathcal{N}(0, 1) for one latent dimension, and what does it say about that dimension?

  1. 1; it carries one nat
  2. 0; if this holds for every input, the dimension carries no information about the input
  3. Infinite; the encoder failed
  4. 0.5; it is half used

A VAE trained with β=4\beta = 4 has KL 0.00 in every dimension, and all its samples look the same. What happened?

  1. Overfitting
  2. Posterior collapse: the encoder outputs the prior and the decoder ignores the code
  3. The learning rate was too small
  4. Mode collapse of the discriminator

Why can a VAE generate new data by decoding z∼N(0,I)\mathbf{z} \sim \mathcal{N}(\mathbf{0}, I), while a plain autoencoder cannot?

  1. Its decoder is larger
  2. The KL term pulls every image's code distribution towards that prior, so prior samples land where the decoder was trained
  3. It uses convolutions
  4. It is trained with labels