Skip to content
BIASED

β-VAE and VQ-VAE

Two ways to change a VAE: a weight β on the KL term that decides how much the code may carry, and a discrete code from a codebook whose prior is learned afterwards.

Two knobs on the ELBO

The VAE leaves two complaints behind. Its samples are blurry, and its fixed Gaussian prior is only roughly filled by the codes the encoder actually produces, so a prior sample can land where the decoder was never trained. The topic The reparameterization trick also left a hint: a different fixed decoder variance reweights the KL term.

Start again from the ELBO of one image:

L(x)=Eqφ(z∣x)[log⁡pθ(x∣z)]⏟reconstruction−DKL(qφ(z∣x) ∥ p(z))⏟KL to the prior.\mathcal L(x) = \underbrace{\mathbb E_{q_\varphi(z \mid x)}\big[\log p_\theta(x \mid z)\big]}_{\text{reconstruction}} - \underbrace{D_{\mathrm{KL}}\big(q_\varphi(z \mid x)\,\|\,p(z)\big)}_{\text{KL to the prior}} .

The first term wants the code to say as much about xx as possible; the second charges for every nat it says. That leaves two independent knobs:

  • change the balance between the terms — the β-VAE;
  • change what a code is, a continuous Gaussian or one symbol out of KK — the VQ-VAE.

The first moves along a trade-off. The second changes where the difficulty of generation lives. Notation as before: an image xx, a code zz, an encoder qφ(z∣x)q_\varphi(z \mid x), a decoder pθ(x∣z)p_\theta(x \mid z), a prior p(z)p(z).

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)).\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).

With β=1\beta = 1 this is the plain VAE. Because the KL is non-negative, β>1\beta > 1 subtracts more than the ELBO does and keeps a lower bound on log⁡pθ(x)\log p_\theta(x), only a looser one. With β<1\beta < 1 the objective can exceed log⁡pθ(x)\log p_\theta(x) and is no longer a bound. Either way β\beta changes which model training prefers, not just the scale of the loss.

Where does a β\beta hide in an ordinary VAE? Take a Gaussian decoder with a fixed variance s2s^2 around the output x^\hat x:

−log⁡pθ(x∣z)=∥x−x^∥22s2+const.-\log p_\theta(x \mid z) = \frac{\lVert x - \hat x \rVert^2}{2 s^2} + \text{const}.

Multiplying the negative ELBO by 2s22s^2 does not move its optimum and gives

∥x−x^∥2+2s2 DKL+const.\lVert x - \hat x \rVert^2 + 2 s^2\, D_{\mathrm{KL}} + \text{const}.

So squared error plus β⋅KL\beta \cdot \mathrm{KL} is exactly a VAE whose decoder variance satisfies β=2s2\beta = 2s^2. The training step of The reparameterization trick, with weight 11 on the KL, was the case s2=12s^2 = \tfrac12. A large β\beta amounts to declaring the pixels very noisy: reconstruction errors become cheap compared with bits of code.

Rate and distortion

Averaged over the data, the two terms get names from information theory (Alemi et al., 2018). The rate is the average KL, measured in nats, and the distortion is the average reconstruction loss:

R=Ex DKL(qφ(z∣x) ∥ p(z)),D=−Ex Eqφ(z∣x)log⁡pθ(x∣z).R = \mathbb E_x\, D_{\mathrm{KL}}\big(q_\varphi(z \mid x)\,\|\,p(z)\big), \qquad D = -\mathbb E_x\, \mathbb E_{q_\varphi(z \mid x)} \log p_\theta(x \mid z).

The negative ELBO is D+RD + R; the β-VAE minimizes D+βRD + \beta R, the Lagrangian of "reconstruct as well as possible at a rate of at most so much". Each β\beta picks one point of the trade-off. Since R≥0R \ge 0, −(D+βR)≤−(D+R)-(D + \beta R) \le -(D + R) for every β≥1\beta \ge 1, so among the weights that keep a bound, β=1\beta = 1 gives the tightest.

