Course contents 08 / 34

08 / 34 · Variational Autoencoders

VAE variants: β-VAE and VQ-VAE

Two changes to a VAE: a weight on the KL term that sets how much the code may carry (β-VAE), and a discrete code from a learned codebook whose prior is fitted afterwards (VQ-VAE and VQ-VAE-2).

On this page 5

A VAE trained on faces gives blurry reconstructions, and its prior samples are worse than its reconstructions, because the codes fill the prior only roughly. Both complaints come from the two terms of its objective:

L(x)=Eqφ(z∣x)[log⁡pθ(x∣z)]−DKL(qφ(z∣x) ∥ p(z)).\begin{aligned} \mathcal L(x) ={}& \mathbb E_{q_\varphi(z \mid x)}\big[\log p_\theta(x \mid z)\big] \\ &- D_{\mathrm{KL}}\big(q_\varphi(z \mid x) \,\|\, p(z)\big) . \end{aligned}

The first term wants the code to say as much about the image xx as possible; the second charges for every nat it says. We can change the balance between them, which is the β-VAE. Or we can change what a code is, a grid of symbols from a learned codebook instead of a Gaussian vector, and fit the prior afterwards with a model strong enough to match the codes, which is the VQ-VAE.

β-VAE: a weight on the KL term#

The β-VAE (Higgins et al., 2017) maximizes

Lβ(x)=Eqφ(z∣x)[log⁡pθ(x∣z)]−β DKL(qφ(z∣x) ∥ p(z)).\begin{aligned} \mathcal L_\beta(x) ={}& \mathbb E_{q_\varphi(z \mid x)}\big[\log p_\theta(x \mid z)\big] \\ &- \beta\, D_{\mathrm{KL}}\big(q_\varphi(z \mid x) \,\|\, p(z)\big) . \end{aligned}

β=1\beta = 1 is the plain VAE. For β>1\beta > 1 the objective is still a lower bound on log⁡pθ(x)\log p_\theta(x), since it subtracts more of a non-negative quantity; for β<1\beta < 1 it can exceed log⁡pθ(x)\log p_\theta(x) and bounds nothing. Either way β\beta changes which model training prefers, not just the scale of the loss. A Gaussian decoder with fixed variance s2s^2 already hides such a weight: with squared error as the loss, the effective β\beta is 2s22s^2.

Rate and distortion#

Averaged over the data, the two terms have names from information theory (Alemi et al., 2018). The rate is the average KL,

R=Ex DKL(qφ(z∣x) ∥ p(z)),R = \mathbb E_{x}\, D_{\mathrm{KL}}\big(q_\varphi(z \mid x) \,\|\, p(z)\big),

in nats. It is the mutual information between images and codes plus the KL from the aggregate posterior to the prior, so it bounds the mutual information from above. The distortion is the average reconstruction loss:

D=−Ex Eqφ(z∣x)log⁡pθ(x∣z).D = -\mathbb E_x\, \mathbb E_{q_\varphi(z \mid x)} \log p_\theta(x \mid z) .

The negative ELBO is D+RD + R, and the β-VAE minimizes D+βRD + \beta R: the Lagrangian of “reconstruct as well as possible with at most a given rate”. Every β\beta picks one point of the trade-off. Since R≥0R \ge 0, −(D+βR)≤−(D+R)-(D + \beta R) \le -(D + R) for β≥1\beta \ge 1, so among the weights that still give a bound, β=1\beta = 1 gives the tightest.

Worked example: one latent dimension#

Take one latent dimension, the prior N(0,1)\mathcal N(0, 1) and a fixed linear decoder p(x∣z)=N(wz,σ2)p(x \mid z) = \mathcal N(wz, \sigma^2) with w=1w = 1 and σ2=0.1\sigma^2 = 0.1. Let the data come from this very model, x∼N(0,w2+σ2)=N(0,1.1)x \sim \mathcal N(0, w^2 + \sigma^2) = \mathcal N(0, 1.1). Holding the decoder fixed isolates what β\beta does to the encoder q(z∣x)=N(m,v)q(z \mid x) = \mathcal N(m, v). Using Eq(x−wz)2=(x−wm)2+w2v\mathbb E_q (x - wz)^2 = (x - wm)^2 + w^2 v and the closed-form KL, the objective for one xx is, up to constants,

