∇
Chapter 32 · Section 32.4 · 95 min

Blurry samples, beta, and posterior collapse

A trained VAE goes wrong in two familiar ways. Its samples come out blurry, like smudged averages of training images. And when its decoder is strong, for example one that writes a sentence one word at a time, it can learn to ignore its code completely. The "autoencoder" has then become an ordinary language model (Bowman et al. 2016). Neither failure is a bug. In both cases the optimizer does exactly what the training objective asks.

This section shows that both failures come from one trade-off inside the VAE's loss. The loss charges for every piece of information the code carries, and it also charges for every error the decoder makes. One weight, β\beta, sets the exchange rate between the two charges. Once you see the trade-off you can predict which details a VAE drops first, measure whether its code is being used, and pick the fix that matches the cause. When a VAE stops using its code, the failure is called posterior collapse. "Why are VAE samples blurry?" and "what is posterior collapse?" are among the most common interview questions on generative models, and this section answers both precisely.

Here is the setup, recapped from §32.3. A data point x∈Rdx\mathbf{x} \in \R^{d_x}, such as an image, is described by a short code z∈Rdz\mathbf{z} \in \R^{d_z}. The encoder maps an input to a Gaussian distribution over codes, qϕ(z∣x)=N(μϕ(x),diag⁡σϕ2(x))q_\phi(\mathbf{z}\mid\mathbf{x}) = \mathcal{N}\big(\boldsymbol\mu_\phi(\mathbf{x}), \operatorname{diag}\boldsymbol\sigma^2_\phi(\mathbf{x})\big), where ϕ\phi stands for the encoder's weights. We call this distribution the encoder's posterior, because it plays the part of the posterior of Bayes rule, the distribution of the code once the input is known. The decoder pθ(x∣z)p_\theta(\mathbf{x}\mid\mathbf{z}), with weights θ\theta, maps a code back to a distribution over inputs. The prior p(z)=N(0,I)p(\mathbf{z}) = \mathcal{N}(\mathbf{0}, \mathbf{I}) is where codes come from when we generate. The prior and the decoder together also define an exact posterior pθ(z∣x)p_\theta(\mathbf{z}\mid\mathbf{x}) by Bayes rule, which we call the true posterior to keep it apart from the encoder's. Training maximizes the evidence lower bound of §32.2, averaged over the training set,

ELBO⁡(x;θ,ϕ)=Eqϕ(z∣x)[log⁡pθ(x∣z)]−DKL(qϕ(z∣x) ∥ p(z))  ≤  log⁡pθ(x).\operatorname{ELBO}(\mathbf{x};\theta,\phi) = \mathbb{E}_{q_\phi(\mathbf{z}\mid\mathbf{x})}\big[\log p_\theta(\mathbf{x}\mid\mathbf{z})\big] - D_{\mathrm{KL}}\big(q_\phi(\mathbf{z}\mid\mathbf{x})\,\Vert\,p(\mathbf{z})\big) \;\le\; \log p_\theta(\mathbf{x}).

In plain words, the first term rewards reconstructing x\mathbf{x} from a code drawn from the encoder. The second term is the KL divergence, which measures how far the encoder's distribution for this input sits from the prior. It is measured in nats, the unit of information when logarithms are natural (1 nat is 1/ln⁡2=1.441/\ln 2 = 1.44 bits). The whole objective is a lower bound on the log-likelihood log⁡pθ(x)\log p_\theta(\mathbf{x}).

The KL term is what this section is about. It charges the model for every nat of information that the code carries about the input. Sometimes a blurred guess costs less than the detail would. Sometimes the decoder can do the whole job without the code. In both cases the optimizer takes the cheaper option. The plan is to make that exact. We name the two terms of the loss rate and distortion, and show that a weight β\beta on the KL term picks one point on a trade-off curve between them. A linear VAE can be solved in closed form. It meets the best limit that information theory allows, and collapse shows up in it as directions that are switched off. That picture then explains posterior collapse and its fixes, splits the KL term into a useful part and a wasted part, and shows what β\beta-VAEs and hierarchical VAEs can and cannot do.

Two formulas from §32.3 recur throughout. A Gaussian decoder with mean network fθ\mathbf{f}_\theta and a fixed variance σx2\sigma_x^2, pθ(x∣z)=N(fθ(z),σx2I)p_\theta(\mathbf{x}\mid\mathbf{z}) = \mathcal{N}(\mathbf{f}_\theta(\mathbf{z}), \sigma_x^2\mathbf{I}), has negative log-likelihood

−log⁡pθ(x∣z)=∥x−fθ(z)∥22σx2+dx2log⁡(2πσx2),-\log p_\theta(\mathbf{x}\mid\mathbf{z}) = \frac{\lVert\mathbf{x} - \mathbf{f}_\theta(\mathbf{z})\rVert^2}{2\sigma_x^2} + \frac{d_x}{2}\log(2\pi\sigma_x^2),

a squared error scaled by 1/(2σx2)1/(2\sigma_x^2) plus a constant. And the KL of a one-dimensional Gaussian N(μ,σ2)\mathcal{N}(\mu, \sigma^2) to the standard normal is 12(μ2+σ2−1−ln⁡σ2)\tfrac12(\mu^2 + \sigma^2 - 1 - \ln\sigma^2) nats.

Why VAE samples are blurry

There are two separate reasons, and it pays to keep them apart. The first is about the decoder's mean, the image it outputs for a code. The second is about the shape of the decoder's distribution around that mean.

The best decoder averages the images that share a code

Suppose two different training images could each have produced the same code. A decoder trained with squared error cannot tell which one it is looking at. Its best answer is then the average of the two, weighted by how likely each one is to have produced that code. An average of two images is a blend, and a blend of shifted images is a blur. Here is the smallest case with numbers.

The same argument works for any number of images, and it is the conditional-mean theorem of §32.1 applied to the encoder's codes. That theorem says the function that minimizes an expected squared error is a conditional mean, whatever the input is.

In plain words, the decoder's output at a code is the average of every training image that could have produced that code, weighted by how likely each one is. When the posteriors of different images overlap, every code in the overlap decodes to a blend. And the KL term pushes every posterior toward N(0,I)\mathcal{N}(\mathbf{0},\mathbf{I}), which means wide and overlapping. Narrow, well-separated posteriors are exactly what the KL charges for. Rezende and Viola (2018) make the same point about overlapping posteriors and blurred reconstructions.

Two images show the mechanism but not the blur we see in real samples. Blur needs many images that differ by small shifts, so that the images sharing a code are neighbors. So take 16 one-dimensional "images" of 16 pixels each, numbered c=0,1,…,15c = 0, 1, \dots, 15. Image cc is a narrow bar, a smooth bump of brightness centered on pixel cc, and neighboring images differ by a one-pixel shift. The code is one number. The encoder sends image cc to N(a cˉ,s2)\mathcal{N}(a\,\bar c, s^2), where cˉ=c−7.5\bar c = c - 7.5 is the bump's position measured from the middle. Two numbers set the encoder, the spacing aa between the code means and the width ss of each posterior.

What decides the blur is the ratio r=s/ar = s/a, the width of one posterior in units of the spacing. With rr small the posteriors do not touch, and with rr large they pile on top of each other. The rate, the average KL to the prior, depends on both numbers. For a given overlap rr the cheapest spacing is a2=1/(v+r2)a^2 = 1/(v + r^2), where v=21.25v = 21.25 is the variance of the positions cˉ\bar c, and the rate is then

R(r)=12ln⁡(1+vr2) nats.\mathcal{R}(r) = \tfrac12\ln\Big(1 + \frac{v}{r^2}\Big)\ \text{nats}.

In plain words, the rate grows as the posteriors narrow relative to the spread of their means. Information theory knows this formula as the capacity of a Gaussian channel whose signal-to-noise ratio is v/r2v/r^2.

∂ Where the rate of the bar toy comes from

The average KL to N(0,1)\mathcal{N}(0, 1) of the posteriors N(acˉ,s2)\mathcal{N}(a\bar c, s^2) is 12(a2v+s2−1−ln⁡s2)\tfrac12\big(a^2 v + s^2 - 1 - \ln s^2\big), with v=116∑ccˉ2=21.25v = \frac1{16}\sum_c\bar c^2 = 21.25. Hold r=s/ar = s/a fixed, so s2=r2a2s^2 = r^2a^2, and minimize over aa. The derivative a(v+r2)−1/aa(v + r^2) - 1/a vanishes at a2=1/(v+r2)a^2 = 1/(v + r^2). Then a2v+s2=1a^2v + s^2 = 1, so the codes as a whole have variance 1, matching the prior, and the rate is 12(−ln⁡s2)=12ln⁡((v+r2)/r2)\tfrac12\big(-\ln s^2\big) = \tfrac12\ln\big((v + r^2)/r^2\big). The squared error of the best decoder depends only on rr, because in the rescaled coordinate u=z/au = z/a each posterior is N(cˉ,r2)\mathcal{N}(\bar c, r^2) and the weights are wc∝e−(u−cˉ)2/(2r2)w_c \propto e^{-(u - \bar c)^2/(2r^2)}.

