Module contents
Lesson 6 of 28Core 100 min

Training VAEs for real: posterior collapse, β-VAE and tighter bounds

Diagnose posterior collapse and aggregate-posterior mismatch, explore the rate-distortion curve with β, examine disentanglement claims, and estimate likelihood with importance sampling and the IWAE bound.

After this lesson you can

  • Diagnose posterior collapse using active units and estimated mutual information, and investigate KL annealing and free bits.
  • Trace and interpret a VAE rate-distortion curve as β varies.
  • Prove monotonicity of the expected IWAE bound in K and estimate log p(x) with importance sampling.
  • Quantify the gap between ELBO and estimated NLL and investigate the amortization gap.
  • Critically evaluate disentanglement claims in light of Locatello et al.

Before you start

The loss is low, but is the latent used?

A VAE can show apparently reasonable loss while its decoder ignores zz. If the decoder models data well without it, the encoder can approach the prior and pay little KL. Another difficulty remains even when the latent is used: ELBO is not log-likelihood, and its gap can be large. This lesson separates three questions: how much information the code carries, which rate-reconstruction trade-off was chosen, and what is known about marginal likelihood.

Total KL alone does not measure all information. Let q(x,z)=pdata(x)q(z∣x)q(x,z)=p_{\mathrm{data}}(x)q(z\mid x) and q(z)=∫pdata(x)q(z∣x)dxq(z)=\int p_{\mathrm{data}}(x)q(z\mid x)dx. Whenever the quantities are well defined,

ExKL⁡(q(z∣x)∥p(z))=Iq(X;Z)+KL⁡(q(z)∥p(z)).\E_x\KL(q(z\mid x)\|p(z))=I_q(X;Z)+\KL(q(z)\|p(z)).

The identity follows by adding and subtracting log⁡q(z)\log q(z) inside the integral. High mean KL can reflect information about xx, mismatch of the aggregate with the prior, or both. Near-zero mean KL bounds both nonnegative terms, but a dimension with small variance of μj(x)\mu_j(x) might still encode information through its posterior variance. An active-unit threshold is an operational diagnostic, not a universal definition of mutual information. Estimating IqI_q with finite mixtures has bias and sampling error; record the estimator and reference set.

A powerful autoregressive decoder receives previous pixels during training and can learn to predict the next without attending to zz. This solution path does not imply every powerful decoder collapses or identify a single cause in a particular run. Compare rates per dimension, variance of means, reconstruction and samples across seeds and held-out data.

InteractiveLatent units during training
  • Latent 1
  • Latent 2
  • Latent 3
  • Latent 4
80/80

Short run on 1437 binarized 8×8 digits and evaluation on 360 held-out images. To induce failure, the final β is 4: this is a strengthened penalty, not the standard VAE objective β = 1. Each curve is per-dimension KL on test, on a common logarithmic scale. A unit counts as active when variance of its test means exceeds 0.01; this is not decided using a KL threshold. Free bits uses 0.15 nats per dimension in the training objective. Annealing raises KL weight over 30 epochs. A single seed does not guarantee a remedy prevents collapse.

Epoch80 / 80
Current KL weight4.00
Active units0 / 4
KL of dimension 10.00016 nats
KL of dimension 20.00010 nats
KL of dimension 30.00007 nats
KL of dimension 40.00015 nats
Compare curves for the specified configurations. They are results of the experiment described in the figure; a remedy alone does not guarantee every unit activates.

Two interventions and their limits

Below the threshold that implementation does not penalize increasing group-average KL; it does not force realized KL to reach λ\lambda. Applying the maximum before or after averaging examples defines different objectives. Another intervention limits decoder capacity or context to make the latent useful, at the cost of expressiveness. In each case, compare with the same budget and evaluate ordinary ELBO separately: the modified training objective is not automatically log-likelihood.

Annealing appears, for example, in the text VAE of Bowman and colleagues; free bits is described by Kingma and colleagues. PixelVAE combines latents with a PixelCNN decoder; this lesson’s lab is a small implementation for studying behavior, not a reproduction of every paper result.

For example, if a dimension has mean KL below threshold, the maximum function is locally constant with respect to that term. The reconstruction gradient can still move the dimension, but may not: no mechanism magically forces a minimum observed rate. With annealing, early optimization steps assign less weight to encoding cost and later recover the chosen weight. When comparing annealed and unannealed training, preserve initialization, data, architecture and number of updates, and record rate evolution because the final outcome does not describe the whole dynamic.

β and the rate-distortion plane