J(m,v)=−(x−wm)2+w2v2σ2−β2(v+m2−1−ln⁡v).\begin{aligned} J(m, v) ={}& -\frac{(x - w m)^2 + w^2 v}{2\sigma^2} \\ &- \frac{\beta}{2}\big(v + m^2 - 1 - \ln v\big) . \end{aligned}

We set both derivatives to zero:

∂J∂v=−w22σ2−β2+β2v=0,∂J∂m=w(x−wm)σ2−βm=0.\begin{aligned} \frac{\partial J}{\partial v} &= -\frac{w^2}{2\sigma^2} - \frac{\beta}{2} + \frac{\beta}{2v} = 0, \\ \frac{\partial J}{\partial m} &= \frac{w(x - wm)}{\sigma^2} - \beta m = 0 . \end{aligned}

They give the optimal encoder:

m=ww2+βσ2 x,v=βσ2w2+βσ2.\begin{aligned} m &= \frac{w}{w^2 + \beta\sigma^2}\, x, \\ v &= \frac{\beta\sigma^2}{w^2 + \beta\sigma^2} . \end{aligned}

At β=1\beta = 1 these are wx/(w2+σ2)wx/(w^2 + \sigma^2) and σ2/(w2+σ2)\sigma^2/(w^2 + \sigma^2), the mean and variance of the exact posterior by the conditional formula, so the bound is tight. Write a=m/xa = m/x, the same for every xx. With w=1w = 1, m=axm = ax has E m2=1.1 a2\mathbb E\, m^2 = 1.1\,a^2 and E(x−m)2=1.1 (1−a)2\mathbb E(x - m)^2 = 1.1\,(1 - a)^2 over x∼N(0,1.1)x \sim \mathcal N(0, 1.1). Averaging the closed-form KL and the expected squared error above gives

R=12(v+1.1 a2−1−ln⁡v),E(x−wz)2=1.1 (1−a)2+v.\begin{aligned} R &= \tfrac12\big(v + 1.1\,a^2 - 1 - \ln v\big), \\ \mathbb E(x - wz)^2 &= 1.1\,(1 - a)^2 + v . \end{aligned}

The table measures distortion by this squared error, which is 2σ2D2\sigma^2 D up to an additive constant. At β=1\beta = 1, a=10/11a = 10/11 and v=1/11v = 1/11, so R=12ln⁡11=1.20R = \tfrac12 \ln 11 = 1.20 and the squared error is 0.009+0.091=0.1000.009 + 0.091 = 0.100:

β\betam/xm / xvvrate RR (nats)distortion
0.250.9760.0241.890.025
10.9090.0911.200.100
40.7140.2860.550.376
160.3850.6150.131.032

Raising β\beta pulls the mean toward 0 and the variance toward 1, so the code says less and the reconstruction gets worse. At β=16\beta = 16 the distortion, 1.03, is close to the data variance 1.1: the code carries almost nothing. Lowering β\beta buys sharper reconstructions with a higher rate.

Figure

β moves a VAE along the rate–distortion curve

Rate–distortion curve of a β-VAEA decreasing curve: as β grows, the rate falls and the distortion rises. β = 0.25: R = 1.89, D = 0.03; β = 1: R = 1.20, D = 0.10; β = 4: R = 0.55, D = 0.38; β = 16: R = 0.13, D = 1.03.00.40.81.200.511.522.5rate R, natsdistortion E(x − wz)²β = 0.25R 1.89, D 0.03β = 1, plain VAER 1.20, D 0.10β = 4R 0.55, D 0.38β = 16R 0.13, D 1.03Rate–distortion curve of a β-VAEA decreasing curve: as β grows, the rate falls and the distortion rises. β = 0.25: R = 1.89, D = 0.03; β = 1: R = 1.20, D = 0.10; β = 4: R = 0.55, D = 0.38; β = 16: R = 0.13, D = 1.03.00.40.81.200.511.522.5rate R, natsdistortion E(x − wz)²β = 0.25β = 1β = 4β = 16
Rate (average KL to the prior, nats) against distortion (average squared error) for one latent dimension, a fixed decoder x | z ~ N(z, 0.1), data x ~ N(0, 1.1) and the optimal encoder for each β from 0.025 to 100. β = 1 gives the exact posterior and distortion 0.1; at β = 4 the rate halves and the error nearly quadruples.

