Session S23

Autoencoders & VAEs

Every model so far mapped an input to a target. What does a network learn when the target is its own input, what must change before it can generate new data, how does a gradient pass through a random draw, and what does a trained VAE generate as the weight on its KL term changes?

Deep Learning · CS 4715/5715 · University of Idaho

Quiz 3 is at the end of class, and the proposal is due this Friday

Three course items come first.

  • Quiz 3 takes the final 30 minutes of today's class (6:45–7:15 PM), in Canvas, with closed materials (Tier 0). It covers Module 3, S13–S22. Online (Web) students and students with flexible-time arrangements may use their assigned flexible completion window.
  • Project: the proposal is due at the end of this week (this Friday); the 12-hour grace period applies.
  • HW4 (evaluation and efficiency) goes out at S26.

Today opens Module 4, on generative models, efficiency and evaluation (S23–S27).

S22 showed that one architecture reads images and text

S22 closed Module 3. Its answer, clause by clause, without the numbers:

  • How it reads an image: as \(P\times P\) patches, projected, with [CLS] first and learned positions added, through a standard encoder. The projection is one strided convolution.
  • What it loses: built-in locality and translation equivariance, which costs accuracy on little data. Small project: a CNN or a pretrained ViT.
  • What attention shows: where [CLS] puts its weight, not why the model decided.
  • One space: two encoders and a cross-entropy over each row and column of the \(N\times N\) cosine matrix, matches on the diagonal, starting at \(\ln N\).
  • What it makes possible: classes typed at test time, retrieval, generation, assistants.

Each of those models predicts a target, such as a class, the next token or the matching caption; S20 generated text by predicting one token at a time. Module 4 generates a whole data point, such as an image, from a random draw.

Today answers four questions, then Quiz 3 takes the last 30 minutes

Each part answers one clause of the title page's question; a fifth closes before the quiz.

partthe question it answers, and how
1 · AutoencodersWhat does a network learn when the target is its own input? A code narrower than the input forces it to learn the data's structure; a noisy arc shows how close its error comes to the noise.
2 · The VAEWhat must change before it can generate? A known distribution to draw codes from, and a loss whose two terms pull against each other.
3 · ReparameterizationHow does a gradient pass through a random draw? The randomness moves into a noise input with no learned parameters; autograd shows the difference.
4 · A tiny VAEWhat does it generate as the KL weight changes? Samples of two clusters, the gap between them, and a sweep from a near-plain autoencoder to collapse.
5 · CloseFive common mistakes, today's answer, next time; then Quiz 3.

Each of Parts 1–4 ends on a self-check. First, a network whose target is its own input.

An autoencoder reconstructs its input through a narrower code

Part 1 · Autoencoders. Generative modeling learns the data distribution itself, well enough to sample new data from it. Today's model is the variational autoencoder (VAE); generative adversarial networks (GANs) follow in S24 and diffusion in S25. The VAE starts from a network that copies its input:

so farxnetworktarget: a label, the next tokenautoencoderencoder fdecoder gThe middle is narrower than the input, so the network must compress.xz = f(x)x= g(z)loss: ‖x − g(f(x))‖2​. The input is its own target, so no labels are needed.Sizes as in the next page's arc example: two numbers in, a one-number code.
  • For a batch \(X\) of shape \((n,2)\), the codes \(Z\) are \((n,1)\) and \(\hat X\) is \((n,2)\); training minimizes \(\frac1{2n}\sum_i\lVert x_i-g(f(x_i))\rVert^2\), the mean over all \(2n\) numbers.
  • A second way to force structure is noise: reconstruct the clean original from a corrupted input (denoising autoencoder, Vincent et al., ICML 2008). The loss compares the output with the clean original, so copying the input, noise included, scores badly.

A linear autoencoder learns only what PCA learns; try a curved dataset

Bourlard and Kamp (1988): with linear layers, the optimal autoencoder spans the same subspace as principal component analysis (PCA), the straight line (in general, the flat subspace) that loses the least squared error when the points are projected onto it; slide 8 draws it in blue. The interesting case is nonlinear. Reading 4.1's test, in code:


import torch
import torch.nn as nn
torch.manual_seed(0)
n = 2000
t = torch.rand(n, 1) * 3.14159                      # (n, 1): the angle
x = torch.cat([torch.cos(t), torch.sin(t)], dim=1) + 0.05 * torch.randn(n, 2)   # (n, 2)
linear_ae = nn.Sequential(nn.Linear(2, 1), nn.Linear(1, 2))
nonlinear_ae = nn.Sequential(
    nn.Linear(2, 32), nn.Tanh(), nn.Linear(32, 1),   # encoder -> 1D code
    nn.Linear(1, 32), nn.Tanh(), nn.Linear(32, 2),   # decoder -> 2D
)
  
  • The data: 2,000 points on a half circle of radius 1, each at an angle t drawn uniformly between 0 and \(\pi\), plus Gaussian noise of standard deviation 0.05 per coordinate. One angle describes a point, but the arc is curved.

Both models train for 2,000 Adam steps; predict where each one ends

Reading 4.1's training function, without its progress prints, on the previous page's x and models:


def train(model, steps=2000):
    opt = torch.optim.Adam(model.parameters(), lr=1e-2)
    for step in range(steps):
        loss = ((model(x) - x) ** 2).mean()
        opt.zero_grad(); loss.backward(); opt.step()
    return loss.item()

lin = train(linear_ae)
non = train(nonlinear_ae)
print(f"final MSE: linear {lin:.4f}  nonlinear {non:.4f}")
print(f"data noise floor (0.05^2 per coord): {0.05**2:.4f}")
  