A worked example. One latent dimension, prior N(0,1)\mathcal N(0, 1), a fixed decoder p(x∣z)=N(wz,σ2)p(x \mid z) = \mathcal N(wz, \sigma^2) with w=1w = 1, σ2=0.1\sigma^2 = 0.1, and data from this very model, x∼N(0,1.1)x \sim \mathcal N(0, 1.1). For an encoder q(z∣x)=N(m,v)q(z \mid x) = \mathcal N(m, v) the β-objective is, up to constants,

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

and setting its derivatives to zero gives the optimal encoder

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

At β=1\beta = 1 they are wx/(w2+σ2)wx/(w^2 + \sigma^2) and σ2/(w2+σ2)\sigma^2/(w^2 + \sigma^2). For the pair (z,x)(z, x) with Var⁡z=1\operatorname{Var} z = 1, Cov⁡(z,x)=w\operatorname{Cov}(z, x) = w and Var⁡x=w2+σ2\operatorname{Var} x = w^2 + \sigma^2, these are the conditional mean and variance of zz given xx from Multivariate Gaussians: the encoder recovers the exact posterior, and the bound is tight.

To average over x∼N(0,1.1)x \sim \mathcal N(0, 1.1), write a=m/xa = m/x, the same for every xx. With w=1w = 1, 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. The closed-form KL and Eq(x−wz)2=(x−wm)2+w2v\mathbb E_q (x - wz)^2 = (x - wm)^2 + w^2 v then average to

R=12(v+1.1 a2−1−ln⁡v),E(x−wz)2=1.1 (1−a)2+v.R = \tfrac12\big(v + 1.1\,a^2 - 1 - \ln v\big), \qquad \mathbb E(x - wz)^2 = 1.1\,(1 - a)^2 + v .

At β=1\beta = 1, a=10/11a = 10/11 and v=1/11v = 1/11, so R=12ln⁡11≈1.20R = \tfrac12 \ln 11 \approx 1.20 nats:

β\beta m/xm/x vv rate RR, nats distortion E(x−wz)2\mathbb E(x - wz)^2
0.25 0.976 0.024 1.89 0.025
1 0.909 0.091 1.20 0.100
4 0.714 0.286 0.55 0.376
16 0.385 0.615 0.13 1.032

Raising β\beta pulls the mean toward 0 and the variance toward 1: the code says less and the reconstruction gets worse.

A high rate is not the same as a code far from the prior. The rate splits into the mutual information I(X;Z)I(X; Z) plus the KL from the aggregate posterior q(z)=Ex q(z∣x)q(z) = \mathbb E_x\, q(z \mid x) to the prior; here q(z)=N(0, (m/x)2⋅1.1+v)q(z) = \mathcal N\big(0,\ (m/x)^2 \cdot 1.1 + v\big). Prior samples suffer when q(z)q(z) leaves the prior, and in a jointly trained VAE a small β\beta penalizes that mismatch less.

What β buys and what it does not

Higgins et al. (2017) report that β>1\beta > 1 makes individual latent coordinates track individual factors of variation — position, scale, rotation of a sprite. They call it disentanglement: a single latent unit is sensitive to one generative factor and relatively invariant to the others. On CelebA with β=250\beta = 250, one unit turns the head while the rest of the face stays; in a plain VAE the same kind of unit also changes the expression, glasses and gender.

The proposed mechanism is the pressure to spend little rate: a factorized prior is cheapest to match with a posterior whose coordinates are independent. But the effect is not guaranteed. Locatello et al. (2019) prove that without supervision or inductive biases disentanglement cannot be identified from data, and across more than 12,000 trained models find that seeds and hyperparameters matter more than the choice of disentangling objective. Burgess et al. (2018) replace the fixed weight by a target rate CC that grows during training,

Eqlog⁡pθ(x∣z)−γ ∣DKL−C∣,\mathbb E_q \log p_\theta(x \mid z) - \gamma\, \big\lvert D_{\mathrm{KL}} - C \big\rvert,

so the code is allowed one more nat at a time.

Push β\beta far enough and the pressure wins outright. In the table, β=16\beta = 16 already leaves a rate of only 0.130.13 nats. A code that is never paid for in KL is a code the decoder learns to do without — the failure known as posterior collapse, which comes back at the end of this topic. The useful reading of β\beta: a dial on the rate, not a switch for interpretability.

