{'fraction_non_alphanumeric': 0.042830410977891746, 'fraction_numerical': 0.011527710398040982, 'mean_word_length': 4.286115520820613, 'pattern_counts': {'":': 0, '<': 0, '<?xml version=': 0, '>': 0, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 7, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
Bit-Swap: Recursive Bits-Back Coding for Lossless Compression with Hierarchical Latent Variables

The bits-back argument suggests that latent variable models can be turned into lossless compression schemes. Translating the bits-back argument into efficient and practical lossless compression schemes for general latent variable models, however, is still an open problem. Bits-Back with Asymmetric Numeral Systems (BB-ANS), recently proposed by Townsend et al. (2019), makes bits-back coding practically feasible for latent variable models with one latent layer, but it is inefficient for hierarchical latent variable models. In this paper we propose Bit-Swap, a new compression scheme that generalizes BB-ANS and achieves strictly better compression rates for hierarchical latent variable models with Markov chain structure. Through experiments we verify that Bit-Swap results in lossless compression rates that are empirically superior to existing techniques. Our implementation is available at https://github.com/fhkingma/bitswap.


Introduction
Likelihood-based generative models-models of joint probability distributions trained by maximum likelihood-have recently achieved large advances in density estimation performance on complex, high-dimensional data. Variational autoencoders (Kingma & Welling, 2013;Kingma et al., 2016), PixelRNN and PixelCNN and their variants (Oord et al., 2016;van den Oord et al., 2016b;Salimans et al., 2017;Parmar et al., 2018;Chen et al., 2017), and flow-based models like RealNVP (Dinh et al., 2014;Kingma & Dhariwal, 2018) can successfully model high dimensional image, video, speech, and text data (Karras et al., 2017;Kalchbrenner et al., 2016b;van den Oord et al., 2016a; Proceedings of the 36 th International Conference on Machine Learning, Long Beach, California, PMLR 97, 2019. Copyright 2019 by the author(s). The sender encodes data x to a code with the least amount of bits possible without losing information. The receiver decodes the code and must be able to exactly reconstruct x. Kalchbrenner et al., 2016a;Vaswani et al., 2017).
The excellent density estimation performance of modern likelihood-based models suggests another application: lossless compression. Any probability distribution can in theory be converted into a lossless code, in which each datapoint is encoded into a number of bits equal to its negative log probability assigned by the model. Since the best expected codelength is achieved when the model matches the true data distribution, designing a good lossless compression algorithm is a matter of jointly solving two problems: 1. Approximating the true data distribution p data (x) as well as possible with a model p θ (x) 2. Developing a practical compression algorithm, called an entropy encoding scheme, that is compatible with this model and results in codelengths equal to − log p θ (x). Unfortunately, it is generally difficult to jointly design a likelihood-based model and an entropy encoding scheme that together achieve a good compression rate while remaining computationally efficient enough for practical use. Any model with tractable density evaluation can be converted into a code using Huffman coding, but building a Huffman tree requires resources that scale exponentially with the dimension of the data. The situation is more tractable, but still practically too inefficient, when autoregressive models are paired with arithmetic coding or asymmetric numeral systems (explained in Section 2.1). The compression rate will be excellent due to to the effectiveness of autoregressive models in density estimation, but the resulting decompression process, which is essentially identical to the sample generation process, will be extremely slow.
Fortunately, fast compression and decompression can be achieved by pairing variational autoencoders with a recently proposed practically efficient coding method called Bits-Back with Asymmetric Numeral Systems (BB-ANS) (Townsend et al., 2019). However, the practical efficiency of BB-ANS rests on two requirements: 1. All involved inference and recognition networks are fully factorized probability distributions 2. There are few latent layers in the variational autoencoder.
The first requirement ensures that encoding and decoding is always fast and parallelizable. The second, as we will discuss later, ensures that BB-ANS achieves an efficient bitrate: it turns out that BB-ANS incurs an overhead that grows with the number of latent variables. But these requirements restrict the capacity of the variational autoencoder and pose difficulties for density estimation performance, and hence the resulting compression rate suffers.
To work toward designing a computationally efficient compression algorithm with a good compression rate, we propose Bit-Swap, which improves BB-ANS's performance on hierarchical latent variable models with Markov chain structure. Compared to latent variables models with only one latent layer, these hierarchical latent variable models allow us to achieve better density estimation performance on complex high-dimensional distributions. Meanwhile, Bit-Swap, as we show theoretically and empirically, yields a better compression rate compared to BB-ANS on these models due to reduced overhead.

Background
First, we will set the stage by introducing the lossless compression problem. Let p data be a distribution over discrete data x = (x 1 , . . . , x D ). Each component Figure 2: Asymmetric Numeral Systems (ANS) operates on a bitstream in a stack-like manner. Symbols are decoded in opposite order as they were encoded.
x is called a symbol. Suppose that a sender would like to communicate a sample x to a receiver through a code, or equivalently a message. The goal of lossless compression is to send this message using the minimum amount of bits on average over p data , while ensuring that x is always fully recoverable by the receiver. See Figure 1 for an illustration.
Entropy encoding schemes use a probabilistic model p θ (x) to define a code with codelengths − log p θ (x). If − log p θ (x) matches − log p data (x) well, then resulting average codelength E[− log p θ (x)] will be close to the entropy of the data H(x), which is the average codelength of an optimal compression scheme.

Asymmetric Numeral Systems
We will employ a particular entropy encoding scheme called Asymmetric Numeral Systems (ANS) (Duda, 2009). Given a univariate probability distribution p(x), ANS encodes a symbol x into a sequence of bits, or bitstream, of length approximately − log p(x) bits. ANS can also code a vector of symbols x using a fully factorized probability distribution p(x) = i p(x i ), resulting in − log p(x) bits. (It also works with autoregressive p(x), but throughout this work we will only use fully factorized models for parallelizability purposes.) ANS has an important property: if a sequence of symbols is encoded, then they must be decoded in the opposite order. In other words, the state of the ANS algorithm is a bitstream with a stack structure. Every time a symbol is encoded, bits are pushed on to the right of the stack; every time a symbol is decoded, bits are popped from the right of the stack. See Figure 2 for an illustration. This property will become important when ANS is used in BB-ANS and Bit-Swap for coding with latent variable models.

Latent Variable Models
The codelength of an entropy encoding technique depends on how well its underlying model p θ (x) approximates the true data distribution p data (x). In this paper, we focus on latent variable models, which approximate p data (x) with a marginal distribution p θ (x) defined by where z is an unobserved latent variable. For continuous z, p θ (x) can be seen as an infinite mixture, which makes such an implicit distribution over x potentially highly flexible.
Since exactly evaluating and optimizing the marginal likelihood p θ (x) is intractable, variational autoencoders introduce an inference model q θ (z|x), which approximates the model posterior p θ (z|x). For any choice of q θ (z|x), we can rewrite the marginal likelihood p θ (x) as follows: As D KL (q θ (z|x) p θ (z|x)) ≥ 0, the inference model and generative model can be found by jointly optimizing the Evidence Lower BOund (ELBO), a lower bound on log p θ (x): For continuous z and a differentiable inference model and generative model, the ELBO can be optimized using the reparameterization trick (Kingma & Welling, 2013).

Bits-Back Coding with ANS
It is not straightforward to use a latent variable model for compression, but it is possible with the help of the inference network q θ (z|x). Assume that both the sender and receiver have access to p θ (x|z), p(z), q θ (z|x) and an entropy encoding scheme. Let x be the datapoint the sender wishes to communicate. The sender can send a latent sample z ∼ q θ (z|x) by coding using the prior p(z), along with x, coded with p θ (x|z). This scheme is clearly valid and allows the receiver to recover the x, but results in an inefficient total codelength of E [− log p θ (x|z) − log p(z)]. Wallace (1990) and Hinton & Van Camp (1993) show in a thought experiment, called the bits-back argument, it is possible to instead transmit − log q θ (z|x) fewer bits in a certain sense, thereby yielding a better net codelength equal to the negative ELBO −L(θ) of the latent variable model. Figure 3, makes the bits-back argument concrete. BB-ANS operates by starting with ANS initialized with a bitstream of N init random bits. Then, to encode x, BB-ANS performs the following steps:

BB-ANS (Townsend et al., 2019), illustrated in
1. Decode z from bitstream using q θ (z|x), subtracting − log q θ (z|x) bits from the bitstream, 2. Encode x to bitstream using p θ (x|z), adding − log p θ (x|z) bits to the bitstream, 3. Encode z to bitstream using p(z), adding − log p(z) bits to the bistream. The resulting bitstream, which has a length of N total := N init + log q θ (z|x) − log p θ (x|z) − log p(z) bits, is then sent to the receiver.
The receiver decodes the data by initializing ANS to the received bitstream, then proceeds in reverse order, with the encode and decode operations swapped: the receiver decodes z using p(z), decodes x using p θ (x|z), then encodes z using q θ (z|x). The final step of encoding z will recover the N init bits that the encoder used to initialize ANS. Thus, the sender will have successfully transmitted x to the receiver, along with the initial N init bits-and it will have taken N total bits to do so.
To summarize, it takes N total bits to transmit x plus N init bits. In this sense, the net number of bits sent regarding x only, ignoring the initial N init bits, is which is on average equal to −L(θ), the negative ELBO.

Initial Bits in Bits-Back Coding
We now turn to the core issue that our work addresses: the amount of initial bits N init required for BB-ANS to function properly.
It is crucial for there to be enough initial bits in the ANS state for the sender to decode z from the initial bitstream. That is, we must have in order to guarantee that the receiver can recover the initial N init bits. If not, then to sample z, the sender must draw Algorithm 1 BB-ANS for lossless compression with hierarchical latent variables. The operations below show the procedure for encoding a dataset D onto a bitstream.
Input: data D, depth L, p θ (x, z 1:L ), q θ (z 1:L |x) Require: ANS bits from an auxiliary random source, and those bits will certainly not be recoverable by the receiver. And, if those bits are not recoverable, then the sender will have spent N total bits to transmit x only, without N init bits in addition. So, we must commit to sending at least N init ≥ − log q θ (z|x) initial bits to guarantee a short net codelength for x.
Unfortunately, the initial number of bits required can be significant. As an example, if the latent variables are continuous, as is common with variational autoencoders, one must discretize the density q θ (z|x) into bins of volume δz, yielding a probability mass function q θ (z|x)δz. But this imposes a requirement on the initial bits: now N init ≥ − log q θ (z|x) − log δz increases as the discretization resolution 1/δz increases. Townsend et al. (2019) remark that initial bits can be avoided by transmitting multiple datapoints in sequence, where every datapoint x i (except for the first one x 1 ) uses the bitstream built up thus far as initial bitstream. This amortizes the initial cost when the number of datapoints transmitted is large, but the cost can be significant for few or moderate numbers of datapoints, as we will see in experiments in Section 6.

Problem Scenario: Hierarchical Latent Variables
Initial bits issues also arise when the model has many latent variables. Models with multiple latent variables are more expressive in practice can more closely model p data , leading to better compression performance. But since − log q θ (z|x) generally grows with the dimension of z, adding more ex-Algorithm 2 Bit-Swap (ours) for lossless compression with hierarchical latent variables. The operations below show the procedure for encoding a dataset D onto a bitstream.
pressive power to the latent variable model via more latent variables will incur a larger initial bitstream for BB-ANS.
We specialize our discussion to the case of hierarchical latent variable models: variational autoencoders with multiple latent variables whose sampling process obeys a Markov chain of the form z L → z L−1 → · · · → z 1 → x, shown schematically in Figure 4. (It is well known that such models are better density estimators than shallower models, and we will verify in experiments in Section 6 that these models indeed can model p data more closely than standard variational autoencoders. A discussion regarding other topologies can be found in Appendix G.) Specifically, we consider a model whose marginal distributions are and whose marginal distribution over x is We define an inference model q θ (z i |z i−1 ) for every latent layer z i , so that we can optimize a variational bound on the marginal likelihood p θ (x). The resulting optimization objective (ELBO) is Figure 4: The model class we are targeting: hierarchical latent variable models. Specifically, variational autoencoders whose sampling process obeys a Markov chain.
Now, consider what happens when this model is used with BB-ANS for compression. Figure 5(b) illustrates BB-ANS for such a model with three latent layers {z 1 , z 2 , z 3 }; the algorithm for arbitrary latent depths L of a hierarchical latent variable model is shown in Algorithm 1.
The first thing the sender must do is decode the latent variables z 1:L from the initial bitstream of ANS. So, the number of bits present in the initial bitstream must be at least where z 0 = x. Notice that N BBANS init must grow with the depth L of the latent variable model. With L sufficiently large, the required initial bits could make BB-ANS impractical as a compression scheme with hierarchical latent variables.

Bit-Swap
To mitigate this issue, we propose Bit-Swap (Algorithm 2), an improved compression scheme that makes bits-back coding efficiently compatible with the layered structure of hierarchical latent variable models. In our proposed model (Equations 5-6), the sampling process of both the generative model and the inference model obeys a Markov chain dependency between the stochastic variables. The data x is generated conditioned on a latent variable z 1 , as in a standard variational autoencoder. However, instead of using a fixed prior for z 1 , we assume that z 1 is generated by a second latent variable z 2 . Subsequently, instead of using a fixed prior for z 2 , we assume that z 2 is generated by third latent variable z 3 , and so on.
These nested dependencies enable us to recursively apply the bits-back argument as follows. Suppose we aim to compress one datapoint x in a lossless manner. With standard BB-ANS, the sender begins by decoding z 1:L , which incurs a large cost of initial bits. With Bit-Swap, we notice that we can apply the first two steps of the bits-back argument on the first latent variable: first decode z 1 and directly afterwards encode x. This adds bits to the bitstream, which means that further decoding operations for z 2:L will need fewer initial bits to proceed. Now, we recursively the bits-back argument for the second latent variable z 2 in a similar fashion: first decode z 2 and afterwards encode z 1 . Similar operations of encoding and decoding can be performed for the remaining latent variables z 3:L : right before decoding z i+1 , Bit-Swap always encodes z i−1 , and hence at least − log p θ (z i−1 |z i ) are available to decode z i+1 ∼ q θ (z i+1 |z i ) without an extra cost of initial bits. Therefore, the amount of initial bits that Bit-Swap needs is bounded by where we used the convention z 0 = x and p θ (z −1 |z 0 ) = 1. We can guarantee that Bit-Swap requires no more initial bits than BB-ANS: See Figure 5(a) for an illustration of Bit-Swap on a model with three latent variables z 1 , z 2 , z 3 .

Experiments
To compare Bit-Swap against BB-ANS, we use the following image datasets: MNIST, CIFAR-10 and ImageNet (32 × 32). Note that the methods are not constrained to this specific type of data. As long as it is feasible to learn a hierarchical latent variable model with Markov chain structure p θ (x) of the data under the given model assumptions, and the data is discrete, it is possible to execute the compression schemes Bit-Swap and BB-ANS on this data.
Referring back to the introduction, designing a good lossless compression algorithm is a matter of jointly solving two problems: 1) approximating the true data distribution p data (x) as well as possible with a model p θ (x), and 2) developing a practical compression scheme that is compatible with this model and results in codelengths equal to − log p θ (x). We address the first point in Section 6.1. As for the second point, we achieve bitrates that are approximately equal to the −L(θ), the negative ELBO, which is an upper bound on − log p θ (x). We will address this in Section 6.2.