The loss is the mean squared error (MSE). The noise has variance \(0.05^2=0.0025\) per coordinate. Which model gets closer to 0.0025, and can either go below it?

The nonlinear code follows the arc, and its error falls below the noise

Answer: the nonlinear model, about 38 times better, and below 0.0025. The printout:


final MSE: linear 0.0494  nonlinear 0.0013
data noise floor (0.05^2 per coord): 0.0025
  
what each model reconstructsone point and its two reconstructionslinear: one straight line,the best any 1D linearprojection can do: MSE 0.0494nonlinear: follows the arc,MSE 0.0013its code tracksthe angle twhy the error drops below the noiseclean pointnoisy pointalong the curve:still on the curveacross the curve:left as errorNoise variance is 0.0025 per coordinate,and only the part across the curve remains.2,000 noisy points on an arc, intrinsically 1D but curved; drawn from a run of the reading's code (seed 0).
  1. Split the noise into a part along the curve and a part across it, each of variance 0.0025. A point moved along is still on the curve, so the code describes it; the part across stays as error (right).
  2. Averaged over 2 coordinates: \(\mathrm{MSE}\approx0.0025/2=0.00125\); the run gives 0.0013. Geometry, not overfitting.

Self-check on shapes and a noisier arc

Three questions on Part 1: shapes and a noisier arc here, and a wider code on the next page.

(a) nonlinear_ae (slide 6) takes a batch of 256 points, shape (256, 2). Its first three layers are the encoder. What is the shape after the encoder, and at the output?

(b) Slide 8 found \(\mathrm{MSE}\approx0.0025/2\) for noise of standard deviation 0.05. Rerun the arc experiment with standard deviation 0.1. About what MSE does the nonlinear model reach?

(a) (256, 1) after the encoder, the code; (256, 2) at the output.

(b) \(0.1^2/2=0.005\): only the part across the curve stays. Slides 6–7's code with 0.1 in place of 0.05 gives 0.0048.

Self-check on a code as wide as the input

The third question on Part 1.

(c) Suppose the code has 2 numbers, as many as the input, and the input has no added noise. What does the autoencoder learn?

(c) The identity, which says nothing about the data. Make the code narrower, or reconstruct the clean point from a noisy copy.

A narrower code or a noisy input forces structure; neither tells us which codes to decode to get new data.

A plain autoencoder compresses, but it cannot generate

Part 2 · The VAE. To generate: pick a code \(z\) (also called the latent variable: never observed in the data; the code space is the latent space), decode it. Which \(z\)?

a plain autoencoderz1​z2​a z froma holedecoderunlike the datacodes of training points:a thin, curved regionwith holesNothing in trainingconstrained thedecoder here.what we wantz1​z2​decoderrealistic data(1) a known distributionwe can sample: 𝒩(0, I)(2) The decoder is trainedso these samples decodeto realistic data.Schematic, not a trained model.
  • Nothing records where the encoder puts the training codes. A \(z\) from a hole can decode to something unlike any training input: no loss term constrained the decoder there.

The VAE provides (1) and (2): it changes what the encoder outputs and adds a loss term.

The VAE encodes a distribution per input

Kingma and Welling (ICLR 2014); Rezende et al., independently (ICML 2014). The VAE fixes where codes come from, then changes what the encoder outputs:

  • The codes get a distribution fixed in advance, the prior \(p(z)=\mathcal N(0,I)\). To generate, draw \(z\) from it, then \(x\) from the decoder's \(p(x\mid z)\).
  • The encoder gives \(q(z\mid x)=\mathcal N\big(\mu(x),\operatorname{diag}\sigma^2(x)\big)\): independent coordinates, mean \(\mu_j\) and variance \(\sigma_j^2\). \(\mu\) and \(\sigma^2\) are each \((B,d)\), for a batch of \(B\) inputs and a \(d\)-number code; today \(d=2\).
  • The encoder outputs only the numbers \(\mu\) and \(\log\sigma^2\); the Gaussian form is a choice that gives the KL divergence (S21) from the prior a closed form (slide 21) and a differentiable sample (slide 23).
  • \(q(z\mid x)\) approximates the true posterior \(p(z\mid x)\), the distribution over the codes that could have produced \(x\), so it is called an approximate posterior.

Training uses both networks; generation skips the encoder

The same model as a pipeline. Solid arrows are the training pass; the dashed green path is generation:

xencoderμ(x)σ(x)2​a distribution per inputKL term: how far q(z | x) is from the prior, pulling it toward the origin at unit scaleprior p(z) = 𝒩(0, I)q(z | x)z: one sample; in training: drawn from q(z | x)decoderxto generate: draw z from the prior, skip the encoderreconstruction term: how wellxrecovers x (squared error, up to scale)

Training needs the encoder; generation needs only the prior and the trained decoder.

The VAE has five distributions, and two of them cannot be computed

symboldistribution ofwhere it comes fromlearned?
\(p(z)\)the code \(z\)the prior, set to \(\mathcal N(0,I)\)no, fixed
\(p(x\mid z)\)the data \(x\), given a codethe decoder: assumed \(\mathcal N(\hat x,s^2I)\) around its output \(\hat x\)the decoder's weights; \(s^2\) is fixed
\(q(z\mid x)\)the code \(z\), given an inputthe encoder: \(\mathcal N\big(\mu(x),\operatorname{diag}\sigma^2(x)\big)\), the approximate posteriorthe encoder's weights
\(p(x)\)the data \(x\)the likelihood \(\int p(x\mid z)\,p(z)\,dz\); cannot be computedwhat training pushes up
\(p(z\mid x)\)the code \(z\), given an inputthe true posterior; cannot be computedapproximated by \(q(z\mid x)\)
  • The decoder network outputs one point \(\hat x\); the Gaussian around it is an assumption, which is why the loss is a squared error.
  • Read the bar as "given": the encoder takes \(x\) and gives \(z\); the decoder takes \(z\) and gives \(x\).

