Module contents
Lesson 7 of 28Advanced 115 min

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 Eq[log⁡pθ(x,z1:L)−log⁡qϕ(z1:L∣x)]\E_q[\log p_\theta(x,z_{1:L})-\log q_\phi(z_{1:L}\mid x)]. The reconstruction term is isolated. For each level, condition on zℓ+1:Lz_{\ell+1:L}: the expectation over zℓz_\ell of log⁡pθ(zℓ∣zℓ+1:L)−log⁡qϕ(zℓ∣x,zℓ+1:L)\log p_\theta(z_\ell\mid z_{\ell+1:L})-\log q_\phi(z_\ell\mid x,z_{\ell+1:L}) is the negative conditional KL. Finally average that KL over the higher latents. The equality is algebraic; Jensen provides L(x)≤log⁡pθ(x)\mathcal L(x)\leq\log p_\theta(x).

∎

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.

InteractiveResampling latent levels

Within each row higher levels are shared; the chosen level is sampled eight times and lower levels take their conditional means, which can change with it. Level 20 is highest: its samples are independent. Rows and grids at different levels use different contexts, so they do not follow the same identity. These are published samples, not new generation when moving the control.

Source: Andrea Dittadi, Ladder VAE, CelebA 64×64. Images distributed under the repository’s MIT license. Observed differences describe this model and these samples, not a universal rule about identity and texture.

Resampled level
1
Chosen level6 / 20
Row1 / 8
Compare interventions on levels of the indicated model and observe output changes. Each level’s interpretation is empirical.

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 π1,…,πK>0\pi_1,\ldots,\pi_K>0 sum to one. The Gumbel-max trick samples a categorical variable using an argmax of continuous variables.

Proof

Define Ek=−log⁡UkE_k=-\log U_k, independent rate-one exponential variables. Maximizing log⁡πk−log⁡Ek\log\pi_k-\log E_k is equivalent to minimizing Tk=Ek/πkT_k=E_k/\pi_k, which is exponentially distributed with rate πk\pi_k. The probability that TiT_i is smallest is ∫0∞πie−πit∏j≠ie−πjt dt=πi/∑jπj=πi\int_0^\infty \pi_i e^{-\pi_i t}\prod_{j\ne i}e^{-\pi_jt}\,dt=\pi_i/\sum_j\pi_j=\pi_i. 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 τ\tau 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.

InteractiveCooling a Gumbel-softmax

Five categories with probabilities 0.40, 0.25, 0.15, 0.12 and 0.08. Each point is a relaxed sample; vertices represent pure categories.

12345

We project 200 of the 4096 samples as combinations of five vertices: the 2D projection is not unique. Each temperature reuses the same Gumbel noises (seed 2027). Sample variance uses all 4096 replicates and divisor N−1. For f(y) = y₁, differentiate with respect to the first logit: y₁(1−y₁)/τ. The mean estimates the relaxed objective gradient; the exact categorical value is π₁(1−π₁). Their difference includes relaxation bias and Monte Carlo error.

1.00
Change temperature and compare samples and gradient dispersion for the objective specified in the figure.

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 zqz_q and identity derivative with respect to zez_e. This biased estimator is not the ordinary derivative of quantization.

A common loss adds reconstruction, ∥sg⁡(ze)−ek∗∥2\|\operatorname{sg}(z_e)-e_{k^*}\|^2 to move codes and γ∥ze−sg⁡(ek∗)∥2\gamma\|z_e-\operatorname{sg}(e_{k^*})\|^2 to commit the encoder; sg⁡\operatorname{sg} 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 nkn_k be the number of vectors assigned to code kk in a batch and sks_k their sum. With 0≤ρ<10\leq\rho<1, update Nk←ρNk+(1−ρ)nkN_k\leftarrow\rho N_k+(1-\rho)n_k and Sk←ρSk+(1−ρ)skS_k\leftarrow\rho S_k+(1-\rho)s_k; then take ek=Sk/Nke_k=S_k/N_k 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.

InteractiveThe life and death of codes
  • Data
  • Used code
  • Code without assignments

