Lesson 5.1 — Variational Autoencoders
Previous lesson · 4.7 State Space Sequence Models · Course overview · Next lesson · 5.2 GANs & Normalizing Flows
From Autoencoder to Variational Autoencoder
A deterministic autoencoder maps each observation to one code and decodes that code into a reconstruction. Minimizing reconstruction error leaves the distribution of codes unconstrained, so a standard-normal draw can land in a region the decoder rarely sees.
A variational autoencoder (VAE) defines both a generative model and an approximate inference model. The encoder returns a mean and variance for each latent coordinate. The decoder returns the parameters of an observation distribution. For a Gaussian decoder, its visible output is usually the conditional mean.
| What you want | Where the latent comes from | What the decoder gives you |
|---|---|---|
| Reconstruct an observed | Encode this and draw from | An observation distribution for this code. Its mean is often displayed as the reconstruction. |
| Generate a new observation | Draw from the prior | Draw a new from . No encoder input is needed. |
Compare the point code and sampled codes for one observation
Deterministic AE vs. Probabilistic VAE
Prior, Likelihood, and Posterior
The prior is the distribution of latent variables before observing data. The likelihood describes how observations are distributed at a given latent point. Integrating over latent points gives the evidence, the model's marginal density of the observation.
A nonlinear decoder usually makes the evidence integral intractable. The encoder supplies an approximation to the posterior. For continuous variables, the quantities in Bayes' rule are densities under the stated model.
The diagonal Gaussian makes the coordinates conditionally independent for a fixed input. The aggregate over different inputs can still have dependence. Predicting log-variance lets the network output any real number while ensuring a positive variance after exponentiation.
Inspect how log-variance sets the spread of latent draws
Gaussian Latent Distribution
Variational Inference
Amortized inference uses one encoder to infer posterior parameters for many observations. It replaces a separate optimization for each input with a shared mapping. For a fixed generative model, fitting the encoder minimizes . The expectation is taken over the encoder’s draws. KL is asymmetric and can become infinite if the reference density assigns zero probability to a set with positive probability under the encoder.
The following linear Gaussian model has a tractable posterior. Let the latent variable have unit normal prior, and observe with independent Gaussian noise of variance . Completing the square in gives the posterior variance and mean .