At β=1\beta=1 we recover negative ELBO. If β≥1\beta\ge1, the maximized objective −D−βR-D-\beta R remains below ELBO and therefore evidence; for 0≤β<10\le\beta<1 no such general guarantee holds. Changing β\beta changes the desired trade-off, but finite-capacity and finite-compute training may not reach the optimal frontier. Slope −β-\beta interprets level lines of D+βRD+\beta R; it does not promise that every pair of trained models follows that slope exactly.

The β-VAE proposal by Higgins and colleagues relates this weight to factorized representations; Alemi and colleagues analyze ELBO in rate-distortion terms.

The next figure uses a short reproducible experiment in src/widgets/m19/l06/train_beta_sweep.py: an encoder and decoder with one 48-unit ReLU hidden layer, eight Gaussian latents and Bernoulli output, trained with Adam. Data are binarized Fashion-MNIST; evaluation uses separate images and five posterior samples per image. The later lab uses another implementation and budget, so its numbers need not match the figure.

InteractiveRate and distortion

Each point is a model and seed; the line shows the D + βR level through the selection.

  • Selected model
  • Other models
  • D + βR constante
Test inputs
Reconstruction
Prior: means

Short run: Fashion-MNIST, binarización fija ≥0.5, 1024 training images, 512 test images, 8 epochs and three seeds per β. Distortion is averaged over 5 posterior samples; reconstructions use the latent mean and prior images show Bernoulli means. They are not binary samples. At β = 1, D + R is the negative-ELBO loss; other β values change the objective. The line is an objective level, not an optimal frontier or fit to points.

1
17
Test KL rate
23.09 nats / image
Test distortion
322.23 nats / image
Line slope
−1.00
Each point corresponds to the experiment and seed described in the figure. Compare rate, distortion and selected-model images without interpreting a short run as the optimal frontier.

A disentanglement score requires defined reference factors, protocol and metric; without such labels it cannot be evaluated in the same way. Locatello and colleagues show unsupervised identification is not guaranteed without inductive biases about model and data, and study over 12,000 models on seven datasets. This does not prohibit learning factors with supervision, structure or additional assumptions. Nor does one β>1\beta>1 or a visually attractive single seed prove causal factors.

Metrics can answer different questions: some check whether a coordinate predicts a known factor, others whether one factor concentrates in few coordinates or different factors affect different parts of the code. A score requires data with available factors and a choice of auxiliary model or discretization. Report protocol and variation across seeds with the mean. A factor absent from the dataset or varying very little is not evaluated merely because the aggregate score is high.

Importance sampling and evidence

For observation xx, draw zk∼iidq(z∣x)z_k\iid q(z\mid x) and define wk=pθ(x,zk)/q(zk∣x)w_k=p_\theta(x,z_k)/q(z_k\mid x) with sufficient support. The mean weight is an unbiased estimator of pθ(x)p_\theta(x) when its expectation exists. Its logarithm is not an unbiased estimator of log⁡pθ(x)\log p_\theta(x): a realization may fall above or below evidence. In log space, logsumexp(log_w)-log(K) prevents overflow.

Proof

For K+1K+1 weights, each appears in KK of the K+1K+1 subsets obtained by removing one position. The mean of those subset means is therefore the mean of the K+1K+1 weights. Log concavity implies the log of that mean is at least the mean of the log subset means. Taking expectations, every subset has the distribution of KK i.i.d. weights, giving LK+1≥LK\mathcal L_{K+1}\ge\mathcal L_K. The second inequality is Jensen applied to the mean weight.

∎

Monotonicity concerns the expectation, not one Monte Carlo realization or curves estimated from few replicates. Convergence of the bound to evidence requires extra conditions to exchange limit and expectation. For example, if weights are bounded between positive constants, their logarithm is also bounded and dominated convergence justifies the interchange. An upper bound alone does not control the tail near zero. Effective sample size diagnoses weight concentration, but high ESS does not prove proposal coverage of the whole posterior.

InteractiveTightening the bound
  • Exact evidence
  • Mean bound
  • One deviation per replicate

Bound in nats; horizontal axis: log₁₀ K

  • Gradient SNR for q mean

SNR; horizontal axis: log₁₀ K

Verifiable model: z ~ N(0, 1), x | z ~ N(z, 1), x = 2 and q(z | x) = N(μ, 1) with μ = 0. Exact posterior is N(1, 1/2). Each point summarizes 60,000 independent fixed-seed replicates per K. The band shows standard deviation of an individual estimate, not a confidence interval for the mean; one replicate may exceed evidence.

SNR is the absolute mean of the reparameterized gradient with respect to μ divided by its standard deviation. Both are estimates: at large K the small mean introduces relative noise. Bound monotonicity is in expectation, not each realization, and falling SNR is not a universal law for every model or parameter.