Training maximizes the ELBO, which bounds \(\log p(x)\) from below

Training should raise the probability the model gives the data:

  • The likelihood \(p(x)\) is the probability the model gives a data point \(x\): \(p(x)=\int p(x\mid z)\,p(z)\,dz\), the average of \(p(x\mid z)\) over every \(z\) from the prior. The decoder is a network, so this integral has no formula, and sampling the prior does not work either: almost every prior \(z\) decodes far from \(x\).
  • Instead, average over \(q(z\mid x)\), the codes likely to have produced \(x\). The price is an inequality: a bound that can be computed, the evidence lower bound (ELBO), derived on slide 19:
\[\log p(x)\ \ge\ \mathbb{E}_{q(z\mid x)}\big[\log p(x\mid z)\big]-\mathrm{KL}\big(q(z\mid x)\,\Vert\,p(z)\big)\]

The ELBO scores reconstruction and penalizes distance from the prior

The ELBO again, one term at a time:

\[\log p(x)\ \ge\ \mathbb{E}_{q(z\mid x)}\big[\log p(x\mid z)\big]-\mathrm{KL}\big(q(z\mid x)\,\Vert\,p(z)\big)\]
  • Reconstruction: encode \(x\), sample \(z\), score \(\log p(x\mid z)\). For a Gaussian decoder of fixed variance \(s^2\), \(p(x\mid z)=\mathcal N(\hat x,s^2I)\) around the decoder's output \(\hat x\), so \(-\log p(x\mid z)=\lVert x-\hat x\rVert^2/(2s^2)+\text{const}\): the squared error.
  • KL: \(\mathrm{KL}(q\Vert p)=\mathbb E_q[\log q-\log p]\ge0\), 0 only when they match (S21). It pulls every \(q(z\mid x)\) toward the origin at unit scale, so the distributions of different inputs overlap.

The ELBO is reconstruction minus the Kullback–Leibler (KL) divergence (S21) from the prior.

The two terms pull against each other

The ELBO's two terms, as the run computes them: the squared error, and the KL in closed form for diagonal Gaussians (natural log, so the KL is in nats; derived on slide 21). The run minimizes

\[\mathcal{L}=\lVert x-\hat x\rVert^2+\beta\cdot\tfrac12\sum\nolimits_{j=1}^{d}\big(\mu_j^2+\sigma_j^2-1-\log\sigma_j^2\big),\qquad\beta=0.1\]
  • In opposite directions: reconstruction is lowest when each input's code is precise (small \(\sigma\)) and apart from the others; KL is lowest when every \(q(z\mid x)\) is the prior. The compromise is a smoother, more sampleable code space, not a guarantee of no holes. The weight \(\beta\) sets the trade (Higgins et al., ICLR 2017); Part 4 sweeps it.

Each KL term is 0 exactly when \(\mu_j=0\) and \(\sigma_j=1\): when \(q(z\mid x)\) is the prior.

Jensen's inequality: the log of an average is at least the average of the logs

Derivation. The next page uses Jensen's inequality and S21's KL divergence:

  • Jensen's inequality: \(\log\) is concave, so \(\log\mathbb E[Y]\ge\mathbb E[\log Y]\) for a positive \(Y\).
  • Two numbers, 1 and 4, each with weight \(\tfrac12\): \(\ln\big((1+4)/2\big)=0.9163\) is at least \((\ln1+\ln4)/2=0.6931\).
  • From S21: \(\mathrm{KL}(q\Vert p)=\mathbb E_q[\log q-\log p]\ge0\), and it is 0 only when \(q\) and \(p\) match.
y12.54ln ychordlog of the average:ln 2.5 = 0.9163average of the logs:(ln 1 + ln 4)/2 = 0.6931

Moving the log inside an average can only lower the value.

Jensen's inequality turns \(\log p(x)\) into the ELBO

Derivation. \(\mathbb E_q\) averages over \(z\sim q(z\mid x)\).

  1. Average over the prior: \(p(x)=\mathbb E_{p(z)}\big[p(x\mid z)\big]=\int p(x\mid z)\,p(z)\,dz\).
  2. Multiply and divide by \(q(z\mid x)\) in the integral: \(p(x)=\int q(z\mid x)\,\frac{p(x\mid z)\,p(z)}{q(z\mid x)}\,dz=\mathbb E_q\big[p(x\mid z)\,p(z)/q(z\mid x)\big]\).
  3. By Jensen with \(Y=p(x\mid z)\,p(z)/q(z\mid x)\): \(\log p(x)\ge\mathbb E_q\big[\log p(x\mid z)+\log p(z)-\log q(z\mid x)\big]\).
  4. Regroup: \(\mathbb E_q[\log p(x\mid z)]-\mathbb E_q[\log q(z\mid x)-\log p(z)]\), reconstruction minus \(\mathrm{KL}(q\Vert p)\): slide 15's ELBO.
  • The ELBO is a lower bound, not \(\log p(x)\) itself: the gap is \(\mathrm{KL}(q(z\mid x)\Vert p(z\mid x))\), zero only when \(q\) is the true posterior. Raising the ELBO raises \(\log p(x)\) or closes the gap.

