Session S23
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
Three course items come first.
Today opens Module 4, on generative models, efficiency and evaluation (S23–S27).
S22 closed Module 3. Its answer, clause by clause, without the numbers:
[CLS] first and learned positions added, through a standard encoder. The projection is one strided convolution.[CLS] puts its weight, not why the model decided.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.
Each part answers one clause of the title page's question; a fifth closes before the quiz.
| part | the question it answers, and how |
|---|---|
| 1 · Autoencoders | What 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 VAE | What must change before it can generate? A known distribution to draw codes from, and a loss whose two terms pull against each other. |
| 3 · Reparameterization | How 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 VAE | What 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 · Close | Five 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.
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:
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
)
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.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?
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
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.
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.
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\)?
The VAE provides (1) and (2): it changes what the encoder outputs and adds a loss term.
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 same model as a pipeline. Solid arrows are the training pass; the dashed green path is generation:
Training needs the encoder; generation needs only the prior and the trained decoder.
| symbol | distribution of | where it comes from | learned? |
|---|---|---|---|
| \(p(z)\) | the code \(z\) | the prior, set to \(\mathcal N(0,I)\) | no, fixed |
| \(p(x\mid z)\) | the data \(x\), given a code | the 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 input | the encoder: \(\mathcal N\big(\mu(x),\operatorname{diag}\sigma^2(x)\big)\), the approximate posterior | the encoder's weights |
| \(p(x)\) | the data \(x\) | the likelihood \(\int p(x\mid z)\,p(z)\,dz\); cannot be computed | what training pushes up |
| \(p(z\mid x)\) | the code \(z\), given an input | the true posterior; cannot be computed | approximated by \(q(z\mid x)\) |
Training should raise the probability the model gives the data:
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)\]The ELBO is reconstruction minus the Kullback–Leibler (KL) divergence (S21) from the prior.
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\]Each KL term is 0 exactly when \(\mu_j=0\) and \(\sigma_j=1\): when \(q(z\mid x)\) is the prior.
Derivation. The next page uses Jensen's inequality and S21's KL divergence:
Moving the log inside an average can only lower the value.
Derivation. \(\mathbb E_q\) averages over \(z\sim q(z\mid x)\).
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\).
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)\):
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.
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\).
.sample() is the naive draw; .rsample() (r for reparameterized) computes \(\mu+\sigma\varepsilon\).
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()]}")
.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.
Two questions on Part 3.
(a) A VAE's step runsz = 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.
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)
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.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
A lower reconstruction error comes with a larger KL: slide 17's trade, in this run's numbers.
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
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.The same 4,000 samples, window by window, against real 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.
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.
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)
A continuous decoder on a connected code space cannot jump from one cluster to the other: some codes decode into the gap.
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 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}")
| is an elementwise "or".std(x1) is the standard deviation of the samples' first coordinate; the last line prints 2.07 for real data.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
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)
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.dec_spread decodes 1,000 prior samples and averages the two output coordinates' standard deviations: how much the output changes with \(z\).
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}")
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
Check that the KL stays above 0 and that the decoder's output depends on \(z\).
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%.
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.
Part 5 · Close. Reading 4.1's pitfalls:
| symptom | cause | fix |
|---|---|---|
| training runs, but the encoder's \(\mu\), \(\sigma\) get no gradient from reconstruction | .sample() where .rsample() is needed | use .rsample(); check that z.grad_fn is not None |
| great reconstructions, but random \(z\) decode to outputs unlike the data | a plain autoencoder: the code space was never shaped to a prior | add the KL term, or sample only encodings of real data |
| KL near 0, and the samples are nearly one point | posterior 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 small | raise \(\beta\) until most prior samples land near the data, with the KL still above 0 |
| the loss scale differs from a reference implementation | mixing sum and mean across the terms rescales the effective \(\beta\) | one reduction convention for both terms |
.rsample() keeps the graph; .sample() has none.Today built a decoder that turns prior samples into data; S24 trains one with no encoder.
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.