1
Exact log p(x)−2.266
Estimated mean L_K−3.412
Estimator deviation2.120
Gradient SNR0.996
The figure’s model has known evidence. Compare replicate means and variability as K changes; an individual replicate need not respect monotonicity.
InteractiveGradient signal and noise

Model: Z has standard normal prior, X given Z is normal with mean Z and variance 1, and X = 1 is observed. Proposal q(Z) = N(μ, 1); exact posterior N(0.5, 0.5).

Computing reproducible replicates: 0 / 8192

Each point summarizes 8192 replicates with seed 871 of the reparameterized IWAE-bound gradient with respect to μ. Signal is absolute mean and noise is standard deviation; K values in the same replicate share prefixes. The dashed reference uses this model’s asymptotic expansion, not exact finite-K SNR. The gray line marks 1/√8192, an indicative scale for Monte Carlo error in SNR, not a confidence bound. At μ = 0.5 the true signal is zero by symmetry and the estimated ratio reflects simulation noise.

-0.5
16
The figure identifies the parameter and estimator. Compare mean signal and variation across replicates as K increases.

A tighter bound does not guarantee a better-trained inference network. Rainforth and colleagues analyze IWAE gradient signal-to-noise ratios; under their asymptotic assumptions, the standard encoder estimator’s SNR can decrease as K−1/2K^{-1/2}. This is not a law for every estimator, baseline, finite range or degenerate case. Generative-model parameter signals can behave differently.

Here SNR is the absolute mean gradient divided by its standard deviation across independent replicates. If the true mean is zero, the ratio is zero when standard deviation is positive; a nonzero sample mean may be noise. Variance of the estimated mean decreases with more external replicates, distinct from increasing KK inside each IWAE estimate. Separating the two avoids interpreting a more precise statistic measurement as an improved gradient.

Aggregate posterior and amortization

InteractivePrior and aggregate posterior
  • Samples from 1000 posteriors
  • Prior equal-density contours
  • Queried point
Bernoulli probabilities per pixel

This is the previous lesson’s 2D VAE, trained 15 epochs on 6000 MNIST images binarized at 128. The cloud draws one reproducible sample from each of 1000 training posteriors; density is evaluated as their full Gaussian mixture, not density of means. Circles of radius 1 and 2 are N(0, I) prior contours.

A small q/p ratio indicates lower relative aggregate density, but absence of points in a finite cloud does not prove a hole or imply a defective image. The decoder shows probabilities, not Bernoulli samples; both the prior and these Gaussians have positive density everywhere in the plane.

Latent point(0.00, 0.00)
log prior density−1.84
log finite aggregate density−5.91
log q(z) / p(z)−4.07
Explore prior density and codes from the described simulations or training. A sparsely occupied region is a diagnostic, not automatic proof that every image there is invalid.

A learned-prior family such as VampPrior attempts to adapt the prior using an encoder-based mixture. It does not eliminate the inference gap by definition or replace sample evaluation. The total evidence-ELBO gap can be conceptually separated into family approximation error and amortization error, studied by Cremer, Li and Duvenaud. Freezing the decoder and locally optimizing qq for one datum gives an achieved improvement; it would equal the exact amortization gap only if the family optimum were found and evaluated without error. Use independent samples to select and evaluate that improvement.

Lab: known evidence

Use Z∼N(0,1)Z\sim\Normal(0,1), X∣Z=z∼N(z,1)X\mid Z=z\sim\Normal(z,1) and observation x=1x=1. The marginal is X∼N(0,2)X\sim\Normal(0,2), so log-evidence can be computed directly. Choose q(z∣x)=N(0.2,1)q(z\mid x)=\Normal(0.2,1), an explicit full-support proposal. This is not a trained network: it lets us check the estimator against a known answer.

[ ]Linear Gaussian modelBrowser
import numpy as np

x_observed = 1.0
proposal_mean = 0.2
def log_normal(x, mean, variance):
    return -0.5*(np.log(2*np.pi*variance) + (x-mean)**2/variance)

def log_weights(z):
    return (log_normal(z, 0, 1) + log_normal(x_observed, z, 1)
            - log_normal(z, proposal_mean, 1))

def iwae_bound(log_w):
    log_w = np.asarray(log_w)
    return np.logaddexp.reduce(log_w, axis=-1) - np.log(log_w.shape[-1])

log_evidence = float(log_normal(x_observed, 0, 2))
print('Log-evidencia exacta:', round(log_evidence, 6))