Performance of Hierarchical Latent Variable Models
We begin our experiments by demonstrating how hierarchical latent variable models with Markov chain structure with different latent layer depths compare to a latent variable model with only one latent variable in terms of how well the models are able to approximate a true data distribution  . Column 2 shows the ELBO in bits/dim of the trained models evaluated on the test data. Column 3 denotes the number of parameters used (in millions). Using the trained models, we executed Bit-Swap and BB-ANS on the test data. We used 2 10 bins to discretize the latent space (see Appendix F). Column 5 denotes the scheme used; BB-ANS or Bit-Swap. Column 4 denotes the average net bitrate in bits/dim (see Section 6.2), averaged over Bit-Swap and BB-ANS. Columns 6-8 show the cumulative moving average in bits/dim (CMA) (see Section 6.2) at various timesteps (1, 50 and 100 respectively). The reported bitrates are the result of compression of 100 datapoints (timesteps), averaged over 100 experiments. We believe that the small discrepancy between the ELBO and the net bitrate comes from the noise resulting from discretization. Also, Bit-Swap reduces to BB-ANS for L = 1.    p data (x). A detailed discussion on the model architecture design can be found in Appendix D.
The results of training of the hierarchical latent variable models are shown in the left three columns of Table 2 (MNIST), 3 (CIFAR-10) and 4 (ImageNet (32 × 32)). One latent layer corresponds to one latent variable z i . The metric we used is bits per dimension (bits/dim) as evaluated by the negative ELBO −L(θ). Note from the resulting ELBO that, as we add more latent layers, the expressive power increases. A discussion on the utility of more latent layers can be found in Appendix E.

