Integer Discrete Flows and Lossless Compression

Emiel Hoogeboom, Jorn W. T. Peters, Rianne van den Berg, Max Welling

Introduction

Every day, 2500 petabytes of data are generated. Clearly, there is a need for compression to enable efficient transmission and storage of this data. Compression algorithms aim to decrease the size of representations by exploiting patterns and structure in data. In particular, lossless compression methods preserve information perfectly–which is essential in domains such as medical imaging, astronomy, photography, text and archiving. Lossless compression and likelihood maximization are inherently connected through Shannon’s source coding theorem , i.e., the expected message length of an optimal entropy encoder is equal to the negative log-likelihood of the statistical model. In other words, maximizing the log-likelihood (of data) is equivalent to minimizing the expected number of bits required per message.

In practice, data is usually high-dimensional which introduces challenges when building statistical models for compression. In other words, designing the likelihood and optimizing it for high dimensional data is often difficult. Deep generative models permit learning these complicated statistical models from data and have demonstrated their effectiveness in image, video, and audio modeling . Flow-based generative models are advantageous over other generative models: i) they admit exact log-likelihood optimization in contrast with Variational AutoEncoders (VAEs) and ii) drawing samples (and decoding) is comparable to inference in terms of computational cost, as opposed to PixelCNNs . However, flow-based models are generally defined for continuous probability distributions, disregarding the fact that digital media is stored discretely–for example, pixels from 8-bit images have 256 distinct values. In order to utilize continuous flow models for compression, the latent space must be quantized. This produces reconstruction errors in image space, and is therefore not suited for lossless compression.

To circumvent the (de)quantization issues, we propose Integer Discrete Flows (IDFs), which are invertible transformations for ordinal discrete data–such as images, video and audio. We demonstrate the effectiveness of IDFs by attaining state-of-the-art lossless compression performance on CIFAR10, ImageNet32 and ImageNet64. For a graphical illustration of the coding steps, see Figure 1. In addition, we show that IDFs achieve generative modelling results competitive with other flow-based methods. The main contributions of this paper are summarized as follows: 1) We introduce a generative flow for ordinal discrete data (Integer Discrete Flow), circumventing the problem of (de)quantization; 2) As building blocks for IDFs, we introduce a flexible transformation layer called integer discrete coupling; 3) We propose a neural network based compression method that leverages IDFs; and 4) We empirically show that our image compression method allows for progressive decoding that maintains the global structure of the encoded image. Code to reproduce the experiments is available at https://github.com/jornpeters/integer_discrete_flows.

Background

The continuous change of variables formula lies at the foundation of flow-based generative models. It admits exact optimization of a (data) distribution using a simple distribution and a learnable bijective map. Let f:X→Zf:\mathcal{X}\to\mathcal{Z} be a bijective map, and pZ(⋅)p_{Z}(\cdot) a prior distribution on Z\mathcal{Z}. The model distribution pX(⋅)p_{X}(\cdot) can then be expressed as:

That is, for a given observation xx, the likelihood is given by pZ(⋅)p_{Z}(\cdot) evaluated at f(x)f(x), normalized by the Jacobian determinant. A composition of invertible functions, which can be viewed as a repeated application of the change of variables formula, is generally referred to as a normalizing flow in the deep learning literature .

The design of invertible transformations is integral to the construction of normalizing flows. In this section two important layers for flow-based generative modelling are discussed.

where ⊙\odot denotes element-wise multiplication and ss and tt may be modelled using neural networks. Given this, the inverse is easily computed, i.e., xa=za\mathbf{x}_{a}=\mathbf{z}_{a}, and xb=(zb−t(xa))⊘s(xa)\mathbf{x}_{b}=(\mathbf{z}_{b}-\mathbf{t}(\mathbf{x}_{a}))\oslash\mathbf{s}(\mathbf{x}_{a}), where ⊘\oslash denotes element-wise division. For f(⋅)f(\cdot) to be invertible, s(xa)\mathbf{s}(\mathbf{x}_{a}) must not be zero, and is often constrained to have strictly positive values.

