Module contents
Lesson 5 of 28Core 120 min

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 z∼p(z)z\sim p(z) and then x∼pθ(x∣z)x\sim p_\theta(x\mid z). For evaluation or inference, the integral may be intractable. The true posterior pθ(z∣x)p_\theta(z\mid x) requires that same marginal in its denominator. A deterministic encoder does not itself solve the integral or specify posterior uncertainty; introduce an approximation qϕ(z∣x)q_\phi(z\mid x).

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 xx with pθ(x)>0p_\theta(x)>0. Assume q(z∣x)q(z\mid x) is positive wherever the joint pθ(x,z)p_\theta(x,z) has mass and that the following expectations exist. Then

pθ(x)=Eq(z∣x)[pθ(x,z)q(z∣x)].p_\theta(x)=\E_{q(z\mid x)}\left[\frac{p_\theta(x,z)}{q(z\mid x)}\right].

Logarithm concavity and Jensen’s inequality give

log⁡pθ(x)≥Eq[log⁡pθ(x,z)−log⁡q(z∣x)]=Eq[log⁡pθ(x∣z)]−KL⁡(q(z∣x)∥p(z)).\log p_\theta(x)\ge\E_q[\log p_\theta(x,z)-\log q(z\mid x)] =\E_q[\log p_\theta(x\mid z)]-\KL(q(z\mid x)\|p(z)).

This is the ELBO, the evidence lower bound. The support assumption matters for the preceding equality: if qq 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 log⁡pθ(z∣x)=log⁡pθ(x,z)−log⁡pθ(x)\log p_\theta(z\mid x)=\log p_\theta(x,z)-\log p_\theta(x) into the definition of KL. Since KL is nonnegative, L≤log⁡pθ(x)\mathcal L\le\log p_\theta(x); equality holds when qq 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:

KL⁡(q∥pθ(z∣x))=Eq[log⁡q(z∣x)−log⁡pθ(x,z)+log⁡pθ(x)]=log⁡pθ(x)−Eq[log⁡pθ(x,z)−log⁡q(z∣x)].\begin{aligned} \KL(q\|p_\theta(z\mid x)) &=\E_q[\log q(z\mid x)-\log p_\theta(x,z)+\log p_\theta(x)]\\ &=\log p_\theta(x)-\E_q[\log p_\theta(x,z)-\log q(z\mid x)]. \end{aligned}

Evidence is constant with respect to zz 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 qq family is too narrow, even its best member may leave a positive gap.

InteractiveClosing the gap
  • Exact posterior
  • Approximation q
ELBOKL gaplog p(x)0

Model: standard normal prior and Gaussian observation with mean z. The KL bar starts at the ELBO endpoint and ends at evidence. Everything is in nats; because these are continuous densities, log evidence need not generally be negative.

1.0
0.70
-0.80
1.40
Posterior: mean0.671
Posterior: deviation0.573
log p(x)−1.454
ELBO−6.332
KL gap4.878
In this Gaussian model the posterior and evidence are known. Move the mean and scale of q and observe how KL determines the distance between ELBO and log-evidence.

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 qϕ(z∣x)=N(μ,diag⁡(σ2))q_\phi(z\mid x)=\Normal(\vb\mu,\operatorname{diag}(\vb\sigma^2)) with σj2>0\sigma_j^2>0 and p(z)=N(0,I)p(z)=\Normal(0,I). Components are independent in both distributions, so KL sums over coordinates. Using Eq[(Zj−μj)2]=σj2\E_q[(Z_j-\mu_j)^2]=\sigma_j^2 and Eq[Zj2]=μj2+σj2\E_q[Z_j^2]=\mu_j^2+\sigma_j^2 in the log density ratio,

KL⁡(q∥p)=12∑j(μj2+σj2−1−log⁡σj2).\KL(q\|p)=\frac12\sum_j\left(\mu_j^2+\sigma_j^2-1-\log\sigma_j^2\right).

It is zero only when all means are zero and variances are one. To avoid negative variances, the network usually produces ℓj=log⁡σj2\ell_j=\log\sigma_j^2 and computes σj=exp⁡(ℓj/2)\sigma_j=\exp(\ell_j/2). Restricting the range of ℓ\ell 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

log⁡q(z)p(z)=−log⁡σ−(z−μ)22σ2+z22.\log\frac{q(z)}{p(z)}=-\log\sigma-\frac{(z-\mu)^2}{2\sigma^2}+\frac{z^2}{2}.

Taking expectations under qq, the second term gives −1/2-1/2 and the third (μ2+σ2)/2(\mu^2+\sigma^2)/2; also −log⁡σ=−12log⁡σ2-\log\sigma=-\tfrac12\log\sigma^2. 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 ε∼N(0,I)\varepsilon\sim\Normal(0,I) independent of parameters, write z=μϕ(x)+exp⁡(ℓϕ(x)/2)⊙εz=\mu_\phi(x)+\exp(\ell_\phi(x)/2)\odot\varepsilon. 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 ff depends on ϕ\phi only through zz and differentiation can be exchanged with integration, the score-function rule gives ∇ϕEqf(Z)=Eq[f(Z)∇ϕlog⁡qϕ(Z)]\nabla_\phi\E_q f(Z)=\E_q[f(Z)\nabla_\phi\log q_\phi(Z)]. A baseline independent of ZZ can be subtracted from ff because Eq[∇ϕlog⁡qϕ(Z)]=0\E_q[\nabla_\phi\log q_\phi(Z)]=0, under regularity assumptions. The pathwise method instead differentiates f(μ+σε)f(\mu+\sigma\varepsilon) with respect to the parameter holding ε\varepsilon fixed. In a VAE the loss can depend explicitly on parameters: include that derivative as well as the one through zz.