Performance of Bit-Swap versus BB-ANS
We now show that Bit-Swap indeed reduces the initial bits required (as discussed in Section 5) and outperforms BB-ANS on hierarchical latent variable models in terms of actual compression rates. To compare the performance of Bit-Swap versus BB-ANS for different depths of the latent layers, we conducted 100 experiments for every model and dataset. In every experiment we compressed 100 datapoints in sequence and calculated the cumulative moving average (CMA) of the resulting lengths of the bitstream after each datapoint. Note that this includes the initial bits necessary for decoding latent layers. In addition, we calculated the net number of bits added to the bitstream after every datapoint, as explained in Section 2.3, and averaged them over all datapoints and experiments for one dataset and model. This can be interpreted as a lower bound of the CMA of a particular model and dataset. We discretized the continuous latent variables z 1:L using 2 10 discretization bins for all datasets and experiments, as explained in Appendix F.
The CMA (with the corresponding average net bitrate) over 100 experiments for every model and dataset is shown in Figure 6. Bit-Swap is depicted in blue and BB-ANS in orange. These graphs show two properties of Bit-Swap and BB-ANS: the difference between Bit-Swap and BB-ANS in the need for initial bits, and the fact that the CMA of Bit-Swap and BB-ANS both amortize towards the average net bitrate. The last five columns of Table 2 (MNIST), 3 (CIFAR-10) and 4 (ImageNet (32 × 32)) show the CMA (in bits/dim) after 1, 50 and 100 datapoints for the Bit-Swap versus BB-ANS and the average net bitrate (in bits/dim).
The initial cost is amortized (see Section 3) as the amount of datapoints compressed grows. Also, the CMA converges to the average net bitrate. The relatively high initial cost of both compression schemes comes from the fact that the initial cost increases with the number of discretization bins, discussed in Appendix F. Furthermore, discretizing the latent space adds noise to the distributions. When using BB-ANS, remember that this initial cost also grows linearly with the amount of latent layers L. Bit-Swap does not have this problem. This results in a CMA performance gap that grows with the amount of latent layers L. The efficiency of Bit-Swap compared to BB-ANS results in much faster amortization, which makes Bit-Swap a more practical algorithm.
Finally, we compared both Bit-Swap and BB-ANS against a number of benchmark lossless compression schemes. For MNIST, CIFAR-10 and Imagenet (32 × 32) we report the bitrates, shown in Table 5, as a result of compressing 100 datapoints in sequence (averaged over 100 experiments) and used the best models reported in Table 2, 3 and 4 to do so. We also compressed 100 single images independently taken from the original unscaled ImageNet, cropped to multiples of 32 pixels on each side, shown in Table 6. First, we trained  the same model as used for Imagenet (32 × 32) on random 32 × 32 patches of the corresponding train set. Then we executed Bit-Swap and BB-ANS by compressing one 32 × 32 block at the time and averaging the bitrates of all the blocks in one image. We used the same cropped images for the benchmark schemes. We did not include deep autoregressive models as benchmark, because they are too slow to be practical (see introduction). Bit-Swap clearly outperforms all other benchmark lossless compression schemes.