Factor-out layers allow for more efficient inference and hierarchical modelling. A general flow, following the change of variables formula, is described as a single map X→Z\mathcal{X}\to\mathcal{Z}. This implies that a dd-dimensional vector is propagated throughout the whole flow model. Alternatively, a part of the dimensions can already be factored-out at regular intervals , such that the remainder of the flow network operates on lower dimensional data. We give an example for two levels (L=2L=2) although this principle can be applied to an arbitrary number of levels:

This approach has two clear advantages. First, it admits a factored model for z\mathbf{z}, p(z)=p(zL)p(zL−1∣zL)⋯p(z1∣z2,…,zL)p(\mathbf{z})=p(\mathbf{z}_{L})p(\mathbf{z}_{L-1}|\mathbf{z}_{L})\cdots p(\mathbf{z}_{1}|\mathbf{z}_{2},\ldots,\mathbf{z}_{L}), which allows for conditional dependence between parts of z\mathbf{z}. This holds because the flow defines a bijective map between yl\mathbf{y}_{l} and [zl+1,…,zL][\mathbf{z}_{l+1},\ldots,\mathbf{z}_{L}]. Second, the lower dimensional flows are computationally more efficient.

2 Entropy Encoding

Lossless compression algorithms map every input to a unique output and are designed to make probable inputs shorter and improbable inputs longer. Shannon’s source coding theorem states that the optimal code length for a symbol xx is −log⁡D(x)-\log\mathcal{D}(x), and the minimum expected code length is lower-bounded by the entropy:

where c(x)c(x) denotes the encoded message, which is chosen such that ∣c(x)∣≈−log⁡pX(x)|c(x)|\approx-\log p_{X}(x), ∣⋅∣|\cdot| is length, H\mathcal{H} denotes entropy, D\mathcal{D} is the data distribution, and pX(⋅)p_{X}(\cdot) is the statistical model that is used by the encoder. Therefore, maximizing the model log-likelihood is equivalent to minimizing the expected number of bits required per message, when the encoder is optimal.

Stream coders encode sequences of random variables with different probability distributions. They have near-optimal performance, and they can meet the entropy-based lower bound of Shannon . In our experiments, the recently discovered and increasingly popular stream coder rANS is used. It has gained popularity due to its computational and coding efficiency. See Appendix A.1 for an introduction to rANS.

Integer Discrete Flows

In contrast to existing coupling layers, the input is split in 75%–25% parts for xa\mathbf{x}_{a} and xb\mathbf{x}_{b}, respectively. As a consequence, rounding is applied to fewer dimensions, which results in less gradient bias. In addition, the transformation is richer, because it is conditioned on more dimensions. Empirically this results in better performance.

Backpropagation through Rounding Operation As shown in Figure 2, a coupling layer in IDF requires a rounding operation (⌊⋅⌉\lfloor\cdot\rceil) on the predicted translation. Since the rounding operation is effectively a step function, its gradient is zero almost everywhere. As a consequence, the rounding operation is inherently incompatible with gradient based learning methods. In order to backpropagate through the rounding operations, we make use of the Straight Through Estimator (STE) . In short, the STE ignores the rounding operation during back-propagation, which is equivalent to redefining the gradient of the rounding operation as follows:

Lower Triangular Coupling There exists a trade-off between the number of integer discrete coupling layers and the complexity of the layers in IDF architectures, due to the gradient bias that is introduced by the rounding operation (see section 4.1). We introduce a multivariate coupling transformation called Lower Triangular Coupling, which is specifically designed such that the number of rounding operations remains unchanged. For more details, see Appendix B.

2 Tractable Discrete distribution

As discussed in Section 2, a simple distribution pZ(⋅)p_{Z}(\cdot) is posed on Z\mathcal{Z} in flow-based models. In IDFs, the prior pZ(⋅)p_{Z}(\cdot) is a factored discretized logistic distribution (DLogistic) . The discretized logistic captures the inductive bias that values close together are related, which is well-suited for ordinal data.