VQ-VAE: a discrete code

The VQ-VAE (van den Oord, Vinyals and Kavukcuoglu, 2017) gives up the continuous code. The encoder still outputs a map of vectors ze(x)∈Rh×w×dz_e(x) \in \mathbb R^{h \times w \times d}, but each vector is replaced by the nearest entry of a learned codebook 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).k^*(i) = \arg\min_k \big\lVert z_e(x)_i - e_k \big\rVert^2, \qquad z_q(x)_i = e_{k^*(i)}.

The code of an image is the grid of indices k∗(i)k^*(i): for a 32×3232 \times 32 image, for instance, an 8×88 \times 8 grid of integers from 1 to 512. In ELBO terms the posterior q(z=k∣x)q(z = k \mid x) is one-hot at k∗k^*. Against a uniform prior over the KK codes, any categorical qq has

DKL(q ∥ Uniform)=∑kqklog⁡qk1/K=log⁡K−H(q),D_{\mathrm{KL}}\big(q \,\|\, \mathrm{Uniform}\big) = \sum_k q_k \log\frac{q_k}{1/K} = \log K - H(q),

and a one-hot qq has zero entropy, so the KL is log⁡K\log K per position — a constant. The KL term drops out, and the VQ-VAE trains as a plain autoencoder with a quantized bottleneck.

A worked example. 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 an encoder output ze=(1.4,0.3)z_e = (1.4, 0.3). The squared distances are

∥ze−e1∥2=2.05,∥ze−e2∥2=0.36+0.09=0.45,∥ze−e3∥2=4.85,\lVert z_e - e_1 \rVert^2 = 2.05, \quad \lVert z_e - e_2 \rVert^2 = 0.36 + 0.09 = 0.45, \quad \lVert z_e - e_3 \rVert^2 = 4.85,

so the decoder receives zq=e2=(2,0)z_q = e_2 = (2, 0) and the code is the index 2. The codebook splits the plane into cells bounded by the perpendicular bisectors between its vectors; every point of a cell maps to the same vector.

Training through the argmin

The argmin has no useful gradient. Inside a cell the quantizer is constant, so its true Jacobian is zero; on a cell boundary it jumps. The VQ-VAE uses the straight-through estimator (Bengio, Léonard and Courville, 2013): in the forward pass the decoder receives zqz_q, in the backward pass the gradient with respect to zqz_q is copied to zez_e unchanged. With the stop-gradient operator sg[⋅]\mathrm{sg}[\cdot] — identity in the forward pass, zero derivative in the backward pass — it is one line:

zq←ze+sg[zq−ze],z_q \leftarrow z_e + \mathrm{sg}[z_q - z_e],

or, in PyTorch, z_q = z_e + (z_q - z_e).detach(). The value is zqz_q; the derivative is that of zez_e. This is a surrogate, not the derivative of quantization: it replaces a zero Jacobian by the identity. The loss has three terms, summed over positions, with e=ek∗e = e_{k^*}:

L=−log⁡pθ(x∣zq(x))+∥sg[ze(x)]−e∥2+βc∥ze(x)−sg[e]∥2.\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 .

The codebook term moves ee toward the encoder output. The commitment term moves the encoder output toward ee; without it nothing stops the encoder outputs from drifting away from the codebook faster than it can follow. The paper uses βc=0.25\beta_c = 0.25. In the example above both terms measure the same 0.450.45 (the second weighted to 0.11250.1125), but their gradients go to different places.

The codebook term is a k-means step, and the paper's appendix 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, and γ=0.99\gamma = 0.99:

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) \textstyle\sum_{i:\, k^*(i) = k} z_e(x)_i, \\ e_k &= m_k / N_k . \end{aligned}