Conclusion
Bit-Swap advances the line of work on practical compression using latent variable models, starting from the theoretical bits-back argument (Wallace, 1990;Hinton & Van Camp, 1993), and continuing on to practical algorithms based on arithmetic coding (Frey & Hinton, 1996;Frey, 1998) and asymmetric numeral systems (Townsend et al., 2019).
Bit-Swap enables us to efficiently compress using hierarchical latent variable models with a Markov chain structure, as it is able to avoid a significant number of initial bits that BB-ANS requires to compress with the same models. The hierarchical latent variable models function as powerful density estimators, so combined with Bit-Swap, we obtain an efficient, low overhead lossless compression algorithm capable of effectively compressing complex, high-dimensional datasets. We will describe a version of Assymetric Numeral Systems that we have assumed access to throughout the paper and used in the experiments, namely the range variant (rANS). All the other versions and interpretations can be found in (Duda, 2009).
ANS encodes a (sequence of) data point(s) into a natural number s ∈ N, which is called the state. We will use unconventional notation, yet consistent with our work: x to denote a single datapoint and s to denote the state. The goal is to obtain a state s whose length of the binary representation grows with a rate that closely matches the entropy of the data distribution involved.
Suppose we wish to encode a datapoint x that can take on two symbols {x 1 , x 2 } that have equal probability. Starting with s = 1. A valid scheme for this distribution is x 2 : s → 2s + 1.
This simply assigns 0 to x 0 and 1 to x 1 in binary. Therefore, it appends 1 or 0 to the right of the binary representation of the state s. Note that this scheme is fully decodable: if the current state is s , we can read of the last encoded symbol by telling if the state s is even (last symbol was x 1 ) or odd (last symbol was x 2 ). Consequently, after figuring out which symbol x was last encoded, the state s before encoding that symbol is obtained by Now, for the general case, suppose that the datapoint x can take on a multitude of symbols x ∈ {x 1 = 1, x 2 = 2, ..., x I = I} with probability {p 1 , p 2 , ..., p I }. In order to obtain a scheme analogous to the case with two symbols {x 1 , x 2 }, we have to assign every possible symbol x i to a specific subset of the natural numbers S i ⊂ N, that partitions the natural numbers. Consequently, N is a disjoint union of the subsets S i . Also, the elements in the subset s ∈ S i corresponding to x i must be chosen such that they occur in N with probability p i . This is accomplished by choosing a multiplier M , called the precision of ANS, that scales up the probabilities {p 1 , p 2 , ..., p I }. The scaled up probability p i is denoted by F [i] and the F 's are chosen such that I i=1 F [i] = M . We also choose subsets {K 1 , K 2 , ...} that form intervals of length M and partition the natural numbers. That means, the first M numbers belong to K 1 , the second M numbers belong to K 2 , and so on. Then, in every partition K n , the first M p 1 numbers are assigned to symbol x 1 and form the subset S n1 , the second M p 2 numbers are assigned to symbol x 2 and form the subset S n2 , and so on. Now, we define S i = ∪ ∞ n=1 S ni . The resulting subsets S i partition the natural numbers N. Furthermore, the elements of S i occur with probability approximately equal to p i in N. Now, suppose we are given an initial state s. The scheme rANS can be interpreted as follows. Encoding a symbol x i is done by converting the state s to a new state s that equals the s th occurrence in the set S i . This operation is made concrete in the following formula: denotes the floor function.
Furthermore, suppose we are given a state s and we wish to know which number was last encoded (or in other words, we wish to decode from s ). Note that the union of the subsets S i partitions the the natural numbers N, so every number can be uniquely identified with one of the symbols x i . Afterwards, if we know what the last encoded symbol x i was, we can figure out the state s that preceded that symbol by doing a look-up for x i in the set S i . The index of x i in S i equals the state s that preceded s . This operation is made concrete in the following formula, which returns a symbol-state (x, s) pair.
The new state s after encoding x i using this scheme is approximately equal to s pi . Consequently, encoding a sequence of symbols x 1 , x 2 , ..., x T onto the initial state s results in a state s T approximately equal to s T ≈ s p1p2···p T . Thus, the resulting codelength is If we divide by T , we obtain an average codelength which approaches the entropy of the data.

