The variational autoencoder: a complete derivation of the ELBO
Add a prior and likelihood to an autoencoder to obtain a trainable deep latent-variable model. Derive the VAE ELBO in two ways, identify its gap as KL to the true posterior, specialize reparameterization to a Gaussian encoder, and calculate each term. Study how decoder likelihood sets the reconstruction-KL trade-off and why samples may look blurred.
After this lesson you can
- Derive the ELBO using Jensen's inequality and the identity log p(x) = ELBO + KL(q ‖ p(z | x)).
- Derive closed-form KL between N(μ, diag σ²) and N(0, I), and reconstruction terms for Bernoulli and Gaussian decoders.
- Implement a VAE from scratch in NumPy and then in PyTorch with a convolutional decoder.
- Empirically compare the variance of reparameterization and REINFORCE estimators.
- Explain how decoder variance acts as an implicit KL weight.
Before you start
From reconstruction to a probabilistic model
The previous autoencoder learned to reconstruct images at codes it had seen. Generating required choosing a latent distribution, and nothing in the loss guaranteed that the decoder would behave well there. A VAE makes that choice part of the model: first describe how data are generated from a prior, then approximate inference of the latent given an observation.
To generate, draw and then . For evaluation or inference, the integral may be intractable. The true posterior requires that same marginal in its denominator. A deterministic encoder does not itself solve the integral or specify posterior uncertainty; introduce an approximation .
Amortization saves work, but the chosen family and network may not represent the true posterior. Distinguish approximation error in the distribution, optimization error and generative-model capacity. Next derive the bound with every piece visible.
First derivation: Jensen
Fix with . Assume is positive wherever the joint has mass and that the following expectations exist. Then
Logarithm concavity and Jensen’s inequality give
This is the ELBO, the evidence lower bound. The support assumption matters for the preceding equality: if omits a region where the joint has mass, the ratio expectation does not integrate the entire marginal. The positive-variance Gaussians used here have full support.
Second derivation: the gap is a KL
The proof follows by substituting into the definition of KL. Since KL is nonnegative, ; equality holds when equals the posterior almost everywhere. A higher bound may result from a better model, a better approximate posterior, or both. The gap is usually unknown precisely because evidence and posterior are intractable.
Expand the calculation while keeping track of the sign:
Evidence is constant with respect to and leaves the expectation. The identity does not say minimizing KL to the prior is equivalent to minimizing KL to the posterior: these appear in different decompositions. The first is computed for training; the second measures the gap and requires the true posterior. If the family is too narrow, even its best member may leave a positive gap.
The figure uses a conjugate case, not the posterior of an image VAE. It illustrates an exact identity that cannot be evaluated directly in large problems. Later cells estimate the expectation with samples, so a run’s estimated ELBO has Monte Carlo noise.
A diagonal Gaussian and its KL
Let with and . Components are independent in both distributions, so KL sums over coordinates. Using and in the log density ratio,
It is zero only when all means are zero and variances are one. To avoid negative variances, the network usually produces and computes . Restricting the range of is a stability decision that changes the admissible model; recording the clipping helps detect saturation. The formula is an instance of KL between Gaussians.
In one dimension, the density ratio satisfies
Taking expectations under , the second term gives and the third ; also . Their sum gives the preceding formula. Diagonal-Gaussian KL is analytical even when expected reconstruction requires Monte Carlo: both terms need not be estimated in the same way.
Reparameterizing for differentiation
For independent of parameters, write . Noise has a fixed distribution and the sample is a differentiable function of parameters. Under conditions permitting interchange of derivative and expectation, estimate the expectation gradient by differentiating through that function: the reparameterization gradient.
The score-function estimator can also be unbiased without differentiating the evaluated function, but often has high variance. No universal comparison exists without specifying function, distribution and baseline. The next figure specifies the estimators; increasing sample count reduces the variance of the mean but does not correct a biased estimator.
More explicitly, if depends on only through and differentiation can be exchanged with integration, the score-function rule gives . A baseline independent of can be subtracted from because , under regularity assumptions. The pathwise method instead differentiates with respect to the parameter holding fixed. In a VAE the loss can depend explicitly on parameters: include that derivative as well as the one through .
Reparameterization and amortized inference are central ideas of Auto-Encoding Variational Bayes; Rezende, Mohamed and Wierstra developed stochastic backpropagation for deep generative models. A single Monte Carlo sample does not automatically make an observed loss exact evidence in either case.
Likelihood is a modeling choice
Multiplying negative ELBO by , ignoring the parameter-independent constant and keeping fixed gives expected squared error plus times KL. Larger variance lowers the relative weight of reconstruction precision against regularization. If is learned, is no longer constant and cannot be dropped. A Gaussian mean optimal under squared error can average conditional alternatives and appear blurred; this does not imply every Gaussian VAE or all its samples must be blurred.
A Bernoulli decoder generates bits; for continuous intensities, calling BCE with fractional targets Bernoulli is not sufficient to claim a log-probability of those continuous values. Binarize under a fixed protocol or choose a likelihood appropriate to the data. When comparing losses, sum reconstruction over observation dimensions and KL over latent dimensions before averaging examples: averaging one per pixel and summing the other changes their relative weight.
With logits and a binary observation , Bernoulli NLL is . Working with logits avoids first calculating probabilities that can round to zero or one. In the Gaussian case the quantity is a density and depends on the scale of ; do not compare it directly with discrete data mass without specifying quantization. For visualization, distinguish the decoder mean from a sample adding noise: the former describes the conditional center and the latter includes the chosen variance.
Per-example KL encourages to approximate the prior, but does not guarantee the aggregate posterior equals it or every region decodes to a plausible image. The comparison is empirical and depends on architecture, data and training. Wasserstein Auto-Encoders explicitly studies regularization of the aggregate encoded distribution, distinct from the VAE objective.
Lab: VAE from scratch in NumPy
Use digits binarized at a fixed threshold. Fix the split before fitting and keep it separate. The MLP encoder produces mean and log-variance; the decoder produces Bernoulli logits. Array indices start at zero. Evaluation uses the same noise samples before and after training to reduce comparison noise: test ELBO remains an estimate, not exact log-evidence.
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
digits = load_digits()
x_all = (digits.data >= 8).astype(float)
train_idx, test_idx = train_test_split(np.arange(len(x_all)), test_size=0.2,
random_state=7, stratify=digits.target)
train_x, test_x = x_all[train_idx], x_all[test_idx]
rng = np.random.default_rng(101)
D, H, Z = 64, 32, 8
def init(a, b):
return rng.normal(0, np.sqrt(2/a), (a, b))
params = {'we': init(D, H), 'be': np.zeros(H),
'wm': init(H, Z)*0.2, 'bm': np.zeros(Z),
'wv': init(H, Z)*0.1, 'bv': np.zeros(Z),
'wd': init(Z, H), 'bd': np.zeros(H),
'wo': init(H, D)*0.3, 'bo': np.zeros(D)}
mom = {k: np.zeros_like(v) for k, v in params.items()}
vel = {k: np.zeros_like(v) for k, v in params.items()}
update_count = 0
eval_eps = np.random.default_rng(102).normal(size=(len(test_x), Z))
print('Entrenamiento y evaluación:', train_x.shape, test_x.shape)The next cell implements loss and backward propagation: the BCE derivative with respect to a logit is ; the reconstruction gradient passes through ; and KL derivatives are and . Dimensions are summed and examples averaged. Log-variance clipping is explicit and its derivative vanishes outside the interval.
def vae_forward(x, eps):
p = params
eh = np.maximum(0, x @ p['we'] + p['be'])
mu = eh @ p['wm'] + p['bm']
raw_lv = eh @ p['wv'] + p['bv']
lv = np.clip(raw_lv, -8, 8)
std = np.exp(0.5*lv)
z = mu + std*eps
dh = np.maximum(0, z @ p['wd'] + p['bd'])
logits = dh @ p['wo'] + p['bo']
return eh, mu, raw_lv, lv, std, z, dh, logits
def loss_parts(x, eps):
_, mu, _, lv, _, _, _, logits = vae_forward(x, eps)
recon = np.sum(np.logaddexp(0, logits) - x*logits, axis=1)
kl = 0.5*np.sum(mu*mu + np.exp(lv) - 1 - lv, axis=1)
return recon.mean(), kl.mean()
def vae_step(x, eps, lr=0.001):
global update_count
p = params
eh, mu, raw_lv, lv, std, z, dh, logits = vae_forward(x, eps)
prob = np.exp(-np.logaddexp(0, -logits))
da = (prob - x)/len(x)
g = {'wo': dh.T @ da, 'bo': da.sum(axis=0)}
ddh = (da @ p['wo'].T) * (dh > 0)
g['wd'], g['bd'] = z.T @ ddh, ddh.sum(axis=0)
dz = ddh @ p['wd'].T
dmu = dz + mu/len(x)
dlv = (0.5*dz*std*eps + 0.5*(np.exp(lv)-1)/len(x)) * (np.abs(raw_lv) < 8)
g['wm'], g['bm'] = eh.T @ dmu, dmu.sum(axis=0)
g['wv'], g['bv'] = eh.T @ dlv, dlv.sum(axis=0)
deh = (dmu @ p['wm'].T + dlv @ p['wv'].T) * (eh > 0)
g['we'], g['be'] = x.T @ deh, deh.sum(axis=0)
update_count += 1
for key in p:
mom[key] = 0.9*mom[key] + 0.1*g[key]
vel[key] = 0.999*vel[key] + 0.001*g[key]*g[key]
mhat = mom[key]/(1-0.9**update_count)
vhat = vel[key]/(1-0.999**update_count)
p[key] -= lr*mhat/(np.sqrt(vhat)+1e-8)
def train_steps(n):
for _ in range(n):
batch = train_x[rng.integers(0, len(train_x), 64)]
vae_step(batch, rng.normal(size=(len(batch), Z)))
initial_recon, initial_kl = loss_parts(test_x, eval_eps)
print('ELBO de test inicial:', round(float(-initial_recon-initial_kl), 3))Train in stages so each browser cell finishes quickly. A single seed does not guarantee every sample is recognizable or the model has converged; inspect the complete sample set and repeat with other seeds before drawing conclusions.
train_steps(1600)
recon, kl = loss_parts(test_x, eval_eps)
print('Pasos:', update_count, 'ELBO test estimado:', round(float(-recon-kl), 3))train_steps(1600)
recon, kl = loss_parts(test_x, eval_eps)
print('Pasos:', update_count, 'ELBO test estimado:', round(float(-recon-kl), 3))train_steps(1600)
recon, kl = loss_parts(test_x, eval_eps)
print('Pasos:', update_count, 'reconstrucción:', round(float(recon), 3),
'KL:', round(float(kl), 3), 'ELBO test estimado:', round(float(-recon-kl), 3))To inspect the decoder, display Bernoulli probabilities and an independent binary sample from each. Probabilities can look gray because they represent per-pixel uncertainty; a Bernoulli sample is a separate operation. The figure does not select examples after the fact.
import matplotlib.pyplot as plt
sample_rng = np.random.default_rng(103)
z = sample_rng.normal(size=(8, Z))
hidden = np.maximum(0, z @ params['wd'] + params['bd'])
logits = hidden @ params['wo'] + params['bo']
probabilities = np.exp(-np.logaddexp(0, -logits))
samples = sample_rng.random(probabilities.shape) < probabilities
fig, axes = plt.subplots(2, 8, figsize=(12, 3))
for i in range(8):
axes[0, i].imshow(probabilities[i].reshape(8, 8), cmap='gray', vmin=0, vmax=1)
axes[1, i].imshow(samples[i].reshape(8, 8), cmap='gray', vmin=0, vmax=1)
axes[0, i].axis('off')
axes[1, i].axis('off')
fig.text(0.02, 0.73, 'Probabilidad', rotation=90, va='center')
fig.text(0.02, 0.27, 'Muestra', rotation=90, va='center')
plt.show()KL per coordinate, averaged over the held-out set, shows which dimensions contribute to the rate term. A small value does not by itself prove a dimension contains no information; defining an active unit requires a declared statistic and threshold.
_, mu, _, lv, _, _, _, _ = vae_forward(test_x, eval_eps)
per_dimension = 0.5*np.mean(mu*mu + np.exp(lv) - 1 - lv, axis=0)
print('KL por dimensión en nats:', np.round(per_dimension, 3))
print('Suma:', round(float(per_dimension.sum()), 3))Local lab: convolutional VAE on two datasets
Train four independent models: MNIST and Fashion-MNIST, each with Bernoulli and fixed-variance Gaussian decoders. The full run uses 20 epochs per model; ORYON_QUICK=1 runs one epoch with 256 training and 128 test images per dataset. That test checks the workflow, not final-model quality. Bernoulli images are deterministically binarized at 0.5; the Gaussian model receives continuous intensities rescaled to [0, 1]. Their ELBOs should therefore not be directly compared: observations and reference measures differ. Gaussian NLL includes its normalizing constant and is a density, not discrete mass.
Each epoch reports an ELBO estimated with one posterior sample, reconstruction and KL summed per image. Test additionally reports mean KL per coordinate and variance across examples of posterior means. As an explicit diagnostic, a coordinate is called active when its test posterior-mean variance exceeds 0.01; the threshold is a convention, not a theorem. The latent plot uses posterior means, and the Gaussian image shown is the decoder mean without added noise. Prior samples and interpolations are calculated during the run; they do not depend on files from another lesson.
Data download to ORYON_DATA_ROOT or ./data. If the MNIST and FashionMNIST folders already exist elsewhere, set ORYON_MNIST_ROOT and ORYON_FASHION_ROOT respectively; each must point to the directory containing the dataset folder.
import os
import math
from pathlib import Path
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader, Subset
from torchvision import datasets, transforms
import matplotlib.pyplot as plt
quick = os.environ.get('ORYON_QUICK') == '1'
root = Path(os.environ.get('ORYON_DATA_ROOT', './data'))
mnist_root = Path(os.environ.get('ORYON_MNIST_ROOT', str(root)))
fashion_root = Path(os.environ.get('ORYON_FASHION_ROOT', str(root)))
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
torch.set_num_threads(1)
epochs = 1 if quick else 20
batch_size = 64 if quick else 128
latent_dim = 2
decoder_variance = 0.05
seed = 137
class ConvVAE(nn.Module):
def __init__(self, latent=2):
super().__init__()
self.encoder = nn.Sequential(
nn.Conv2d(1, 16, 4, 2, 1), nn.ReLU(),
nn.Conv2d(16, 32, 4, 2, 1), nn.ReLU(), nn.Flatten())
self.mu = nn.Linear(32 * 7 * 7, latent)
self.logvar = nn.Linear(32 * 7 * 7, latent)
self.expand = nn.Linear(latent, 32 * 7 * 7)
self.decoder = nn.Sequential(
nn.ConvTranspose2d(32, 16, 4, 2, 1), nn.ReLU(),
nn.ConvTranspose2d(16, 1, 4, 2, 1))
def encode(self, x):
h = self.encoder(x)
return self.mu(h), self.logvar(h).clamp(-12, 12)
def decode_logits(self, z):
return self.decoder(self.expand(z).reshape(-1, 32, 7, 7))
def forward(self, x, eps=None):
mu, logvar = self.encode(x)
if eps is None:
eps = torch.randn_like(mu)
z = mu + torch.exp(0.5 * logvar) * eps
return self.decode_logits(z), mu, logvar
def prepare(images, likelihood):
# Cada ejemplo Bernoulli es un vector binario, no una escala de grises.
return (images >= 0.5).float() if likelihood == 'bernoulli' else images
def terms(x, logits, mu, logvar, likelihood):
if likelihood == 'bernoulli':
per_pixel = F.binary_cross_entropy_with_logits(logits, x, reduction='none')
else:
mean = torch.sigmoid(logits)
per_pixel = 0.5 * ((x - mean).square() / decoder_variance
+ math.log(2 * math.pi * decoder_variance))
reconstruction = per_pixel.flatten(1).sum(dim=1)
kl_per_dim = 0.5 * (mu.square() + logvar.exp() - 1 - logvar)
return reconstruction, kl_per_dim
def load_data(name):
cls, directory = ((datasets.MNIST, mnist_root) if name == 'MNIST'
else (datasets.FashionMNIST, fashion_root))
train_all = cls(directory, train=True, download=True, transform=transforms.ToTensor())
test_all = cls(directory, train=False, download=True, transform=transforms.ToTensor())
train = Subset(train_all, range(256)) if quick else train_all
test = Subset(test_all, range(128)) if quick else test_all
return train, test
def run_one(name, likelihood, train, test):
torch.manual_seed(seed)
if device.type == 'cuda':
torch.cuda.manual_seed_all(seed)
model = ConvVAE(latent_dim).to(device)
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
order = torch.Generator().manual_seed(seed + 1)
loader = DataLoader(train, batch_size=batch_size, shuffle=True,
generator=order, num_workers=0)
for epoch in range(epochs):
model.train()
n = 0
total_rec = total_kl = 0.0
for images, _ in loader:
x = prepare(images, likelihood).to(device)
logits, mu, logvar = model(x)
rec, kl = terms(x, logits, mu, logvar, likelihood)
loss = (rec + kl.sum(dim=1)).mean()
optimizer.zero_grad(set_to_none=True)
loss.backward()
optimizer.step()
n += len(x)
total_rec += rec.detach().sum().item()
total_kl += kl.detach().sum().item()
print(name, likelihood, 'época', epoch + 1,
'ELBO entrenamiento MC1', round(-(total_rec + total_kl) / n, 3),
'| reconstrucción NLL', round(total_rec / n, 3),
'| KL', round(total_kl / n, 3), flush=True)
model.eval()
test_loader = DataLoader(test, batch_size=batch_size, shuffle=False, num_workers=0)
# Un generador propio hace reproducible la muestra Monte Carlo de evaluación.
evaluation_rng = torch.Generator(device=device).manual_seed(seed + 2)
all_mu, all_kl, all_labels, examples = [], [], [], []
total_rec = 0.0
with torch.no_grad():
for images, labels in test_loader:
x = prepare(images, likelihood).to(device)
eps = torch.randn((len(x), latent_dim), generator=evaluation_rng, device=device)
logits, mu, logvar = model(x, eps)
rec, kl = terms(x, logits, mu, logvar, likelihood)
total_rec += rec.sum().item()
all_mu.append(mu.cpu())
all_kl.append(kl.cpu())
all_labels.append(labels)
if not examples:
examples.append(x[:8].cpu())
means = torch.cat(all_mu)
kl_dims = torch.cat(all_kl).mean(dim=0)
labels = torch.cat(all_labels)
active_variance = means.var(dim=0, unbiased=False)
rec_mean = total_rec / len(means)
kl_mean = kl_dims.sum().item()
print(name, likelihood, 'test ELBO MC1', round(-rec_mean - kl_mean, 3),
'| reconstrucción NLL', round(rec_mean, 3), '| KL', round(kl_mean, 3))
print('KL media por dimensión:', np.round(kl_dims.numpy(), 4).tolist(),
'| Var de medias por dimensión:', np.round(active_variance.numpy(), 4).tolist(),
'| unidades activas > 0.01:', int((active_variance > 0.01).sum().item()))
# Posteriores test; una muestra por imagen para reconstrucción, su media para el mapa.
x = examples[0].to(device)
sample_rng = torch.Generator(device=device).manual_seed(seed + 3)
with torch.no_grad():
mu, logvar = model.encode(x)
eps = torch.randn(mu.shape, generator=sample_rng, device=device)
z = mu + torch.exp(0.5 * logvar) * eps
reconstruction = torch.sigmoid(model.decode_logits(z)).cpu()
prior = torch.randn((8, latent_dim), generator=sample_rng, device=device)
generated_mean = torch.sigmoid(model.decode_logits(prior)).cpu()
alpha = torch.linspace(0, 1, 8, device=device)[:, None]
interpolated = torch.sigmoid(model.decode_logits((1 - alpha) * mu[0] + alpha * mu[1])).cpu()
fig, axes = plt.subplots(4, 8, figsize=(12, 5))
rows = (x.cpu(), reconstruction, generated_mean, interpolated)
for row, images in enumerate(rows):
for col in range(8):
axes[row, col].imshow(images[col, 0], cmap='gray', vmin=0, vmax=1)
axes[row, col].axis('off')
for pos, text in zip((0.88, 0.65, 0.42, 0.19),
('Entrada', 'Reconstrucción', 'Media del prior', 'Interpolación')):
fig.text(0.01, pos, text, rotation=90, va='center')
fig.suptitle(name + ' / ' + likelihood)
plt.show()
plt.close(fig)
fig, ax = plt.subplots(figsize=(5, 4))
sample = min(len(means), 1000)
points = ax.scatter(means[:sample, 0].numpy(), means[:sample, 1].numpy(),
c=labels[:sample].numpy(), cmap='tab10', s=8, vmin=-0.5, vmax=9.5)
fig.colorbar(points, ax=ax, ticks=np.arange(10), label='Clase')
ax.set_title(name + ' / ' + likelihood + ': medias posteriores de test')
ax.set_xlabel('μ₁'); ax.set_ylabel('μ₂')
plt.show()
plt.close(fig)
del model, optimizer, loss, logits, x, mu, logvar, eps, z, prior, alpha, rec, kl
if device.type == 'cuda':
torch.cuda.empty_cache()
print('Dispositivo:', device, '| prueba corta:', quick)
for dataset_name in ('MNIST', 'Fashion-MNIST'):
train, test = load_data(dataset_name)
for likelihood in ('bernoulli', 'gaussian'):
run_one(dataset_name, likelihood, train, test)
del train, testnpm run lab and open the connection link.Exercises
Step 1 of 3. How is evidence expressed as an expectation under q?
Step 1 of 2. What does the logarithm of the normalizing constants contribute?
vae_loss(x, decoder_out, mu, logvar, likelihood) with NumPy. Arrays have batch on the first axis. For bernoulli, decoder_out contains logits and x is binary. For gaussian, decoder_out is (mean, log_variance) and variance broadcasts over x. Return the per-example mean of NLL summed over observations plus KL summed over latents. Reject unknown likelihoods.import numpy as np
def vae_loss(x, decoder_out, mu, logvar, likelihood):
passA VAE defines a generative model and learns an approximate posterior. The ELBO combines probabilistic reconstruction with KL to the prior, and its gap from evidence is KL to the true posterior. The scale and units of each term matter as much as architecture.