where σ(⋅)\sigma(\cdot) denotes the sigmoid, the cumulative distribution function of a standard Logistic. In the context of a factor-out layer, the mean μ\mu and scale ss are conditioned on the subset of

data that is not factored out. That is, the input to the llth factor-out layer is split into zl\mathbf{z}_{l} and yl\mathbf{y}_{l}. The conditional distribution on zl,i\mathbf{z}_{l,i} is then given as DLogistic(zl,i∣μ(yl)i,s(yl)i)\text{DLogistic}(\mathbf{z}_{l,i}|\boldsymbol{\mu}(\mathbf{y}_{l})_{i},\textbf{s}(\mathbf{y}_{l})_{i}), where μ(⋅)\boldsymbol{\mu}(\cdot) and s(⋅)\textbf{s}(\cdot) are parametrized as neural networks.

Discrete Mixture distributions The discretized logistic distribution is unimodal and therefore limited in complexity. With a marginal increase in computational cost, we increase the flexibility of the latent prior on zL\mathbf{z}_{L} by extending it to a mixture of KK logistic distributions :

Note that as K→∞K\to\infty, the mixture distribution can model arbitrary univariate discrete distributions. In practice, we find that a limited number of mixtures (K=5K=5) is usually sufficient for image density modelling tasks.

3 Lossless Source Compression

Lossless compression is an essential technique to limit the size of representations without destroying information. Methods for lossless compression require i) a statistical model of the source, and ii) a mapping from source symbols to bit streams.

IDFs are a natural statistical model for lossless compression of ordinal discrete data, such as images, video and audio. They are capable of modelling complicated high-dimensional distributions, and they provide error-free reconstructions when inverting latent representations. The mapping between symbols and bit streams may be provided by any entropy encoder. Specifically, stream coders can get arbitrarily close to the entropy regardless of the symbol distributions, because they encode entire sequences instead of a single symbol at a time.

In the case of compression using an IDF, the mapping f:x↦zf:\mathbf{x}\mapsto\mathbf{z} is defined by the IDF. Subsequently, z\mathbf{z} is encoded under the distribution pZ(z)p_{Z}(\mathbf{z}) to a bitstream c\mathbf{c} using an entropy encoder. Note that, when using factor-out layers, pZ(z)p_{Z}(\mathbf{z}) is also defined using the IDF. Finally, in order to decode a bitstream c\mathbf{c}, an entropy encoder uses pZ(z)p_{Z}(\mathbf{z}) to obtain z\mathbf{z}. and the original image is obtained by using the map f−1:z↦xf^{-1}:\mathbf{z}\mapsto\mathbf{x}, i.e., the inverse IDF. See Figure 1 for a graphical depiction of this process.

In rare cases, the compressed file may be larger than the original. Therefore, following established practice in compression algorithms, we utilize an escape bit. That is, the encoder will decide whether to encode the message or save it in raw format and encode that decision into the first bit.

Architecture

The IDF architecture is split up into one or more levels. Each level consists of a squeeze operation , DD integer flow layers, and a factor-out layer. Hence, each level defines a mapping from yl−1\mathbf{y}_{l-1} to [zl,yl][\mathbf{z}_{l},\mathbf{y}_{l}], except for the final level LL, which defines a mapping yL−1↦zL\mathbf{y}_{L-1}\mapsto\mathbf{z}_{L}. Each of the DD integer flow layers per level consist of a permutation layer followed by an integer discrete coupling layer. Following , the permutation layers are initialized once and kept fixed throughout training and evaluation. Figure 5 shows a graphical illustration of a two level IDF. The specific architecture details for each experiment are presented in Appendix D.1. In the remainder of this section, we discuss the trade-off between network depth and performance when rounding operations are used.

The performance of IDFs depends on a trade-off between complexity and gradient bias, influenced by the number of rounding functions. Increasing the performance of standard normalizing flows is often achieved by increasing the depth, i.e., the number of flow-modules. However, for IDFs each flow-module results in additional rounding operations that introduce gradient bias. As a consequence, adding more flow layers hurts performance, after some point, as is depicted in Figure 5. We found that the limitation of using fewer coupling layers in an IDF can be negated by increasing the complexity of the neural networks part of the coupling and factor-out layers. That is, we use DenseNets in order to predict the translation t\mathbf{t} in the integer discrete coupling layers and μ\mu and ss in the factor-out layers.