There are 512 reproducible points: four isotropic Gaussians with deviation 0.45, centered at (±2, ±2), with equal sample counts. Four codes start near the clouds and twelve near x = 4.1 and y = 4.1. The cell assigns each point to its nearest code. Perplexity is exp(−Σ p log p), with p computed over all points; it measures usage balance, not reconstruction quality alone.

Each step uses all data. Gradient descends mean squared distance; EMA smooths counts and sums with factor 0.85. If reset is enabled, after eight steps without assignments a code moves to the worst-represented point. Data are fixed: this isolates quantization and does not train a neural encoder.

Codebook update
Step0
Codes used4 / 16
Usage perplexity4.00
Mean squared error0.428
Resets0
Change updating and resets, and observe codes and usage on the data from the described experiment.

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.

InteractiveThe FSQ grid
  • Code grid
  • Bounded continuous point
  • Chosen code
xyz

The figure shows continuous output after bounding each component with tanh, not unbounded input. Each component is then rounded and normalized by ⌊L/2⌋. For L = 8 possible integers are −4, …, 3; for L = 5 they are −2, …, 2. The first coordinate’s asymmetric offset ensures eight levels, not nine.

The index uses mixed radix: (c₁ + 4) + 8(c₂ + 2) + 40(c₃ + 2). All 200 codes are possible, but need not be used equally often when an encoder is trained. Ties round to the even integer, as in the paper’s implementation; the straight-through estimator applies during training and does not change this direct result.

1.20
-0.60
0.35
35°
Levels per axis8 × 5 × 5
Possible codes200
Integer code(3, -1, 1)
Index from 0 to 199135
Normalized code(0.75, −0.50, 0.50)
Explore how three continuous coordinates are bounded and converted into a discrete combination.

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 NN ordered indices, a causal prior factorizes p(k1:N)=∏i=1Np(ki∣k<i)p(k_{1:N})=\prod_{i=1}^{N}p(k_i\mid k_{<i}). 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 k1,…,kN−1k_1,\ldots,k_{N-1} and labels are k1,…,kNk_1,\ldots,k_N. The causal mask prevents position ii 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 KK codes, one index’s KL is log⁡K\log K, 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.

[ ]EMA and dead codesBrowser
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 qq and constructs a local surrogate whose value at z0z_0 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.

[ ]Surrogate gradient and commitmentBrowser
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.

[ ]VQ-VAE and transformer over codesLocal 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, 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()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

ProofAn exponential race
Prove: Prove that argmax of log π plus independent Gumbel noise produces a categorical variable with probabilities π.
0
Assume strictly positive π summing to one.

Step 1 of 3. If U is uniform on (0, 1), what distribution does E = −log U have?

NumericStoring indices
An image is represented by a 16×16 grid of indices from an 8192-entry vocabulary. How many bits are needed with fixed length, excluding metadata and compression?
CodeUpdating a codebook
Implement an EMA step for vectors x shaped (N, D), codes shaped (K, D), previous counts and sums. Return (new codes, new counts, new sums, indices). Assign each vector to its nearest neighbor; use decay to average counts and sums, divide with minimum eps, and reset codes whose updated count is below threshold using batch examples cyclically. On reset, set count to one and sum to the chosen example. Do not modify the arguments.
import numpy as np

def ema_step(x, codes, counts, sums, decay=0.9, threshold=0.0, eps=1e-8):
  pass
Shift+Enter to run
QuizUniform prior
What follows when a deterministic discrete encoder has constant KL relative to a uniform prior?
CodeStraight-through and EMA in PyTorch
Implement VectorQuantizerEMA(K, D, decay, commitment, dead_threshold). forward(z) receives (..., D) and returns (z_st, commitment, indices). Use nearest neighbor, straight-through to z, commitment without gradients into the codebook, and EMA sum and count buffers. During training reset codes with updated count below dead_threshold using batch examples; do not modify buffers during evaluation. Also implement perplexity(indices, K).
import 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):
  pass
Shift+Enter to run
QuizInterpreting an intervention
In a hierarchical image VAE, which conclusion about levels is defensible?
Key idea

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