B. The bits-back argument
We will present a detailed explanation of the bits-back argument that is fitted to our case. Again, suppose that a sender would like to communicate a sample x to a receiver through a code that comprises the minimum amount of bits on average over p data . Now suppose that both the sender and receiver have access to the distributions q θ (z|x), p(x|z) and p(z), which parameters are optimized such that p θ (x) = p θ (x|z)p(z)dz approximates p data (x) well. Furthermore, both the sender and receiver have access to an entropy encoding technique like ANS. A naive compression scheme for the sender is 1. Sample z ∼ q θ (z|x) 2. Encode x using p θ (x|z) 3. Encode z using p(z).
This would result in a bitrate equal to N total = − log p θ (x|z) − log p(z). The resulting bitstream gets sent over and the receiver would proceed in the following way: 1. Decode z using p(z) 2. Decode x using p θ (x|z).
Consequently, the sample x is recovered in a lossless manner at the receiver's end. However, we can do better using the bits-back argument, which lets us achieve a bitrate of log q θ (z|x) − log p θ (x|z) − log p(z), which is equal to N total − log q θ (z|x). To understand this, we have to clarify what decoding means. If the model fits the true distributions perfectly, entropy encoding can be understood as a (bijective) mapping between datapoints and uniformly random distributed bits. Therefore, assuming that the bits are uniformly random distributed, decoding information x or z from the bitstream can be interpreted as sampling x or z. Now, assume the sender has access to an arbitrary bitstream N init that is already set in place. This can be in the form of previously compressed datapoints or other auxilary information. Looking at the naive compression scheme, we note that the step 'Sample z ∼ q θ (z|x)' can be substituted by 'Decode z using q θ (z|x)'. Consequently, the compression scheme at the sender's end using the bits-back argument is 1. Decode z using q θ (z|x) 2. Encode x using p θ (x|z)