The cell computes the best decoder on a grid of codes. For each β\beta it picks the overlap that minimizes the loss, the squared error over 2σx22\sigma_x^2 plus β\beta times the rate, with σx2=0.1\sigma_x^2 = 0.1. It prints the rate, the squared error, and how many images the decoder effectively averages at an image's own code. That last number is eH(w)e^{H(\mathbf{w})}, the exponential of the entropy of the weights wcw_c. It is 1 when one image gets all the weight and 16 when all sixteen get equal weight. The cell also plots the decoded bar.

Python · cell 1

So blur and collapse are not two different failures. They are two positions on one curve, and the rest of the section is about that curve.

Why does a squared-error VAE decode a blur?
Sixteen training images, each a bar at one pixel. Top, where each image's codes land. Bottom, what z decodes to.
Loading interactive figure…

In practice, this means a VAE's blur gets worse when you raise the KL weight and better when you let the code spend more nats. An interviewer who asks "why are VAE samples blurry" wants this argument first.

A factorized decoder cannot say "here or there"

The second reason is about the decoder's distribution, not its mean. Take a Gaussian decoder with a diagonal covariance, pθ(x∣z)=∏iN(xi;fi(z),σx2)p_\theta(\mathbf{x}\mid\mathbf{z}) = \prod_i \mathcal{N}(x_i; f_i(\mathbf{z}), \sigma_x^2), where fi(z)f_i(\mathbf{z}) is its mean for pixel ii. It treats whatever the code leaves undecided as independent noise on each pixel. Suppose the code fixes "a face, looking left" but not the exact position of one eyelash. The true distribution of images given that code is then a set of sharp images, each with the eyelash in a slightly different place. No product of independent per-pixel Gaussians can represent that set. The best one, in the sense of the highest expected log-likelihood, puts its mean at the pixelwise average, a soft gray streak. It spreads the rest as per-pixel noise.

Sampling from that decoder gives the gray streak plus white speckle, which looks worse than the mean. So papers display the mean fθ(z)\mathbf{f}_\theta(\mathbf{z}) instead, and that displayed mean is the blur. Some decoders can represent correlated uncertainty, such as autoregressive pixel models that generate one pixel at a time given the ones before it. We will see shortly that they cause the opposite problem, a decoder so good that it ignores the code. The practical answers are adversarial and perceptual losses that let the decoder commit to one sharp texture (§32.6), and discrete codes (§32.5).

One more setting acts on both reasons, the decoder variance σx2\sigma_x^2. The squared error is divided by 2σx22\sigma_x^2 and the KL is multiplied by β\beta, so raising σx2\sigma_x^2 does the same thing as raising β\beta. §32.3 called this a hidden KL weight, and the linear model below shows that only the product βσx2\beta\sigma_x^2 matters. So a VAE trained with a large fixed σx2\sigma_x^2 is blurry for the same reason as one trained with a large β\beta. Its posteriors overlap more, which is the first reason. Its code also carries less, so more of each image is left undecided for the factorized decoder to average, which is the second.

Rate, distortion, and beta as a price

The two terms of the negative ELBO measure two different costs, and they deserve names. The rate is how many nats the code spends describing each example. The distortion is how many nats the decoder still needs to describe the example once it has the code. The names come from information theory, where a rate counts the bits sent per symbol and a distortion is the error that the description leaves. Alemi et al. (2018) introduced this reading of the VAE.

The weight β\beta is a price. Minimizing D+βR\mathcal{D} + \beta\mathcal{R} buys a nat of rate only if it lowers the distortion by at least β\beta nats. With β=2\beta = 2, for example, an extra nat in the code must save 2 nats of distortion to be worth it. A large β\beta makes rate expensive, so the optimum has low rate and high distortion.

There is a picture for this. Consider every encoder and decoder the architecture can represent, and plot the (R,D)(\mathcal{R}, \mathcal{D}) pair of each one. The lower-left edge of that cloud is a curve D(R)\mathcal{D}(\mathcal{R}), the least distortion achievable at each rate. Minimizing D+βR\mathcal{D} + \beta\mathcal{R} lands on that edge, at the point where a straight line of slope −β-\beta just touches it. Where the curve is smooth, setting the derivative of D(R)+βR\mathcal{D}(\mathcal{R}) + \beta\mathcal{R} to zero gives dD/dR=−β\mathrm{d}\mathcal{D}/\mathrm{d}\mathcal{R} = -\beta. In plain words, each β\beta selects one point on the trade-off curve, and β\beta is the slope there.

What point does the ordinary β=1\beta = 1 choose? When the decoder is powerful enough to model the data by itself, it may choose to send nothing at all.

In plain words, if the decoder can do the job alone, then at β=1\beta = 1 using the code can at best tie with ignoring it. It ties only if the encoder matches the true posterior exactly. With any approximation error in the encoder, using the code loses. Above β=1\beta = 1 ignoring the code wins outright. Below β=1\beta = 1 rate is cheap, and the model prefers to use the code. The cases that made collapse famous are discrete data, sentences in Bowman et al. (2016) and binarized MNIST in Alemi et al. (2018), so the theorem applies to them as stated.

The theorem shows up in real models. On binarized MNIST, a VAE trained just above β=1\beta = 1 ignored its code, and one trained at β=1\beta = 1 used it, with almost the same ELBO.

The ELBO alone cannot tell a model that uses its code from one that ignores it. In practice, log the rate and the distortion separately, never only their sum. "Two VAEs have the same ELBO, so are they equally good?" is a classic interview trap, and the answer is no.

The best possible trade-off for Gaussian data

To judge any of these trade-offs we need the limit, the least rate that any description could get away with at a given error. Information theory supplies it. The mutual information I(x;x^)I(\mathbf{x};\hat{\mathbf{x}}) between a source x\mathbf{x} and a reconstruction x^\hat{\mathbf{x}} is how many nats knowing one tells you about the other (§0.5). Shannon's rate-distortion function is the least mutual information that any randomized description can have while keeping the expected squared error at most Dsq\mathcal{D}_{\text{sq}},

R⋆(Dsq)=min⁡p(x^∣x) :  E∥x−x^∥2≤DsqI(x;x^).\mathcal{R}^\star(\mathcal{D}_{\text{sq}}) = \min_{p(\hat{\mathbf{x}}\mid\mathbf{x})\,:\;\mathbb{E}\lVert\mathbf{x} - \hat{\mathbf{x}}\rVert^2 \le \mathcal{D}_{\text{sq}}} I(\mathbf{x};\hat{\mathbf{x}}).

Shannon's rate-distortion theorem says what this number means in practice. It is the least number of nats per source vector that any code needs to reach that error, when many source vectors are described together (Cover and Thomas, chapter 10).

Start with one number. Let xx be Gaussian with variance 4, and allow a squared error of 1. The answer is 12ln⁡(4/1)=0.693\tfrac12\ln(4/1) = 0.693 nats, exactly 1 bit. In general one Gaussian number with variance λ\lambda costs 12ln⁡(λ/D)\tfrac12\ln(\lambda/D) nats at error DD, so each extra bit divides the error variance by 4. With several independent numbers the question becomes how to split the error budget among them, and the answer has a picture.

Draw each variance λi\lambda_i as a bar and pour water to height ν\nu. Wherever the water covers a bar, that component is not described at all. Wherever a bar sticks out, the part above the water is what the description carries, and the water underneath is the error left behind. The rule is to describe the large components and drop the small ones. A component gets any rate only once the error on every larger component has been pushed below that component's own variance.

∂ Proof of reverse water-filling

One Gaussian component. Let x∼N(0,λ)x \sim \mathcal{N}(0, \lambda) and let x^\hat x be any reconstruction with E(x−x^)2≤D≤λ\mathbb{E}(x - \hat x)^2 \le D \le \lambda. Using differential entropies hh,

I(x;x^)=h(x)−h(x∣x^)=h(x)−h(x−x^∣x^)≥h(x)−h(x−x^)≥12ln⁡(2πeλ)−12ln⁡(2πeD)=12ln⁡λD.I(x;\hat x) = h(x) - h(x\mid\hat x) = h(x) - h(x - \hat x\mid\hat x) \ge h(x) - h(x - \hat x) \ge \tfrac12\ln(2\pi e\lambda) - \tfrac12\ln(2\pi e D) = \tfrac12\ln\frac{\lambda}{D}.

The second step shifts by a known quantity. The third holds because conditioning cannot increase entropy. The fourth holds because a Gaussian has the largest entropy of any variable with a given second moment, here at most DD. The bound is achieved by the "backward channel" x=x^+nx = \hat x + n with x^∼N(0,λ−D)\hat x \sim \mathcal{N}(0, \lambda - D) and independent n∼N(0,D)n \sim \mathcal{N}(0, D), for which every inequality is an equality. If D≥λD \ge \lambda, the reconstruction x^=0\hat x = 0 costs nothing, so the rate is 0.

