Hierarchical VAEs and discrete latents: NVAE, VQ-VAE and tokenizers
Explore two ways to enrich a single Gaussian latent: top-down hierarchical VAEs, which connect autoregression and diffusion, and discrete representations using Gumbel-softmax, VQ-VAE, codebook diagnostics, finite scalar quantization and two-stage generation.
After this lesson you can
- Write the ELBO of a top-down hierarchical VAE and explain information allocation across levels.
- Prove the Gumbel-max trick and implement temperature-controlled Gumbel-softmax relaxation.
- Implement vector quantization with straight-through, commitment loss, EMA and code resets.
- Diagnose codebook collapse with usage perplexity and compare it with FSQ.
- Train a two-stage pipeline: VQ-VAE plus a transformer prior over codes.
Before you start
Two ways to enrich the code
In the previous lesson one Gaussian vector had to describe the whole image. One alternative distributes uncertainty over several levels: the generator makes progressive decisions, and each level can depend on higher levels. Another converts representations into symbols from a finite vocabulary. In both cases, distinguish the probabilistic model from the tricks that enable training.
Proof
Expand . The reconstruction term is isolated. For each level, condition on : the expectation over of is the negative conditional KL. Finally average that KL over the higher latents. The equality is algebraic; Jensen provides .
∎Each KL measures additional information relative to its level’s conditional prior, not a predetermined semantic-information quota. To study allocation, hold higher variables fixed, resample descendants and compare outputs. When changing a higher variable, regenerate its descendants from the corresponding conditional: keeping them arbitrarily can create a combination outside the model distribution. In images, some models show global variations at higher levels and detail below; this is not a law for every architecture or training run.
Ladder VAE combines bottom-up data information with top-down generator predictions. NVAE and VDVAE study deep hierarchies. Stability matters: large initial KL can dominate the gradient and produce non-finite values. NVAE uses spectral regularization, a penalty related to spectral norms that differs from imposing exact spectral normalization at every update. Gradients can also be controlled and KL recorded by level. VDVAE analyzes how a sufficiently deep hierarchy can represent autoregressive models; that does not mean every trained hierarchy automatically learns that factorization.
Diffusion offers another connection: a fixed perturbation chain defines an inference distribution toward increasingly noisy levels; a learned reverse chain generates from noise. Its variational objective can be viewed as a sum of terms between conditional distributions, although particular models and parameterizations add simplifications. We revisit those assumptions in the forward diffusion process.
A category without differentiating argmax
Let sum to one. The Gumbel-max trick samples a categorical variable using an argmax of continuous variables.
Proof
Define , independent rate-one exponential variables. Maximizing is equivalent to minimizing , which is exponentially distributed with rate . The probability that is smallest is . Ties have probability zero.
∎A relaxed sample allows differentiation with respect to logits while keeping noise fixed, but optimizes a function of a continuous variable: its gradient is generally biased relative to the discrete categorical objective. As decreases, the sample approaches a one-hot vector and gradients can become highly variable. One sample does not quantify that variance: repeat independent noise draws and state the objective and parameter. Jang, Gu and Poole describe the relaxation and its annealing.
Turning vectors into indices
Nearest-neighbor selection is constant within regions and provides no useful gradient across boundaries. The straight-through estimator uses the quantized vector in the forward pass and copies a surrogate gradient to the encoder in the backward pass. In PyTorch, z_e + (z_q - z_e).detach() has value and identity derivative with respect to . This biased estimator is not the ordinary derivative of quantization.
A common loss adds reconstruction, to move codes and to commit the encoder; preserves the value and stops the gradient. The first does not move the encoder and the second does not move the codebook. Another implementation updates codes as ratios of exponentially smoothed sums and counts: do not also apply the codebook loss as an independent update without specifying the objective. These ideas and a learned prior appear in van den Oord, Vinyals and Kavukcuoglu.
For an explicit EMA update, let be the number of vectors assigned to code in a batch and their sum. With , update and ; then take with protection for small denominators. Protection and initialization especially affect unvisited codes. If resetting one with a batch vector, also update its sum and count: changing only the vector leaves EMA state inconsistent and the next update could undo the reset.
Perplexity describes marginal usage over the selected set and window. Alone it does not measure reconstruction, conditional entropy, perceptual quality or effective prior capacity. Resetting an infrequently used code near current data can give it opportunities, but threshold and window change what counts as dead. Compare seeds, per-code frequencies and distortion before and after.
Quantizing each coordinate
An even number of levels requires care with offsets and endpoints: a symmetric function followed by naive rounding does not guarantee exactly eight values. The FSQ paper uses a parity-aware bounding scheme. No learned codebook vectors can become stale, but this does not guarantee that data use all 200 combinations. Measure the joint histogram and reconstruction; possible and observed combinations are different quantities.
Generating in two stages
Two-stage generation first learns a discrete encoder and decoder, then encodes the dataset and trains a prior over indices. If an image produces ordered indices, a causal prior factorizes . During generation each index is sampled only from previous ones and the decoder transforms the completed grid into an image.
During training the transformer input is shifted one position: a start symbol precedes and labels are . The causal mask prevents position from consulting later inputs. Cross-entropy in nats per index measures the prior over fixed-tokenizer codes. It is not automatically a likelihood of the original image: a lossy representation can assign the same sequence to different images and requires an observation model to evaluate pixel probabilities.
With a deterministic posterior and uniform prior over codes, one index’s KL is , constant with respect to the encoder. This observation does not train a good prior: a uniform distribution can place mass on rare index sequences. The second stage learns sequence distribution, so evaluate tokenizer reconstruction and sample quality and diversity. VQ-VAE-2 uses hierarchical discrete representations and priors to generate images. Visual tokenizers connect to causal transformers and multimodal models.
Lab: quantization and usage
First calculate neighbors, counts and an EMA update without a machine-learning library. Two clusters use a fixed seed; they are an explicit demonstration model, not measurements on images. The update accumulates sums and counts with the same factor; resetting replaces low-use codes with current examples. Compare distortion and perplexity, since increased usage does not ensure lower error.
import numpy as np
rng = np.random.default_rng(71)
x = np.concatenate([rng.normal((-2, 0), 0.35, (160, 2)),
rng.normal((2, 0), 0.35, (160, 2))])
initial = rng.normal((4, 4), 0.2, (16, 2))
def assignments(x, codes):
distances = ((x[:, None, :] - codes[None, :, :]) ** 2).sum(axis=2)
return np.argmin(distances, axis=1)
def perplexity(index, k):
count = np.bincount(index, minlength=k)
p = count[count > 0] / count.sum()
return np.exp(-(p * np.log(p)).sum())
def fit(restart):
local_rng = np.random.default_rng(72)
codes = initial.copy()
count = np.ones(len(codes)) * 0.01
sums = codes * count[:, None]
for step in range(60):
batch = x[local_rng.choice(len(x), 64, replace=False)]
index = assignments(batch, codes)
counts = np.bincount(index, minlength=len(codes))
batch_sums = np.zeros_like(codes)
np.add.at(batch_sums, index, batch)
count = 0.9 * count + 0.1 * counts
sums = 0.9 * sums + 0.1 * batch_sums
codes = sums / np.maximum(count[:, None], 1e-8)
if restart and step % 10 == 9:
dead = np.flatnonzero(count < 0.05)
for j in dead:
codes[j] = batch[local_rng.integers(len(batch))]
count[j] = 1.0
sums[j] = codes[j]
index = assignments(x, codes)
distortion = np.mean(np.sum((x - codes[index]) ** 2, axis=1))
return perplexity(index, len(codes)), distortion
for restart in (False, True):
p, d = fit(restart)
print('Reinicio:', restart, '| perplejidad:', round(p, 3), '| distorsión:', round(d, 4))The straight-through forward pass is identical to quantization. Its derivative cannot be represented as the exact derivative of argmin in NumPy: it is a chosen backpropagation rule. To check it manually, the next cell freezes and constructs a local surrogate whose value at is the quantized value and whose derivative is identity. Finite differences check reconstruction gradients of that surrogate and, separately, commitment gradients. They do not compare against the derivative of true quantization, which differs.
z0 = np.array([[0.2, 0.3], [0.7, -0.4]])
book = np.array([[0., 0.], [1., 0.]])
target = np.array([[0.3, -0.1], [0.9, 0.2]])
q = book[assignments(z0, book)].copy()
gamma = 0.25
n = len(z0)
def surrogate_reconstruction(z):
output = q + (z - z0) # El residuo q - z0 está congelado.
return 0.5 * np.sum((output - target)**2) / n
def commitment_loss(z):
return gamma * np.sum((z - q)**2) / n # q se trata como constante.
def finite_gradient(function, z):
result = np.zeros_like(z)
for index in np.ndindex(z.shape):
plus, minus = z.copy(), z.copy()
plus[index] += 1e-6
minus[index] -= 1e-6
result[index] = (function(plus) - function(minus)) / 2e-6
return result
grad_reconstruction = (q - target) / n
grad_commitment = 2 * gamma * (z0 - q) / n
assert np.allclose(finite_gradient(surrogate_reconstruction, z0), grad_reconstruction)
assert np.allclose(finite_gradient(commitment_loss, z0), grad_commitment)
print('Índices:', assignments(z0, book))
print('Gradiente sustituto de reconstrucción:', grad_reconstruction)
print('Gradiente de compromiso:', grad_commitment)The PyTorch lab implements this rule with detach; the preceding numerical comparison checks the surrogate rule and does not prove the estimator unbiased.
Local lab: VQ-VAE and causal prior
First train a VQ-VAE on grayscale Fashion-MNIST: two spatial reductions turn 28×28 pixels into a 7×7 code grid. Then freeze the quantizer, transform official training and test splits separately, and fit a causal transformer to 49 raster-order positions. The prior sees a start token and previous codes, never the code it predicts. A perturbation test checks this property. Finally generate 49 indices one by one and decode them.
The code reports mean squared reconstruction error per pixel, perplexity and codes used on test. The prior reports cross-entropy in nats per test code. None is the bpd of lesson 3’s PixelCNN: VQ-VAE is lossy compression and the prior assigns probability to codes, not the 784 original intensities. Run that lesson to compare samples visually: its PixelCNN is class-conditioned and this prior is unconditional, so visual differences cannot be attributed to architecture alone. Comparing image probabilities would require a complete probabilistic decoder model and common evaluation. The quick test does not estimate quality of fully trained models.
By default the lab uses all images and 12 epochs per stage. Set ORYON_QUICK=1 to check the workflow: 256 training images, 64 test images, one epoch per stage and a smaller network. If set, ORYON_FASHION_ROOT points to the directory containing FashionMNIST; otherwise it uses ORYON_DATA_ROOT or ./data. PyTorch and torchvision are required. Images and table are generated during this run.
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, TensorDataset
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')))
torch.manual_seed(19)
np.random.seed(19)
torch.set_num_threads(1)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
K, D = 128, 32
batch_size = 32 if quick else 128
epochs_vq = 1 if quick else 12
epochs_prior = 1 if quick else 12
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(64)) if quick else test_all
train_loader = DataLoader(train, batch_size=batch_size, shuffle=True, num_workers=0)
train_ordered = DataLoader(train, batch_size=batch_size, shuffle=False, num_workers=0)
test_loader = DataLoader(test, batch_size=batch_size, shuffle=False, num_workers=0)
class VQVAE(nn.Module):
def __init__(self):
super().__init__()
width = 32 if quick else 64
self.encoder = nn.Sequential(
nn.Conv2d(1, width, 4, stride=2, padding=1), nn.ReLU(),
nn.Conv2d(width, width, 4, stride=2, padding=1), nn.ReLU(),
nn.Conv2d(width, D, 3, padding=1))
self.codebook = nn.Embedding(K, D)
nn.init.uniform_(self.codebook.weight, -1 / K, 1 / K)
self.decoder = nn.Sequential(
nn.Conv2d(D, width, 3, padding=1), nn.ReLU(),
nn.ConvTranspose2d(width, width, 4, stride=2, padding=1), nn.ReLU(),
nn.ConvTranspose2d(width, 1, 4, stride=2, padding=1), nn.Sigmoid())
def encode(self, x):
z = self.encoder(x).permute(0, 2, 3, 1).contiguous()
flat = z.reshape(-1, D)
e = self.codebook.weight
distances = flat.square().sum(1, keepdim=True) + e.square().sum(1) - 2 * flat @ e.T
index = distances.argmin(dim=1).reshape(x.size(0), 7, 7)
quantized = self.codebook(index)
return z, quantized, index
def forward(self, x):
z, q, index = self.encode(x)
# El decoder ve q; su gradiente se copia al encoder, no al codebook.
straight_through = z + (q - z).detach()
reconstruction = self.decoder(straight_through.permute(0, 3, 1, 2))
codebook_loss = F.mse_loss(q, z.detach())
commitment_loss = F.mse_loss(z, q.detach())
return reconstruction, codebook_loss, commitment_loss, index
def decode_indices(self, index):
q = self.codebook(index.reshape(-1, 7, 7)).permute(0, 3, 1, 2)
return self.decoder(q)
vq = VQVAE().to(device)
optimizer = torch.optim.Adam(vq.parameters(), lr=2e-3)
for epoch in range(epochs_vq):
vq.train()
total = 0.0
for x, _ in train_loader:
x = x.to(device)
reconstruction, codebook_loss, commitment, _ = vq(x)
loss = F.mse_loss(reconstruction, x) + codebook_loss + 0.25 * commitment
optimizer.zero_grad(set_to_none=True)
loss.backward()
optimizer.step()
total += loss.item() * x.size(0)
print('VQ época', epoch + 1, 'pérdida media', round(total / len(train), 5))
@torch.no_grad()
def extract(loader):
vq.eval()
codes, counts = [], torch.zeros(K, dtype=torch.long)
squared, pixels = 0.0, 0
for x, _ in loader:
x = x.to(device)
reconstruction, _, _, indices = vq(x)
squared += (reconstruction - x).square().sum().item()
pixels += x.numel()
cpu_indices = indices.reshape(x.size(0), 49).cpu()
codes.append(cpu_indices)
counts += torch.bincount(cpu_indices.reshape(-1), minlength=K)
probability = counts.float() / counts.sum()
positive = probability[probability > 0]
perplexity = torch.exp(-(positive * positive.log()).sum()).item()
return torch.cat(codes), squared / pixels, perplexity, (counts > 0).sum().item()
train_codes, train_mse, train_ppl, train_used = extract(train_ordered)
test_codes, test_mse, test_ppl, test_used = extract(test_loader)
print('Train/test MSE por píxel:', round(train_mse, 5), round(test_mse, 5))
print('Train/test perplejidad y códigos usados:',
round(train_ppl, 2), train_used, '/', K, '|', round(test_ppl, 2), test_used, '/', K)
class CausalPrior(nn.Module):
def __init__(self):
super().__init__()
width = 64 if quick else 128
layer = nn.TransformerEncoderLayer(width, 4, 4 * width, dropout=0.1,
batch_first=True, norm_first=True)
self.tokens = nn.Embedding(K + 1, width) # índice K: inicio de secuencia
self.positions = nn.Embedding(49, width)
self.network = nn.TransformerEncoder(layer, 1 if quick else 4, enable_nested_tensor=False)
self.head = nn.Linear(width, K)
def forward(self, prefix):
length = prefix.size(1)
positions = torch.arange(length, device=prefix.device)
x = self.tokens(prefix) + self.positions(positions)[None]
future = torch.triu(torch.ones(length, length, dtype=torch.bool, device=prefix.device), diagonal=1)
return self.head(self.network(x, mask=future))
def shifted(codes):
return torch.cat([torch.full_like(codes[:, :1], K), codes[:, :-1]], dim=1)
prior = CausalPrior().to(device)
prior.eval()
with torch.no_grad():
example = test_codes[:2].to(device)
changed = example.clone()
changed[:, 20:] = (changed[:, 20:] + 1) % K
before = prior(shifted(example))[:, :21]
after = prior(shifted(changed))[:, :21]
assert torch.allclose(before, after, atol=1e-6), 'La máscara deja ver el futuro'
print('Prueba de causalidad: superada')
code_train = DataLoader(TensorDataset(train_codes), batch_size=batch_size, shuffle=True)
code_test = DataLoader(TensorDataset(test_codes), batch_size=batch_size, shuffle=False)
optimizer_prior = torch.optim.AdamW(prior.parameters(), lr=3e-4)
for epoch in range(epochs_prior):
prior.train()
total, count = 0.0, 0
for (codes,) in code_train:
codes = codes.to(device)
logits = prior(shifted(codes))
loss = F.cross_entropy(logits.reshape(-1, K), codes.reshape(-1))
optimizer_prior.zero_grad(set_to_none=True)
loss.backward()
nn.utils.clip_grad_norm_(prior.parameters(), 1.0)
optimizer_prior.step()
total += loss.item() * codes.numel()
count += codes.numel()
print('Prior época', epoch + 1, 'nats/código train', round(total / count, 4))
prior.eval()
vq.eval()
with torch.no_grad():
total, count = 0.0, 0
for (codes,) in code_test:
codes = codes.to(device)
logits = prior(shifted(codes))
total += F.cross_entropy(logits.reshape(-1, K), codes.reshape(-1), reduction='sum').item()
count += codes.numel()
print('Prior test: nats/código', round(total / count, 4))
original = next(iter(test_loader))[0][:4].to(device)
reconstruction, _, _, _ = vq(original)
prefix = torch.full((4, 1), K, dtype=torch.long, device=device)
for _ in range(49):
logits = prior(prefix)[:, -1, :]
token = torch.multinomial(logits.softmax(-1), 1)
prefix = torch.cat((prefix, token), dim=1)
generated = vq.decode_indices(prefix[:, 1:])
fig, axes = plt.subplots(3, 4, figsize=(8, 6))
for row, batch in enumerate((original, reconstruction, generated)):
for col, image in enumerate(batch.cpu()):
axes[row, col].imshow(image[0], cmap='gray', vmin=0, vmax=1)
axes[row, col].axis('off')
axes[row, 0].set_title(('Test', 'Reconstrucción', 'Muestra del prior')[row])
plt.tight_layout()
plt.show()
plt.close(fig)
del x, reconstruction, codebook_loss, commitment, loss, codes, logits
del original, generated, prefix, before, after, example, changed, batch
del vq, prior, optimizer, optimizer_prior
if torch.cuda.is_available():
torch.cuda.empty_cache()npm run lab and open the connection link.Exercises
Step 1 of 3. If U is uniform on (0, 1), what distribution does E = −log U have?
import numpy as np
def ema_step(x, codes, counts, sums, decay=0.9, threshold=0.0, eps=1e-8):
passimport torch
from torch import nn
class VectorQuantizerEMA(nn.Module):
def __init__(self, K, D, decay=0.9, commitment=0.25, dead_threshold=0.0):
super().__init__()
pass
def forward(self, z):
pass
def perplexity(indices, K):
passHierarchy distributes decisions among conditional levels; quantization creates a vocabulary of indices. Straight-through changes the gradient rule, while a learned prior models which sequences of those indices are plausible.