A high rate does not mean a code far from the prior. Here the aggregate posterior is N(0,(m/x)2⋅1.1+v)\mathcal N\big(0, (m/x)^2 \cdot 1.1 + v\big). At β=0.25\beta = 0.25 its variance is 1.071 and its KL to the prior is 0.001 of the 1.89 nats, so almost all of the rate is information about xx. Prior samples suffer only when the aggregate posterior leaves the prior or the decoder is wrong where the prior puts mass. In this toy the decoder is fixed and exact, so prior samples stay exact for every β\beta; in a jointly trained VAE a small β\beta also weakens the penalty on the mismatch, and samples can get worse.

What β buys and what it does not#

Higgins et al. (2017) report that β>1\beta > 1 makes single latent coordinates track single factors of variation, such as the position, scale and rotation of a sprite. They call this disentanglement: a latent unit is sensitive to one generative factor and relatively invariant to the others. On CelebA with β=250\beta = 250, single units turn the head, change the smile or the hair while the rest of the face stays; in a plain VAE the unit that turns the head also changes the expression and other attributes (their Figure 1).

The proposed mechanism is the pressure to spend little rate: a factorized prior is cheapest to match with a posterior whose coordinates are independent. The effect is not guaranteed. Locatello et al. (2019) prove that without supervision or inductive biases disentanglement cannot be identified from data, and in more than 12,000 trained models find that random seeds and hyperparameters matter more than the choice among disentangling objectives. Burgess et al. (2018) replace the fixed weight by a target rate CC that grows during training, maximizing Eqlog⁡pθ(x∣z)−γ ∣DKL−C∣\mathbb E_q \log p_\theta(x \mid z) - \gamma\,\lvert D_{\mathrm{KL}} - C \rvert, so that the code is allowed one more nat at a time. What β\beta reliably controls is the rate.

VQ-VAE: a discrete latent code#

Start from k-means. Its encoder maps a point to the one-hot index of the nearest centre, and its decoder maps the index back to that centre: an autoencoder with a discrete code. Sampling an index uniformly and decoding it is a valid generative model, but a poor one, since it can only produce KK centres (He, 2024, lecture 2).

The VQ-VAE (van den Oord, Vinyals and Kavukcuoglu, 2017) makes this deep and spatial. The encoder outputs a map of vectors ze(x)z_e(x) of shape h×w×dh \times w \times d, and each vector ze(x)iz_e(x)_i at position ii is replaced by the nearest of KK learned codebook vectors e1,…,eK∈Rde_1, \dots, e_K \in \mathbb R^d before it reaches the decoder:

k∗(i)=arg⁡min⁡k∥ze(x)i−ek∥2,zq(x)i=ek∗(i).\begin{aligned} k^*(i) &= \arg\min_k \big\lVert z_e(x)_i - e_k \big\rVert^2, \\ z_q(x)_i &= e_{k^*(i)} . \end{aligned}

The code of an image is the grid of indices k∗(i)k^*(i): for the 32×3232 \times 32 images below, 64 integers between 1 and 512 at the bottom level.

Figure

Vector quantization: the nearest codebook vector

Codebook cells in the planeA square split into three cells by the lines x = 1, y = 1 and y = x. Each cell holds its codebook vector and a few encoder outputs. The output (1.4, 0.3) is joined by a dashed line to its nearest vector e₂ = (2, 0).e₁e₃encoder output zezq = e₂each encoder output is replacedby the nearest codebook vector:the plane splits into Voronoi cells‖ze − e₂‖² = 0.45, the smallest‖ze − e₁‖² = 2.05‖ze − e₃‖² = 4.85Codebook cells in the planeA square split into three cells by the lines x = 1, y = 1 and y = x. Each cell holds its codebook vector and a few encoder outputs. The output (1.4, 0.3) is joined by a dashed line to its nearest vector e₂ = (2, 0).e₁e₃encoder output zezq = e₂each encoder output is replacedby the nearest codebook vector:the plane splits into Voronoi cells‖ze − e₂‖² = 0.45, the smallest‖ze − e₁‖² = 2.05‖ze − e₃‖² = 4.85
The codebook e₁ = (0, 0), e₂ = (2, 0), e₃ = (0, 2) splits the plane into three cells; dots are encoder outputs coloured by cell. The red output (1.4, 0.3) is closest to e₂, which the decoder receives. The commitment term pulls the output toward e₂; the codebook update moves e₂ toward its cell’s mean.