Many independent components. For any description, I(x;x^)=∑ih(xi)−∑ih(xi∣x<i,x^)≥∑ih(xi)−∑ih(xi∣x^i)=∑iI(xi;x^i)I(\mathbf{x};\hat{\mathbf{x}}) = \sum_i h(x_i) - \sum_i h(x_i\mid x_{\lt i},\hat{\mathbf{x}}) \ge \sum_i h(x_i) - \sum_i h(x_i\mid\hat x_i) = \sum_i I(x_i;\hat x_i). The first sum uses independence, and the inequality again uses that conditioning cannot increase entropy. With Di=E(xi−x^i)2D_i = \mathbb{E}(x_i - \hat x_i)^2, the one-component bound gives I(x;x^)≥∑imax⁡(0,12ln⁡(λi/Di))I(\mathbf{x};\hat{\mathbf{x}}) \ge \sum_i \max\big(0, \tfrac12\ln(\lambda_i/D_i)\big), and describing each component on its own with its own backward channel achieves this. What is left is to split the budget, minimizing ∑i12ln⁡(λi/Di)\sum_i\tfrac12\ln(\lambda_i/D_i) over 0<Di≤λi0 \lt D_i \le \lambda_i subject to ∑iDi=Dsq\sum_i D_i = \mathcal{D}_{\text{sq}}.