Each row of the next matrix is an independent replicate of the bound estimator for one KK. Report mean, standard deviation of one replicate and standard error of the mean. As KK grows, less bias is expected under this example’s assumptions, but a small difference between estimated means may be noise; do not force outputs to be monotonic.

[ ]Bound replicatesBrowser
rng = np.random.default_rng(610)
repetitions = 400
for k in (1, 2, 4, 16, 64, 256, 1000):
    z = proposal_mean + rng.normal(size=(repetitions, k))
    estimate = iwae_bound(log_weights(z))
    sd = estimate.std(ddof=1)
    print('K:', k, 'media:', round(float(estimate.mean()), 5),
          'desv. réplica:', round(float(sd), 5),
          'error estándar:', round(float(sd/np.sqrt(repetitions)), 5))

Evidence is known here, so bias can be seen directly. With a real VAE it is usually unavailable: an estimate with many weights does not automatically become truth. Repeat with different seeds and proposals, inspect weight concentration and record the evaluation method. The following calculation uses ESS⁡=(∑w)2/∑w2\operatorname{ESS}=(\sum w)^2/\sum w^2 in log space for one replicate; it does not measure probability in regions the proposal never visited.

[ ]One replicate and its ESSBrowser
z = proposal_mean + rng.normal(size=1000)
lw = log_weights(z)
log_sum = np.logaddexp.reduce(lw)
ess = np.exp(2*log_sum - np.logaddexp.reduce(2*lw))
print('Log de media de pesos:', round(float(iwae_bound(lw)), 5))
print('ESS entre 1 y K:', round(float(ess), 2), 'de', len(lw))
print('Diferencia de esa réplica con la evidencia:', round(float(iwae_bound(lw)-log_evidence), 5))

This replicate may exceed log-evidence. The bound inequality concerns its expectation, not every output. For large KK, computing weights in blocks can reduce memory; each block must contribute to one global sum, not an unweighted mean of logarithms of different-sized blocks.

Local lab: does a PixelCNN use the latent?

Train a VAE with binarized MNIST images and an autoregressive decoder conditioned on zz. The mask and causality test hold zz fixed and verify that the current pixel cannot read the present or future. Compare four treatments with the same initialization: ordinary ELBO, KL annealing, free bits and both together. The short test reduces data, width and epochs; the normal run provides the full experiment.

The reported NLL is reconstruction loss conditioned on one q(z∣x)q(z\mid x) sample, not marginal NLL. Mutual information is estimated for the empirical mixture of test examples, with one sample per component; its estimator is noisy and can be negative. Neither an active unit nor KL thresholding guarantees useful information or better samples. Compare curves and repeat across seeds before attributing differences to treatment.