What happens to the KL term? With a categorical posterior q(c∣x)q(c \mid x) over KK codes and a uniform prior,

DKL(q(c∣x) ∥ Uniform)=log⁡K−H(q(c∣x)).D_{\mathrm{KL}}\big(q(c \mid x) \,\|\, \mathrm{Uniform}\big) = \log K - H\big(q(c \mid x)\big) .

The identity is one line: ∑cqlog⁡(q/(1/K))=log⁡K+∑cqlog⁡q\sum_c q \log\big(q/(1/K)\big) = \log K + \sum_c q \log q. The VQ-VAE’s posterior is one-hot at k∗k^*, so its entropy is zero and the KL is log⁡K\log K per position, a constant (Isachenko, 2025, lecture 4). The KL term drops out, and the VQ-VAE trains as an autoencoder with a quantized bottleneck.

Training through the argmin#

The argmin has no useful gradient: a small change of zez_e either keeps the same eke_k or jumps to another. The VQ-VAE uses the straight-through estimator (Bengio, Léonard and Courville, 2013): the forward pass feeds zqz_q to the decoder, and the backward pass copies the gradient with respect to zqz_q to zez_e unchanged. In code it is one line, z_q = z_e + (z_q - z_e).detach(), whose value is zqz_q and whose derivative is that of zez_e.

The copy is a surrogate. Inside a cell the quantizer is constant, so its true Jacobian is zero, and on a cell boundary it jumps; straight-through replaces that Jacobian by the identity. The decoder’s gradient, evaluated at ek∗e_{k^*}, is a reasonable guess for the direction in which to move zez_e only when zez_e is close to ek∗e_{k^*}. Two extra terms keep it close. With sg[⋅]\mathrm{sg}[\cdot] the stop-gradient, which passes its argument forward and has zero derivative, and e=ek∗e = e_{k^*}, the loss summed over positions is

L=−log⁡pθ(x∣zq(x))+∥sg[ze(x)]−e∥2+βc∥ze(x)−sg[e]∥2.\begin{aligned} \mathcal L ={}& -\log p_\theta\big(x \mid z_q(x)\big) \\ &+ \big\lVert \mathrm{sg}[z_e(x)] - e \big\rVert^2 \\ &+ \beta_c \big\lVert z_e(x) - \mathrm{sg}[e] \big\rVert^2 . \end{aligned}

The reconstruction term trains the decoder and, through the copy, the encoder. The codebook term moves ee toward the encoder output and does not touch the encoder. The commitment term moves the encoder output toward ee and does not touch the codebook; without it the encoder outputs can drift away faster than the codebook follows. The paper uses βc=0.25\beta_c = 0.25 and reports that results are robust to it.

Worked example: one quantization step#

Take d=2d = 2, K=3K = 3, the codebook e1=(0,0)e_1 = (0, 0), e2=(2,0)e_2 = (2, 0), e3=(0,2)e_3 = (0, 2) and one encoder output ze=(1.4,0.3)z_e = (1.4, 0.3), the red point of the figure. The squared distances are

∥ze−e1∥2=1.96+0.09=2.05,∥ze−e2∥2=0.36+0.09=0.45,∥ze−e3∥2=1.96+2.89=4.85.\begin{aligned} \lVert z_e - e_1\rVert^2 &= 1.96 + 0.09 = 2.05, \\ \lVert z_e - e_2\rVert^2 &= 0.36 + 0.09 = 0.45, \\ \lVert z_e - e_3\rVert^2 &= 1.96 + 2.89 = 4.85 . \end{aligned}