InteractiveTwo gradient estimators

For Z = μ + σε and standard normal ε, compare f′(Z) with f(Z)ε/σ. Each estimate averages N independent samples; REINFORCE uses no baseline.

Exact variance of the average
  • REINFORCE without baseline
  • Reparameterization
Distribution of 256 simulated estimates

Preparing reproducible simulations…

Curves use exact Gaussian moments and variance divided by N. Histograms are a reproducible simulation with seed 427: each pair of estimates shares the same ε, but its N samples are independent. Sample variances fluctuate. Differentiation is with respect to μ with σ fixed; an appropriate baseline can reduce REINFORCE variance.

0.8
0.70
16
Exact gradient
1.6000
Exact variance: reparameterization
0.122500
Exact variance: REINFORCE
1.071620
Compare estimators for several functions and sample counts. The score function is shown without a baseline.

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 2s22s^2, ignoring the parameter-independent constant and keeping s2s^2 fixed gives expected squared error plus 2s22s^2 times KL. Larger variance lowers the relative weight of reconstruction precision against regularization. If s2s^2 is learned, Dlog⁡s2/2D\log s^2/2 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.

InteractiveVariance changes the trade-off
Test image
Reconstructed mean
Mean for a prior z

Three distinct models, trained from scratch on 1437 8×8 digits with the same seed for 60 epochs. Metrics use 360 held-out images; NLL uses 8 q samples per image and includes the Gaussian constant. Images use the same example and prior z for comparison; the decoder mean is shown without adding noise. A short run does not guarantee a monotonic trend or establish a general quality comparison.

0.02
MSE with z equal to q mean0.05034
Mean KL, nats per image5.004
Reconstruction NLL, nats per image15.193
Mean ELBO, nats per image−20.197
Compare the models and measurements shown. Reconstruction scale changes with variance, and conclusions depend on training and seed.

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 aia_i and a binary observation xix_i, Bernoulli NLL is ∑i[softplus⁡(ai)−xiai]\sum_i[\operatorname{softplus}(a_i)-x_i a_i]. 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 xx; 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.

InteractiveA VAE latent space
  • 0
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
Bernoulli probabilities per pixel

Each point is the VAE posterior mean or deterministic AE code; colors indicate known labels not used for training. The same 1000 MNIST examples from 6000 training images are shown. VAE ellipses have one standard deviation per axis and dashed circles of radii 1 and 2 are equal-density contours of the standard normal prior.

The VAE was trained on images binarized at threshold 128 with Bernoulli likelihood; the earlier AE uses grayscale intensities and squared error. Their coordinates, scales and objectives are not directly comparable. The VAE prior has positive density everywhere in the plane: this guarantees neither convincing samples nor absence of poorly learned regions. Distance is measured only to visible codes.

Model
100
Point coordinates(0.98, −0.23)
Distance to nearest visible mean0.000
Class of that mean7
Deviations of that posterior(0.12, 0.13)
Explore codes and their approximate distributions, and compare with the previous autoencoder. KL regularization does not guarantee absence of holes or exact agreement with the prior.

Per-example KL encourages q(z∣x)q(z\mid x) 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 8×88\times8 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.

[ ]Digits and VAE parametersBrowser
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 σ(a)−x\sigma(a)-x; the reconstruction gradient passes through z=μ+exp⁡(ℓ/2)εz=\mu+\exp(\ell/2)\varepsilon; and KL derivatives are μ\mu and (eℓ−1)/2(e^\ell-1)/2. Dimensions are summed and examples averaged. Log-variance clipping is explicit and its derivative vanishes outside the interval.

[ ]Forward pass, backward pass and AdamBrowser
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.

[ ]First training segmentBrowser
train_steps(1600)
recon, kl = loss_parts(test_x, eval_eps)
print('Pasos:', update_count, 'ELBO test estimado:', round(float(-recon-kl), 3))
[ ]Second training segmentBrowser
train_steps(1600)
recon, kl = loss_parts(test_x, eval_eps)
print('Pasos:', update_count, 'ELBO test estimado:', round(float(-recon-kl), 3))
[ ]Third training segmentBrowser
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.

[ ]Generate from the priorBrowser
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.

[ ]KL per dimensionBrowser
_, 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.

[ ]Convolutional VAE, ELBO and latent spaceLocal GPU
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, test
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

ProofThe bound and its gap
Prove: Derive the ELBO using Jensen and prove that its gap is KL to the posterior.
0
Assume densities with sufficient support and finite expectations.

Step 1 of 3. How is evidence expressed as an expectation under q?

ProofKL per coordinate
Prove: Derive KL from a diagonal Gaussian to a standard normal prior.
0
For each component E[(Z−μ)²] = σ² and E[Z²] = μ² + σ².

Step 1 of 2. What does the logarithm of the normalizing constants contribute?

NumericKL to the prior
For diagonal normal q with mean (1, 0) and variances (0.5, 1), calculate KL(q || N(0, I)) in nats.
QuizA large variance
In a VAE with a fixed-variance Gaussian decoder, what effect can increasing that variance have?
CodeA loss with consistent units
Implement 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):
  pass
Shift+Enter to run
Key idea

A 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.