Self-check on the ELBO when \(q(z\mid x)\) is the prior

One question on the derivation's result, the ELBO \(\mathbb E_q[\log p(x\mid z)]-\mathrm{KL}\big(q(z\mid x)\,\Vert\,p(z)\big)\).

Self-check: if \(q(z\mid x)=p(z)\), what is the ELBO?

The KL term is 0, so the ELBO is \(\mathbb E_{p(z)}[\log p(x\mid z)]\): the decoder is scored on codes from the prior, which carry nothing about \(x\).

The KL to the prior has a closed form, one coordinate at a time

Derivation. Prerequisites: the Gaussian log-density \(\log\mathcal N(z;\mu,\sigma^2)=-\tfrac12\log(2\pi\sigma^2)-(z-\mu)^2/(2\sigma^2)\), and for \(z\sim\mathcal N(\mu,\sigma^2)\): \(\mathbb E[(z-\mu)^2]=\sigma^2\) and \(\mathbb E[z^2]=\mu^2+\sigma^2\). Both \(q\) and the prior have independent coordinates, so the KL is a sum over \(j\); here one coordinate, \(j\) dropped, against \(p=\mathcal N(0,1)\):

  1. \(\mathrm{KL}=\mathbb E_q[\log q-\log p]=\mathbb E_q\big[-\tfrac12\log\sigma^2-(z-\mu)^2/(2\sigma^2)+z^2/2\big]\): the two \(-\tfrac12\log2\pi\) cancel.
  2. Take the two averages: \(\mathrm{KL}=-\tfrac12\log\sigma^2-\tfrac12+\tfrac12(\mu^2+\sigma^2)\).
  3. Collect: \(\mathrm{KL}=\tfrac12\big(\mu^2+\sigma^2-1-\log\sigma^2\big)\), slide 17's term, in nats.
  • The run's \(\beta\): with a decoder variance \(s^2\), \(-\log p(x\mid z)=\lVert x-\hat x\rVert^2/(2s^2)+\text{const}\), so the run's loss with \(\beta=2s^2\) is \(2s^2\) times the negative ELBO, up to a constant: minimizing it maximizes the ELBO. Other \(\beta\) reweight the KL (\(\beta\)-VAE). The run's \(\beta=0.1\) is the ELBO for \(s^2=0.05\).

Self-check on two KL values and a run with a large KL

Three questions on Part 2.

(a) For one input, \(\mu=(0,0)\) and \(\sigma^2=(1,1)\). What is its KL, and what does the code tell the decoder about \(x\)?

(b) \(\mu=(2,0)\), \(\sigma^2=(1,1)\). Its KL?

(c) Reconstructions are excellent and the KL is large. Which term is winning? What do prior samples decode to?

(a) 0: it is the prior. Nothing, if every input gets this output: they all look the same to the decoder.

(b) 2 nats: \(z_1\) gives \(\tfrac12(4+1-1-0)=2\), and \(z_2\) gives 0.

(c) Reconstruction. The codes move away from the prior, so prior samples land where the decoder was not trained and decode to outputs unlike the data (slide 11).

The VAE's loss trades reconstruction against a KL term that pulls codes toward the prior.

Reparameterization moves the randomness out of the learned path

Part 3 · Reparameterization. The reconstruction term samples \(z\) from \(q(z\mid x)\). A random draw is not an operation autograd can differentiate, so no gradient passes back through it to \(\mu\) and \(\sigma\).

  • Instead of \(z\sim\mathcal N(\mu,\sigma^2)\), write \(z=\mu+\sigma\,\varepsilon\), \(\varepsilon\sim\mathcal N(0,1)\), elementwise over \((B,d)\): \(B\) inputs, \(d\) code numbers each. Same distribution: mean \(\mu\), variance \(\sigma^2\). The randomness sits in \(\varepsilon\), which has no learned parameters.
Normal(mu, sigma).sample(): z ∼ 𝒩(μ, σ2​)μσdraw zzdecoder, lossNo gradient reaches μ or σ.Normal(mu, sigma).rsample(): z = μ + σεμσ+×ε ∼ 𝒩(0, 1)no learned parameterszdecoder, lossdz/dμ = 1dz/dσ = εforward computationgradient on the way back

.sample() is the naive draw; .rsample() (r for reparameterized) computes \(\mu+\sigma\varepsilon\).

One demo samples both ways, then backpropagates through each

Reading 4.1's demo, with the loss \(z_1^2+z_2^2\); its lines for log_sigma.grad and for the naive draw's value are left out:


import torch
from torch.distributions import Normal
torch.manual_seed(0)
mu = torch.tensor([0.5, -1.0], requires_grad=True)
log_sigma = torch.tensor([0.0, 0.0], requires_grad=True)   # log sigma = 0, so sigma = 1
dist = Normal(mu, log_sigma.exp())    # second argument: the standard deviation sigma
# Naive sampling: draw z ~ N(mu, sigma^2) directly
z_naive = dist.sample()
print(f"sample():  requires_grad = {z_naive.requires_grad}, grad_fn = {z_naive.grad_fn}")
try:
    (z_naive ** 2).sum().backward()
except RuntimeError as e:
    print(f"sample():  backward() fails: {e}")