The nearest vector is e2e_2, so the decoder receives zq=(2,0)z_q = (2, 0) and the code is the index 2. The codebook term is 0.450.45 and the commitment term 0.25⋅0.45=0.11250.25 \cdot 0.45 = 0.1125: the same distance, with gradients sent to different places. If the decoder’s loss has gradient gg with respect to zqz_q, the encoder receives gg at zez_e plus the commitment gradient

2βc(ze−e2)=0.5⋅(−0.6,0.3)=(−0.3,0.15),2\beta_c(z_e - e_2) = 0.5 \cdot (-0.6, 0.3) = (-0.3, 0.15),

which points from e2e_2 toward zez_e, so a descent step moves zez_e toward e2e_2.

The codebook as online k-means#

The codebook term moves each eke_k toward the encoder outputs assigned to it: the update of k-means. The appendix of the VQ-VAE paper replaces it by exponential moving averages. Each code keeps a count NkN_k and a sum mkm_k, updated with the nkn_k outputs assigned to it in the batch:

Nk←γNk+(1−γ) nk,mk←γ mk+(1−γ)∑i: k∗(i)=kze(x)i,ek=mk/Nk,\begin{aligned} N_k &\leftarrow \gamma N_k + (1 - \gamma)\, n_k, \\ m_k &\leftarrow \gamma\, m_k + (1 - \gamma) \sum_{i:\, k^*(i) = k} z_e(x)_i, \\ e_k &= m_k / N_k , \end{aligned}

with γ=0.99\gamma = 0.99, and the codebook term leaves the loss. Each eke_k is then a running mean of its cell, the k-means centroid computed online. With N2=10N_2 = 10 and m2=(20,0)m_2 = (20, 0), so that e2=(2,0)e_2 = (2, 0), and a batch of two outputs (1.4,0.3)(1.4, 0.3) and (1.8,−0.1)(1.8, -0.1) assigned to it, the update gives N2=9.92N_2 = 9.92, m2=(19.832,0.002)m_2 = (19.832, 0.002) and e2=(1.9992,0.0002)e_2 = (1.9992, 0.0002): a small step toward the batch mean (1.6,0.1)(1.6, 0.1).

Where the prior went#

During training the prior is uniform, and sampling the indices independently and uniformly would give an image of random patches. The positions of a code grid are not independent, so the prior must model their joint distribution (He, 2024, lecture 2). The VQ-VAE fits it after the autoencoder: encode the training set into grids of indices and train an autoregressive model on them, a PixelCNN in the paper, which predicts each index from the ones before it. Generation samples a grid from this prior and decodes it.

The split divides the work. The autoencoder handles the pixels, and the prior models a grid that is tens of times smaller and made of symbols, where autoregressive models are strong (autoregressive models). The same grids, now called image tokens, are what transformer and diffusion priors model later in the course.

VQ-VAE-2: two levels of codes#

A single grid has to carry both the global layout and the fine texture. VQ-VAE-2 (Razavi, van den Oord and Vinyals, 2019) uses a coarse top grid for the layout and a finer bottom grid for detail, quantized after seeing the top. For ImageNet at 256×256256 \times 256 the grids are 32×3232 \times 32 and 64×6464 \times 64 with 512 codes each; FFHQ at 1024×10241024 \times 1024 uses three levels. The prior is hierarchical too: an autoregressive model over the top codes, with self-attention, and a conditional one over the bottom codes given the top.

Figure

A small VQ-VAE-2: two code maps