So each eke_k is a running mean of its cell, an online k-means centroid. It inherits the k-means weak spot. A code that no output selects has nk=0n_k = 0: both NkN_k and mkm_k are only multiplied by γ\gamma, and ek=mk/Nke_k = m_k / N_k stays where it was. Its cell keeps taking no outputs, so it stays a dead code. In a toy run with encoder outputs in four small blobs and 64 codes started from N(0,I)\mathcal N(0, I), only 25 codes are still in use after 500 EMA steps. Practical fixes restart unused codes at recent encoder outputs (Jukebox), which in the same toy brings back all 64 and more than halves the quantization error, or look codes up in a low-dimensional normalized space (ViT-VQGAN).

The prior is learned afterwards

Because the KL is constant, training leaves the prior uniform, and sampling indices independently and uniformly would give an image of random patches. So the VQ-VAE fits the prior after the autoencoder: encode the training set into grids of indices and train an autoregressive model on them — a PixelCNN in the paper — that predicts each index from the ones before it. Generation samples a grid from this prior and decodes it.

The two stages split the work. The autoencoder handles pixels; the prior only has to model a grid that is far smaller and made of symbols, where autoregressive models are strong. The price is that the prior is fitted to a frozen autoencoder, and sampling is still sequential, one index at a time.

VQ-VAE-2 (Razavi, van den Oord and Vinyals, 2019) uses two grids: a coarse top grid for the layout and a finer bottom grid for detail, quantized after seeing the top. The prior is hierarchical too — an autoregressive model over the top codes and a conditional one over the bottom codes given 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.

How many bits? 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. The image is 32⋅32⋅3=307232 \cdot 32 \cdot 3 = 3072 bytes, or 24,57624{,}576 bits. Its code is 8080 indices of log⁡2512=9\log_2 512 = 9 bits, 720720 bits — about 34 times fewer — and the priors need 8080 sequential steps instead of 30723072.

Neither knob removes the blur. Both keep a decoder likelihood such as a Gaussian per pixel, and the squared error it contains is minimized by the average of all images that fit a code. Any likelihood of that kind invites averaging. The next topic, GANs as a two-player game, asks what happens if we never write a likelihood down at all.

Optional: VAPNEV

Optional depth; nothing later depends on it. The blur comes from the decoder likelihood, so there is a middle road: keep a likelihood, but make it smarter than an independent Gaussian per pixel.

VAPNEV (Agrawal and Dukkipati, 2016; an anagram of VAE-NVP) keeps the Gaussian code and the ELBO and changes the reconstruction term. The decoder network outputs the mean and variances of a Gaussian over an intermediate y∈RDy \in \mathbb R^D, and an invertible real NVP flow fzf_z, conditioned on the code, maps the image to yy:

y=fz(x),y∣z∼N(μθ(z),σθ2(z)),x=fz−1(y).y = f_z(x), \qquad y \mid z \sim \mathcal N\big(\mu_\theta(z), \sigma_\theta^2(z)\big), \qquad x = f_z^{-1}(y).

By the change of variables the likelihood is exact:

log⁡pθ(x∣z)=log⁡N(fz(x); μθ(z),σθ2(z))+log⁡∣det⁡Jfz(x)∣.\log p_\theta(x \mid z) = \log\mathcal N\big(f_z(x);\, \mu_\theta(z), \sigma_\theta^2(z)\big) + \log\big\lvert\det J_{f_z}(x)\big\rvert .

The flow is a stack of coupling layers whose scale and shift also see the code, yb=xb⊙exp⁡(sz(xa))+tz(xa)y_b = x_b \odot \exp\big(s_z(x_a)\big) + t_z(x_a). It mixes pixels, so for a given code the model can represent dependencies between them. The formula and the layers are derived in The change of variables.

The decoder is strong — strong enough to model the images without the code. The authors saw the KL term drop to zero early in training, posterior collapse again, and countered it with KL annealing: a weight on the KL that starts at 0 and grows to 1 during training. In the language of this topic, a β\beta schedule.

A flow inside the decoder buys a sharper likelihood at the price of a heavier model and a fight with posterior collapse. The next topic, GANs as a two-player game, takes the opposite route and drops the likelihood altogether.

Check your understanding

The same questions as in Pulse. Answers are shared between modes.

Full notes

Answers are saved on the server and tied to this browser until you sign in.