# Reparameterized sampling: z = mu + sigma * eps, eps ~ N(0, 1)
z_rep = dist.rsample()   # same as mu + log_sigma.exp() * torch.randn(2)
print(f"rsample(): z = {[round(v, 4) for v in z_rep.tolist()]}")
print(f"rsample(): requires_grad = {z_rep.requires_grad}")
(z_rep ** 2).sum().backward()
print(f"rsample(): mu.grad        = {[round(v, 4) for v in mu.grad.tolist()]}")
# Check: for the loss z^2, dL/dmu = 2z, since dz/dmu = 1
print(f"expected mu.grad        = {[round(v, 4) for v in (2 * z_rep).tolist()]}")
  

Autograd sees a graph only through .rsample()

The demo's printout:


sample():  requires_grad = False, grad_fn = None
sample():  backward() fails: element 0 of tensors does not require grad and does not have a grad_fn
rsample(): z = [-1.6788, -0.4316]
rsample(): requires_grad = True
rsample(): mu.grad        = [-3.3576, -0.8631]
expected mu.grad        = [-3.3576, -0.8631]
  
  • .sample(): a tensor's grad_fn records the operation that produced it, and backward() follows these records. Here it is None, so there is no graph to follow and backward() raises.
  • .rsample(): mu.grad equals the chain rule's \(2z\), since \(dz/d\mu=1\).

The naive sample has no graph; the reparameterized one carries a full graph.

Self-check on which network learns and one draw by hand

Two questions on Part 3.

(a) A VAE's step runs
z = Normal(mu, sigma).sample()
loss = ((dec(z) - x) ** 2).sum()
and loss.backward(). Which network gets a gradient from this loss?

(b) \(\mu=0.5\), \(\sigma=2\), \(\varepsilon=-1.2\). Compute \(z\), \(dz/d\mu\) and \(dz/d\sigma\).

(a) The decoder only: backward() runs, because the loss reaches the decoder's weights, but z has no graph back to \(\mu\) and \(\sigma\), so the encoder silently gets nothing (slide 24's loss reached no weights, so it raised). Use .rsample().

(b) \(z=0.5+2\cdot(-1.2)=-1.9\); \(dz/d\mu=1\); \(dz/d\sigma=\varepsilon=-1.2\).

.rsample() lets the gradient reach \(\mu\) and \(\sigma\); .sample() stops it at the draw.

The tiny VAE models two clusters through a 2-number code

Part 4 · A tiny VAE. Reading 4.1's script, first part: the data, two Gaussian clusters at \((-2,0)\) and \((+2,0)\) with standard deviation 0.5, and the two networks. In real_batch, side picks each point's cluster: a fair coin flip, True or False, becomes 1 or 0 and then \(+2\) or \(-2\).


import torch
import torch.nn as nn
torch.manual_seed(0)
# Data: mixture of two 2D Gaussians at (-2, 0) and (+2, 0), std 0.5
def real_batch(n):
    side = (torch.rand(n, 1) < 0.5).float() * 4 - 2      # -2 or +2
    return torch.cat([side, torch.zeros(n, 1)], dim=1) + 0.5 * torch.randn(n, 2)
enc = nn.Sequential(nn.Linear(2, 64), nn.ReLU(), nn.Linear(64, 4))  # -> mu (2), logvar (2)
dec = nn.Sequential(nn.Linear(2, 64), nn.ReLU(), nn.Linear(64, 2))
opt = torch.optim.Adam(list(enc.parameters()) + list(dec.parameters()), lr=1e-3)
  
real_batch(256), seed 0−202x1x2one batch through the modelxencμ (256, 2)logvar (256, 2)z = μ + σεdecx̂(256, 2)2→64→4(256, 2)2→64→2(256, 2)Shapes for one batch of 256 points; z = μ + σε is Part 3's reparameterization.

A tiny VAE trains on two clusters with Part 2's loss

The script's training loop, \(\beta=0.1\), a new batch of 256 points at every step:


for step in range(4000):
    x = real_batch(256)                                    # (256, 2)
    h = enc(x)                                             # (256, 4)
    mu, logvar = h[:, :2], h[:, 2:]                        # (256, 2) each
    z = mu + (0.5 * logvar).exp() * torch.randn_like(mu)   # reparameterization
    recon = ((dec(z) - x) ** 2).sum(dim=1).mean()          # reconstruction term
    kl = (-0.5 * (1 + logvar - mu ** 2 - logvar.exp()).sum(dim=1)).mean()
    loss = recon + 0.1 * kl                                # beta = 0.1
    opt.zero_grad(); loss.backward(); opt.step()
    if step % 1000 == 0 or step == 3999:
        print(f"step {step:4d}  recon {recon.item():.4f}  KL {kl.item():.4f}")
  
  • logvar is \(\log\sigma^2\), which may be any real number; (0.5 * logvar).exp() turns it into \(\sigma\), always positive. torch.randn_like(mu) is \(\varepsilon\), in the shape of mu.
  • kl is Part 2's closed form with the minus sign outside; logvar.exp() is \(\sigma^2\). Each .sum(dim=1) adds over the 2 coordinates, one number per point, (256,); .mean() averages over the batch.

Reconstruction error falls as the KL rises to about 2.8 nats

The loop's printout; the figure draws steps 0, 1000 and 3999:


step    0  recon 5.1227  KL 0.1519
step 1000  recon 0.1019  KL 2.8391
step 2000  recon 0.0883  KL 2.6634
step 3000  recon 0.1046  KL 2.6021
step 3999  recon 0.1053  KL 2.5339
  
  • Step 0: small random initial weights put \(\mu\) and \(\log\sigma^2\) near 0, so the untrained encoder outputs roughly the prior and the KL is near 0.
  • From step 0 to step 1000, reconstruction error fell while KL rose to about 2.8 nats: the two terms trade off. After that both change little.