Training and generation in a two-level VQ-VAETraining: a 32×32 image goes through the bottom encoder to an 8×8 map, the top encoder compresses it to 4×4, the top map is quantized, decoded back to 8×8, combined with the bottom features and quantized as the bottom map; the decoder reconstructs the image from the upsampled top codes and the bottom codes. Generation: a PixelCNN samples 16 top codes, a conditional PixelCNN 64 bottom codes, and the decoder turns them into an image.image32×32×3bottom encoder÷4 → 8×8top encoder÷2 → 4×4quantize top4×4 codes of 512top decoder4×4 → 8×8quantize bottom8×8 codes of 512decodertop ↑ + bottomreconstruction32×32×3PixelCNN (top)16 codes, one by oneconditional PixelCNN64 bottom codesdecodera new imagetraininggenerationTraining and generation in a two-level VQ-VAETraining: a 32×32 image goes through the bottom encoder to an 8×8 map, the top encoder compresses it to 4×4, the top map is quantized, decoded back to 8×8, combined with the bottom features and quantized as the bottom map; the decoder reconstructs the image from the upsampled top codes and the bottom codes. Generation: a PixelCNN samples 16 top codes, a conditional PixelCNN 64 bottom codes, and the decoder turns them into an image.image32×32×3bottom encoder÷4 → 8×8top encoder÷2 → 4×4quantize top4×4 codes of 512top decoder4×4 → 8×8quantize bottom8×8 codes of 512decodertop ↑ + bottomreconstruction32×32×3PixelCNN (top)16 codes, one by oneconditional PixelCNN64 bottom codesdecodera new imagetraininggeneration
Top: training on 32×32 CIFAR-10. The 4×4 top map is quantized first; its decoded version and the bottom features give the 8×8 bottom map, and the decoder receives both. Bottom: generation, a PixelCNN for the top codes, then a conditional one for the bottom codes. Codebooks hold 512 vectors of dimension 64.

How much does the code compress? A small version for 32×3232 \times 32 CIFAR-10 images uses a 4×44 \times 4 top grid and an 8×88 \times 8 bottom grid with 512 codes each:

QuantityValue
image, 32⋅32⋅332 \cdot 32 \cdot 3 bytes24,576 bits
code, 16+6416 + 64 indices of log⁡2512=9\log_2 512 = 9 bits720 bits
ratioabout 34
sequential sampling steps, subpixels against codes3072 against 80
at 256×256256 \times 256: subpixels against 322+64232^2 + 64^2 codes196,608 against 5120

The prior samples 80 indices one after another instead of 3072 subpixels.

A third change to the VAE keeps the Gaussian code and replaces the pixel-wise likelihood pθ(x∣z)p_\theta(x \mid z) by the exact likelihood of a normalizing flow conditioned on zz, which can model dependencies between pixels for a given code. VAPNEV (Agrawal and Dukkipati, 2016) does this with a real NVP flow; it needs the flows of a later section and appears there as an application of flow architectures.

Where it breaks: dead codes#

A code that no encoder output selects gets no update and stays where it was initialized: a dead code. Under the codebook loss its term is absent from the sum; under the EMA, nk=0n_k = 0 multiplies both NkN_k and mkm_k by γ\gamma, which leaves ek=mk/Nke_k = m_k/N_k where it was. Its cell keeps taking no outputs, so it stays dead, and the effective codebook shrinks.

A toy run shows the size of the effect. The encoder outputs are four small blobs at (±0.3,±0.3)(\pm 0.3, \pm 0.3) with standard deviation 0.1, and the 64 codes start from N(0,I)\mathcal N(0, I), so most of them start far from every output. After 500 EMA steps:

import numpy as np

def run(restart, steps=500, K=64, B=256, gamma=0.99, seed=0):
    rng = np.random.default_rng(seed)
    blobs = lambda n: rng.normal(scale=0.1, size=(n, 2)) + rng.choice([-0.3, 0.3], size=(n, 2))
    e = rng.normal(size=(K, 2))                         # codebook drawn from N(0, I)
    N, m, last = np.ones(K), e.copy(), np.zeros(K)      # EMA counts, sums, last use
    for t in range(1, steps + 1):
        z = blobs(B)                                    # encoder outputs
        k = ((z[:, None] - e[None]) ** 2).sum(-1).argmin(1)
        n = np.bincount(k, minlength=K)
        s = np.zeros((K, 2)); np.add.at(s, k, z)
        N, m = gamma * N + (1 - gamma) * n, gamma * m + (1 - gamma) * s
        e = m / N[:, None]
        last[n > 0] = t
        if restart and t % 20 == 0:                     # restart codes unused for 20 steps
            dead = last < t - 20
            e[dead] = z[rng.choice(B, dead.sum())]
            N[dead], m[dead] = 1.0, e[dead]
    z = blobs(4096)
    k = ((z[:, None] - e[None]) ** 2).sum(-1).argmin(1)
    return np.unique(k).size, ((z - e[k]) ** 2).sum(1).mean()