[ ]Diagnose collapse with an autoregressive decoderLocal GPU
import math
import os
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_MNIST_ROOT', './data'))
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
seed = 47
latent_dim = 8
width = 12 if quick else 32
blocks = 3
epochs = 2 if quick else 12
batch_size = 32 if quick else 64
free_nats = 0.1
active_threshold = 0.01
ramp_epochs = max(2, epochs // 2)
transform = transforms.ToTensor()
train_all = datasets.MNIST(root, train=True, transform=transform, download=True)
test_all = datasets.MNIST(root, train=False, transform=transform, download=True)
train = Subset(train_all, range(512)) if quick else train_all
test = Subset(test_all, range(128 if quick else 1024))
test_loader = DataLoader(test, batch_size=batch_size, shuffle=False, num_workers=0)

def binary(images):
    # La misma binarización determinista para los cuatro modelos y el test.
    return (images.to(device) >= 0.5).float()

class CausalConv(nn.Conv2d):
    def __init__(self, inputs, outputs, stream, first):
        kernel = (3, 3) if stream == 'vertical' else (1, 3)
        super().__init__(inputs, outputs, kernel, padding=(kernel[0] // 2, 1))
        mask = torch.zeros_like(self.weight)
        if stream == 'vertical':
            mask[:, :, 0, :] = 1
            if not first:
                # Las características verticales de la fila actual solo ven filas anteriores.
                mask[:, :, 1, :] = 1
        else:
            mask[:, :, 0, 0] = 1
            if not first:
                mask[:, :, 0, 1] = 1
        self.register_buffer('mask', mask)

    def forward(self, x):
        return F.conv2d(x, self.weight * self.mask, self.bias, padding=self.padding)

def gate(a):
    left, right = a.chunk(2, dim=1)
    return torch.tanh(left) * torch.sigmoid(right)

class PixelBlock(nn.Module):
    def __init__(self, inputs, first):
        super().__init__()
        self.first = first
        self.vertical = CausalConv(inputs, 2 * width, 'vertical', first)
        self.horizontal = CausalConv(inputs, 2 * width, 'horizontal', first)
        self.v_to_h = nn.Conv2d(2 * width, 2 * width, 1)
        self.z_to_v = nn.Linear(latent_dim, 2 * width)
        self.z_to_h = nn.Linear(latent_dim, 2 * width)
        self.h_out = nn.Conv2d(width, width, 1)

    def forward(self, vertical, horizontal, z):
        v = self.vertical(vertical) + self.z_to_v(z)[:, :, None, None]
        h = self.horizontal(horizontal) + self.v_to_h(v) + self.z_to_h(z)[:, :, None, None]
        h = self.h_out(gate(h))
        if not self.first:
            h = h + horizontal
        return gate(v), h

class VAE(nn.Module):
    def __init__(self):
        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(), nn.Linear(32 * 7 * 7, 64), nn.ReLU())
        self.mu = nn.Linear(64, latent_dim)
        self.logvar = nn.Linear(64, latent_dim)
        self.layers = nn.ModuleList([PixelBlock(1, True)] +
                                    [PixelBlock(width, False) for _ in range(blocks - 1)])
        self.output = nn.Sequential(nn.ReLU(), nn.Conv2d(width, width, 1), nn.ReLU(), nn.Conv2d(width, 1, 1))

    def encode(self, x):
        h = self.encoder(x)
        return self.mu(h), self.logvar(h).clamp(-8, 4)

    def decode(self, x, z):
        vertical = horizontal = x
        for layer in self.layers:
            vertical, horizontal = layer(vertical, horizontal, z)
        return self.output(horizontal)

def kl_values(mu, logvar):
    return 0.5 * (mu.square() + logvar.exp() - 1 - logvar)

@torch.no_grad()
def check_causality(model):
    # Mantén z fijo: modificar el presente y el futuro no cambia el logit actual.
    model.eval()
    a = torch.randn(1, 1, 8, 8, device=device)
    z = torch.zeros(1, latent_dim, device=device)
    for row, col in ((0, 0), (3, 4), (7, 7)):
        b = a.clone()
        b[:, :, row, col:] += 1.7
        b[:, :, row + 1:, :] -= 2.1
        assert torch.allclose(model.decode(a, z)[:, :, row, col],
                              model.decode(b, z)[:, :, row, col], atol=1e-6, rtol=0)

@torch.no_grad()
def diagnose(model):
    model.eval()
    all_mu, all_logvar = [], []
    nll_sum = count = 0
    # Generadores separados hacen repetible la estimación sin alterar el entrenamiento.
    generator = torch.Generator(device=device).manual_seed(120)
    for images, _ in test_loader:
        x = binary(images)
        mu, logvar = model.encode(x)
        epsilon = torch.randn(mu.shape, generator=generator, device=device)
        z = mu + torch.exp(0.5 * logvar) * epsilon
        logits = model.decode(x, z)
        nll_sum += F.binary_cross_entropy_with_logits(logits, x, reduction='sum').item()
        count += len(x)
        all_mu.append(mu)
        all_logvar.append(logvar)
    mu, logvar = torch.cat(all_mu), torch.cat(all_logvar)
    per_dim = kl_values(mu, logvar).mean(dim=0)
    var_mu = mu.var(dim=0, unbiased=False)
    active = int((var_mu > active_threshold).sum().item())

    # I(X;Z) para la mezcla empírica de estas imágenes de test. Una muestra de
    # cada q(z|x) y logsumexp por bloques evitan un tensor N×N×D completo.
    epsilon = torch.randn(mu.shape, generator=generator, device=device)
    z = mu + torch.exp(0.5 * logvar) * epsilon
    log_q_own = -0.5 * (epsilon.square() + logvar + math.log(2 * math.pi)).sum(dim=1)
    log_q_mix = []
    for chunk in z.split(64):
        differences = chunk[:, None, :] - mu[None, :, :]
        log_components = -0.5 * (differences.square() * torch.exp(-logvar)[None, :, :] +
                                 logvar[None, :, :] + math.log(2 * math.pi)).sum(dim=2)
        log_q_mix.append(torch.logsumexp(log_components, dim=1) - math.log(len(mu)))
    mi = (log_q_own - torch.cat(log_q_mix)).mean().item()
    return {'nll': nll_sum / count, 'kl': per_dim.cpu().numpy(),
            'var_mu': var_mu.cpu().numpy(), 'active': active, 'mi': mi}

def train_one(anneal, free):
    torch.manual_seed(seed)
    if device.type == 'cuda':
        torch.cuda.manual_seed_all(seed)
    model = VAE().to(device)
    check_causality(model)
    optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
    data_rng = torch.Generator().manual_seed(seed + 1)
    loader = DataLoader(train, batch_size=batch_size, shuffle=True,
                        generator=data_rng, num_workers=0)
    history = []
    for epoch in range(epochs):
        model.train()
        beta = min(1.0, (epoch + 1) / ramp_epochs) if anneal else 1.0
        for images, _ in loader:
            x = binary(images)
            mu, logvar = model.encode(x)
            z = mu + torch.exp(0.5 * logvar) * torch.randn_like(mu)
            logits = model.decode(x, z)
            nll = F.binary_cross_entropy_with_logits(logits, x, reduction='sum') / len(x)
            rate = kl_values(mu, logvar).mean(dim=0)
            # Free bits se aplica por dimensión tras promediar el lote.
            penalty = torch.clamp(rate, min=free_nats).sum() if free else rate.sum()
            loss = nll + beta * penalty
            optimizer.zero_grad(set_to_none=True)
            loss.backward()
            optimizer.step()
        metrics = diagnose(model)
        history.append(metrics)
        print('recocido', anneal, 'free bits', free, 'época', epoch + 1,
              'beta', round(beta, 3), 'NLL', round(metrics['nll'], 3),
              'KL por dimensión', np.round(metrics['kl'], 3),
              'activas', metrics['active'], 'MI estimada', round(metrics['mi'], 3))
    del model, optimizer, loss, logits, mu, logvar, z, x, nll, rate, penalty
    if device.type == 'cuda':
        torch.cuda.empty_cache()
    return history

print('Dispositivo:', device, '| prueba corta:', quick, '| ejemplos test:', len(test))
runs = {}
for anneal in (False, True):
    for free in (False, True):
        runs[(anneal, free)] = train_one(anneal, free)

fig, axes = plt.subplots(2, 2, figsize=(10, 6), sharex=True)
for ax, ((anneal, free), history) in zip(axes.flat, runs.items()):
    values = np.stack([h['kl'] for h in history])
    for j in range(latent_dim):
        ax.plot(np.arange(1, epochs + 1), values[:, j], label=f'z{j + 1}')
    ax.set_title(f'Recocido: {anneal}; free bits: {free}')
    ax.set_xlabel('Época')
    ax.set_ylabel('KL de test, nats')
axes.flat[0].legend(ncol=2, fontsize=7)
fig.tight_layout()
plt.show()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Local lab: β, IWAE and the amortization gap

On Fashion-MNIST deterministically binarized at 0.5, train VAEs with several β values and, separately, IWAE models with several K values. Repeat each configuration with three seeds. The table separates KL rate, Bernoulli distortion, ELBO and importance estimates. When β differs from 1 the training objective is not ELBO; IWAE trains with β = 1. Training and test are the official splits.

The full run uses 20 epochs per model and evaluates 128 test images with 5000 importance samples per image, in blocks that avoid storing all samples in memory. The mean describes that subset, not the whole test set. Set ORYON_QUICK=1 to check the workflow with fewer images, one epoch, 16 importance samples and fewer refinement steps. The short test does not estimate full-run quality. Log-mean weight is a random estimate, not exact log p(x); its expectation is a bound and one realization need not be monotonic.

To study amortization, fix the trained decoder and directly optimize the mean and log-variance of a separate Gaussian posterior per test image. Then compare both estimated ELBOs using common noise independent of optimization. Their difference is a practical estimate depending on steps, Gaussian family and Monte Carlo noise: it may be negative and is not the exact amortization gap defined by a global optimum.

Data download to ORYON_DATA_ROOT or ./data; alternatively set ORYON_FASHION_ROOT to the directory containing the FashionMNIST folder. Curves and metrics are generated during the run and do not require files from other lessons.

[ ]Beta sweep, IWAE and local refinementLocal 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_FASHION_ROOT', os.environ.get('ORYON_DATA_ROOT', './data')))
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
torch.set_num_threads(1)
latent = 8
batch_size = 64 if quick else 128
epochs = 1 if quick else 20
eval_count = 16 if quick else 128
importance_k = 16 if quick else 5000
importance_chunk = 8 if quick else 64
refine_steps = 8 if quick else 150
refine_count = 8 if quick else 16
seeds = (17, 29, 41)
configs = ([(0.5, 1), (1.0, 1), (4.0, 1), (1.0, 3)] if quick
           else [(0.25, 1), (1.0, 1), (4.0, 1), (16.0, 1), (1.0, 5), (1.0, 20)])

train_all = datasets.FashionMNIST(root, train=True, download=True, transform=transforms.ToTensor())
test_all = datasets.FashionMNIST(root, train=False, download=True, transform=transforms.ToTensor())
train = Subset(train_all, range(256)) if quick else train_all
test = Subset(test_all, range(eval_count))

class VAE(nn.Module):
    def __init__(self):
        super().__init__()
        self.encoder = nn.Sequential(nn.Flatten(), nn.Linear(784, 128), nn.ReLU())
        self.mu = nn.Linear(128, latent)
        self.logvar = nn.Linear(128, latent)
        self.decoder = nn.Sequential(nn.Linear(latent, 128), nn.ReLU(), nn.Linear(128, 784))

    def encode(self, x):
        h = self.encoder(x)
        return self.mu(h), self.logvar(h).clamp(-12, 12)

    def decode(self, z):
        return self.decoder(z)

def binary(images):
    return (images >= 0.5).float().flatten(1)

def kl_normal(mu, logvar):
    return 0.5 * (mu.square() + logvar.exp() - 1 - logvar).sum(dim=1)

def log_weights(model, x, mu, logvar, eps):
    # x: B×784; eps: B×K×d. Solo K por bloque llega al decodificador.
    batch, k, _ = eps.shape
    z = mu[:, None, :] + torch.exp(0.5 * logvar[:, None, :]) * eps
    logits = model.decode(z.reshape(-1, latent)).reshape(batch, k, 784)
    target = x[:, None, :].expand_as(logits)
    log_px = -F.binary_cross_entropy_with_logits(logits, target, reduction='none').sum(dim=2)
    log_pz = -0.5 * (z.square() + math.log(2 * math.pi)).sum(dim=2)
    log_qz = -0.5 * (eps.square() + logvar[:, None, :] + math.log(2 * math.pi)).sum(dim=2)
    return log_px + log_pz - log_qz, log_px

def train_model(beta, k_train, seed):
    torch.manual_seed(seed)
    if device.type == 'cuda':
        torch.cuda.manual_seed_all(seed)
    model = VAE().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()
        total = count = 0
        for images, _ in loader:
            x = binary(images).to(device)
            mu, logvar = model.encode(x)
            if k_train == 1:
                z = mu + torch.exp(0.5 * logvar) * torch.randn_like(mu)
                logits = model.decode(z)
                rec = F.binary_cross_entropy_with_logits(logits, x, reduction='none').sum(dim=1)
                loss = (rec + beta * kl_normal(mu, logvar)).mean()
            else:
                eps = torch.randn((len(x), k_train, latent), device=device)
                logw, _ = log_weights(model, x, mu, logvar, eps)
                loss = -(torch.logsumexp(logw, dim=1) - math.log(k_train)).mean()
            optimizer.zero_grad(set_to_none=True)
            loss.backward()
            optimizer.step()
            total += loss.detach().item() * len(x)
            count += len(x)
        print('semilla', seed, 'β', beta, 'K entrenamiento', k_train,
              'época', epoch + 1, 'pérdida media', round(total / count, 3), flush=True)
    return model

@torch.no_grad()
def evaluate(model, seed):
    model.eval()
    generator = torch.Generator(device=device).manual_seed(seed + 100)
    loader = DataLoader(test, batch_size=min(16, eval_count), shuffle=False, num_workers=0)
    sums = {'distortion': 0.0, 'rate': 0.0, 'elbo': 0.0, 'iwae5': 0.0, 'logp': 0.0}
    count = 0
    for images, _ in loader:
        x = binary(images).to(device)
        mu, logvar = model.encode(x)
        kl = kl_normal(mu, logvar)
        running = torch.full((len(x),), -torch.inf, device=device)
        first_five = []
        first_logpx = []
        done = 0
        while done < importance_k:
            k = min(importance_chunk, importance_k - done)
            eps = torch.randn((len(x), k, latent), generator=generator, device=device)
            logw, logpx = log_weights(model, x, mu, logvar, eps)
            running = torch.logaddexp(running, torch.logsumexp(logw, dim=1))
            if done < 5:
                first_five.append(logw[:, :min(k, 5 - done)])
            if done < 8:
                first_logpx.append(logpx[:, :min(k, 8 - done)])
            done += k
        distortion = -torch.cat(first_logpx, dim=1).mean(dim=1)
        iwae5 = torch.logsumexp(torch.cat(first_five, dim=1), dim=1) - math.log(5)
        logp_estimate = running - math.log(importance_k)
        count += len(x)
        sums['distortion'] += distortion.sum().item()
        sums['rate'] += kl.sum().item()
        sums['elbo'] += (-distortion - kl).sum().item()
        sums['iwae5'] += iwae5.sum().item()
        sums['logp'] += logp_estimate.sum().item()
    return {key: value / count for key, value in sums.items()}

def refine_posterior(model, seed):
    model.eval()
    for parameter in model.parameters():
        parameter.requires_grad_(False)
    examples = torch.stack([binary(test[i][0].unsqueeze(0))[0] for i in range(refine_count)]).to(device)
    with torch.no_grad():
        mu0, logvar0 = model.encode(examples)
    mu = mu0.detach().clone().requires_grad_()
    logvar = logvar0.detach().clone().requires_grad_()
    optimizer = torch.optim.Adam([mu, logvar], lr=0.03)
    fit_rng = torch.Generator(device=device).manual_seed(seed + 201)
    for _ in range(refine_steps):
        lv = logvar.clamp(-12, 12)
        eps = torch.randn((len(examples), 4, latent), generator=fit_rng, device=device)
        _, logpx = log_weights(model, examples, mu, lv, eps)
        objective = (logpx.mean(dim=1) - kl_normal(mu, lv)).mean()
        optimizer.zero_grad(set_to_none=True)
        (-objective).backward()
        optimizer.step()
    # La muestra de comparación es independiente de las muestras de optimización.
    compare_rng = torch.Generator(device=device).manual_seed(seed + 202)
    compare_k = 8 if quick else 128
    eps = torch.randn((len(examples), compare_k, latent), generator=compare_rng, device=device)
    with torch.no_grad():
        _, initial_px = log_weights(model, examples, mu0, logvar0, eps)
        _, refined_px = log_weights(model, examples, mu, logvar.clamp(-12, 12), eps)
        initial = (initial_px.mean(dim=1) - kl_normal(mu0, logvar0)).mean().item()
        refined = (refined_px.mean(dim=1) - kl_normal(mu, logvar.clamp(-12, 12))).mean().item()
    return initial, refined

results = []
print('Dispositivo:', device, '| prueba corta:', quick, '| K evaluación:', importance_k)
for beta, train_k in configs:
    for seed in seeds:
        model = train_model(beta, train_k, seed)
        metrics = evaluate(model, seed)
        initial, refined = refine_posterior(model, seed)
        result = {'beta': beta, 'train_k': train_k, 'seed': seed, **metrics,
                  'elbo_amortized_subset': initial, 'elbo_refined_subset': refined}
        results.append(result)
        print('TEST', result, '| mejora práctica ELBO:', round(refined - initial, 4), flush=True)
        del model
        if device.type == 'cuda':
            torch.cuda.empty_cache()

fig, ax = plt.subplots(figsize=(6, 4))
for beta in sorted({r['beta'] for r in results if r['train_k'] == 1}):
    rows = [r for r in results if r['train_k'] == 1 and r['beta'] == beta]
    ax.scatter([r['rate'] for r in rows], [r['distortion'] for r in rows], label='β=' + str(beta))
ax.set_xlabel('KL media por imagen (nats)')
ax.set_ylabel('NLL de reconstrucción por imagen (nats)')
ax.set_title('Test: puntos por semilla; no son frontera óptima')
ax.legend()
plt.show()
plt.close(fig)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

ProofComparing K and K+1
Prove: Prove monotonicity of the expected IWAE bound for positive i.i.d. weights.
0
Consider the K+1 subsets obtained by removing one weight.

Step 1 of 3. What is the mean of the subset means?

NumericA threshold in bits
There are 32 dimensions and the free-bits threshold is 0.25 nats per dimension. How many bits per image equal the sum of these thresholds?
QuizDiagnosing collapse
A model has eight dimensions: four have clearly positive mean KL and four are near zero below a fixed threshold. Which diagnosis is most appropriate?
QuizWhat Locatello allows
Which claim is compatible with the result on lack of unsupervised identifiability?
CodeSumming weights by blocks
Implement iwae_bound(log_w) for a (B, K) matrix of log-weights and estimate_nll(model, x, K, chunk). model.log_weights(x, n) returns (B, n) new log-weights per block. Combine sums in log space, including a smaller final block; return the per-example mean estimated NLL. Reject K or chunk below one.
import numpy as np

def iwae_bound(log_w):
  pass

def estimate_nll(model, x, K, chunk):
  pass
Shift+Enter to run
Key idea

Rate combines information and aggregate mismatch. The IWAE bound tightens in expectation as KK grows, but its estimator, its gradient and exact likelihood are different objects. Diagnosis and comparison require recording seeds, units and protocols.