recon5.12270.10190.1053KL0.15192.83912.5339010003999step

A lower reconstruction error comes with a larger KL: slide 17's trade, in this run's numbers.

Prior samples decode to both clusters, and 18% land in the gap

The script then decodes 4,000 samples \(z\sim\mathcal N(0,I)\), with no encoder anywhere, and counts where they land:


# Generate: sample z from the prior N(0, I), decode
with torch.no_grad():
    gen = dec(torch.randn(4000, 2))
frac_left = ((gen[:, 0] + 2).abs() < 1).float().mean()
frac_right = ((gen[:, 0] - 2).abs() < 1).float().mean()
print(f"generated samples near left mode:  {frac_left.item():.4f}")
print(f"generated samples near right mode: {frac_right.item():.4f}")
print(f"generated samples in the gap (|x1| < 1): "
      f"{(gen[:, 0].abs() < 1).float().mean().item():.4f}")
  

generated samples near left mode:  0.3865
generated samples near right mode: 0.4120
generated samples in the gap (|x1| < 1): 0.1787
  
  • A mode is a peak of the data distribution, here a cluster center. gen[:, 0] is each sample's \(x_1\), and \(\lvert x_1+2\rvert<1\) means within 1 of the left center: \(-3<x_1<-1\).
  • .float().mean() turns each True or False into 1 or 0 and averages them: the fraction of the 4,000 samples in the window.

Against real data, the gap holds 18% of the samples instead of about 2%

The same 4,000 samples, window by window, against real data:

z ∼ 𝒩(0, I), no encoderz1​This strip decodes into the gap;which side decodes to the left cluster is arbitrary.decoderleft~39%48%gap18%about2%right~41%48%18% against about 2%|x1​ + 2| < 1|x1​| < 1|x1​ − 2| < 1x1​generatedreal data

Codes drawn from a run of the reading's code (seed 0). Real data: each cluster puts 95% of its points within 2 sd (1.0) of its center, so 48% per window and about 2% in the gap.

  • That is generation, and the gap comes with it: with a connected prior (one region, no break) and a continuous decoder, some codes decode into the gap; 18% is this run's share.
  • On images, gap samples look like blends. VAE images are also blurry for a second reason: a pixelwise Gaussian loss averages several plausible sharp outputs into one.

Reading 4.1 decodes the straight line between two clusters' codes

The reading trains the same tiny VAE again (seed 0, \(\beta=0.1\)), encodes one point from each cluster, and decodes codes along the line between them, \((1-\alpha)\,z_{\text{left}}+\alpha\,z_{\text{right}}\):


# Encode one point from each cluster, then walk the straight line between codes
with torch.no_grad():
    x_left = torch.tensor([[-2.0, 0.0]])
    x_right = torch.tensor([[2.0, 0.0]])
    z_left = enc(x_left)[:, :2]
    z_right = enc(x_right)[:, :2]
    print(f"z_left  = ({z_left[0,0]:.4f}, {z_left[0,1]:.4f})")
    print(f"z_right = ({z_right[0,0]:.4f}, {z_right[0,1]:.4f})")
    print(f"{'alpha':>6} {'z':>20} {'decoded x':>20}")
    for a in [0.0, 0.2, 0.4, 0.5, 0.6, 0.8, 1.0]:
        z = (1 - a) * z_left + a * z_right
        xd = dec(z)
        print(f"{a:>6.1f} ({z[0,0]:>8.4f},{z[0,1]:>8.4f}) ({xd[0,0]:>8.4f},{xd[0,1]:>8.4f})")
  

The code of a point is its \(\mu\), the first two of enc's four outputs.

Walking between the two clusters' codes passes through the gap

The printout; \(\alpha\) runs from the left point's code (0) to the right point's (1):


z_left  = (0.8202, 0.0062)
z_right = (-0.8541, 0.0178)
 alpha                    z            decoded x
   0.0 (  0.8202,  0.0062) ( -1.9741, -0.0044)
   0.2 (  0.4853,  0.0085) ( -1.6061, -0.0036)
   0.4 (  0.1505,  0.0109) ( -0.6543, -0.0210)
   0.5 ( -0.0169,  0.0120) (  0.0698, -0.0207)
   0.6 ( -0.1844,  0.0132) (  0.7951, -0.0206)
   0.8 ( -0.5192,  0.0155) (  1.6218, -0.0012)
   1.0 ( -0.8541,  0.0178) (  2.0531,  0.0165)
  
  • The first code coordinate carries the cluster: \(z_1=0.8202\) for the left point, \(-0.8541\) for the right; which sign goes left is arbitrary.
  • The decoded \(x_1\) slides from \(-1.9741\) to \(2.0531\) with no detour, and the midpoint, \(\alpha=0.5\), decodes to \(x_1=0.0698\): inside the gap.

A continuous decoder on a connected code space cannot jump from one cluster to the other: some codes decode into the gap.

One sweep retrains the tiny VAE at five values of \(\beta\)

Reading 4.1's sweep wraps slides 27–28's training in one function, with beta in place of 0.1 and seed 0 at every call; it ends by decoding 4,000 prior samples:


def train_vae(beta, steps=4000):
    torch.manual_seed(0)
    enc = nn.Sequential(nn.Linear(2, 64), nn.ReLU(), nn.Linear(64, 4))
    dec = nn.Sequential(nn.Linear(2, 64), nn.ReLU(), nn.Linear(64, 2))
    opt = torch.optim.Adam(list(enc.parameters()) + list(dec.parameters()), lr=1e-3)
    for step in range(steps):
        x = real_batch(256)
        h = enc(x)
        mu, logvar = h[:, :2], h[:, 2:]
        z = mu + (0.5 * logvar).exp() * torch.randn_like(mu)
        recon = ((dec(z) - x) ** 2).sum(dim=1).mean()
        kl = (-0.5 * (1 + logvar - mu ** 2 - logvar.exp()).sum(dim=1)).mean()
        (recon + beta * kl).backward()
        opt.step(); opt.zero_grad()
    with torch.no_grad():
        gen = dec(torch.randn(4000, 2))
        near = (((gen[:, 0] + 2).abs() < 1) | ((gen[:, 0] - 2).abs() < 1)).float().mean()
        spread = gen[:, 0].std()
    return recon.item(), kl.item(), near.item(), spread.item()
  

The sweep runs the function at each \(\beta\), then measures real data

The loop that calls train_vae at each \(\beta\), then the same two statistics for real data:


print(f"{'beta':>6} {'recon':>8} {'KL':>8} {'near a mode':>12} {'sample std(x1)':>15}")
for beta in [0.01, 0.1, 1.0, 5.0, 20.0]:
    r, k, near, spread = train_vae(beta)
    print(f"{beta:>6.2f} {r:>8.4f} {k:>8.4f} {near:>12.4f} {spread:>15.4f}")
ref = real_batch(4000)
near_ref = (((ref[:, 0] + 2).abs() < 1) | ((ref[:, 0] - 2).abs() < 1)).float().mean()
print(f"reference (real data): near-a-mode {near_ref.item():.4f}  "
      f"std(x1) {ref[:, 0].std().item():.4f}")
  
  • "Near a mode" is slide 30's two windows together; | is an elementwise "or".
  • std(x1) is the standard deviation of the samples' first coordinate; the last line prints 2.07 for real data.
  • Each row is one run: the last step's reconstruction and KL, then the two statistics of its 4,000 decoded prior samples.

From a near-plain autoencoder to collapse as the KL weight grows

The sweep's printout, and its KL and near-a-mode columns as bars:


  beta    recon       KL  near a mode  sample std(x1)
  0.01   0.0111   5.1732       0.5890          1.7474
  0.10   0.1053   2.5339       0.7985          1.8853
  1.00   0.6592   0.9289       0.8673          1.8662
  5.00   2.1014   0.3707       0.6938          1.4817
 20.00   4.5083   0.0000       0.0000          0.0283
reference (real data): near-a-mode 0.9555  std(x1) 2.0708
  
5.170.0159%2.530.180%0.93187%0.37569%0.00200%this session's runfinal KLβnear a modeβ too small:a large KL, and samplesmiss the clustersβ = 20:KL is 0, and the samplesare nearly one pointReading 4.1's β sweep; real data has 96% near a mode.
  • \(\beta=0.01\): nearly a plain autoencoder. \(\beta=1\): the most samples near a mode, with worse reconstructions than at 0.1. \(\beta=20\): the samples are nearly one point.

Collapse needs no large \(\beta\) when the decoder can model the data alone

At \(\beta=20\) the KL reached 0. A decoder that can model the data without \(z\) gets there with no large \(\beta\): using \(z\) then only adds KL, so the loss is lowest with \(q(z\mid x)=p(z)\) for every input. Reading 4.1 gives the decoder a learned output variance and trains (with \(\beta=1\)) on two datasets, the two clusters and pure Gaussian noise \(\mathcal N(0,I)\):


# Two datasets. "clusters": the two-mode data from above -- real structure to encode.
# "noise": pure N(0, I) -- nothing to encode beyond what a noise model explains.
def clusters(n):
    side = (torch.rand(n, 1) < 0.5).float() * 4 - 2
    return torch.cat([side, torch.zeros(n, 1)], dim=1) + 0.5 * torch.randn(n, 2)

def noise(n):
    return torch.randn(n, 2)
  
  • The next page's train(data_fn) is slide 28's loop with a learned decoder variance, stored as its log log_s2 and trained with the rest. Its loss is nll + kl, so \(\beta=1\): nll is the Gaussian negative log-likelihood with variance log_s2.exp(), up to a constant.
  • After training, dec_spread decodes 1,000 prior samples and averages the two output coordinates' standard deviations: how much the output changes with \(z\).

The collapse test trains the same model once on each dataset


def train(data_fn, steps=4000):
    torch.manual_seed(0)
    enc = nn.Sequential(nn.Linear(2, 64), nn.ReLU(), nn.Linear(64, 4))
    dec = nn.Sequential(nn.Linear(2, 64), nn.ReLU(), nn.Linear(64, 2))
    log_s2 = torch.zeros(1, requires_grad=True)   # learned decoder output variance
    opt = torch.optim.Adam(list(enc.parameters()) + list(dec.parameters()) + [log_s2], lr=1e-3)
    for step in range(steps):
        x = data_fn(256)
        h = enc(x)
        mu, logvar = h[:, :2], h[:, 2:]
        z = mu + (0.5 * logvar).exp() * torch.randn_like(mu)
        nll = 0.5 * (((dec(z) - x) ** 2) / log_s2.exp() + log_s2).sum(dim=1).mean()   # Gaussian NLL
        kl = (-0.5 * (1 + logvar - mu ** 2 - logvar.exp()).sum(dim=1)).mean()
        loss = nll + kl
        opt.zero_grad(); loss.backward(); opt.step()
    with torch.no_grad():
        zs = torch.randn(1000, 2)
        dec_spread = dec(zs).std(dim=0).mean()   # how much the output changes with z
    return kl.item(), log_s2.exp().item(), dec_spread.item()