for restart in (False, True):
    used, err = run(restart)
    print(f"restart={restart}: codes used {used} of 64, quantization error {err:.4f}")
# restart=False: codes used 25 of 64, quantization error 0.0056
# restart=True: codes used 64 of 64, quantization error 0.0024

Without restarts 39 of the 64 codes are dead, and the mean squared quantization error is more than twice what the full codebook achieves. Restarting unused codes at recent encoder outputs, as in Jukebox (Dhariwal et al., 2020), revives all of them. Looking codes up in a low-dimensional, normalized space, as in ViT-VQGAN (Yu et al., 2022), attacks the same problem from the other side. Implementations often add a small constant to the counts so that unused codes do not divide by zero; that keeps the arithmetic safe and revives nothing.

What changed#

VAEβ-VAEVQ-VAE / VQ-VAE-2
codecontinuous Gaussiancontinuous Gaussiangrid of indices into a codebook
objectiveELBOreconstruction − β · KLreconstruction + codebook + commitment
priorfixed N(0,I)\mathcal N(0, I)the same, weighted by β\betauniform in training, then a learned autoregressive model
gradient through the codereparameterizationreparameterizationstraight-through copy
typical troubleblur, holes in the priorthe trade-off itselfdead codes, slow sequential prior

The β-VAE moves along the VAE’s rate–distortion curve without leaving it. The VQ-VAE leaves it: it gives up the likelihood bound during training, and in exchange the prior becomes a separate model as strong as we can afford.

What you should remember#

  • β-VAE minimizes distortion + β · rate; β > 1 gives a lower rate and worse reconstructions, and disentanglement is not guaranteed.
  • Rate = mutual information + KL from the aggregate posterior to the prior; a high rate is mostly information.
  • VQ-VAE: nearest codebook vector, constant KL of log⁡K\log K per position, straight-through gradient, codebook and commitment terms.
  • The EMA codebook update is online k-means; dead codes need restarts.
  • The prior over code grids is learned afterwards by an autoregressive model; VQ-VAE-2 uses a coarse and a fine grid.

Notebook#

The VQ-VAE part follows the VQ-VAE-2 notebook of the HSE-LAMBDA Deep Generative Models repository. It has no saved outputs, so it documents the procedure only.

  • Quantizer: distances to all 512 codebook vectors through ∥a∥2−2a⊤e+∥e∥2\lVert a\rVert^2 - 2a^\top e + \lVert e\rVert^2, the EMA update with decay 0.99, the commitment distance and the straight-through line. The codebook is a buffer moved only by the EMA. Its counts start at 0 while its sums start at the random codebook, so after the first update an unselected code is divided by a smoothed count of about 10−510^{-5} and its norm grows about 10510^5 times. In our own toy run of this update, not a notebook output, only 2 or 3 of the 512 codes were selected between steps 2 and 1000; starting the counts at 1 avoids the jump.
  • Model: residual encoders that downsample CIFAR-10 by 4 to an 8×88 \times 8 bottom map and by 2 more to a 4×44 \times 4 top map, 64-dimensional codes, and a decoder that receives the upsampled top codes with the bottom codes. Training: MSE plus 0.250.25 times the commitment term, Adam at 3⋅10−43 \cdot 10^{-4}, batch 32, five epochs.
  • Priors: two PixelCNNs of seven 7×77 \times 7 masked layers without gating, an unconditional one for the top codes and a conditional one for the bottom codes. The condition is mixed into the input before the first type-A mask, so the mask also hides it at the position being predicted; we checked by differentiating a re-implementation. The condition should enter every layer unmasked, as in the conditional Gated PixelCNN. The plain stack also has the blind spot.
  • Sampling: 16 sequential steps for the top grid and 64 for the bottom grid, each rerunning the network on the whole grid. save_image(..., range=(-1, 1)) uses an argument that torchvision renamed to value_range.

The β-VAE has no trained example: the VAE notebook has a beta argument but trains only with β=1\beta = 1.

Next#

Two grids of samples, one from a β-VAE and one from a VQ-VAE, look different: one is smoother, the other sharper but sometimes broken. The VQ-VAE’s ELBO is not even comparable with the β-VAE’s. The next note starts the Evaluation section, which scores a generator by its samples alone.

References#