Splitting the budget. Take Dsq<∑iλi\mathcal{D}_{\text{sq}} \lt \sum_i\lambda_i (otherwise Di=λiD_i = \lambda_i for all ii costs nothing). A minimizer exists, because the objective is continuous on the feasible set and grows without bound as any Di→0D_i \to 0. An exchange argument pins it down. Suppose a minimizer had components ii and jj with Di<λiD_i \lt \lambda_i and Di<DjD_i \lt D_j. Move a small amount ε>0\varepsilon \gt 0 of distortion from jj to ii. This stays feasible, because ii has room below λi\lambda_i and the budget is unchanged. The objective changes at the rate −12Di+12Dj<0-\tfrac{1}{2D_i} + \tfrac{1}{2D_j} \lt 0, so the move lowers it, a contradiction. (In words, −ln⁡-\ln is convex, so a unit of distortion saves more rate where the distortion is still small.) Hence every component with Di<λiD_i \lt \lambda_i has Di≥DjD_i \ge D_j for all jj. All such components share the largest value, call it ν\nu, and every other component has Di=λi≤νD_i = \lambda_i \le \nu. Both cases read Di=min⁡(λi,ν)D_i = \min(\lambda_i, \nu). At least one component has Di<λiD_i \lt \lambda_i, since otherwise the budget would be ∑iλi\sum_i\lambda_i. The budget fixes ν\nu uniquely, because ∑imin⁡(λi,ν)\sum_i\min(\lambda_i, \nu) is strictly increasing in ν\nu below max⁡iλi\max_i\lambda_i. So the only candidate is the water-filling allocation, and since a minimizer exists, it is the minimizer. (These are the KKT conditions of convex optimization, with the common ν\nu as the budget's multiplier.) Finally, with k≥1k \ge 1 components above the water, R⋆=∑active12ln⁡λi−k2ln⁡ν\mathcal{R}^\star = \sum_{\text{active}}\tfrac12\ln\lambda_i - \tfrac k2\ln\nu and Dsq=kν+∑restλi\mathcal{D}_{\text{sq}} = k\nu + \sum_{\text{rest}}\lambda_i, so dR⋆/dDsq=(−k/(2ν))/k=−1/(2ν)\mathrm{d}\mathcal{R}^\star/\mathrm{d}\mathcal{D}_{\text{sq}} = (-k/(2\nu))/k = -1/(2\nu).

Once you know which components sit under the water, the water level has a closed form. Computing it is a short and common coding question.

Core

Reverse water-filling

Implement water_fill(eigs, D) for a Gaussian source whose component variances are eigs (positive, in any order) and a target squared-error distortion D > 0. Return (nu, rate, Di), the water level, Shannon's rate in nats, and the per-component distortions Di=min⁡(λi,ν)D_i = \min(\lambda_i, \nu) in the input order. If D is at least the total variance, return nu = max(eigs), rate 0, and Di=λiD_i = \lambda_i. Solve for ν\nu exactly, without bisection.

Tests, hints, verified solutions, and AI help, with Pro at $7.99 a month.

The linear beta-VAE is reverse water-filling

The simplest VAE whose optimum we can find exactly is the linear one. Here we ask where β\beta puts it. Given enough latent dimensions, it lands exactly on Shannon's limit, and β\beta sets the water level.

The data are centered, with covariance Σx=UΛU⊤\boldsymbol\Sigma_x = \mathbf{U}\boldsymbol\Lambda\mathbf{U}^\top. Its eigenvalues are λ1≥⋯≥λdx\lambda_1 \ge \dots \ge \lambda_{d_x} and its orthonormal eigenvectors ui\mathbf{u}_i are the principal directions of §0.10, the directions along which the data vary most. The decoder is linear, pθ(x∣z)=N(Wz,σx2I)p_\theta(\mathbf{x}\mid\mathbf{z}) = \mathcal{N}(\mathbf{W}\mathbf{z}, \sigma_x^2\mathbf{I}) with W∈Rdx×dz\mathbf{W}\in\R^{d_x\times d_z} and a fixed σx2\sigma_x^2. The encoder is linear too, with a diagonal covariance shared by all inputs, qϕ(z∣x)=N(V⊤x,diag⁡(v))q_\phi(\mathbf{z}\mid\mathbf{x}) = \mathcal{N}(\mathbf{V}^\top\mathbf{x}, \operatorname{diag}(\mathbf{v})) with V∈Rdx×dz\mathbf{V}\in\R^{d_x\times d_z}. This is the linear VAE of §32.3, also used by Lucas et al. (2019). We drop the constant dx2log⁡(2πσx2)\tfrac{d_x}{2}\log(2\pi\sigma_x^2) from the distortion and write D′=Dsq/(2σx2)\mathcal{D}' = \mathcal{D}_{\text{sq}}/(2\sigma_x^2).

Recall that probabilistic PCA (pPCA) is the model x=Wz+noise\mathbf{x} = \mathbf{W}\mathbf{z} + \text{noise} with z∼N(0,I)\mathbf{z} \sim \mathcal{N}(\mathbf{0}, \mathbf{I}) and Gaussian noise of a fixed variance. Its maximum-likelihood W\mathbf{W} points along the top principal directions, and it switches off every direction whose variance is below the noise (§32.2). Its exact posterior has the same covariance for every input, which is why our encoder needs no input-dependent variance.

In plain words, β\beta and the decoder variance matter only through their product, the water level. Every principal direction whose variance clears the water is encoded, and it leaves exactly ν\nu of squared error behind. Every direction below the water is switched off, and its latent dimension sits exactly on the prior. That switched-off dimension is posterior collapse in its cleanest form, and it is not a training failure. It is the optimum. Lucas et al. (2019) made this point for β=1\beta = 1, where the water level is the decoder variance itself.

∂ Proof that the linear beta-VAE solves reverse water-filling

Step 1, only the water level matters. Divide the objective by β>0\beta \gt 0. It becomes E∥x−Wz∥2/(2βσx2)+R\mathbb{E}\lVert\mathbf{x} - \mathbf{W}\mathbf{z}\rVert^2/(2\beta\sigma_x^2) + \mathcal{R}. Up to a constant, that is the negative expected ELBO of the same linear VAE with its decoder variance set to ν=βσx2\nu = \beta\sigma_x^2. So we need the best β=1\beta = 1 linear VAE with decoder noise ν\nu.

Step 2, the ELBO can be made tight, so we are maximizing the pPCA likelihood. For a fixed W\mathbf{W} the model is probabilistic PCA with noise ν\nu. Its exact posterior is N(M−1W⊤x,νM−1)\mathcal{N}(\mathbf{M}^{-1}\mathbf{W}^\top\mathbf{x}, \nu\mathbf{M}^{-1}) with M=W⊤W+νI\mathbf{M} = \mathbf{W}^\top\mathbf{W} + \nu\mathbf{I} (§32.2). If the columns of W\mathbf{W} are orthogonal, M\mathbf{M} is diagonal, so the exact posterior has a linear mean and a diagonal shared covariance. That is in our encoder family (take V=WM−1\mathbf{V} = \mathbf{W}\mathbf{M}^{-1}, so that V⊤x=M−1W⊤x\mathbf{V}^\top\mathbf{x} = \mathbf{M}^{-1}\mathbf{W}^\top\mathbf{x}, and v\mathbf{v} the diagonal of νM−1\nu\mathbf{M}^{-1}), and then the ELBO equals log⁡pW(x)\log p_{\mathbf{W}}(\mathbf{x}). For any W\mathbf{W} the ELBO is at most log⁡pW(x)\log p_{\mathbf{W}}(\mathbf{x}). So the best ELBO lies between the best likelihood over orthogonal-column W\mathbf{W} and the best likelihood over all W\mathbf{W}. These agree, because Tipping and Bishop (1999) showed that the likelihood with fixed noise is maximized by W=U1:dzdiag⁡(max⁡(0,λi−ν))R\mathbf{W} = \mathbf{U}_{1:d_z}\operatorname{diag}\big(\sqrt{\max(0, \lambda_i - \nu)}\big)\mathbf{R} for any rotation R\mathbf{R}, and R=I\mathbf{R} = \mathbf{I} has orthogonal columns. (This is Lemma 1 of Lucas et al. 2019 with ν\nu in place of their noise variance.)

Why those directions. Tipping and Bishop's stationarity analysis shows that the columns of an optimal W\mathbf{W}, after the rotation R\mathbf{R} is removed, lie along eigenvectors of Σx\boldsymbol\Sigma_x. In that eigenbasis the model covariance WW⊤+νI\mathbf{W}\mathbf{W}^\top + \nu\mathbf{I} has variance ci=wi2+νc_i = w_i^2 + \nu along a direction with a column and ν\nu along the others. The expected log-likelihood is −12∑i(ln⁡ci+λi/ci)-\tfrac12\sum_i(\ln c_i + \lambda_i/c_i) plus a constant. For a direction with a column, ln⁡c+λ/c\ln c + \lambda/c over c≥νc \ge \nu is minimized at c=λc = \lambda if λ≥ν\lambda \ge \nu (so w2=λ−νw^2 = \lambda - \nu) and at c=νc = \nu otherwise (so w=0w = 0). Giving a column to direction ii saves g(λi)=ln⁡ν+λi/ν−ln⁡λi−1≥0g(\lambda_i) = \ln\nu + \lambda_i/\nu - \ln\lambda_i - 1 \ge 0, which grows with λi\lambda_i above ν\nu, so the dzd_z columns go to the largest eigenvalues.

Step 3, the numbers per direction. Write xi=ui⊤xx_i = \mathbf{u}_i^\top\mathbf{x}, with variance λi\lambda_i. For an active direction, Mii=wi2+ν=λiM_{ii} = w_i^2 + \nu = \lambda_i, so the posterior mean is mi=wixi/λim_i = w_ix_i/\lambda_i and the posterior variance is ν/λi\nu/\lambda_i. Then E[mi2]=wi2/λi=1−ν/λi\mathbb{E}[m_i^2] = w_i^2/\lambda_i = 1 - \nu/\lambda_i, and the Gaussian KL from §32.3, averaged over the data, is

12(E[mi2]+νλi−1−ln⁡νλi)=12(1−νλi+νλi−1+ln⁡λiν)=12ln⁡λiν.\tfrac12\Big(\mathbb{E}[m_i^2] + \frac{\nu}{\lambda_i} - 1 - \ln\frac{\nu}{\lambda_i}\Big) = \tfrac12\Big(1 - \frac{\nu}{\lambda_i} + \frac{\nu}{\lambda_i} - 1 + \ln\frac{\lambda_i}{\nu}\Big) = \tfrac12\ln\frac{\lambda_i}{\nu}.

The reconstruction along ui\mathbf{u}_i is wiziw_iz_i with zi=mi+ν/λi ϵiz_i = m_i + \sqrt{\nu/\lambda_i}\,\epsilon_i, where ϵi\epsilon_i is standard normal noise. Its mean part is wimi=(1−ν/λi)xiw_im_i = (1 - \nu/\lambda_i)x_i, which leaves an error (ν/λi)xi(\nu/\lambda_i)x_i with variance ν2/λi\nu^2/\lambda_i. Its noise part adds wi2ν/λi=(λi−ν)ν/λiw_i^2\nu/\lambda_i = (\lambda_i - \nu)\nu/\lambda_i. The total is ν2/λi+ν−ν2/λi=ν\nu^2/\lambda_i + \nu - \nu^2/\lambda_i = \nu. A direction without a column is not reconstructed at all, so its error is λi\lambda_i. An unused latent dimension has wj=0\mathbf{w}_j = \mathbf{0} and q(zj∣x)=N(0,1)q(z_j\mid\mathbf{x}) = \mathcal{N}(0, 1), so its rate is 0. These are exactly the reverse water-filling allocations.

Here are the numbers for the chapter's running spectrum.

A theorem about the global optimum is only useful if gradient descent finds it. The cell trains a linear β\beta-VAE on a five-dimensional spectrum (4,2,1,0.5,0.25)(4, 2, 1, 0.5, 0.25), rotated by a random orthogonal matrix so that the principal directions are not the coordinate axes. It uses σx2=0.5\sigma_x^2 = 0.5 and β=1.5\beta = 1.5, so ν=0.75\nu = 0.75, and dz=4d_z = 4. It descends the exact expected loss, whose gradients are short matrix expressions.

Python · cell 2

Gradient descent lands on the closed form to four decimals. Three directions clear the water at 0.75 and get rates of 0.837, 0.490, and 0.144 nats. The fourth latent dimension carries nothing. It is free to take the direction with eigenvalue 0.5, but 0.5 is below the water, so encoding that direction would cost more rate than it saves in error. The squared error is 3×0.75+0.5+0.25=3.03 \times 0.75 + 0.5 + 0.25 = 3.0. The next cell traces the whole curve for the running spectrum as β\beta varies, for each latent size.

Python · cell 3

In the plot, the solid black curve is Shannon's limit for this spectrum, and the dashed curve is the linear VAE with dz=2d_z = 2. That VAE follows the limit exactly until the water drops below the third eigenvalue. After that the third direction has no latent dimension to go to, and the curve leaves the limit. Each β\beta is one point on the curve, and the slope there is −1/(2βσx2)-1/(2\beta\sigma_x^2), steeper for small β\beta.

The widget below draws the same curves, under the eigenvalues drawn as bars with the water level across them. It fixes the decoder variance at σx2=0.5\sigma_x^2 = 0.5, since only the product βσx2\beta\sigma_x^2 matters. Change the spectrum, β\beta, and the number of latent dimensions dzd_z, or press Raise β, and watch directions sink below the water one at a time. Try the flat spectrum, where every direction crosses the water together and the code collapses all at once.

How does β trade rate against distortion?
Each bar is the data's variance along one principal direction. The part above the water level βσₓ² is encoded, with σₓ² fixed at 0.5.
Loading interactive figure…

This is the cleanest answer to an interview question that comes up often, "which latent dimensions of a VAE collapse, and why?" In the linear model the answer is exact. The directions whose variance is below βσx2\beta\sigma_x^2 collapse, and it is optimal that they do.

Interview

Solve the linear beta-VAE

Implement linear_beta_vae(eigs, sigma2_x, beta, d_z) for the optimum of the linear β\beta-VAE above. Return (rate, dist, active), three arrays with one entry per eigenvalue in the input order. rate is the rate of each principal direction in nats, dist is the squared error left in it, and active says whether it is encoded. The eigenvalues may come in any order. A direction exactly at the water level is not active.

Tests, hints, verified solutions, and AI help, with Pro at $7.99 a month.

Why the blur is a low-pass filter

The linear theorem also says which details a VAE drops first, the directions of smallest variance. For images that has a concrete meaning. Call an image model stationary if its statistics do not depend on position, with the image wrapped around at its borders. The eigenvectors of a stationary model's covariance are the sines and cosines of the Fourier basis. So its principal directions are spatial frequencies, patterns of stripes at a given spacing and angle. Its eigenvalues form the power spectrum, the variance at each frequency. The power spectra of natural images fall off roughly as 1/f21/f^2 with spatial frequency ff, an empirical regularity measured across many photographs (Field 1987; van der Schaaf and van Hateren 1996). Fine detail, the edges and texture, lives at high frequencies and has the smallest variance.

So reverse water-filling spends any budget on the lowest frequencies and drops everything above a cutoff. An image with its high frequencies removed is, by definition, a blurred image. The cell builds a 64×6464\times64 image model with a 1/f21/f^2 spectrum and finds the water level for several budgets in bits per pixel. It then shows a random image from the model next to its optimal reconstruction at 0.05 bits per pixel.

Python · cell 4

At 0.05 bits per pixel the optimal code keeps about 7 percent of the Fourier modes, all of them below a cutoff of about 9.5 cycles per image. Its reconstruction explains just over half the variance. Each kept mode is also shrunk by 1−ν/λi1 - \nu/\lambda_i, the posterior-mean factor from the derivation. The reconstruction looks like the image seen through frosted glass. Real VAEs are nonlinear and images are not Gaussian, so this is a model, not a measurement of any particular VAE. But the pressure it isolates is real. At a finite rate the ELBO saves most by dropping the details that carry the least variance, and in natural images those are the fine ones.

Posterior collapse

We have now seen collapse twice, as the gray corner of the bar toy and as directions below the water. Here is the definition, and how to measure it.

The two statistics answer different questions. Activity asks whether the code changes with the input, which is how a Gaussian encoder carries information in practice. The per-dimension rate asks what the dimension costs, and a dimension can cost something without carrying anything. Take an encoder whose output in dimension jj is N(3,1)\mathcal{N}(3, 1) for every input. It pays 12(9+1−1−0)=4.5\tfrac12(9 + 1 - 1 - 0) = 4.5 nats per example and tells the decoder nothing. Later in the section we will see exactly where such wasted nats live.

Both statistics take a few lines of code, and computing them is the first thing to do when a VAE looks suspicious.

Warm-up

Measure latent usage

Implement latent_usage(mu, logvar, thresh=1e-2). Its inputs mu and logvar have shape (N, d_z) and hold the mean and the log-variance of a diagonal Gaussian posterior for each of NN examples. Return (A, kl_dim, active), each of shape (d_z,). A is the activity defined above, the variance over examples of the means, with the 1/N1/N convention. kl_dim is the per-dimension rate, the average KL to N(0,1)\mathcal{N}(0, 1) in nats. active is the boolean mask A > thresh.

Tests, hints, verified solutions, and AI help, with Pro at $7.99 a month.

Collapse has two causes

Collapse has two different causes, and they call for different fixes. Telling them apart is the most useful skill in this section.

Collapse at the optimum. Sometimes collapse is what the objective wants. The linear theorem showed one case, where directions below the water level switch off at the global optimum. The theorem on powerful decoders showed another. Chen et al. (2017) state the general principle, which they call information preference. Any information that the decoder can model by itself is cheaper to model there. Routing it through the code costs an extra DKL(qϕ(z∣x)∥pθ(z∣x))D_{\mathrm{KL}}(q_\phi(\mathbf{z}\mid\mathbf{x})\Vert p_\theta(\mathbf{z}\mid\mathbf{x})), the gap between the ELBO and the log-likelihood (§32.2), while modeling it in the decoder costs nothing extra. An autoregressive decoder predicts each token or pixel from the previous ones, which is exactly what a language model does (§6.2). It can model nearly everything by itself, so it takes nearly everything.

Bowman et al. (2016) saw this on the Penn Treebank, a standard corpus of newspaper sentences. A VAE with an LSTM decoder, a recurrent network that writes one word at a time, was trained plainly. It converged to zero KL and the same likelihood as the LSTM language model alone. With two fixes defined below, KL annealing and word dropout, their reported model kept a KL of 2 nats. Its test negative log-likelihood bound was 101 nats per sentence, against the language model's exact 100.

Collapse by optimization. Other times the objective would like to use the code, but training never finds that solution. He et al. (2019) traced the mechanism. At initialization the encoder's qϕ(z∣x)q_\phi(\mathbf{z}\mid\mathbf{x}) and the model's true posterior pθ(z∣x)p_\theta(\mathbf{z}\mid\mathbf{x}) are both close to the prior. As the decoder learns, its true posterior starts to move. The encoder chases this moving target and lags behind, so the codes the decoder sees say little about the input. The gap term DKL(qϕ(z∣x)∥pθ(z∣x))D_{\mathrm{KL}}(q_\phi(\mathbf{z}\mid\mathbf{x})\Vert p_\theta(\mathbf{z}\mid\mathbf{x})) then pulls the true posterior back toward the uninformative encoder. The decoder learns to ignore the code, and both settle at the prior. Kingma et al. (2016) describe the same trap. Near the start, qϕ≈pq_\phi \approx p is attractive, the encoder's gradients are mostly noise, and the state is a stable equilibrium that is hard to leave.

The fixes, and which cause each one treats

Each fix below changes either the objective or only the path of training. A fix that changes the objective can act on collapse at the optimum. A fix that changes only the path can act only on collapse by optimization. Knowing which is which predicts when a fix will work.

  • KL annealing, or warm-up (Bowman et al. 2016; Sønderby et al. 2016). Replace β\beta by a schedule βt\beta_t that rises from 0 to 1 over training, linearly as βt=min⁡(1,t/Twarm)\beta_t = \min(1, t/T_{\text{warm}}) at step tt, or along a sigmoid. Early on the code is free, so the decoder learns to use it before the KL is charged in full. It changes only the path, since the final objective is the ordinary ELBO.
  • Cyclical annealing (Fu et al. 2019). Split training into MM cycles of TcycT_{\text{cyc}} steps and ramp within each cycle, βt=min⁡(1,τt/ρ)\beta_t = \min(1, \tau_t/\rho), where τt=(t mod Tcyc)/Tcyc\tau_t = (t \bmod T_{\text{cyc}})/T_{\text{cyc}} is the position inside the cycle and ρ\rho is the fraction of each cycle spent ramping. The paper's defaults are M=4M = 4 and ρ=0.5\rho = 0.5. Each return to β=0\beta = 0 lets the decoder learn again from informative codes, starting from the better codes of the previous cycle.
  • Free bits (Kingma et al. 2016), defined in the box below. A floor on each group's rate, below which the KL is not charged. This changes the objective.
  • A committed rate (Razavi et al. 2019). Choose the posterior and prior families so that their KL can never fall below some δ>0\delta \gt 0, which the paper calls a δ\delta-VAE. The simplest version gives the posterior a fixed variance σq2≠1\sigma_q^2 \neq 1. Then DKL(N(μ,σq2)∥N(0,1))≥12(σq2−1−ln⁡σq2)>0D_{\mathrm{KL}}(\mathcal{N}(\mu, \sigma_q^2)\Vert\mathcal{N}(0,1)) \ge \tfrac12(\sigma_q^2 - 1 - \ln\sigma_q^2) \gt 0 whatever the mean. The paper's sequence models instead pair an independent posterior with a prior that is correlated in time. Either way the minimum rate is paid whether or not the code is used, so collapsing no longer saves it.
  • Weaker decoders. Word dropout replaces a random fraction of the decoder's input words with an unknown-word token, so the decoder must get that information from the code (Bowman et al. 2016). The variational lossy autoencoder restricts an autoregressive image decoder to a small receptive field, so the code must carry the global structure (Chen et al. 2017).
  • Aggressive inference (He et al. 2019). Before each decoder update, update the encoder repeatedly until the ELBO stops improving, so it never lags. In their runs that took about 30 to 100 encoder steps per decoder step. They do this only early in training, until the mutual information between inputs and codes stops rising, and then return to ordinary updates.
  • Target the rate directly. Burgess et al. (2018) replace βR\beta\mathcal{R} by γ∣R−C∣\gamma\lvert\mathcal{R} - C\rvert, with a large γ\gamma (1,000 in their experiments) and a target capacity CC raised slowly during training (to 25 nats on the dSprites shapes dataset). GECO, short for generalized ELBO with constrained optimization (Rezende and Viola 2018), instead minimizes the KL subject to a constraint on the reconstruction error. The constraint enters the loss with a Lagrange multiplier, a weight that training raises while the error is above its target and lowers once it is below.

In plain words, each group gets λfb\lambda_{\text{fb}} nats of rate for free, averaged over the batch. While a group spends less than that, its KL term has zero gradient. The only force acting on it is then the reconstruction term, which rewards using the code. When the posterior and prior factorize across groups, as diagonal Gaussians do, the free-bits penalty is never smaller than the true KL. So the objective is still a lower bound on the log-likelihood, just a looser one.

Why the batch average? The floor is meant for a rate, and a rate is an average over data. Clamping each example separately would switch the KL gradient off example by example. It would hand every example its own allowance, however much the group carries on average. And it would loosen the bound further, since the average of a maximum is at least the maximum of the average.

Which of these fixes help in the linear model, where collapse is at the optimum? The cell trains the running example three ways, with σx2=0.5\sigma_x^2 = 0.5, β=1\beta = 1, and dz=3d_z = 3, so the third direction, λ=0.25\lambda = 0.25, sits below the water at 0.5. It trains plainly, with a linear warm-up over the first half of training, and with free bits at 0.25 nats per dimension.

Python · cell 5

In deep VAEs, where collapse is often an optimization trap, annealing does help. That is why NVAE warms up its KL term, and why the Ladder VAE paper found warm-up crucial for keeping its upper layers active (Sønderby et al. 2016). Both models appear in the hierarchical VAEs below. The table collects the fixes.

fixwhat it changesacts oncostwhere it is used
KL annealing, linear or sigmoidthe path only, βt\beta_t from 0 to 1collapse by optimizationone schedule length to tunesentence VAEs, Ladder VAE, NVAE
cyclical annealingthe path only, repeated rampscollapse by optimizationtwo settings, cycles and ramp fractiontext VAEs
free bitsthe objective, a rate floor per groupbotha looser bound, and the floor is a design choiceVAEs with inverse autoregressive flows, many hierarchical VAEs, DreamerV3
committed rate (δ\delta-VAE)the families, so the KL is at least δ\deltabothrestricted posterior or priorsequence VAEs
weaker decoder, word dropoutthe decodercollapse at the optimumworse likelihood, by designsentence VAEs, variational lossy autoencoder
aggressive inferencethe path, more encoder stepscollapse by optimization30 to 100 extra encoder steps per update, early ontext and image VAEs
target rate (∣R−C∣\lvert\mathcal{R} - C\rvert, GECO)the objective, a chosen rate or errorbothneeds a targetβ\beta-VAE capacity schedules, GECO
architecture (skip connections, top-down inference)which solutions are easy to reachmostly optimizationdesign effortVDVAE, NVAE
discrete codesthe posterior, a fixed rate of log⁡K\log K per codebotha quantizer to trainVQ-VAE (§32.5)
aggregate matching (AAE, MMD-VAE, WAE)the objective, a divergence between qϕ(z)q_\phi(\mathbf{z}) and p(z)p(\mathbf{z}) instead of a per-example KLcollapse at the optimum, since information is freeno likelihood bound, and a kernel or a critic to tuneInfoVAE, Wasserstein and adversarial autoencoders

In training code the schedules and the floor combine into one function of the step.

Interview

A KL penalty with warm-up, cyclical annealing, and free bits

Implement the KL part of a VAE training loss as it appears in real training code, kl_penalty(kl, step, schedule="constant", warmup=1000, cycle=1000, ratio=0.5, free_bits=0.0). The input kl has shape (B, d_z) and holds the closed-form KL of each example in each latent dimension, and step is an integer counted from 0. Return (beta, penalty). The weight beta follows the schedule. "constant" is 1, "linear" is min⁡(1,t/Twarm)\min(1, t/T_{\text{warm}}) with TwarmT_{\text{warm}} = warmup, and "cyclical" is the ramp-then-hold schedule of cyclical annealing, min⁡(1,τt/ρ)\min(1, \tau_t/\rho) with τt=(t mod Tcyc)/Tcyc\tau_t = (t \bmod T_{\text{cyc}})/T_{\text{cyc}}, cycle length TcycT_{\text{cyc}} = cycle, and ramp fraction ρ\rho = ratio. The penalty is

penalty=βt∑j=1dzmax⁡(λfb, 1B∑b=1BKLbj).\text{penalty} = \beta_t\sum_{j=1}^{d_z}\max\Big(\lambda_{\text{fb}},\ \frac1B\sum_{b=1}^{B}\mathrm{KL}_{bj}\Big).

With free_bits=0 this is βt\beta_t times the batch mean of each example's total KL.

Tests, hints, verified solutions, and AI help, with Pro at $7.99 a month.

The same experiment with a small nonlinear VAE in PyTorch shows the same behaviors. The data have two true factors pushed through a nonlinear map into 12 dimensions. The model has 8 latent dimensions, and a decoder variance of 0.3 sets a high water level.

🔥 In PyTorchfor a machine with PyTorch

The plain model uses 3 of its 8 dimensions and leaves the rest on the prior. Warm-up ends in the same place. Free bits lift every dimension to at least the 0.1-nat floor. The weakest of the three used dimensions drops from 0.5 to 0.1 nats, because its information is spread over the newly free ones, the same respreading the linear model showed. The activity statistic now counts all 8 units as active, even though six of them carry only about the free 0.1 nats. So a jump in active units after adding free bits is not, by itself, evidence of a better code. Whether the respreading is a fix or a waste depends on what you wanted the code for.

What the KL term really pays for

The rate pays for two different things, and only one of them helps. Splitting it in two explains both the wasted nats of the constant-offset encoder and why samples from the prior can look bad. The split needs one new object. The aggregate posterior qϕ(z)=1N∑nqϕ(z∣xn)q_\phi(\mathbf{z}) = \frac1N\sum_n q_\phi(\mathbf{z}\mid\mathbf{x}_n) is the distribution of codes over the whole dataset, the cloud you get by encoding every training example.

The decomposition is due to Hoffman and Johnson (2016), who called it ELBO surgery. In plain words, the rate pays for information, how much the code says about which example it came from. That can never exceed log⁡N\log N nats, the cost of naming one example out of NN. The rate also pays for a mismatch, how far the cloud of all codes is from the prior. Only the information helps reconstruction. The mismatch is pure cost, and it is also what breaks sampling. A VAE generates by drawing z\mathbf{z} from p(z)p(\mathbf{z}), but the decoder has only been trained on codes from qϕ(z)q_\phi(\mathbf{z}). Regions where the prior has mass and the aggregate posterior has little are called prior holes. Codes drawn there decode to things the decoder was never asked to produce, often blends like the halfway codes in the bar widget.

The bar toy makes this exact, because its code is one number and the integrals can be done on a grid.

Python · cell 6

With wide, overlapping posteriors almost all of the rate is information. As they narrow, the information climbs to its ceiling, ln⁡16=2.773\ln 16 = 2.773 nats, and stops. Past that point every extra nat of rate buys nothing for reconstruction and goes entirely into the mismatch, since sixteen narrow spikes look less and less like a standard normal. That is the precise sense in which a VAE trained to low distortion on a finite dataset gets bad samples.

Four responses follow from the decomposition.

  • Choose a better prior. For a fixed encoder, the prior that minimizes the mismatch is the aggregate posterior itself. The VampPrior approximates it with a mixture of the encoder's posteriors at mm learned pseudo-inputs a1,…,am\mathbf{a}_1, \dots, \mathbf{a}_m, points in data space, p(z)=1m∑k=1mqϕ(z∣ak)p(\mathbf{z}) = \frac1m\sum_{k=1}^{m} q_\phi(\mathbf{z}\mid\mathbf{a}_k) (Tomczak and Welling 2018).
  • Fit a second model to the codes. The two-stage VAE trains a second, small VAE on samples from qϕ(z)q_\phi(\mathbf{z}) and generates through both (Dai and Wipf 2019). Latent diffusion takes the same idea to its conclusion, fitting a diffusion model to the codes of an autoencoder.
  • Split further. The mismatch itself splits into a total correlation, DKL(qϕ(z)∥∏jqϕ(zj))D_{\mathrm{KL}}(q_\phi(\mathbf{z})\Vert\prod_j q_\phi(z_j)), which measures dependence between latent dimensions, and the sum of per-dimension mismatches (Chen et al. 2018). Penalizing the total correlation gives a handle on disentanglement, which a later subsection takes up.
  • Stop charging for information. Penalize only the mismatch, which is the family of models in the next subsection.
Research

ELBO surgery by Monte Carlo

Implement elbo_surgery(mu, logvar, S, rng) for a dataset of NN diagonal Gaussian posteriors with means mu and log-variances logvar, both of shape (N, d_z), and the prior N(0,I)\mathcal{N}(\mathbf{0}, \mathbf{I}). Return (mean_kl, mi, marginal_kl) as floats. mean_kl is the exact average KL. The other two are Monte Carlo estimates of IqI_q and DKL(qϕ(z)∥p(z))D_{\mathrm{KL}}(q_\phi(\mathbf{z})\Vert p(\mathbf{z})) from S samples z∼qϕ(z∣xn)\mathbf{z}\sim q_\phi(\mathbf{z}\mid\mathbf{x}_n) per example, drawn with rng. Use the same samples for both estimates. The function must stay finite for posteriors so narrow that their densities overflow.

Tests, hints, verified solutions, and AI help, with Pro at $7.99 a month.

Autoencoders that charge only for the mismatch

The decomposition says the rate pays for two things. Only one of them, the mismatch DKL(qϕ(z)∥p(z))D_{\mathrm{KL}}(q_\phi(\mathbf{z})\Vert p(\mathbf{z})), is what breaks sampling. The other, the information IqI_q, is what pushes the code to say less. Charging for it is what lets ignoring the code tie or win when the decoder is strong. A family of autoencoders keeps the first charge and drops the second. They minimize

Lagg=Epdata(x) Eqϕ(z∣x)[c(x,fθ(z))]+λagg D(qϕ(z),p(z)),\mathcal{L}_{\text{agg}} = \mathbb{E}_{p_{\text{data}}(\mathbf{x})}\,\mathbb{E}_{q_\phi(\mathbf{z}\mid\mathbf{x})}\big[c\big(\mathbf{x}, \mathbf{f}_\theta(\mathbf{z})\big)\big] + \lambda_{\text{agg}}\,\mathbb{D}\big(q_\phi(\mathbf{z}), p(\mathbf{z})\big),

where cc is a reconstruction cost (squared error, or a negative log-likelihood), D\mathbb{D} is any divergence that is zero exactly when its two arguments are equal, and λagg>0\lambda_{\text{agg}} \gt 0 is a weight. There is no per-example KL. In plain words, reconstruct well, and make the cloud of all codes look like the prior, but let each individual code say as much about its input as it likes.

The difficulty is that qϕ(z)q_\phi(\mathbf{z}) is a mixture over the whole dataset, so D\mathbb{D} has no closed form. It can be estimated from a minibatch, though. The codes of a minibatch, zb∼qϕ(z∣xb)\mathbf{z}_b \sim q_\phi(\mathbf{z}\mid\mathbf{x}_b) with xb\mathbf{x}_b drawn from the data, are samples from qϕ(z)q_\phi(\mathbf{z}), and samples from p(z)p(\mathbf{z}) cost nothing. Three models differ only in how they estimate D\mathbb{D} from those two batches.

  • The adversarial autoencoder (AAE, Makhzani et al. 2015) trains a discriminator in code space to tell codes from prior samples, and trains the encoder to fool it. In its ideal form that game minimizes the Jensen-Shannon divergence between qϕ(z)q_\phi(\mathbf{z}) and p(z)p(\mathbf{z}), as §32.6 derives for the image-space game of a tokenizer. The encoder can be deterministic, because the discriminator only ever sees samples.
  • The MMD-VAE of InfoVAE (Zhao, Song, and Ermon 2017) uses the maximum mean discrepancy, a kernel distance between two samples defined below.
  • The Wasserstein autoencoder (WAE, Tolstikhin et al. 2018) arrives at the same objective from optimal transport, and estimates D\mathbb{D} either with a discriminator (WAE-GAN) or with the maximum mean discrepancy (WAE-MMD).

The maximum mean discrepancy is the batch estimator these models made standard. Writing its unbiased form is a common interview coding question.

In plain words, the codes should be as similar to prior samples, on average, as each set is to itself. The estimate leaves out the diagonal terms k(zi,zi)k(\mathbf{z}_i, \mathbf{z}_i), because a point compared with itself is not a draw of two independent points. Because it is unbiased, it is often slightly negative when Q=PQ = P, which is correct, since its average is zero. §33.7 uses the same estimator to score generated samples against a known distribution.

∂ Why the estimate is unbiased, and what keeping the diagonal adds

For i≠ji \ne j, the codes zi\mathbf{z}_i and zj\mathbf{z}_j are independent draws from QQ, so each of the n(n−1)n(n-1) ordered pairs has expectation E k(z,z′)\mathbb{E}\,k(\mathbf{z}, \mathbf{z}'). The same holds for the m(m−1)m(m-1) prior pairs and the nmnm cross pairs, and linearity of expectation gives the result. A diagonal term k(zi,zi)=1k(\mathbf{z}_i, \mathbf{z}_i) = 1 (for both kernels above) is not a draw of k(z,z′)k(\mathbf{z}, \mathbf{z}'). Keeping the diagonal and dividing by n2n^2 and m2m^2, the plain "biased" estimate, adds 1n(1−E k(z,z′))+1m(1−E k(z~,z~′))>0\frac1n\big(1 - \mathbb{E}\,k(\mathbf{z}, \mathbf{z}')\big) + \frac1m\big(1 - \mathbb{E}\,k(\tilde{\mathbf{z}}, \tilde{\mathbf{z}}')\big) \gt 0 in expectation. That is a penalty that does not vanish even when the codes match the prior exactly.

Which kernel? The WAE authors found that the RBF kernel fails exactly when it is needed most. Early in training some codes land far from the prior. There exp⁡(−∥z−z~∥2/(2ℓ2))\exp(-\lVert\mathbf{z} - \tilde{\mathbf{z}}\rVert^2/(2\ell^2)) and its gradient are numerically zero, so nothing pulls those codes back. The IMQ kernel decays only as the inverse square of the distance, so far codes still feel a pull. WAE used it with C=2dzσz2C = 2d_z\sigma_z^2 for a prior N(0,σz2I)\mathcal{N}(\mathbf{0}, \sigma_z^2\mathbf{I}), which is the expected squared distance between two prior samples.

What do these models buy, and what do they give up? With no charge for information, reconstruction rewards every nat the code carries. So the incentive to collapse is gone even with a powerful decoder, and the mismatch penalty still shapes the code space for sampling. The cost is that Lagg\mathcal{L}_{\text{agg}} is not a bound on any likelihood, so these are autoencoders with a well-shaped code space, not density models. And nothing limits how narrow each posterior becomes, up to the log⁡N\log N ceiling on a finite dataset. InfoVAE reports that keeping the encoder's variances from vanishing is enough in practice, and WAE accepts the extreme case and uses deterministic encoders.

Research

The MMD penalty of a Wasserstein autoencoder

Implement mmd_penalty(Zq, Zp, kernel_scale, kernel="imq") for a batch of codes Zq of shape (n, d) and prior samples Zp of shape (m, d), where nn and mm may differ and both are at least 2. Return (mmd2, grad). The first is the unbiased estimate MMD⁡^2\widehat{\operatorname{MMD}}{}^2 above, as a float. The second is its gradient with respect to the codes, an array of shape (n, d), which is what trains the encoder. The kernel is either "rbf", exp⁡(−r2/(2ℓ2))\exp(-r^2/(2\ell^2)), or "imq", 1/(1+r2/(2ℓ2))1/(1 + r^2/(2\ell^2)), where rr is the distance between the two points and ℓ\ell is kernel_scale. Use no Python loops over points.

Tests, hints, verified solutions, and AI help, with Pro at $7.99 a month.

Beta-VAE and the limits of disentanglement

So far a large β\beta has been the problem. A β\beta-VAE sets β\beta above 1 on purpose, to make the code expensive (Higgins et al. 2017). The authors trained on synthetic images generated from a few independent factors, such as position, scale, rotation, and shape. With an expensive code, single latent dimensions often lined up with single factors, so that moving one latent number moved one factor. This property is called disentanglement. The hope was that it would make representations easier to interpret and make downstream tasks need fewer labeled examples.

Why should an expensive code be disentangled? The rate-distortion picture gives the most honest answer. Raising β\beta raises the water level, so the code keeps only the few directions of largest variance. With a diagonal posterior, each latent dimension prefers to hold one direction. In the linear model this is exact, since the optimum aligns latent dimensions with the principal directions whenever the eigenvalues are distinct. Rolinek et al. (2019) argue that the diagonal posterior has the same effect in deep VAEs. But principal directions are directions of large variance, and nothing guarantees that they are the factors a human would name. Burgess et al. (2018) give a related account, in which a slowly raised capacity CC lets factors enter the code one at a time, the ones that most reduce the reconstruction error first.

There is a deeper problem. The standard normal prior looks the same in every rotated coordinate system, and the likelihood cannot break that symmetry. For any orthogonal matrix Q\mathbf{Q}, the rotated code z′=Qz\mathbf{z}' = \mathbf{Q}\mathbf{z} has the same distribution N(0,I)\mathcal{N}(\mathbf{0},\mathbf{I}). The decoder z′↦fθ(Q⊤z′)\mathbf{z}'\mapsto\mathbf{f}_\theta(\mathbf{Q}^\top\mathbf{z}') then defines exactly the same distribution over data. So the likelihood gives no reason to prefer one set of latent axes over any rotation of them. Locatello et al. (2019) showed that this problem is not special to Gaussians.

In plain words, take any generative model with independent factors and a decoder. Composing the decoder with f−1\mathbf{f}^{-1} gives a second model with the same prior and the same distribution over data, whose latent coordinates each mix all the original factors. A method that sees only data cannot tell the two apart. So if it finds the disentangled one, that was due to its inductive biases, the assumptions built into the architecture, the diagonal posterior, and the optimizer, not to the data.

Interpretability research meets the same wall from another side. The sparse autoencoders of §23.6 get their features from an explicit sparsity bias, not from the data alone. An interviewer may ask whether a β\beta-VAE "discovers the true factors". The precise answer is that it finds high-variance directions aligned with its diagonal posterior. Nothing in the data alone can single out the true factors.

Hierarchical VAEs

The most successful answer to blur and collapse in likelihood-based VAEs is depth in the latent space itself. A hierarchical VAE has LL groups of latents generated top-down, each group conditioned on the ones above it,

pθ(x,z1:L)=p(zL)∏l=1L−1pθ(zl∣z>l)  pθ(x∣z1:L),p_\theta(\mathbf{x}, \mathbf{z}_{1:L}) = p(\mathbf{z}_L)\prod_{l=1}^{L-1}p_\theta(\mathbf{z}_l\mid\mathbf{z}_{\gt l})\;p_\theta(\mathbf{x}\mid\mathbf{z}_{1:L}),

where z>l=(zl+1,…,zL)\mathbf{z}_{\gt l} = (\mathbf{z}_{l+1}, \dots, \mathbf{z}_L). The top groups are small and coarse, such as a 1×11\times1 or 4×44\times4 map in an image model, and the lower groups are fine. The encoder uses the same top-down order, qϕ(z1:L∣x)=∏lqϕ(zl∣x,z>l)q_\phi(\mathbf{z}_{1:L}\mid\mathbf{x}) = \prod_l q_\phi(\mathbf{z}_l\mid\mathbf{x}, \mathbf{z}_{\gt l}). The chain rule of KL divergence then splits the rate into one term per group,

DKL(qϕ(z1:L∣x) ∥ pθ(z1:L))=∑l=1LEqϕ(z>l∣x)[DKL(qϕ(zl∣x,z>l) ∥ pθ(zl∣z>l))].D_{\mathrm{KL}}\big(q_\phi(\mathbf{z}_{1:L}\mid\mathbf{x})\,\Vert\,p_\theta(\mathbf{z}_{1:L})\big) = \sum_{l=1}^{L}\mathbb{E}_{q_\phi(\mathbf{z}_{\gt l}\mid\mathbf{x})}\Big[D_{\mathrm{KL}}\big(q_\phi(\mathbf{z}_l\mid\mathbf{x},\mathbf{z}_{\gt l})\,\Vert\,p_\theta(\mathbf{z}_l\mid\mathbf{z}_{\gt l})\big)\Big].

It follows by writing the log ratio of the two products as a sum of per-group log ratios and taking the expectation one group at a time. In plain words, each group's prior is now learned and conditional, so a group pays only for what the groups above it did not already predict. Collapse can happen group by group, and the per-group rate is the thing to monitor.

Three designs mark the progress.

  • Ladder VAE (Sønderby et al. 2016) introduced the top-down encoder. Each group's posterior merges a bottom-up Gaussian estimate N(μ^l,σ^l2)\mathcal{N}(\hat{\boldsymbol\mu}_l, \hat{\boldsymbol\sigma}^2_l), computed from x\mathbf{x}, with the top-down prior N(μp,l,σp,l2)\mathcal{N}(\boldsymbol\mu_{p,l}, \boldsymbol\sigma^2_{p,l}). The merge is a precision-weighted average, σq,l−2=σ^l−2+σp,l−2\boldsymbol\sigma_{q,l}^{-2} = \hat{\boldsymbol\sigma}_l^{-2} + \boldsymbol\sigma_{p,l}^{-2} and μq,l=σq,l2⊙(μ^l⊙σ^l−2+μp,l⊙σp,l−2)\boldsymbol\mu_{q,l} = \boldsymbol\sigma_{q,l}^2\odot(\hat{\boldsymbol\mu}_l\odot\hat{\boldsymbol\sigma}_l^{-2} + \boldsymbol\mu_{p,l}\odot\boldsymbol\sigma_{p,l}^{-2}), which is the product of the two Gaussian densities. The authors found warm-up and batch normalization crucial for keeping the upper groups active.
  • NVAE (Vahdat and Kautz 2020) writes each posterior relative to its prior, q=N(μp+Δμ,(σpΔσ)2)q = \mathcal{N}(\mu_p + \Delta\mu, (\sigma_p\Delta\sigma)^2) in each dimension. The KL becomes 12(Δμ2/σp2+Δσ2−ln⁡Δσ2−1)\tfrac12\big(\Delta\mu^2/\sigma_p^2 + \Delta\sigma^2 - \ln\Delta\sigma^2 - 1\big), so it depends mainly on the encoder's relative outputs Δμ\Delta\mu and Δσ\Delta\sigma. NVAE adds spectral regularization, a penalty on each layer's largest singular value, to keep the KL from blowing up. During KL warm-up it also balances the KL across groups so that none switches off. It reached 2.91 bits per dimension on CIFAR-10, in the units of §32.3.
  • VDVAE (Child 2021) went deep, with 45 stochastic layers on CIFAR-10 for 2.87 bits per dimension, and needed neither free bits nor KL warm-up. Its appendix shows the architecture deciding collapse. In a 73-layer model on ImageNet 32×3232\times32, removing the residual connections from the top-down blocks left the first 45 layers encoding nothing. A learned upsampler left the first 13 encoding nothing. With nearest-neighbor upsampling, the first layers all encoded information.

Two formulas from these designs are worth being able to write from memory, the Ladder merge and NVAE's residual KL. The chain rule above is the check that ties them together. In a two-level model whose every piece is linear and Gaussian, the joint posterior and the joint prior are both Gaussians over (z1,z2)(\mathbf{z}_1, \mathbf{z}_2). So the joint KL can be computed directly with the full-covariance Gaussian KL of §32.3 and compared with the sum of the per-group KLs.

Research

Ladder merge, NVAE's residual KL, and the KL chain rule

Implement three functions, all elementwise over the latent dimensions.

  1. ladder_merge(mu_hat, logvar_hat, mu_p, logvar_p) returns (mu_q, logvar_q), the Ladder VAE posterior that combines a bottom-up estimate N(μ^,σ^2)\mathcal{N}(\hat\mu, \hat\sigma^2) with a top-down prior N(μp,σp2)\mathcal{N}(\mu_p, \sigma_p^2) by the precision-weighted average above.
  2. nvae_residual_kl(delta_mu, log_delta_sigma, sigma_p) returns, per dimension, DKL(N(μp+Δμ,(σpΔσ)2) ∥ N(μp,σp2))D_{\mathrm{KL}}\big(\mathcal{N}(\mu_p + \Delta\mu, (\sigma_p\Delta\sigma)^2)\,\Vert\,\mathcal{N}(\mu_p, \sigma_p^2)\big). Here log_delta_sigma is ln⁡Δσ\ln\Delta\sigma and sigma_p is a standard deviation.
  3. two_level_kl(mu_hat1, logvar_hat1, A, logvar_p1, m2, logvar2) returns (kl_top, kl_bottom) as floats for a two-level hierarchy with z2∈Rd2\mathbf{z}_2 \in \R^{d_2}, z1∈Rd1\mathbf{z}_1 \in \R^{d_1}, and A∈Rd1×d2\mathbf{A} \in \R^{d_1\times d_2}. The prior is p(z2)=N(0,I)p(\mathbf{z}_2) = \mathcal{N}(\mathbf{0}, \mathbf{I}) and p(z1∣z2)=N(Az2,diag⁡σp,12)p(\mathbf{z}_1\mid\mathbf{z}_2) = \mathcal{N}(\mathbf{A}\mathbf{z}_2, \operatorname{diag}\boldsymbol\sigma_{p,1}^2). The posterior is q(z2∣x)=N(m2,diag⁡v2)q(\mathbf{z}_2\mid\mathbf{x}) = \mathcal{N}(\mathbf{m}_2, \operatorname{diag}\mathbf{v}_2), and q(z1∣x,z2)q(\mathbf{z}_1\mid\mathbf{x}, \mathbf{z}_2) is the Ladder merge of the bottom-up estimate N(μ^1,diag⁡σ^12)\mathcal{N}(\hat{\boldsymbol\mu}_1, \operatorname{diag}\hat{\boldsymbol\sigma}_1^2) with p(z1∣z2)p(\mathbf{z}_1\mid\mathbf{z}_2). kl_top is DKL(q(z2∣x)∥p(z2))D_{\mathrm{KL}}(q(\mathbf{z}_2\mid\mathbf{x})\Vert p(\mathbf{z}_2)). kl_bottom is Eq(z2∣x)[DKL(q(z1∣x,z2)∥p(z1∣z2))]\mathbb{E}_{q(\mathbf{z}_2\mid\mathbf{x})}\big[D_{\mathrm{KL}}(q(\mathbf{z}_1\mid\mathbf{x}, \mathbf{z}_2)\Vert p(\mathbf{z}_1\mid\mathbf{z}_2))\big], with the expectation done in closed form. The arguments are μ^1\hat{\boldsymbol\mu}_1, log⁡σ^12\log\hat{\boldsymbol\sigma}_1^2, A\mathbf{A}, log⁡σp,12\log\boldsymbol\sigma_{p,1}^2, m2\mathbf{m}_2, and log⁡v2\log\mathbf{v}_2, in that order.

The tests check that kl_top + kl_bottom equals the joint KL of the two Gaussians over (z1,z2)(\mathbf{z}_1, \mathbf{z}_2).

Tests, hints, verified solutions, and AI help, with Pro at $7.99 a month.

Two neighbors of this idea deserve a sentence each. A richer posterior can replace depth. The inverse autoregressive flow pushes a diagonal Gaussian through invertible autoregressive maps so that the posterior can be correlated (Kingma et al. 2016). That is a normalizing flow, a model family that flow matching revisits in continuous time. And a diffusion model is a hierarchical VAE with two special choices. Its encoder is fixed rather than learned, with each layer adding a little Gaussian noise, and it has as many layers as noise levels. That is how diffusion models derive their training loss from the same ELBO.

Choosing the KL weight in practice

The ELBO cannot choose a point on the rate-distortion curve for you (Alemi et al. 2018), so practitioners choose one deliberately, by what the code is for. Two production systems show how far from 1 that choice can land.

The second choice does not contradict anything above. A latent-diffusion autoencoder is never sampled from its prior. A diffusion model is trained afterwards on its codes, which is the two-stage idea, so prior holes do not matter and there is no reason to pay for matching N(0,I)\mathcal{N}(\mathbf{0},\mathbf{I}). The choice comes down to what the code is for.

you needset the KL weightwhy
likelihoods (compression, density estimation)β=1\beta = 1, with depth to put the rate where it helps, as in NVAE and VDVAEonly β=1\beta = 1 gives a bound on the log-likelihood
a representation for downstream usea target rate or distortion, enforced by a capacity schedule or GECOthe ELBO alone does not fix how much the code carries
codes for a second-stage generatora tiny β\beta, or discrete codes whose rate is fixed by constructionthe generator learns the aggregate posterior, so the mismatch is irrelevant

Discrete codes are where §32.5 begins.

Read more

Watch next

🎬 L4 Latent Variable Models (VAE) -- CS294-158-SP20 Deep Unsupervised Learning -- UC Berkeley · Pieter AbbeelBerkeley's deep unsupervised learning lecture on VAEs. It covers the ELBO, the main VAE variants, posterior collapse and its fixes, and beta-VAE, at the level of this section.
🎬 Challenging Common Assumptions in the Unsupervised Learning of Disentangled Representations · Yannic KilcherA walkthrough of the Locatello et al. impossibility theorem and the 12,000-model study that this section's disentanglement part summarizes.
🎬 NVAE: A Deep Hierarchical Variational Autoencoder (Paper Explained) · Yannic KilcherExplains hierarchical VAEs as NVAE builds them, with top-down inference, residual normal distributions, and spectral regularization, which complements the hierarchical VAE part of this section.