Related Work

There exist several deep generative modelling frameworks. This work builds mainly upon flow-based generative models, described in . In these works, invertible functions for continuous random variables are developed. However, quantizing a latent representation, and subsequently inverting back to image space may lead to reconstruction errors .

Other likelihood-based models such as PixelCNNs utilize a decomposition of conditional probability distributions. However, this decomposition assumes an order on pixels which may not reflect the actual generative process. Furthermore, drawing samples (and decoding) is generally computationally expensive. VAEs optimize a lower bound on the log likelihood instead of the exact likelihood. They are used for lossless compression with deterministic encoders and through bits-back coding. However, the performance of this approach is bounded by the lower bound. Moreover, in bits back coding a single data example can be inefficient to compress, and the extra bits should be random, which is not the case in practice and may also lead to coding inefficiencies .

Non-likelihood based generative models tend to utilize Generative Adversarial Networks , and can generate high-quality images. However, since GANs do not optimize for likelihood, which is directly connected to the expected number of bits in a message, they are not suited for lossless compression.

In the lossless compression literature, numerous reversible integer to integer transforms have been proposed . Specifically, lossless JPEG2000 uses a reversible integer wavelet transform . However, because these transformations are largely hand-designed, they are difficult to tune for real-world data, which may require complicated nonlinear transformations.

Around time of submission, unpublished concurrent work appeared that explores discrete flows. The main differences between our method and this work are: i) we propose discrete flows for ordinal discrete data (e.g. audio, video, images), whereas they are are focused on categorical data. ii) we provide a connection with the source coding theorem, and present a compression algorithm. iii) We present results on more large-scale image datasets.

Experiments

To test the compression performance of IDFs, we compare with a number of established lossless compression methods: PNG ; JPEG2000 ; FLIF , a recent format that uses machine learning to build decision trees for efficient coding; and Bit-Swap , a VAE based lossless compression method. We show that IDFs outperform all these formats on CIFAR10, ImageNet32 and ImageNet64. In addition, we demonstrate that IDFs can be very easily tuned for specific domains, by compressing the ER + BCa histology dataset. For the exact treatment of datasets and optimization procedures, see Section D.4.

The compression performance of IDFs is compared with competing methods on standard datasets, in bits per dimension and compression rate. The IDFs and Bit-Swap are trained on the train data, and compression performance of all methods is reported on the test data in Table 1. IDFs achieve state-of-the-art lossless compression performance on all datasets.

Even though one can argue that a compressor should be tuned for the source domain, the performance of IDFs is also examined on out-of-dataset examples, in order to evaluate compression generalization. We utilize the IDF trained on Imagenet32, and compress the CIFAR10 and ImageNet64 data. For the latter, a single image is split into four 32×3232\times 32 patches. Surprisingly, the IDF trained on ImageNet32 (IDF†) still outperforms the competing methods showing only a slight decrease in compression performance on CIFAR10 and ImageNet64, compared to its source-trained counterpart.

As an alternative method for lossless compression, one could quantize the distribution pZ(⋅)p_{Z}(\cdot) and the latent space Z\mathcal{Z} of a continuous flow. This results in reconstruction errors that need to be stored in addition to the latent representation z\mathbf{z}, such that the original data can be recovered perfectly. We show that this scheme is ineffective for lossless compression. Results are presented in Appendix C.

2 Tuneable Compression