Encode z using p(z).
This results in a total bitrate equal to N total = N init + log q θ (z|x) − log p θ (x|z) − log p(z). The total resulting bitstream gets sent over, and the receiver now proceeds as: 1. Decode z using p(z).

Decode x using p θ (x|z)
3. Encode z using q θ (z|x) and, again, the sample x is recovered in a lossless manner. But now, in the last step, the receiver has recovered the N init bits of auxiliary information that were set in place, thus gaining N init bits "back". Ignoring the initial bits N init , the net number of bits regarding x is which is on average equal to the negative ELBO −L(θ).
If the N init bits consist of relevant information, the receiver can then proceed by decompressing that information after gaining these "bits back". As an example, Townsend et al.
(2019) point out that it is possible to compress a sequence of datapoints {x 1:N }, where every datapoint x i (except for the first one x 1 ) uses the bitstream built up thus far as initial bitstream. Then, at the receiver's end, the datapoints {x 1:N } get decompressed in reverse order. This way the receiver effectively gains the "bits back" after finishing the three decompression steps of each datapoint x i , such that decompression of the next datapoint x i−1 can proceed. The only bits that can be irrelevant or redundant are the initial bits needed to compress the first datapoint x 1 , though this information gets amortized when compressing multiple datapoints.

C. AC and ANS: Queue vs. Stack
Entropy encoding techniques make lossless compression possible given an arbitrary discrete distribution p(x) over data. There exist several practical compression schemes, of which the most common flavors are 1. Arithmetic Coding (AC) (Witten et al., 1987) 2. Asymmetric Numeral Systems (ANS). (Duda, 2009) Both schemes operate by encoding the data into single number (in its binary representation equivalent to a sequence of bits or bitstream) and decoding the other way around, where the single number serves as the message to be sent. By doing so, both schemes result in a message length with a small overhead of around 2 bits. That is, in case of compressing x, sending/receiving a corresponding codelength of approximately However, AC and ANS differ in how they operate on the bitstream. In AC, the bitstream is treated as a queue structure, where the first bits of the bitstream are the first to be decoded (FIFO).