Read the left panel as an inference problem. A sensor has reported a value above its usual range. The prior allows many hidden states, but the reading favors states further to the right. The solid curve is the exact posterior for this linear sensor. A VAE encoder learns to approximate this kind of update for a more complicated decoder.
Now keep the hidden state and take an independent second reading with the same sensor. The solid curve on the right describes the possible repeat readings given the first one. It is wider than the solid curve on the left because a repeat reading adds its own measurement noise. Following the two dashed curves instead generates a reading before any observation has been supplied.
The posterior precision is the sum of the prior precision and the observation precision contributed through . When is nonzero, a lower noise variance concentrates the posterior near . With weak evidence it approaches the prior. These exact relationships belong to the stated observation model.
For the plotted sensor , the conditional variance of a new reading is . This addition uses independent measurement noise for the repeat reading.
Change sensor noise and inspect the exact posterior
Prior & Posterior Explorer
Evidence Lower Bound
For a fixed observation, substitute Bayes' rule into the KL from the encoder distribution to the true posterior. The log evidence is constant with respect to the latent draw.
The gap to the log evidence is the posterior KL. The KL in the trainable expression compares the encoder distribution with the prior. These terms answer different questions. The first measures the accuracy of inference for a fixed model, while the second penalizes a departure from the model's chosen prior.
For one Gaussian coordinate, evaluating the expected log-density ratio uses and .
With natural logarithms, this KL is measured in nats. At a particular sampled value , the log density ratio can be negative. Its expectation for each diagonal Gaussian dimension is nonnegative. In the lab, move the mean or change the variance and use the shaded density curves to see where the contributions come from.
KL Divergence Visualizer
Reparameterization and Gradients
Draw standard-normal noise and hold it fixed while differentiating the sampled computation. Moving the encoder mean translates the sample, while changing log-variance stretches or compresses its displacement from the mean.
For a differentiable loss and under conditions that permit moving the gradient inside the expectation, averaging these pathwise gradients estimates the reconstruction gradient. Draw fresh noise across training updates. For a finite-difference check, reuse the same draw on both sides. PyTorch's Normal.rsample() preserves this path through the sample to the distribution parameters.
Reparameterization Gradient Player
Reconstruction and the KL Penalty
For standardized continuous inputs, the example uses a Gaussian observation model with fixed identity covariance. The reconstruction loss follows directly from its negative log-density.
The implementation drops the constant term, sums over observation coordinates, and averages across the batch. The case gives the negative ELBO up to an additive constant. Changing changes the objective and the balance between reconstruction and prior alignment. A Bernoulli observation model instead yields binary cross-entropy for binary observations.
The encoder maps to a tanh hidden layer of width 10 and outputs separate mean and log-variance heads of shape . The decoder maps through another width-10 tanh layer to . The default latent width is two. Training draws one noise vector per observation per update, while fixed independent validation noise makes checkpoints comparable.
ELBO & β-VAE Loss Explorer
Latent Sampling and Posterior Collapse
A reconstruction uses a draw from the encoder distribution for a particular observation. Generation starts with a draw from the prior. Decoding either draw gives a Gaussian conditional mean. Under this example's likelihood, a full observation sample also adds independent unit Gaussian noise. An interpolation between two posterior means can pass through low-density regions and need not satisfy constraints of a real mechanical system.
The expected prior penalty splits into mutual information between observation and latent code and a penalty on the aggregate posterior. Posterior collapse occurs when the code conveys little information about the observation and the decoder can ignore it. Diagnose this by comparing KL per dimension, decoder sensitivity to the code, reconstruction, and downstream prediction together.
Latent Space Interpolation
Engineering Experiment · Probabilistic State Representation
The synthetic sensor generator from Lesson 3.1 draws uniformly from and uniformly from . It constructs a six-coordinate observation and a scalar target . There are 120 training examples and 60 validation examples, and standardization uses training statistics. The default seed is 3, with 1000 added for validation.
The AE and VAE share the initialization of the encoder mean head and decoder and use the same Adam settings. The AE disables the variance head, giving the two models different active parameter counts. The generation comparison decodes 60 fixed standard-normal codes and evaluates their decoder means against 60 validation observations. The AE uses this prior as an experimental convention. The two directions of nearest-neighbor error are coarse proxies for closeness and coverage in the standardized six-dimensional space.
For the frozen probe, fit a linear map from the AE code or VAE posterior mean to on the training data, with a ridge penalty of 0.01 on the weights. Evaluate its MSE on held-out observations. The mean-code reconstruction is , which can differ from the expectation of the nonlinear decoder under the posterior.
Live VAE Training & Sampling
PyTorch benchmark · 200 updates on the default split
| Metric | AE | VAE β=.1 | VAE β=1 |
|---|---|---|---|
| Mean reconstruction MSE | .086222 | .079008 | .312096 |
| One-draw reconstruction MSE | .086222 | .100872 | .456784 |
| KL (nats/sample) | — | 3.669327 | 1.008158 |
| Generated → validation NN MSE | .343654 | .145416 | .155998 |
| Validation → generated NN MSE | .384065 | .136119 | .285204 |
| Frozen probe MSE | .106623 | .090545 | .019048 |
On this split, gives lower nearest-neighbor errors for generated decoder means, and gives the lowest frozen-probe error with higher reconstruction MSE. The unit observation variance spreads full model samples off the low-dimensional sensor manifold, so these mean-based comparisons describe a particular generation procedure. Both the training and validation data are synthetic.
Reproducible PyTorch implementation
The script uses PyTorch autograd and Adam. Reuse the seed and noise stream to compare it with the browser run. For gradient debugging, compare the analytic KL gradient and the reconstruction path on a single sample with fixed noise.
import math, torch
from torch import nn
import torch.nn.functional as F
torch.set_default_dtype(torch.float64)
torch.set_num_threads(1)
def rng(seed):
s=seed & 0xffffffff
def r():
nonlocal s
s=(1664525*s+1013904223)&0xffffffff
return s/4294967296
return r
def gaussian(r): return math.sqrt(-2*math.log(max(r(),1e-15)))*math.cos(2*math.pi*r())
def noise(r,n,k): return torch.tensor([[gaussian(r) for _ in range(k)] for _ in range(n)])
def dataset(n,seed):
r=rng(seed); X=[];Y=[]
for _ in range(n):
x,u=4*r()-2,2*r()-1
X.append([x,math.sin(2*x),math.cos(2*x),x*x/2,u,math.sin(x+u)])
Y.append(.65*x+.5*math.sin(2*x)+.35*u)
return torch.tensor(X),torch.tensor(Y)
class Model(nn.Module):
def __init__(self,k,seed):
super().__init__(); self.k=k
self.layers=nn.ModuleList([nn.Linear(6,10),nn.Linear(10,k),nn.Linear(10,k),nn.Linear(k,10),nn.Linear(10,6)])
r=rng(seed+2000)
with torch.no_grad():
for l in self.layers:
l.weight.copy_(torch.tensor([.8*(r()-.5) for _ in range(l.weight.numel())]).reshape_as(l.weight));l.bias.zero_()
def encode(self,x):
h=self.layers[0](x).tanh();return self.layers[1](h),self.layers[2](h)
def decode(self,z):return self.layers[4](self.layers[3](z).tanh())
def forward(self,x,eps,vae=True):
mu,lv=self.encode(x);z=mu+(lv*.5).exp()*eps if vae else mu
return self.decode(z),mu,lv
def probe(z,y,zv,yv):
z=torch.cat([torch.ones(len(z),1),z],1);zv=torch.cat([torch.ones(len(zv),1),zv],1)
R=.01*torch.eye(z.shape[1]);R[0,0]=0
w=torch.linalg.solve(z.T@z+R,z.T@y);return ((zv@w-yv)**2).mean().item()
def run(seed=3,k=2,beta=.1,lr=.02,epochs=200,vae=True):
x,y=dataset(120,seed);v,yv=dataset(60,seed+1000);m,s=x.mean(0),x.std(0,correction=0)+1e-8;x,v=(x-m)/s,(v-m)/s
model=Model(k,seed);opt=torch.optim.Adam(model.parameters(),lr=lr);r=rng(seed+3000);ev=noise(rng(seed+4000),60,k);prior=noise(rng(seed+5000),60,k);hist=[]
for t in range(epochs+1):
if t%10==0 or t==epochs:
with torch.no_grad():
rec,mu,lv=model(v,ev,vae);kl=(.5*(mu.square()+lv.exp()-1-lv).sum(1)).mean().item() if vae else 0.;nll=(.5*(rec-v).square().sum(1)).mean().item();det=(model.decode(mu)-v).square().mean().item();gen=model.decode(prior);dist=torch.cdist(gen,v).square()/6
hist.append(dict(t=t,rec=nll,kl=kl,obj=nll+(beta*kl if vae else 0),det=det,prior=dist.min(1).values.mean().item(),coverage=dist.min(0).values.mean().item(),p=[dict(w=l.weight.tolist(),b=l.bias.tolist()) for l in model.layers]))
if t==epochs:break
eps=noise(r,len(x),k);rec,mu,lv=model(x,eps,vae);loss=.5*(rec-x).square().sum(1).mean()
if vae:loss=loss+beta*.5*(mu.square()+lv.exp()-1-lv).sum(1).mean()
opt.zero_grad();loss.backward();opt.step()
with torch.no_grad(): hist[-1]['probe']=probe(model.encode(x)[0],y,model.encode(v)[0],yv)
return hist
if __name__=='__main__':
for vae,beta in [(False,0),(True,.1),(True,1.)]:
h=run(beta=beta,vae=vae);print(vae,beta,{k:v for k,v in h[-1].items() if k!='p'})
References and Next Lesson
- Kingma and Welling introduce the ELBO and the pathwise estimator used by the VAE. Auto-Encoding Variational Bayes
- Chapter 17 develops the latent-variable interpretation and training objective. Understanding Deep Learning
- Kingma and Welling give a broader treatment of variational inference and reparameterization. An Introduction to Variational Autoencoders
- The distribution API documents normal distributions, reparameterized draws, and KL. PyTorch distributions
The next lesson compares an implicit generator with an invertible model whose density can be evaluated directly.
Previous lesson · 4.7 State Space Sequence Models · Course overview · Next lesson · 5.2 GANs & Normalizing Flows