Thus far, IDFs have been tested on standard machine learning datasets. In this section, IDFs are tested on a specific domain, medical images. In particular, the ER + BCa histology dataset is used, which contains 141 regions of interest scanned at 40×40\times, where each image is 2000×20002000\times 2000 pixels (see Figure 6, left). Since current hardware does not support training on such large images directly, the model is trained on random 80×8080\times 80px patches. See Figure 6, right for samples from the model. Likewise, the compression is performed in a patch-based manner, i.e., each patch is compressed independently of all other patches. IDFs are again compared with FLIF and JPEG2000, and also with a modified version of JPEG2000 that has been optimized for virtual microscopy specifically, named JP2-WSI . Although the IDF is at a disadvantage because it has to compress in patches, it considerably outperforms the established formats, as presented in Table 2.

3 Progressive Image Rendering

In general, transferring data may take time because of slow internet connections or disk I/O. For this reason, it is desired to progressively visualize data, i.e., to render the image with more detail as more data arrives. Several graphics formats support progressive loading. However, the encoded file size may increase by enabling this option, depending on the format , whereas IDFs support progressive rendering naturally. To partially render an image using IDFs, first the received variables are decoded. Next, using the hierarchical structure of the prior and ancestral sampling, the remaining dimensions are obtained. The progressive display of IDFs for ImageNet64 is presented in Figure 8, where the rows use approximately 15%, 30%, 60%, and 100% of the bitstream. The global structure is already captured by smaller fragments of the bitstream, even for fragments that contain only 15% of the stream.

4 Probability Mass Estimation

In addition to a statistical model for compression, IDFs can also be used for image generation and probability mass estimation. Samples are drawn from an ImageNet 32×\times32 IDF and presented in Figure 7. IDFs are compared with recent flow-based generative models, RealNVP , Glow , and Flow++ in analytical bits per dimension (negative log2-likelihood). To compare architectural changes, we modify the IDFs to Continuous models by dequantizing, disabling rounding, and using a continuous prior. The continuous versions of IDFs tend to perform slightly better, which may be caused by the gradient bias on the rounding operation. IDFs show competitive performance on CIFAR10, ImageNet32, and ImageNet64, as presented in Table 3. Note that in contrast with IDFs, RealNVP uses scale transformations, Glow has 1×11\times 1 convolutions and actnorm layers for stability, and Flow++ uses the aforementioned, and an additional flow for dequantization. Interestingly, IDFs have comparable performance even though the architecture is relatively simple.

Conclusion

We have introduced Integer Discrete Flows, flows for ordinal discrete data that can be used for deep generative modelling and neural lossless compression. We show that IDFs are competitive with current flow-based models, and that we achieve state-of-the-art lossless compression performance on CIFAR10, ImageNet32 and ImageNet64. To the best of our knowledge, this is the first lossless compression method that uses invertible neural networks.

References

Appendix A Additional background

Asymmetric Numeral Systems (ANS) is a recent approach to entropy coding. The range-based variant: rANS, is generally used as a faster replacement for arithmetic coding, because a state is only represented by a single number and fewer mathematical operations are required .

The encoding function of rANS encodes a symbol ss into a code c′c^{\prime} given the so far existing code cc:

where mm is a large integer that functions as the quantization denominator. Integers are chosen for lsl_{s} such that p(s)≈\nicefraclsmp(s)\approx\nicefrac{{l_{s}}}{{m}}, where p(s)p(s) denotes the probability of symbol ss. Each symbol is associated with a unique interval [bs,bs+ls)[b_{s},b_{s}+l_{s}), where bs=∑i=1s−1lib_{s}=\sum_{i=1}^{s-1}l_{i}, as depicted in Figure 9.

The decoding function needs to retrieve the encoded symbol ss, and the previous state cc from the new code c′c^{\prime}. First consider the term c′ mod mc^{\prime}\text{ mod }m, which is equal to the last two terms of the encoding function: c mod ls+bsc\text{ mod }l_{s}+b_{s}. This term is guaranteed to lie in the interval [bs[b_{s}, bs+ls)b_{s}+l_{s}). Therefore, the symbol can be retrieved by finding:

Consequently with the knowledge of ss, the previous state cc can be obtained by computing:

In practice, mm is chosen as a power of two (for example 2322^{32}). As such, multiplication and division with mm reduces to bit shifts and modulo mm reduces to a binary masking operation.

