NVAE: A Deep Hierarchical Variational Autoencoder
- Publication
- NeurIPS 2020Conference
- First submitted to arXiv
- arXiv:2007.03898
Cite this paper · BibTeX
The citation identifies the linked source version. It cites the original paper and its authors.
@misc{imagegenerationnvae2020,
title = {{NVAE: A Deep Hierarchical Variational Autoencoder}},
author = {Arash Vahdat and Jan Kautz},
year = {2020},
eprint = {2007.03898},
archivePrefix = {arXiv},
url = {https://arxiv.org/abs/2007.03898}
}
The introduction of the NVAE paper says, "In this paper, we aim to make VAEs great again by architecture design." The phrasing sounds familiar. The N in the model's name stands for the French Nouveau.
VAEs needed to be great "again" because their report card in 2020 didn't look good. Compare log-likelihoods on CIFAR-10: among VAEs without an autoregressive decoder, the best at the time was BIVA at 3.08 bits/dim, while VFlow, a flow model without autoregressive components, had already reached 2.98, and the autoregressive PixelSNAIL was at 2.85. The images they sampled were mostly a blur, too.
The two authors, from NVIDIA, argue that VAE research had spent nearly all its effort on the statistical side, things like better approximate posteriors, tighter bounds and dealing with posterior collapse, while the network architectures were mostly borrowed straight from classification. This paper goes the other way: it leaves the VAE objective alone, concentrates on designing the network, and adds a few techniques that let thirty-some groups of latent variables train stably. The end result is 2.91 bits/dim on CIFAR-10; the authors also say it is the first VAE successfully applied to 256×256 natural images.
This note first follows one CIFAR-10 image through the whole network, then looks at the two designs for stable training, and finally reads the numbers, along with what the community ran into when reproducing results with the official code.
Defining the problem
bits/dim
Every paper in this line compares models in bits/dim, so let's pin it down first.
The probability a model assigns to an image is . Use this model for lossless compression, and the image needs at least bits; divide by the image's dimension , and you get the average number of bits per dimension:
A CIFAR-10 image is , so . 2.91 bits/dim means about 8,940 bits per image on average, and 3.08 means about 9,460 bits. The smaller the number, the better the model's probability estimate for the data. A VAE can only compute a lower bound on the log-likelihood, so VAE numbers often carry a in front, meaning the true value is no worse than this.
Thirty groups of latent variables
NVAE is a hierarchical VAE. The latent variables are split into groups , and both the prior and the approximate posterior generate them group by group in the same order, each group conditioned on all the groups before it:
Every conditional distribution is a normal distribution with independent dimensions. Plug this into the ELBO, and the KL term splits into one term per group:
Here . The KL of group is computed given the groups already sampled before it, and can be read as how much information this group encodes for this image. On CIFAR-10, NVAE uses 30 groups.
The approximate posterior and the prior share the same top-down order, an approach that started with Ladder VAE.
The bidirectional encoder

This figure is an example with three groups of latent variables. The diamonds are residual networks, the plus signs in circles are feature merges, and is a trainable parameter.
On the right, (b) is the generative model. Starting from , it merges in the first group's sample , passes through a stretch of residual network and computes the prior for ; after sampling , it merges again and continues down, finally outputting .
On the left, (a) is inference. The red bottom-up network first extracts features at every level going up from . Inference also needs a top-down path, and instead of building a separate one, NVAE reuses the generative model's (blue, marked shared). Each group's approximate posterior is computed by merging the current state of this path with the bottom-up features at the same depth. This structure comes from IAF-VAE (Kingma et al., 2016).
With that, the skeleton of the statistical model is set, and NVAE doesn't touch it. What it has to work out is what goes into all those in the figure, and how to train thirty-some KL terms together without blowing up.
The authors list several ways a VAE needs something different from a classification network:
- Keep the information. A VAE wants to maximize the mutual information between the input and the latent variables, so the network has to hold on to as much of the input as it can; a classification network throws away whatever doesn't matter for the class all along the way.
- Overparameterization cuts unevenly. The marginal likelihood depends only on the generative model, so an oversized decoder can hurt test-set log-likelihood; a stronger encoder, on the other hand, helps, narrowing the amortization gap.
- Long-range correlations. Skin tone should be consistent across a face, and the left and right sides roughly symmetric; correlations that span the whole image like these need a large receptive field.
- The KL has no upper bound. With many groups, training becomes unstable. The best VAEs of the time (IAF-VAE, BIVA) didn't use BN, worried that the randomness it brings would make things worse.
Solving the problem
Following one CIFAR-10 image
First, a walk through the shape of the whole network. The sizes below follow Table 6 in the appendix and the CIFAR-10 configuration of the official code.
- A image is rescaled to and passed through a convolution, becoming .
- Two preprocessing residual cells; the second halves the spatial size and doubles the channels, giving .
- The bottom-up network stacks 30 stages on , each with two encoder residual cells, and at the end of each stage it keeps the features for the corresponding group of latent variables.
- The top group: the last bottom-up features go through a small convolutional head that outputs 40 channels, the first 20 being the mean and the last 20 . has shape , and its prior is a standard normal.
- The decoder starts from , a trainable tensor. and are concatenated along the channels (276 channels) and squeezed back to 256 with a convolution.
- Each group after that: the decoder first passes through two generative-model residual cells, then reads off this group's prior with a convolution; meanwhile, the encoder adds the decoder state, passed through a convolution, to the bottom-up features at the same depth, and reads off the approximate posterior's parameters. Sample , concatenate it back into the decoder state, and move on to the next group.
- Once all 30 groups are done, postprocessing cells upsample back to and output, for each pixel, a discretized logistic mixture with 10 components.
Count the latent variables. Each group has , so 30 groups make 153,600, while the image itself has only 3,072 numbers: 50 times as many latent variables as data. The authors also say that with more latent variables than data dimensions, the model naturally switches many of them off.
The CelebA HQ 256 version is bigger. Preprocessing first shrinks the image to , and the latent variables are spread over five scales from to , with 4, 4, 4, 8 and 16 groups respectively: 36 groups and about 6 million latent variables in all, against a data dimension of 196,608.
The generative model's residual cell

On the left is the cell used by the generative model (the decoder), which is also the core of the NVAE architecture. Take a feature map from the CIFAR-10 decoder through it:
- First, a BN.
- A convolution expands the channels times, to 1,536.
- BN plus Swish.
- A depthwise convolution: each channel uses its own kernel, with no mixing across channels.
- BN plus Swish.
- A convolution squeezes the channels back to 256.
- BN, then SE, and finally an addition with the input.
Why depthwise convolution? The most direct way to handle long-range correlations is a bigger kernel, but then the parameter count explodes. Work it out for 256 channels in and 256 channels out:
- A regular convolution: parameters.
- A depthwise convolution: parameters.
Depthwise convolution is 256 times cheaper, but each channel is computed on its own, which limits what it can express. So the authors follow MobileNetV2: expand the channels with a convolution first, then do the depthwise convolution, and finally mix the channels with another convolution. The whole cell has parameters, roughly 825,000, about half of one regular convolution (not counting BN and SE). In early experiments the authors found that depthwise convolution worked better than regular convolution, with a parameter count and compute several orders of magnitude smaller.
Compared with MobileNetV2's inverted residual block, NVAE's cell adds one more BN at each end, swaps the activation for Swish, and adds SE at the end.
Batch normalization. The IAF-VAE paper had said that the noise BN brings hurts performance, so the best VAEs of the time had all switched to weight normalization. The NVAE authors observed that BN's harm shows up at evaluation, not in training. At evaluation, BN uses the moving-average statistics accumulated during training, and even a small shift in them can change the network's output drastically. They adjust BN's momentum (the official code uses 0.05) and add a regularizer on each BN layer's scale parameters (in the code, the sum over layers of each layer's maximum ), so that small errors in the statistics don't get amplified by BN.
This echoes a finding from Ladder VAE years earlier: that paper was also surprised to find how much BN helped deep VAEs.
Swish and SE. Swish is ; the authors found BN with Swish works better than the weight normalization with ELU used in earlier work. SE first averages each channel globally, passes the result through a small two-layer network and a sigmoid to get a weight per channel, and multiplies those weights back onto the feature map.
On the right, (b) is the encoder's cell: just BN-Swish- convolution twice, plus SE, with the channel count unchanged. The authors found that depthwise convolution didn't help in the encoder, while regular convolution saves memory, so the bottom-up network uses this cell. As for order, BN and activation first, then convolution, works better than the original ResNet's convolution, BN, activation.
Memory
Depthwise convolution saves parameters but eats memory. The cell above expands to 1,536 channels at , and every step's feature map has to be kept for backpropagation; with 30 groups of two cells each, that adds up to a lot. The authors use two tricks:
- Mixed precision. With NVIDIA's APEX library, every operation that can safely be cast to half precision (convolutions included) runs in FP16, saving 40% of GPU memory.
- Fuse BN and Swish and keep only one feature map. Swish can't be computed in place, so originally BN's output and Swish's output each had to be stored. The authors write the two as a single operation that stores only one copy and recomputes BN during backpropagation, which is gradient checkpointing. The extra compute time is hardly noticeable, and on CIFAR-10 it saves another 18% of memory.
Together, the two tricks allow bigger batches, raising training throughput from 34 to 64 images per second.
Residual Normal
Next comes the first design for stable training.
The usual approach uses two networks to produce the parameters of the prior and of the approximate posterior separately. With many groups, keeping the two sides in step is hard; as soon as some group's two distributions drift too far apart, the KL produces a very steep gradient that pushes the parameters into a region they can hardly come back from.
The authors stop having the approximate posterior predict its own mean and standard deviation directly, and have it predict a shift and a scaling relative to the prior instead. For the -th variable of group , the prior is , and the approximate posterior is defined as:
and come from the encoder. The official code adds up the means predicted by the two sides and adds up their , which is equivalent to multiplying the standard deviations.
Now the KL. The KL between two one-dimensional normal distributions is:
Substitute and . The first term becomes ; the second splits into and . Collected together, this is Eq. 2 of the paper:
The formula gives away two things.
First, when the encoder outputs and , the KL is 0 wherever the prior happens to be. When the prior moves, the approximate posterior moves with it; the encoder only has to describe "how far this image is from what the prior expects."
Second, the prior's standard deviation appears only in the term . Run the numbers once, with and :
- With a prior , the KL is nats.
- With a prior , the KL is nats.
The encoder's output is exactly the same, yet the KL is 100 times larger, just because the decoder has made the prior very confident. So the paper says that as long as the produced by the decoder has a lower bound, the KL is determined mainly by the encoder's relative parameters; the authors hypothesize that a KL like this is easier to optimize.
The idea points the same way as Ladder VAE, which the paper also mentions. Ladder VAE uses precision weighting so that the approximate posterior takes a weighted average of the prior and the evidence from the data; NVAE has the approximate posterior start from the prior and add a shift. Both have inference start from the prior.
What the paper doesn't say is that the official code takes out insurance on that lower bound. When building a normal distribution, both and first go through , which softly clamps them to , and then gets 0.01 added. When someone asked about it in issue #27, the author answered that it was added for stability, that it helps a little but doesn't fully solve the problem, and that every experiment in the paper uses it. The author also added that although each variable's KL is bounded, there are millions of variables, and once the encoder and the prior get slightly out of balance, the sum can still become enormous.
Spectral regularization
Residual normal makes the KL easier to optimize, but the KL still has no upper bound. The authors' second design keeps the encoder's output from swinging wildly with its input, a kind of smoothness described by the Lipschitz constant. The network's Lipschitz constant can't be computed, so the authors push down an upper bound for each layer instead, adding a term to the objective:
is the largest singular value of the -th convolutional layer's weights, approximated with power iteration. A linear layer's largest singular value is the largest factor by which it can stretch the length of its input; hold every layer's stretch factor down, and the whole network's output won't jump around wildly with its input, so the latent variables' parameters won't fly off somewhere far away either.
The term goes on both the encoder and the decoder; the authors' reasoning is that a sharp decoder may force a sharp encoder. is 0.01 or 0.1 in most experiments, with 0.1 used only when training is unstable. CelebA HQ and FFHQ need smoothing as strong as 1 or 10 at the start to stay stable, so there decays exponentially from 10 to its final value, over the same length as the KL warm-up.

This is an FFHQ experiment from the appendix, two training runs that differ only in . The vertical axis is KL, on a log scale.
The red line, , is doing fine for the first 2,000 steps; then, within a few steps, the KL leaps from about to about nats and gets stuck around , and that run is finished. The blue line, , has no such jump and comes down steadily the whole way.
The authors say they first tried the usual fixes, such as gradient clipping or limiting the normal distribution's parameters to a small range, and none of them could stabilize training without hurting performance.
KL warm-up and KL balancing
Two more training tricks sit in the appendix.
KL warm-up. As in Ladder VAE, the KL term is multiplied by a that rises linearly from 0 to 1 over the first 30% of training.
KL balancing. Among thirty-some groups of latent variables, a few always get pressed to 0 by the KL early in training and shut off as a whole group. During warm-up, the authors give each group's KL a coefficient :
is proportional to this group's average KL over the current batch and inversely proportional to the group's size, then normalized so that all the sum to the number of groups (the authors filled in the implementation details in issue #26).
Take two groups of the same size. The first has an average KL of 1 nat and the second 9 nats; starts out proportional to 1 and 9, and normalizing to a sum of 2 gives 0.2 and 1.8. The first group, close to shutting off, now feels only a fifth of its original KL penalty and has room to encode a bit more information; the second group, with its large KL, gets pressed a bit harder. After warm-up, every goes back to 1 and the objective is the original ELBO.
Other settings
- Flows in the encoder. After each group is sampled, a few inverse autoregressive flows can follow to make the approximate posterior more flexible. They sit only in the encoder and aren't used when sampling, so sampling doesn't get slower. The authors use shift-only flows, ; adding scaling didn't help.
- Optimizer. AdaMax, learning rate 0.01, cosine decay; 0.008 for FFHQ. The official code also, by default, ramps the learning rate up linearly from 0 over the first 5 epochs.
- Decoder output distribution. Bernoulli for MNIST and a discretized logistic mixture for the other datasets; each pixel's output doesn't depend on any other pixel.
- Evaluation. Test-set log-likelihood is estimated with 1,000 importance-weighted samples.
These models don't come cheap. From Table 6:
| Dataset | Groups | GPU | Hours |
|---|---|---|---|
| MNIST | 15 | 2 × V100 16GB | 21 |
| CIFAR-10 | 30 | 8 × V100 16GB | 55 |
| ImageNet 32 | 28 | 24 × V100 32GB | 70 |
| CelebA 64 | 35 | 8 × V100 16GB | 92 |
| CelebA HQ 256 | 36 | 24 × V100 32GB | 94 |
| FFHQ 256 | 36 | 24 × V100 32GB | 160 |
Compiled from Table 6 of the paper.
Discussion
Main results
| Model | CIFAR-10 | ImageNet | CelebA HQ |
|---|---|---|---|
| NVAE | 2.91 | 3.92 | 0.70 |
| NVAE (no flow) | 2.93 | − | − |
| BIVA | 3.08 | 3.96 | − |
| IAF-VAE | 3.11 | − | − |
| VFlow | 2.98 | − | − |
| ANF | 3.05 | 3.92 | 0.72 |
| Flow++ | 3.08 | 3.86 | − |
| Glow | 3.35 | 4.09 | 1.03 |
| MaCow ¹ | 3.16 | − | 0.67 |
| δ-VAE ¹ | 2.83 | 3.77 | − |
| PixelSNAIL ² | 2.85 | 3.80 | − |
| SPN ² | − | 3.85 | 0.61 |
Compiled from Table 1 of the paper, in bits/dim, lower is better; ImageNet is and CelebA HQ is . ¹ Generative model with autoregressive components; ² autoregressive model.
Start with the models that have no autoregressive components. On CIFAR-10, NVAE pushes the best result from VFlow's 2.98 to 2.91, 0.17 to 0.2 better than VAEs like BIVA and IAF-VAE; on CelebA HQ it edges out ANF's 0.72 with 0.70. ImageNet is the exception, where NVAE's 3.92 ties ANF and loses to Flow++'s 3.86.
Further down the table, models with autoregressive components are still ahead. On CIFAR-10, δ-VAE has 2.83 and PixelSNAIL 2.85; on CelebA HQ, SPN has 0.61. NVAE narrows the gap to autoregressive models but hasn't caught up.
Three more datasets aren't in the table. On MNIST, NVAE gets 78.01 nats (the version without flows actually does better), against 78.41 for BIVA; on CelebA 64, NVAE gets 2.03 and BIVA 2.48, the widest gap. FFHQ comes in at 0.69, and the authors say this is the first VAE trained on FFHQ.
Taking the flows out of the encoder only moves CIFAR-10 back from 2.91 to 2.93. From this the authors conclude that the main progress comes from the network architecture: with normal distributions as the approximate posterior, a well-designed network can make up for part of what is lacking on the statistical side.
Samples and scales
Before reading VAE samples, you need to know about two sampling-time settings.
The first is temperature. At sampling time, the standard deviation of each of the prior's conditional distributions is multiplied by some below 1, so samples concentrate in high-probability regions: quality goes up and diversity goes down. The paper's CelebA HQ samples use , and FFHQ .
The second is BN statistics. The authors found that if BN uses the current batch's statistics at sampling time, instead of the moving averages from training, samples are more diverse and better in quality even at low temperature. So that one sample doesn't depend on the other samples in its batch, they follow BigGAN: at the given temperature, they first sample 500 times to re-estimate BN's moving averages, then use those statistics for the real sampling. The log-likelihoods in the table above use the default BN statistics.

This figure checks what each scale of the hierarchy is responsible for. The CelebA HQ model has five scales; each row fixes the samples of the top few scales and resamples the rest.
The first row fixes nothing, and the four faces are entirely different people. The second row fixes only the groups at the top scale, and face shape, pose and composition are already settled; what still varies is hair color, skin tone and eye color. The more scales are fixed going down, the more alike the four faces become, until in the fifth row only fine differences in strands of hair and lighting are left. Global structure sits almost entirely in the top scale; the authors also notice that the lowest scale can still shift hair color slightly, which they attribute to the large receptive field that comes with depthwise convolution.
Sampling speed is where VAEs shine. On a 12 GB Titan V, a batch of 36 images at takes 2.03 seconds, 56 ms per image; MaCow reports 434.2 ms per image in a similar setting, about 8 times slower.
The paper doesn't report FID. Later work filled in that number and also exposed an easily missed detail. In issue #30 the NVAE author explained that two follow-up papers, NCP-VAE and VAEBM, retrained NVAE with a Gaussian output distribution so that they could backpropagate through generated images, getting a CelebA HQ FID of about 40.26; the later LSGM went back to the original public checkpoint (with discretized logistic mixture outputs) and measured an FID of 29.76; and in LSGM's table, NVAE's FID on CIFAR-10 is 23.49. Same architecture, only the output distribution swapped, and the FID differs by more than 10. The author's explanation is that the logistic mixture can itself describe the dependencies among RGB channels, so the latent space has less information to encode.
Ablations
All ablations are on CIFAR-10, with a scaled-down NVAE whose residual cells have half the channels and no flows.
Normalization and activation, using the encoder-style cell, for different numbers of groups :
| Setup | |||
|---|---|---|---|
| WN + ELU | 3.36 | 3.27 | 3.31 |
| BN + ELU | 3.36 | 3.26 | 3.22 |
| BN + Swish | 3.34 | 3.23 | 3.16 |
Compiled from Table 2 of the paper, test-set bits/dim.
With the WN + ELU that IAF-VAE and BIVA use, going from 20 to 40 groups actually makes things worse; switch to BN, and 40 groups beat 20; switch further to Swish, and 40 groups reach 3.16. BN's advantage is most visible with many groups.
Where the residual cells go:
| Encoder | Decoder | bpd | Hours | Memory |
|---|---|---|---|---|
| Regular | Regular | 3.11 | 43.3 | 6.3 GB |
| Separable | Regular | 3.12 | 49.0 | 10.6 GB |
| Regular | Separable | 3.07 | 48.0 | 10.7 GB |
| Separable | Separable | 3.07 | 50.4 | 14.9 GB |
Compiled from Table 3 of the paper. "Separable" is the depthwise cell, and "Regular" is the encoder-style cell.
The depthwise cell is useful only in the decoder, where it brings bits/dim from 3.11 down to 3.07; in the encoder it brings no benefit at all and costs an extra 4 GB of memory. The cost is plain to see as well: with depthwise cells in the decoder, memory rises from 6.3 GB to 10.7 GB. That is exactly what the two memory tricks earlier are there to handle.
Residual normal. Comparing 40-group models with and without residual normal, the number of active latent channels is 53 and 54, the reconstruction term is 1.80 in both, the training KL drops from 1.36 to 1.32, and the test set goes from 3.19 down to 3.16 bits/dim. It doesn't make more latent variables active; what it does is make the KL easier to push down. The appendix also shows that early in warm-up, the model without residual normal shuts off more latent variables.
SR and SE. The same 40-group model scores 3.16; without spectral regularization it's 3.18, and without SE 3.22. SR was added for stability in the first place, and the authors found it also improved the score a little.
Posterior collapse. The full CIFAR-10 model has 30 groups, and thanks to KL balancing most of them have similar average KLs, with only one group shut off entirely.
On the scaled-down model, residual normal, SR, SE and the decoder's depthwise cells each contribute 0.02 to 0.06 bits/dim; BN plus Swish contributes the most at 40 groups, 0.15. The full model's 2.91 is these improvements piled up.
Official code and reproduction
The official code is written in PyTorch and comes with complete training commands for every dataset. In October 2020 the community asked for pretrained models, the author replied "in a couple of weeks," and on November 19 checkpoints for MNIST, CIFAR-10, CelebA 64, CelebA HQ and FFHQ went up. That promise was kept.
Training itself goes less smoothly.
NaN. Someone training on CelebA 64 with a small batch hit NaN by the 5th epoch. The author explained that the learning rate ramps up linearly to 0.01 over the first 5 epochs, and that with small batches it easily diverges right then, recommending 0.005 or even 0.001. The README later gained a Known Issues section, which says that if NaN shows up after a few epochs, you can increase the spectral regularization , decay it exponentially, or lower the learning rate; another entry says that in very rare cases training freezes outright after two or three days, which the authors put down to a race condition in a low-level library, and recommends killing the run and continuing from the last checkpoint.
Memory. A footnote in the paper's appendix says that CelebA HQ can be trained with a scaled-down 24-channel model on 8 GPUs, with 6 images per GPU. A user reported in issue #17 that following this on eight 32 GB V100s, the 24-channel model fit only 5 images per GPU and the original 30-channel one only 3, and that they also ran into NaN. The author suggested checking the PyTorch version and lowering the learning rate to 0.008; the issue is still open.
NaN from BN readjustment. The paper's best-looking samples rely on the BN statistics re-estimation described above. In July 2022 a user reported in issue #36 that sampling from the official CelebA 64 checkpoint with --readjust_bn gave some generated images that were simply NaN; dropping the option made them normal again, but quality fell noticeably. The same user hit it on CelebA HQ 256 too, and in October 2023 someone else reproduced it on CIFAR-10 with the official evaluation command. The maintainers never replied (the readjusted statistics occasionally come out Not a Number).
On a practical note, the official code is released under NVIDIA's source code license, which allows only non-commercial research or evaluation use.
Conclusion
NVAE puts its effort into the network and the training details. It replaces the decoder's residual cell with an expanded depthwise convolution, paired with BN, Swish and SE; has the approximate posterior predict a shift and scaling relative to the prior; holds down every layer's stretch factor with spectral regularization; and keeps thirty-some groups of latent variables alive with KL warm-up and balancing. It reaches 2.91 bits/dim on CIFAR-10, the best among models without autoregressive components, and generates faces with a VAE. The ablations show that most of the parts are worth only 0.02 to 0.06 bits/dim each; only together do they add up to that number.
If you want to train it yourself, size up the hardware first: the official CelebA HQ setting is 24 V100s with 32 GB each, running for 94 hours. With smaller batches, both the learning rate and need adjusting, and keep an eye on every group's KL the whole time. Once the KL jumps several orders of magnitude within a few steps, that run usually can't be saved; the README says as well that continuing from a checkpoint after NaN usually doesn't help. And before putting it into a product, remember that non-commercial license.
The following year, the NVAE authors used NVAE as the backbone in LSGM, putting a score-based diffusion model into its latent space and reaching an FID of 2.10 on CIFAR-10. The job of generating images went to the diffusion model, and the VAE was left to provide the latent space.