Bit-Swap
) ) x pθ (x|z1) qθ (z1|x) encode decode encode decode Figure 7: Arithmetic Coding (AC) operates on a bitstream in a queue-like manner. Symbols are decoded in the same order as they were encoded.
In ANS, the bitstream is treated as a stack structure, where the last bits of the bitstream are the first to be decoded (LIFO).  AC and ANS both operate on one discrete symbol x d at the time. Therefore, the compression schemes are constrained to a distribution p(x) that encompasses a product of discrete directed univariate distributions in order to operate. Furthermore, both the sender and receiver need to have access to the compression scheme and the model in order to be able to communicate. Frey & Hinton (1996) implement the bits-back theory on a single datapoint x using AC. Then the net codelength is equal to the ELBO, given the fact that we have access to an initial random bitstream. However, we must consider the length of the initial bitstream, which we call the initial bits, from which we decode z when calculating the actual codelength, in which case the codelength degenerates to E q θ (·|x) [− log p θ (x, z)] bits. So implementing bits-back on a single datapoint will not result in the advantage of getting "bits back".
By communicating a sequence of datapoints D, only the first datapoint x 1 needs to have an initial random bitstream set in place. Afterwards, a subsequent datapoint x i may just use the existing bitstream build up thus far to decode the corresponding latent variable z i . This procedure was first described by (Frey, 1998), and was called bits-back with feedback. We will use the shorter and more convenient term chaining, which was introduced by (Townsend et al., 2019).
Chaining is not directly possible with AC, because the existing bitstream is treated as a queue structure. Whereas bits-back only works if the latent variable z ∼ p(z) is decoded earlier than the corresponding datapoint x ∼ p θ (x|z), demanding z to be 'stacked' on top of x when decoding.  Figure 9: A schematic representation of the networks corresponding to q θ (z 1 |x) (left) and q θ (z i |z i−1 ) (right) of the inference model. The arrows show the direction of the forward propagation.
Frey solves this problem by reversing the order of bits of the encoded (z, x) before adding it to the bitstream. This incurs a cost between 2 to 32 bits to the encoding procedure of each datapoint x ∈ D, depending on implementation.

D. Model Architecture
For all three datasets (MNIST, CIFAR-10 and ImageNet (32 × 32)), we chose a Logistic distribution (µ = 0, σ = 1) for the prior p(z L ) and conditional Logistic distributions for q θ (z i |z i−1 ), q θ (z 1 |x) and p θ (z i |z i+l ). The distribution p θ (x|z 1 ) is chosen to be a discretized Logistic distribution as defined in . We modeled the Logistic distributions by a neural network for every pair of parameters (µ, σ). A schematic representation of the different networks is shown in Figure 9 and 10. The σ parameter of p θ (x|z 1 ) is modeled unconditionally, and optimized directly. We chose Residual blocks (He et al., 2015) as hidden layers. We also used Dropout (Srivastava et al., 2014) to prevent overfitting, Weight Normalization and Data-Dependent Initialization , Polyak averaging  Figure 10: A schematic representation of the networks corresponding to p θ (x|z 1 ) (left) and p θ (z i |z i+l ) (right) of the generative model. The arrows show the direction of the forward propagation. (Polyak & Juditsky, 1992) of the model's parameters and the Adam optimizer (Kingma & Ba, 2015).
To make a fair comparison between the different latent layer depths L for one dataset, we used B 'ordinary' Residual blocks for the entire inference model and B for the generative model, that is kept fixed for all latent layer depths L. The blocks are distributed over the L networks that make up the inference model and L networks that make up the generative model. In addition, we added P 'processing' Residual blocks at the beginning/end of the network corresponding to q θ (z 1 |x) and p θ (x|z 1 ) respectively. Finally, we decreased the channel dimension of the output of all the Residual blocks in order to ensure that the parameter count stays constant (or regresses) as we add more latent layers. All the chosen hyperparameters are shown in Table 7. We refer to the code https: //github.com/fhkingma/bitswap for further details on the implementation.