Appendix B Lower Triangular Coupling

There exists a trade-off between the number of integer discrete coupling layers and the complexity of the layers in IDF architectures, due to the gradient bias that is introduced by the rounding operation. For this reason, it is desired to increase the flexibility of layers without increasing the number of rounding operations. We introduce a multivariate coupling transformation called Lower Triangular Coupling, which is specifically designed such that the number of rounding operations remains unchanged. In practice, Lower Triangular Coupling does not offer significant improvements over standard coupling layers, and they both attain 4.15 bits per dimension (standard ±\pm0.009 and lower triangular ±\pm0.007), which is averaged over two runs with random weight initialization. The method is presented below for completeness.

The transformation of xb\mathbf{x}_{b} is formed by multiplication with a strictly lower triangular matrix L\mathbf{L} which is conditioned on xa\mathbf{x}_{a}:

The main trick is to round the sum of all transformations, such that no additional gradient bias is introduced. This transformation is guaranteed to be invertible, and the inverse can be found with a modified version of forward substitution:

where xi(b)x_{i}^{(b)} denotes the iith element of xb\mathbf{x}_{b}, and t\mathbf{t} and L\mathbf{L} are still conditioned on xa\mathbf{x}_{a}, however, this notation is dropped for clarity. The continuous case can even be solved analytically by using the inverse xb=(I+L)−1(zb−t)\mathbf{x}_{b}=(\mathbf{I}+\mathbf{L})^{-1}\left(\mathbf{z}_{b}-\mathbf{t}\right).

Appendix C Quantizing a Continuous Flow

To test the lossless compression performance of continuous flows, the latent space is quantized to a linear spaced bins. Because the latent space is quantized, the reconstructions may contain errors. To enable lossless compression, FLIF is used to encode the errors in reconstruction. Hence, given the quantized latent variables and the reconstruction errors, the original input can be obtained.

The performance of the quantized flow is shown in Figure 10. When the bin size is large (1128\frac{1}{128}), encoding the latent representation requires relatively few bits, because the probability area is larger. However, the residuals are higher, and require more bits to be modelled. Analogously, when the bin size is small (1512\frac{1}{512}), encoding the latent representation requires more bits, but the residual can be modelled using fewer bits. Although the bits required for the residual or the quantized latents may be small individually, their sum is always large. In total the quantized flow performs poorly on lossless compression.

Appendix D Experimental details

The coupling and factor out layers are parametrized using neural networks. These networks are DenseNets . Specifically we use n=512n=512 intermediate channels and a depth d=12d=12. In contrast with standard DenseNets, we do not use normalization layers. A single layer in the densenet consists of:

D.2 IDF architecture

The exact architecture for experiments is specified in Table 4. All models are trained using Adamax with standard parameters. Furthermore, the learning rate is computed as: lr=lrbase⋅decayepoch\text{{lr}}=\text{{lr}}_{\text{{base}}}\cdot\text{{decay}}^{\text{{epoch}}}. We follow the preprocessing procedure for CIFAR10 as described in . For ImageNet32 and ImageNet64, we do use additional preprocessing. For the ER + BCa dataset, we employ random horizontal and vertical flips during training.

D.3 Dataset preparation

The dataset for CIFAR10 originally consists of 50000 train images and 10000 test images. We use the last 10000 images for validation which results in 40000 train, 10000 validation and 10000 test images. ImageNet32 and ImageNet64 originally contain approximately 1250000 train and 50000 validation images. The validation images are used solely for testing, and 20000 images are randomly selected as a new validation set. This results in roughly 1230000 train, 20000 validation and 50000 test images.

The ER + BCa dataset http://andrewjanowczyk.com/wp-static/nuclei.tgz is split into 114114 train images and 2828 test images such that specific patients IDs only occur in one of the two sets. The test patient identifiers are:

D.4 Hardware and Software

The code for our experiments is implemented using PyTorch . The model implementations are based on the codebase released along with whereas the rANS coder implementation was taken from . All experiments were run using 4 Nvidia GTX 1080Ti GPUs.