for name, fn in [("two clusters", clusters), ("pure noise  ", noise)]:
    kl, s2, spread = train(fn)
    print(f"{name}:  final KL {kl:.4f}   decoder sigma^2 {s2:.4f}   "
          f"std of dec(z) over z {spread:.4f}")
  

In posterior collapse, the decoder stops using the code

Posterior collapse: the approximate posterior \(q(z\mid x)\) (slide 12) is the prior for every input. The printout:


two clusters:  final KL 1.4967   decoder sigma^2 0.1526   std of dec(z) over z 1.1276
pure noise  :  final KL 0.0107   decoder sigma^2 0.9943   std of dec(z) over z 0.0993
  
  • On pure noise the code goes unused: KL 0.0107, a decoder variance of 0.9943 that matches the data's 1, and an output that barely changes with \(z\) (0.0993). Together with samples that are nearly one point (slide 36's \(\beta=20\) row), those are the symptoms.
  • Why noise: the decoder's own Gaussian, mean 0 and variance 1, already fits \(\mathcal N(0,I)\) data exactly, so \(z\) has nothing to add and the KL goes to its minimum, 0.
  • In practice, collapse hit early sentence VAEs, whose LSTM decoders could model sentences without \(z\) (Bowman et al., CoNLL 2016); the standard fix is KL annealing: start \(\beta\) at 0 and ramp it up.

Check that the KL stays above 0 and that the decoder's output depends on \(z\).

Self-check on a collapsed run and a near-plain autoencoder

Three questions on Part 4: two runs to diagnose here, and the gap on the next page.

(a) Your run ends with KL 0.0000 and a sample std(x1) of 0.03; the data's is 2.07. What happened? Name one fix.

(b) Your run ends with KL 5.17 nats, a reconstruction error of 0.01, and 59% of prior samples near a mode. Which way do you move \(\beta\)?

(a) Posterior collapse, as in the \(\beta=20\) row: \(\beta\) is too high, so lower it (the \(\beta=1\) row kept 87% near a mode). Annealing from 0 is the fix when a strong decoder ignores \(z\) (previous page).

(b) Up: that is the 0.01 row, close to a plain autoencoder; \(\beta=1\) reached 87%.

Self-check on the gap and longer training

The third question on Part 4.

(c) Would longer training remove the 18% of samples in the gap?

(c) Not all of them: a connected prior and a continuous decoder still decode some codes into the gap (slide 33). Longer runs of this script do leave fewer samples there; how many is each run's measurement.

The tiny VAE generates both clusters with some samples in the gap; too small a \(\beta\) gives nearly a plain autoencoder, too large a \(\beta\) collapses it.

Five mistakes in your own VAE, each with its cause and its fix

Part 5 · Close. Reading 4.1's pitfalls:

symptomcausefix
training runs, but the encoder's \(\mu\), \(\sigma\) get no gradient from reconstruction.sample() where .rsample() is neededuse .rsample(); check that z.grad_fn is not None
great reconstructions, but random \(z\) decode to outputs unlike the dataa plain autoencoder: the code space was never shaped to a prioradd the KL term, or sample only encodings of real data
KL near 0, and the samples are nearly one pointposterior collapse: \(\beta\) too high, or a decoder that ignores \(z\)\(\beta\) too high: lower \(\beta\); a decoder that ignores \(z\): anneal \(\beta\) from 0; either way check that the output depends on \(z\)
\(\sigma\to0\), a large KL, a plain autoencoder in effect\(\beta\) too smallraise \(\beta\) until most prior samples land near the data, with the KL still above 0
the loss scale differs from a reference implementationmixing sum and mean across the terms rescales the effective \(\beta\)one reduction convention for both terms

Today's answer to the title page's question, clause by clause

  • Target is its own input: a code narrower than the input, or a noisy input with the clean point as the target, forces the network to learn the data's structure. On the arc, a 1D nonlinear code reaches 0.0013, below the 0.0025 noise.
  • Before it can generate: a known prior \(\mathcal N(0,I)\) to sample from, and a loss of reconstruction plus a KL term that pulls each \(q(z\mid x)\) toward that prior. The result is a smoother, more sampleable code space, not one free of holes.
  • Through a random draw: \(z=\mu+\sigma\varepsilon\) puts the randomness in \(\varepsilon\). .rsample() keeps the graph; .sample() has none.
  • What it generates: both clusters, with 18% of samples in the gap. \(\beta=0.01\) is nearly a plain autoencoder, \(\beta=1\) puts the most samples near a mode (87%), and \(\beta=20\) collapses.

Today built a decoder that turns prior samples into data; S24 trains one with no encoder.

For next time

  • Next session (S24), Monday: GANs, the idea and its failure modes. A GAN keeps a decoder like today's, drops the encoder, and trains it against a second network, a discriminator.
  • Read: 4.2 GANs.
  • Try it yourself #2 in reading 4.1: rerun the tiny VAE with \(\beta\) at 0.001, 0.1 and 1.0; record the reconstruction, the KL and the share of prior samples in the gap.
  • Looking ahead (S25): Stable Diffusion runs diffusion inside the latent space of an autoencoder trained with a small KL term.

Quiz 3 · the final 30 minutes (6:45–7:15 PM)

Everyone completes Quiz 3 in Canvas.
Covers Module 3: S13–S22.

Online (Web) students and students with flexible-time arrangements may use their assigned flexible completion window.

Closed materials (Tier 0). No late quizzes; make-ups only in the syllabus's three cases.