E. Usefulness of Latent Layers & Posterior Collapse
Posterior collapse is one of the drawbacks of using variational auto-encoders . Especially when using deep hierarchies of latent variables, the higher latent layers can become redundant and therefore unused (Zhao et al., 2017). We will counter this problem by using the free-bits technique as explained in  and . As a result of this technique, all latent layers across all models and datasets are used. To demonstrate this, we generated stack plots of the number of bits/dim required per stochastic layer to encode the test set over time shown in Figure 11. The bottom-most (white) area corresponds to the bottom-most (reconstruction of x) layer, the second area from the bottom denotes the first latent layer, the third area denotes the second latent layer, and so on.
F. Discretization of z 1:L In order to perform lossless compression with continuous latent distributions, we need to determine how to discretize the latent space z i for every corresponding distribution p θ (z i |z i+1 ), q θ (z i |z i−1 ) and p(z L ). In (Townsend et al., 2019), based on (MacKay, 2003), they show that if the bins δ z of z ∼ p(z) match the bins δ z of z ∼ q θ (z|x), continuous latents can be discretized up to arbitrary precision, without affecting the net compression rate as a result of getting "bits back". We generalize this result to hierarchical latent variables by stating that the bins δ zi of the latent conditional generative distributions (z 1 , .., z L ) ∼ p θ (z 1 , .., z L ) have to match the bins δ zi of the inference distributions (z 1 , .., z L ) ∼ q θ (z 1 , .., z L |x) in order to avoid affecting the compression rate. Nonetheless, the length of the initial bitstream needed to decode latent sample z 1 ∼ q θ (z 1 |x) (or possibly samples (z 1 , .., z L ) ∼ q θ (z 1 , .., z L |x)) is still dependent on the corresponding bin size(s) δ zi . Therefore, we cannot make the bin sizes δ zi too small without affecting the total codelength too much.
There are several discetization techniques we could use. One option is to simply discretize uniformly, which means dividing the space into bins of equal width. However, given the constraint that the initial bitstream needed increases with larger precision, we have to make bin sizes reasonably large. Accordingly, uniform discretization of non-uniform distributions could lead to large discretization errors and this could lead to inefficient codelengths.
An option is to follow the discretization technique used in (Townsend et al., 2019) by dividing the latent space into bins that have equal mass under some distribution (as opposed to equal width). Ideally, the bins δ zi of z i ∼ p θ (z i |z i+1 ) match the bins δ zi of z i ∼ q θ (z i |z i−1 ) and the bins δ zi have equal mass under either p θ (z i |z i+1 ) or q θ (z i |z i−1 ). However, when using ANS with hierarchical latent variable models it is not possible to let the discretization of z i ∼ q θ (z i |z i−1 ) depend on bins based on p θ (z i |z i+1 ), because z i+1 is not yet available for the sender when decoding z i . Conversely, discretization of z i ∼ p θ (z i |z i+1 ) cannot depend on bins based on q θ (z i |z i−1 ), since z i−1 is not yet available for the receiver decoding z i . Note that the operations of the compression scheme at the sender end have to be the opposite of the operations at the receiver end and we need the same discretizations for both ends. Under this conditions, it is not possible to use either p θ (z i |z i+1 ) or p θ (z i |z i−1 ) for the bin sizes δ zi and at the same time match the bins δ zi of z i ∼ p θ (z i |z i+1 ) with the bins δ zi of z i ∼ q θ (z i |z i−1 ).
So, we sampled a batch from the latent generative model

# Epochs
Bits per dimension Figure 11: Stack plots of the number of bits/dim required per stochastic layer to encode the test set over time. The bottom-most (white) area corresponds to the bottom-most (reconstruction of x) layer, the second area from the bottom denotes the first latent layer, the third area denotes the second latent layer, and so on.
p θ (z 1 , .., z L ) by ancestral sampling and a batch from the latent inference model (using the training dataset) right after learning. This gives us unbiased estimates of the statistics of the marginal distributions p θ (z 1 ), .., p(z L ), defined in Equation 5, which we can save as part of the model. Consequently, we used the marginal distributions to determine the bin sizes for discretization of z i ∼ p θ (z i |z i+1 ) and z i ∼ q θ (z i |z i−1 ). Note that we only have to perform this sampling operation once, hence this process does not affect the compression speed.
However, we found that using uniform discretization for all latent layers L except for the top one (corresponding to the prior) gives the best discretization and leads to the best compression results. Nevertheless, the top layer is discretized with bins that have equal mass under the prior, following Townsend et al. (2019).

G. General Applicability of Bit-Swap
Our work only concerns a very particular case of hierarchical latent variable models, namely hierarchical latent variable models in which the sampling process of both the generative-and inference model corresponding variational autoencoder obey Markov chains of the form z L → z L−1 → · · · → z 1 → x and z L ← z L−1 ← · · · ← z 1 ← x respectively. It might seem very restrictive to only be able to assume this topology of stochastic dependencies. However, the Bit-Swap idea can in fact be applied to any latent variable topology in which it is possible to apply the bits-back argument in a recursive manner.
To show this we present two hypothetical latent variable topologies in Figure 12. Figure 12(a) shows an asymmetrical tree structure of stochastic dependencies and Figure  12(b) shows a symmetrical tree structure of stochastic dependencies where the variables of one hierarchical layer can also be connected. In Figure 12(c) and 12(d) we show the corresponding Bit-Swap compression schemes.
The more general applicability of Bit-Swap allows us to design complex stochastic dependencies and potentially stronger models. This might be an interesting direction for future work.