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, β, 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, such as an image, is described by a short codez∈Rdz. The encoder maps an input to a Gaussian distribution over codes, qϕ(z∣x)=N(μϕ(x),diagσϕ2(x)), where ϕ 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 decoderpθ(x∣z), with weights θ, maps a code back to a distribution over inputs. The priorp(z)=N(0,I) is where codes come from when we generate. The prior and the decoder together also define an exact posterior pθ(z∣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,
In plain words, the first term rewards reconstructing 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/ln2=1.44 bits). The whole objective is a lower bound on the log-likelihood logpθ(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 β 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 β-VAEs and hierarchical VAEs can and cannot do.
Two formulas from §32.3 recur throughout. A Gaussian decoder with mean network fθ and a fixed variance σx2, pθ(x∣z)=N(fθ(z),σx2I), has negative log-likelihood
−logpθ(x∣z)=2σx2∥x−fθ(z)∥2+2dxlog(2πσx2),
a squared error scaled by 1/(2σx2) plus a constant. And the KL of a one-dimensional Gaussian N(μ,σ2) to the standard normal is 21(μ2+σ2−1−lnσ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), 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,…,15. Image c is a narrow bar, a smooth bump of brightness centered on pixel c, and neighboring images differ by a one-pixel shift. The code is one number. The encoder sends image c to N(acˉ,s2), where cˉ=c−7.5 is the bump's position measured from the middle. Two numbers set the encoder, the spacing a between the code means and the width s of each posterior.
What decides the blur is the ratio r=s/a, the width of one posterior in units of the spacing. With r small the posteriors do not touch, and with r large they pile on top of each other. The rate, the average KL to the prior, depends on both numbers. For a given overlap r the cheapest spacing is a2=1/(v+r2), where v=21.25 is the variance of the positions cˉ, and the rate is then
R(r)=21ln(1+r2v)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/r2.
∂ Where the rate of the bar toy comes from
The average KL to N(0,1) of the posteriors N(acˉ,s2) is 21(a2v+s2−1−lns2), with v=161∑ccˉ2=21.25. Hold r=s/a fixed, so s2=r2a2, and minimize over a. The derivative a(v+r2)−1/a vanishes at a2=1/(v+r2). Then a2v+s2=1, so the codes as a whole have variance 1, matching the prior, and the rate is 21(−lns2)=21ln((v+r2)/r2). The squared error of the best decoder depends only on r, because in the rescaled coordinate u=z/a each posterior is N(cˉ,r2) and the weights are wc∝e−(u−cˉ)2/(2r2).
The cell computes the best decoder on a grid of codes. For each β it picks the overlap that minimizes the loss, the squared error over 2σx2 plus β times the rate, with σx2=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), the exponential of the entropy of the weights wc. 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), where fi(z) is its mean for pixel i. 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) 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. The squared error is divided by 2σx2 and the KL is multiplied by β, so raising σx2 does the same thing as raising β. §32.3 called this a hidden KL weight, and the linear model below shows that only the product βσx2 matters. So a VAE trained with a large fixed σx2 is blurry for the same reason as one trained with a large β. 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 β is a price. Minimizing D+βR buys a nat of rate only if it lowers the distortion by at least β nats. With β=2, for example, an extra nat in the code must save 2 nats of distortion to be worth it. A large β 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) pair of each one. The lower-left edge of that cloud is a curve D(R), the least distortion achievable at each rate. Minimizing D+βR lands on that edge, at the point where a straight line of slope −β just touches it. Where the curve is smooth, setting the derivative of D(R)+βR to zero gives dD/dR=−β. In plain words, each β selects one point on the trade-off curve, and β is the slope there.
What point does the ordinary β=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 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 ignoring the code wins outright. Below β=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 ignored its code, and one trained at β=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 informationI(x;x^) between a source x and a reconstruction 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,
R⋆(Dsq)=p(x^∣x):E∥x−x^∥2≤DsqminI(x;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 x be Gaussian with variance 4, and allow a squared error of 1. The answer is 21ln(4/1)=0.693 nats, exactly 1 bit. In general one Gaussian number with variance λ costs 21ln(λ/D) nats at error D, 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 as a bar and pour water to height ν. 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,λ) and let x^ be any reconstruction with E(x−x^)2≤D≤λ. Using differential entropies h,
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 D. The bound is achieved by the "backward channel" x=x^+n with x^∼N(0,λ−D) and independent n∼N(0,D), for which every inequality is an equality. If D≥λ, the reconstruction 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). The first sum uses independence, and the inequality again uses that conditioning cannot increase entropy. With Di=E(xi−x^i)2, the one-component bound gives I(x;x^)≥∑imax(0,21ln(λi/Di)), and describing each component on its own with its own backward channel achieves this. What is left is to split the budget, minimizing ∑i21ln(λi/Di) over 0<Di≤λi subject to ∑iDi=Dsq.
Splitting the budget. Take Dsq<∑iλi (otherwise Di=λi for all i costs nothing). A minimizer exists, because the objective is continuous on the feasible set and grows without bound as any Di→0. An exchange argument pins it down. Suppose a minimizer had components i and j with Di<λi and Di<Dj. Move a small amount ε>0 of distortion from j to i. This stays feasible, because i has room below λi and the budget is unchanged. The objective changes at the rate −2Di1+2Dj1<0, so the move lowers it, a contradiction. (In words, −ln is convex, so a unit of distortion saves more rate where the distortion is still small.) Hence every component with Di<λi has Di≥Dj for all j. All such components share the largest value, call it ν, and every other component has Di=λi≤ν. Both cases read Di=min(λi,ν). At least one component has Di<λi, since otherwise the budget would be ∑iλi. The budget fixes ν uniquely, because ∑imin(λi,ν) is strictly increasing in ν below maxiλ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 ν as the budget's multiplier.) Finally, with k≥1 components above the water, R⋆=∑active21lnλi−2klnν and Dsq=kν+∑restλi, so dR⋆/dDsq=(−k/(2ν))/k=−1/(2ν).
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,ν) in the input order. If D is at least the total variance, return nu = max(eigs), rate 0, and Di=λi. Solve for ν exactly, without bisection.
import numpy as np
def water_fill(eigs, D):
lam = np.asarray(eigs, dtype=float)
nu = D / len(lam) # placeholder: assumes every component is above the water
Di = np.full_like(lam, nu)
return nu, float(np.sum(0.5 * np.log(lam / nu))), Di
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 β puts it. Given enough latent dimensions, it lands exactly on Shannon's limit, and β sets the water level.
The data are centered, with covariance Σx=UΛU⊤. Its eigenvalues are λ1≥⋯≥λdx and its orthonormal eigenvectors ui 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) with W∈Rdx×dz and a fixed σx2. The encoder is linear too, with a diagonal covariance shared by all inputs, qϕ(z∣x)=N(V⊤x,diag(v)) with V∈Rdx×dz. This is the linear VAE of §32.3, also used by Lucas et al. (2019). We drop the constant 2dxlog(2πσx2) from the distortion and write D′=Dsq/(2σx2).
Recall that probabilistic PCA (pPCA) is the model x=Wz+noise with z∼N(0,I) and Gaussian noise of a fixed variance. Its maximum-likelihood 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,β 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 ν 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, 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. It becomes E∥x−Wz∥2/(2βσx2)+R. Up to a constant, that is the negative expected ELBO of the same linear VAE with its decoder variance set to ν=βσx2. So we need the best β=1 linear VAE with decoder noise ν.
Step 2, the ELBO can be made tight, so we are maximizing the pPCA likelihood. For a fixed W the model is probabilistic PCA with noise ν. Its exact posterior is N(M−1W⊤x,νM−1) with M=W⊤W+νI (§32.2). If the columns of W are orthogonal, 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, so that V⊤x=M−1W⊤x, and v the diagonal of νM−1), and then the ELBO equals logpW(x). For any W the ELBO is at most logpW(x). So the best ELBO lies between the best likelihood over orthogonal-column W and the best likelihood over all 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 for any rotation R, and R=I has orthogonal columns. (This is Lemma 1 of Lucas et al. 2019 with ν in place of their noise variance.)
Why those directions. Tipping and Bishop's stationarity analysis shows that the columns of an optimal W, after the rotation R is removed, lie along eigenvectors of Σx. In that eigenbasis the model covariance WW⊤+νI has variance ci=wi2+ν along a direction with a column and ν along the others. The expected log-likelihood is −21∑i(lnci+λi/ci) plus a constant. For a direction with a column, lnc+λ/c over c≥ν is minimized at c=λ if λ≥ν (so w2=λ−ν) and at c=ν otherwise (so w=0). Giving a column to direction i saves g(λi)=lnν+λi/ν−lnλi−1≥0, which grows with λi above ν, so the dz columns go to the largest eigenvalues.
Step 3, the numbers per direction. Write xi=ui⊤x, with variance λi. For an active direction, Mii=wi2+ν=λi, so the posterior mean is mi=wixi/λi and the posterior variance is ν/λi. Then E[mi2]=wi2/λi=1−ν/λi, and the Gaussian KL from §32.3, averaged over the data, is
The reconstruction along ui is wizi with zi=mi+ν/λiϵi, where ϵi is standard normal noise. Its mean part is wimi=(1−ν/λi)xi, which leaves an error (ν/λi)xi with variance ν2/λi. Its noise part adds wi2ν/λi=(λi−ν)ν/λi. The total is ν2/λi+ν−ν2/λi=ν. A direction without a column is not reconstructed at all, so its error is λi. An unused latent dimension has wj=0 and q(zj∣x)=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 β-VAE on a five-dimensional spectrum (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 and β=1.5, so ν=0.75, and dz=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.0. The next cell traces the whole curve for the running spectrum as β 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=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 β is one point on the curve, and the slope there is −1/(2βσx2), steeper for small β.
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, since only the product βσx2 matters. Change the spectrum, β, and the number of latent dimensions dz, 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 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 β-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/f2 with spatial frequency f, 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×64 image model with a 1/f2 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−ν/λ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 j is N(3,1) for every input. It pays 21(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 N 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/N convention. kl_dim is the per-dimension rate, the average KL to N(0,1) in nats. active is the boolean mask A > thresh.
import numpy as np
def latent_usage(mu, logvar, thresh=1e-2):
raise NotImplementedError
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)), 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) and the model's true posterior pθ(z∣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)) 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ϕ≈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 β by a schedule βt that rises from 0 to 1 over training, linearly as βt=min(1,t/Twarm) at step t, 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 M cycles of Tcyc steps and ramp within each cycle, βt=min(1,τt/ρ), where τt=(tmodTcyc)/Tcyc is the position inside the cycle and ρ is the fraction of each cycle spent ramping. The paper's defaults are M=4 and ρ=0.5. Each return to β=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, which the paper calls a δ-VAE. The simplest version gives the posterior a fixed variance σq2=1. Then DKL(N(μ,σq2)∥N(0,1))≥21(σq2−1−lnσq2)>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 by γ∣R−C∣, with a large γ (1,000 in their experiments) and a target capacity C 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 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, β=1, and dz=3, so the third direction, λ=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.
fix
what it changes
acts on
cost
where it is used
KL annealing, linear or sigmoid
the path only, βt from 0 to 1
collapse by optimization
one schedule length to tune
sentence VAEs, Ladder VAE, NVAE
cyclical annealing
the path only, repeated ramps
collapse by optimization
two settings, cycles and ramp fraction
text VAEs
free bits
the objective, a rate floor per group
both
a looser bound, and the floor is a design choice
VAEs with inverse autoregressive flows, many hierarchical VAEs, DreamerV3
committed rate (δ-VAE)
the families, so the KL is at least δ
both
restricted posterior or prior
sequence VAEs
weaker decoder, word dropout
the decoder
collapse at the optimum
worse likelihood, by design
sentence VAEs, variational lossy autoencoder
aggressive inference
the path, more encoder steps
collapse by optimization
30 to 100 extra encoder steps per update, early on
the objective, a divergence between qϕ(z) and p(z) instead of a per-example KL
collapse at the optimum, since information is free
no likelihood bound, and a kernel or a critic to tune
InfoVAE, 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) with Twarm = warmup, and "cyclical" is the ramp-then-hold schedule of cyclical annealing, min(1,τt/ρ) with τt=(tmodTcyc)/Tcyc, cycle length Tcyc = cycle, and ramp fraction ρ = ratio. The penalty is
penalty=βtj=1∑dzmax(λfb,B1b=1∑BKLbj).
With free_bits=0 this is β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 posteriorqϕ(z)=N1∑nqϕ(z∣xn) 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 logN nats, the cost of naming one example out of N. 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 from p(z), but the decoder has only been trained on codes from qϕ(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, ln16=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 m learned pseudo-inputs a1,…,am, points in data space, p(z)=m1∑k=1mqϕ(z∣ak) (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) 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)), 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 N diagonal Gaussian posteriors with means mu and log-variances logvar, both of shape (N, d_z), and the prior N(0,I). Return (mean_kl, mi, marginal_kl) as floats. mean_kl is the exact average KL. The other two are Monte Carlo estimates of Iq and DKL(qϕ(z)∥p(z)) from S samples z∼qϕ(z∣xn) 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.
import numpy as np
def elbo_surgery(mu, logvar, S, rng):
mean_kl = float((0.5 * (mu**2 + np.exp(logvar) - 1.0 - logvar)).sum(1).mean())
return mean_kl, 0.0, mean_kl # placeholder: pretends the code carries no information
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)), is what breaks sampling. The other, the information Iq, 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
where c is a reconstruction cost (squared error, or a negative log-likelihood), D is any divergence that is zero exactly when its two arguments are equal, and λagg>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) is a mixture over the whole dataset, so D has no closed form. It can be estimated from a minibatch, though. The codes of a minibatch, zb∼qϕ(z∣xb) with xb drawn from the data, are samples from qϕ(z), and samples from p(z) cost nothing. Three models differ only in how they estimate 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) and p(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 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), 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=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=j, the codes zi and zj are independent draws from Q, so each of the n(n−1) ordered pairs has expectation Ek(z,z′). The same holds for the m(m−1) prior pairs and the nm cross pairs, and linearity of expectation gives the result. A diagonal term k(zi,zi)=1 (for both kernels above) is not a draw of k(z,z′). Keeping the diagonal and dividing by n2 and m2, the plain "biased" estimate, adds n1(1−Ek(z,z′))+m1(1−Ek(z~,z~′))>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)) 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σz2 for a prior N(0,σz2I), 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 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 logN 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 n and m may differ and both are at least 2. Return (mmd2, grad). The first is the unbiased estimate MMD2 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)), or "imq", 1/(1+r2/(2ℓ2)), where r is the distance between the two points and ℓ 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 β has been the problem. A β-VAE sets β 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 β 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 C 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, the rotated code z′=Qz has the same distribution N(0,I). The decoder z′↦fθ(Q⊤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 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 β-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 L groups of latents generated top-down, each group conditioned on the ones above it,
where z>l=(zl+1,…,zL). The top groups are small and coarse, such as a 1×1 or 4×4 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). The chain rule of KL divergence then splits the rate into one term per group,
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), computed from x, with the top-down prior N(μp,l,σp,l2). The merge is a precision-weighted average, σq,l−2=σ^l−2+σp,l−2 and μq,l=σq,l2⊙(μ^l⊙σ^l−2+μp,l⊙σ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) in each dimension. The KL becomes 21(Δμ2/σp2+Δσ2−lnΔσ2−1), so it depends mainly on the encoder's relative outputs Δμ and Δσ. 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×32, 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). 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.
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) with a top-down prior N(μp,σp2) by the precision-weighted average above.
nvae_residual_kl(delta_mu, log_delta_sigma, sigma_p) returns, per dimension, DKL(N(μp+Δμ,(σpΔσ)2)∥N(μp,σp2)). Here log_delta_sigma is lnΔσ and sigma_p is a standard deviation.
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, z1∈Rd1, and A∈Rd1×d2. The prior is p(z2)=N(0,I) and p(z1∣z2)=N(Az2,diagσp,12). The posterior is q(z2∣x)=N(m2,diagv2), and q(z1∣x,z2) is the Ladder merge of the bottom-up estimate N(μ^1,diagσ^12) with p(z1∣z2). kl_top is DKL(q(z2∣x)∥p(z2)). kl_bottom is Eq(z2∣x)[DKL(q(z1∣x,z2)∥p(z1∣z2))], with the expectation done in closed form. The arguments are μ^1, logσ^12, A, logσp,12, m2, and logv2, in that order.
The tests check that kl_top + kl_bottom equals the joint KL of the two Gaussians over (z1,z2).
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). The choice comes down to what the code is for.
you need
set the KL weight
why
likelihoods (compression, density estimation)
β=1, with depth to put the rate where it helps, as in NVAE and VDVAE
only β=1 gives a bound on the log-likelihood
a representation for downstream use
a target rate or distortion, enforced by a capacity schedule or GECO
the ELBO alone does not fix how much the code carries
codes for a second-stage generator
a tiny β, or discrete codes whose rate is fixed by construction
the generator learns the aggregate posterior, so the mismatch is irrelevant
Alemi et al. (2018). Fixing a Broken ELBO. The rate-distortion view of VAEs, the bounds H−D≤I≤R, and experiments showing equal ELBOs with very different codes.
Zhao, Song & Ermon (2017). InfoVAE: Information Maximizing Variational Autoencoders. Reweights the information and mismatch parts of the KL separately, and shows the ELBO, the beta-VAE, and the adversarial autoencoder as members of one family.
Tolstikhin et al. (2018). Wasserstein Auto-Encoders. The optimal-transport derivation of an aggregate-matching autoencoder, deterministic encoders, and why the IMQ kernel beats the RBF kernel for MMD in code space.
Cover & Thomas (2006). Elements of Information Theory, chapter 10. Rate-distortion theory, the Gaussian source, and reverse water-filling, proved carefully.
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.