Skip to content
ImagineWorld

Deep Generative Modeling for Neural Compression

node_idnode-book_deep-generative-modeling_chapter-08-deep-generative-modeling-for-neural-compression
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num8
chapter_titleDeep Generative Modeling for Neural Compression
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 8 — Deep Generative Modeling for Neural Compression

Section titled “Chapter 8 — Deep Generative Modeling for Neural Compression”

Chapter 8 Deep Generative Modeling for Neural Compression

8.1 Introduction

In December 2020, Facebook reported having around 1.8 billion daily active users and around 2.8 billion monthly active users [1]. Assuming that users uploaded, on average, a single photo each day, the resulting volume of data would give a very rough (let me stress it: a very rough) estimate of around 3000TB of new images per day. This single case of Facebook alone already shows us potential great costs associated with storing and transmitting data. In the digital era we can simply say this: efficient and effective manner of handling data (i.e., faster and smaller) means more money in the pocket.

The most straightforward way of dealing with these issues (i.e., smaller and faster) is based on applying compression, and, in particular, image compression algorithms (codecs) that allow us to decrease the size of an image. Instead of changing infrastructure, we can efficiently and effectively store and transmit images by making them simply smaller! Let us be honest, the more we compress an image, the more and faster we can send and the less disk memory we need!

If we think of image compression, probably the first association is JPEG or PNG, standards used on the daily basis by everyone. I will not go into details of these standards (e.g., see [2, 3] for an introduction) but what it is important to know is that they use some pre-defined math like Discrete Cosine Transform. The main advantage of the standard codecs like JPEG is that they are interpretable, i.e., all steps are hand-designed and their behavior could be predicted. However, this comes at the cost of insufficient flexibility that could drastically decrease their performance. So how we can increase the flexibility of transformations? Any idea? Anyone? Do I hear deep learning [4, 5]? Indeed! Many of today’s image compression algorithms are enhanced by neural networks.

The emerging field of compression algorithms using neural networks is called neural compression. Neural compression becomes a leading trend in developing new codecs where neural networks replace parts of the standard codecs [6], or

© The Author(s), under exclusive license to Springer Nature Switzerland AG 2022 J. M. Tomczak, Deep Generative Modeling, https://doi.org/10.1007/978-3-030-93158-2_8

neural-based codecs are trained [7] together with quantization [8] and entropy coding [9–12]. We will discuss the general compression scheme in detail in the next subsection but here it is important to understand why deep generative modeling is important in the context of neural compression. The answer was given a long time ago by Claude Shannon who showed in [13] that (informally):

The length of a message representing a source data is proportional to the entropy of this data.

We do not know the entropy of data because we do not know the probability distribution of data, p(x)p(\mathbf{x}), but we can estimate it using one of the deep generative models we have discussed so far! Because of that, recently, there is an increasing interest in using deep generative modeling to improve neural compression. We can use deep generative models for modeling probability distribution for entropy coders [9–12], but also to significantly increase the final reconstruction and compression quality by incorporating new schemes for inference [14] and reconstruction [15].

Before we jump into neural compression, it is beneficial (and educational, don’t be afraid of refreshing the basics!) to remind ourselves what is image (or data, in general) compression. We can distinguish two image compression approaches [16], namely:

  • lossless compression: a method that preserves all information and reconstructions are error-free,
  • lossy compression: information is not preserved completely by a compression method.

A general recipe for designing a compression algorithm relies on devising a uniquely decodable code whose expected length is as close as possible to the entropy of the data [13]. The general compression system consists of two components [16, 17]: an encoder and a decoder. Please do not think of it as a deterministic VAE because it is not the same. There are some similarities but in the compression task, we are really interested in sending the bitstream while in VAEs we typically do not care at all. We play with floats and say about codes just to make it more intuitive but it requires a few extra steps to turn it into a “real” compression scheme. We are going to explain these extra in the next sections. Alright, let’s start!

In the encoder, the goal is to transform an image into a discrete signal. It is important to understand that the signal does not necessarily need to be binary. The transformation we use could be invertible, however, it is not a requirement. If the transformation is invertible, then we can use its inverse in the decoder and, in principle, we can talk about lossless compression. Why? Take a look at the flow- 8.2 General Compression Scheme

[!visual-conversion] Flow diagram with real embedded photographs (original/reconstructed cat image) — photographic content. Cropped from page 183. source_page: pages/page-183.png | visual_type: diagram + photographs

dgm-fig-8.1-compression-codec.png Fig. 8.1 A general image compression system (a codec)

based models where we discussed invertibility. However, if the transformation is not invertible, then some information is lost and we land in the group of lossy compression methods. Next, after applying the transformation to the input image, the discrete signal is encoded into a bitstream in a lossless manner. In other words, discrete symbols are mapped to binary variables (bits). Typically, entropy coders utilize information about the probability of symbol occurrence, e.g., Huffman coders or arithmetic coders [16]. This is important to understand that for many entropy coders we need to know p(x)p(\mathbf{x}) and here we can use deep generative models.

Decoder

Once the message (i.e., the bits) is sent and received, the bitstream is decoded to the discrete signal by the entropy decoder. The entropy decoder is the inversion of the entropy encoder. Entropy coding methods allow us to receive the original symbols from the bitstream. Eventually, an inverse transformation (not necessarily the inversion of the encoder transformation) is applied to reconstruct the original image.

The Full Scheme

Please see Fig.8.1 for a general scheme of a compression system (a codec). The standard codecs mainly utilize multi-scale image decomposition like wavelet representation [3, 18] that are further quantized. Considering a specific discrete transformation (e.g., Discrete Cosine Transform (DCT)) results in a specific codec (e.g., JPEG [2]).

The Objective

The final performance of a codec is evaluated in terms of reconstruction error and compression ratio. The reconstruction error is called distortion measure and is calculated as a difference between the original image and the reconstructed image using the mean square error (MSEMSE) (typically, the peak signal-to-noise ratio PSNRPSNR expressed as 10log⁡102552MSE10 \log_{10} \frac{255^2}{MSE} is reported) or perceptual metrics like the multi-scale structure similarity index (MS-SSIMMS\text{-}SSIM) [19]. The compression ratio, called rate, is usually expressed by the bits per pixel (bpp), i.e., the total size in bits of the encoder output divided by the total size in pixels of the encoder input [17]. Typically, the performance of codecs is compared by inspecting the rate-distortion plane (i.e., plotting curves on a plane with the rate on the x-axis and the distortion on the y-axis).

Formally, we assume an auto-encoder architecture (see Fig. 8.1 again) with an encoding transformation, fe:X→Yf_e : \mathcal{X} \to \mathcal{Y}, that takes an input x\mathbf{x} and returns a discrete signal y\mathbf{y} (a code). After sending the message, a reconstruction x^\hat{\mathbf{x}} is given by a decoder, fd:Y→Xf_d : \mathcal{Y} \to \mathcal{X}. Moreover, there is an (adaptive) entropy coding model that learns the distribution p(y)p(\mathbf{y}) and is further used to turn the discrete signal y\mathbf{y} into a bitstream by an entropy coder (e.g., Huffman coding, arithmetic coding). If a compression method has any adaptive (hyper)parameters, it could be learned by optimizing the following objective function:

L(x)=d(x,x^)+βr(y) ,(8.1)\mathcal{L}(\mathbf{x}) = d(\mathbf{x}, \hat{\mathbf{x}}) + \beta r(\mathbf{y}) \,, \tag{8.1}

where d(⋅,⋅)d(\cdot, \cdot) is the distortion measure (e.g., PSNR, MS-SSIM), and r(⋅)r(\cdot) is the rate measure (e.g., r(y)=−ln⁡p(y)r(\mathbf{y}) = -\ln p(\mathbf{y})), β>0\beta > 0 is a weighting factor controlling the balance between rate and distortion. Notice that distortion requires both the encoder and the decoder, and rate requires the encoder, and the entropy model.

We have discussed all necessary concepts of image compression and now we can delve into neural compression. However, before we do that, the first question we face is whether we can get any benefit from using neural networks for compression and where and how we can use them in this context. As mentioned already, standard codecs utilize a series of pre-defined transformations and mathematical operations. But how does it work?

Let us quickly discuss one of the most commonly used codecs: JPEG. In the JPEG codec, an RGB image is first linearly transformed to the YCbCr format:

[YCbCr]=[0128128]+[0.2990.5870.114−0.168736−0.3312640.50.5−0.48688−0.081312][RGB](8.2)\begin{bmatrix} Y \\ Cb \\ Cr \end{bmatrix} = \begin{bmatrix} 0 \\ 128 \\ 128 \end{bmatrix} + \begin{bmatrix} 0.299 & 0.587 & 0.114 \\ -0.168736 & -0.331264 & 0.5 \\ 0.5 & -0.48688 & -0.081312 \end{bmatrix} \begin{bmatrix} R \\ G \\ B \end{bmatrix} \tag{8.2}

Then, the Cb and Cr channels are downscaled, typically two or three times (the first compression stage). After that, each channel is split into, e.g., 8×88 \times 8 blocks, and fed to the discrete cosine transform (DCT) that is eventually quantized (the 8.4 Neural Compression: Components

[!visual-conversion] Flow diagram with real embedded photographs — photographic content. Cropped from page 185. source_page: pages/page-185.png | visual_type: diagram + photographs

dgm-fig-8.2-jpeg-system.png Fig. 8.2 A JPEG compression system second compression stage). After all, the Huffman coding could be used. To decode the signal, the inverse DCT is used, the Cb and Cr channels are upscaled and the RGB representation is recovered. The whole system is presented in Fig. 8.2. As you can notice, each step is easy to follow and if you know how DCT works, the whole procedure is a white box. There are some hyperparameters but, again, they have a very clear interpretation (e.g., how many times the Cb and Cr channels are downscaled, the size of blocks).

8.4 Neural Compression: Components

Alright, we know now how a standard codec works. However, one of the problems with standard codecs is that they are not necessarily flexible. One may ask whether DCT is the optimal transformation for all images. The answer is, with high probability, no. If we are willing to give up the nicely designed white box, we can turn it into a black box by replacing all mathematical operations with neural networks. The potential gain is increased flexibility and potentially better performance (both in terms of distortion and rate).

We need to remember though that learning neural network requires the differentiability of the whole approach. However, we require a discrete output of the neural network that could break the backpropagation! For this purpose, we must formulate a differentiable quantization procedure. Additionally, to obtain a powerful model, we need an adaptive entropy coding model. This is an important component of the neural compression pipeline because it not only optimizes the compression ratio (i.e., the rate) but also helps to learn a useful codebook. Next, we will discuss both components in detail.

Encoders and Decoders In neural compression, unlike in VAEs, the encoder and the decoder consist of neural networks with no additional functions. As a result, we focus on architectures rather than how to parameterize a distribution, for instance. The output of the encoder is a continuous code (floats) and the output of the decoder is a reconstruction of an image. Below we present PyTorch classes for an encoder and a decoder with examples of neural networks.

# The encoder is simply a neural network that takes an image and
# outputs a corresponding code.
class Encoder(nn.Module):
def __init__(self, encoder_net):
super(Encoder, self).__init__()
self.encoder = encoder_net
def encode(self, x):
h_e = self.encoder(x)
return h_e
def forward(self, x):
return self.encode(x)
# The decoder is simply a neural network that takes a quantized
# code and returns an image.
class Decoder(nn.Module):
def __init__(self, decoder_net):
super(Decoder, self).__init__()
self.decoder = decoder_net
def decode(self, z):
h_d = self.decoder(z)
return h_d
def forward(self, z, x=None):
x_rec = self.decode(z)
return x_rec

Listing 8.1 Classes for an encoder and a decoder

# ENCODER
e_net = nn.Sequential(
nn.Linear(D, M*2), nn.BatchNorm1d(M*2), nn.ReLU(),
nn.Linear(M*2, M), nn.BatchNorm1d(M), nn.ReLU(),
nn.Linear(M, M//2), nn.BatchNorm1d(M//2), nn.ReLU(),
nn.Linear(M//2, C)
)
encoder = Encoder(encoder_net=e_net)
# DECODER
d_net = nn.Sequential(
nn.Linear(C, M//2), nn.BatchNorm1d(M//2), nn.ReLU(),
nn.Linear(M//2, M), nn.BatchNorm1d(M), nn.ReLU(),

8.4 Neural Compression: Components

nn.Linear(M, M*2), nn.BatchNorm1d(M*2), nn.ReLU(),
nn.Linear(M*2, D)
decoder = Decoder(decoder_net=d_net)

Listing 8.2 Examples of neural networks for the encoder and the decoder

Differentiable Quantization The problem with utilizing neural networks in the compression context is that we must ensure training by backpropagation that is equivalent to using only differentiable operations. Unfortunately, working with discrete outputs of a neural network breaks differentiability and requires applying approximations of gradients (e.g., the Straight-Through Estimator). However, we can use quantization of codes y and make it differentiable with relatively simple tricks.

We assume that the encoder gives us a code y∈RMy \in \mathbb{R}^M. Moreover, we assume that there is a codebook c∈RKc \in \mathbb{R}^K. We can think of the codebook as a vector of additional parameters (yes, parameters, we can also learn it!). Now, the whole idea relies on quantizing y to values in the codebook c. Easy right? Well, it is easy but it still tells us nothing. Quantizing in this context means that we will take every element in y and find the closest value in the codebook and replace it with this codebook value. We can implement it using matrix calculus in the following manner. First, we repeat y K-times and we repeat c M-times that gives us two matrices: Y∈RM×KY \in \mathbb{R}^{M \times K} and C∈RM×KC \in \mathbb{R}^{M \times K}. Now, we can calculate a similarity matrix, for instance: S=exp⁡{−(Y−C)2}∈RM×KS = \exp\{-\sqrt{(Y - C)^2}\} \in \mathbb{R}^{M \times K}. The matrix S has the highest value where the m-th value of y, ymy_m, is closest to the k-th vale of c, ckc_k. So far so good, all operations are differentiable. However, there is no quantization here (i.e., values are not discrete). Since we have the similarity matrix S∈RM×KS \in \mathbb{R}^{M \times K} and we can apply the softmax non-linearity with temperature to the second dimension of S, namely S^=softmax2(τ⋅S)\hat{S} = \text{softmax}_2(\tau \cdot S) (here, the subscript denotes that we calculate the softmax w.r.t the second dimension) where τ≫1\tau \gg 1 (e.g., τ=107\tau = 10^7). Since we apply the softmax to the similarity matrix multiplied by a very large number, the resulting matrix, S^\hat{S}, will still consist of floats but numerically these values will be 0’s and a single 1. An example of this kind of quantization is presented in Fig. 8.3.

Importantly, the softmax non-linearity is differentiable and, eventually, the whole procedure is differentiable. In the end, we can calculate quantized codes by multiplying the codebook with the 0-1 similarity matrix, namely

y^=S^c.(8.3)\hat{y} = \hat{S}c. \tag{8.3}

The resulting code, y^\hat{y}, consists of values from the codebook only.

We can ask ourselves whether indeed we gain anything because values of y^\hat{y} are still floats. So, in other words, where is the discrete signal we want to turn into the bitstream? We can answer it in two ways. First, there are only K possible values in the codebook. Hence, the values are discrete but represented by a finite number of floats. Second, the real magic happens when we calculate the matrix S^\hat{S}. Notice that this matrix is indeed discrete! In each row, there is a single position with 1

[!visual-conversion] Color-coded distance/index matrix (shading encodes distance values in panel a; the source scan is grayscale-only, so exact values can’t be reliably read off or asserted in a table). Cropped from page 188. source_page: pages/page-188.png | visual_type: shaded grid / heatmap

dgm-fig-8.3-quantization-codes.png Fig. 8.3 An example of the quantization of codes. (a) Distances. (b) Indices. (c) Quantized code

and 0’s elsewhere. As a result, either we look at it from the codebook perspective or the similarity matrix perspective, we should be convinced that indeed we can turn any real-valued vector into a vector consisting of real values but from a finite set. And, most importantly, this whole procedure of quantizing, allows us to apply the backpropagation algorithm! This quantization approach (or very similar) was used in many neural compression methods, e.g., [8, 11] or [10]. We can also use other differential quantization techniques, e.g., vector quantization [16]. However, we prefer to stick to a simple codebook that turns to be pretty effective in practice.

class Quantizer(nn.Module):
def __init__(self, input_dim, codebook_dim, temp=1.e7):
super(Quantizer, self).__init__()
# temperature for softmax
self.temp = temp
# dimensionality of the inputs and the codebook
self.input_dim = input_dim
self.codebook_dim = codebook_dim
# codebook layer (a codebook)
# initialize uniformly and a Parameter (learnable)
self.codebook = nn.Parameter(torch.FloatTensor(1, self.
codebook_dim).uniform_(-1/self.codebook_dim, 1/self.
codebook_dim))
# A function for codebook indices (a one-hot representation)
# to values in the codebook.
def indices2codebook(self, indices_onehot):
return torch.matmul(indices_onehot, self.codebook.t()).squeeze()
# A function to change integers to a one-hot representation.
def indices_to_onehot(self, inputs_shape, indices):

[^1]

8.4 Neural Compression: Components

indices_hard = torch.zeros(inputs_shape[0], inputs_shape
[1], self.codebook_dim)
indices_hard.scatter_(2, indices, 1)
# The forward function:
# - First, distances are calculated between input values and
# codebook values.
# - Second, indices (soft - differentiable, hard - non-
# differentiable) between the encoded values and the codebook
# values are calculated.
# - Third, the quantizer returns indices and quantized code (
# the output of the encoder).
# - Fourth, the decoder maps the quantized code to the
# observable space (i.e., it decodes the code back).
def forward(self, inputs):
# inputs - a matrix of floats, B x M
inputs_shape = inputs.shape
# repeat inputs
inputs_repeat = inputs.unsqueeze(2).repeat(1, 1, self.
codebook_dim)
# calculate distances between input values and the
codebook values
distances = torch.exp(-torch.sqrt(torch.pow(inputs_repeat
- self.codebook.unsqueeze(1), 2)))
# indices (hard, i.e., nondiff)
indices = torch.argmax(distances, dim=2).unsqueeze(2)
indices_hard = self.indices_to_onehot(inputs_shape=
inputs_shape, indices=indices)
# indices (soft, i.e., diff)
indices_soft = torch.softmax(self.temp * distances, -1)
# quantized values: we use soft indices here because it
allows backpropagation
quantized = self.indices2codebook(indices_onehot=
indices_soft)
return (indices_soft, indices_hard, quantized)

Listing 8.3 A Quantizer class

Adaptive Entropy Coding Model The last piece in the whole puzzle is entropy coding. We rely on entropy coders like Huffman coding or arithmetic coding. Either way, these entropy coders require from us an estimate of the probability distribution over codes, p(y)p(y). Once they have it, they can losslessly compress the discrete signal into a bitstream. In general, we can encode discrete symbols to bits separately (e.g., Huffman coding) or encode the whole discrete signal into a bit representation (e.g., arithmetic coding). In compression systems, arithmetic coding is preferable over Huffman coding because it is faster and more accurate (i.e., better compression) [16].

We will not review and explain in detail how arithmetic coding works. We refer to [16] (or any other book on data compression) for details. There are two facts we need to know and remember. First, if we provide probabilities of symbols, then arithmetic coding does not need to make an extra pass through the signal to estimate them. Second, there is an adaptive variant of arithmetic coding that allows modifying probabilities while compressing symbols sequentially (also known as progressive coding).

These two remarks are important for us because, as mentioned earlier, we can estimate p(y)p(y) using a deep generative model. Once we learn the deep generative model, the arithmetic coding can use it for lossless compression of codes. Moreover, if we use a model that factorizes the distribution, e.g., an autoregressive model, then we can also utilize the idea of progressive coding.

In our example, we use the autoregressive model that takes quantized code and returns the probability of each value in the codebook (i.e., the indices). In other words, the autoregressive model outcomes probabilities over the codebook values. It is worth to mention though that in our implementation we use the term “entropy coding” but we mean an entropy coding model. Moreover, it is worth mentioning that there are specialized distributions for compression purposes, e.g., the scale hyperprior [9], but here we are interested in deep generative modeling for neural compression.

class ARMEntropyCoding(nn.Module):
def __init__(self, code_dim, codebook_dim, arm_net):
super(ARMEntropyCoding, self).__init__()
self.code_dim = code_dim
self.codebook_dim = codebook_dim
self.arm_net = arm_net # it takes B x 1 x code_dim and
# outputs B x codebook_dim x code_dim
def f(self, x):
h = self.arm_net(x.unsqueeze(1))
h = h.permute(0, 2, 1)
p = torch.softmax(h, 2)
return p
def sample(self, quantizer=None, B=10):
x_new = torch.zeros((B, self.code_dim))
for d in range(self.code_dim):
p = self.f(x_new)
indx_d = torch.multinomial(p[:, d, :], num_samples=1)
codebook_value = quantizer.codebook[0, indx_d].
squeeze()
x_new[:, d] = codebook_value
return x_new

8.4 Neural Compression: Components

def forward(self, z, x):
p = self.f(x)
return -torch.sum(z * torch.log(p), 2)

Listing 8.4 An adaptive entropy coding model using an ARM class

A Neural Compression System We have discussed all components of a neural compression system and gave some very specific examples of how they could be implemented. There are many other propositions on how these could be formulated, ranging from elaborated neural network architectures for encoders and decoders to various quantization schemes and entropy coding models. Nevertheless, the presented neural compressor should give you a good idea of how neural networks could be utilized for image (or, generally, data) compression.

In Fig. 8.4, we represent a neural compression system where the transformations in Fig. 8.1 are replaced by neural networks together with a (differentiable) quantization procedure. We also highlight that floats are quantized to obtain a discrete signal. Altogether, comparing Figs. 8.1 and 8.4, we can notice that the whole pipeline is the same and the differences lie in how transformations are implemented.

The main difference, perhaps, is that a neural compressor could be trained end-to-end and specialized to given data. In fact, the objective of the neural compressor could be seen as a penalized reconstruction error of auto-encoders. Let us assume we have given training data D={x1,…,xN}\mathcal{D} = \{ \mathbf{x}_1, \ldots, \mathbf{x}_N \} and the corresponding empirical distribution pdata(x)p_{data}(\mathbf{x}). Moreover, we have an encoder network with weights ϕ\phi, y=fe,ϕ(x)\mathbf{y} = f_{e,\phi}(\mathbf{x}), a differentiable quantizer with a codebook c\mathbf{c}, y^=Q(y;x)\hat{\mathbf{y}} = Q(\mathbf{y}; \mathbf{x}), a decoder network with weights θ\theta, x^=fd,θ(y^)\hat{\mathbf{x}} = f_{d,\theta}(\hat{\mathbf{y}}), and the entropy coding model with weights λ\lambda, pλ(y^)p_{\lambda}(\hat{\mathbf{y}}). We can train the model in the end-to-end-fashion by minimizing the following objective (β>0\beta > 0):

[!visual-conversion] Flow diagram with real embedded photographs (cat image, encoder/decoder pipeline) — photographic content. Cropped from page 191. source_page: pages/page-191.png | visual_type: diagram + photographs

dgm-fig-8.4-neural-compression-system.png Fig. 8.4 A neural compression system

L(θ,ϕ,λ,c)=Ex∼pdata(x)[(x−fd,θ(Q(fe,ϕ(x);c)))2]+\mathcal{L}(\theta, \phi, \lambda, \mathbf{c}) = \mathbb{E}_{\mathbf{x} \sim p_{data}(\mathbf{x})} \left[ (\mathbf{x} - f_{d,\theta}(Q(f_{e,\phi}(\mathbf{x}); \mathbf{c})))^2 \right] + +βEy^∼pdata(x)δ(Q(fe,ϕ(x);c)−y^)[−ln⁡pλ(y^)](8.4)+ \beta \mathbb{E}_{\hat{\mathbf{y}} \sim p_{data}(\mathbf{x})} \delta(Q(f_{e,\phi}(\mathbf{x}); \mathbf{c}) - \hat{\mathbf{y}}) \left[ -\ln p_{\lambda}(\hat{\mathbf{y}}) \right] \tag{8.4} =Ex∼pdata(x)[(x−x^)2]+βEy^∼pdata(x)δ(Q(fe,ϕ(x);c)−y^)[−ln⁡pλ(y^)].(8.5)= \mathbb{E}_{\mathbf{x} \sim p_{data}(\mathbf{x})} \left[ (\mathbf{x} - \hat{\mathbf{x}})^2 \right] + \beta \mathbb{E}_{\hat{\mathbf{y}} \sim p_{data}(\mathbf{x})} \delta(Q(f_{e,\phi}(\mathbf{x}); \mathbf{c}) - \hat{\mathbf{y}}) \left[ -\ln p_{\lambda}(\hat{\mathbf{y}}) \right]. \tag{8.5}

If we look into the objective, we can immediately notice that the first component, Ex∼pdata(x)[(x−x^)2]\mathbb{E}_{\mathbf{x} \sim p_{data}(\mathbf{x})} \left[ (\mathbf{x} - \hat{\mathbf{x}})^2 \right], is the Mean Squared Error (MSE) loss. In other words, it is the reconstruction error. The second part, Ex∼pdata(x)[−ln⁡pλ(y^)]\mathbb{E}_{\mathbf{x} \sim p_{data}(\mathbf{x})} \left[ -\ln p_{\lambda}(\hat{\mathbf{y}}) \right], is the cross-entropy between q(y^)=pdata(x) δ(Q(fe,ϕ(x);c)−y^)q(\hat{\mathbf{y}}) = p_{data}(\mathbf{x}) \, \delta(Q(f_{e,\phi}(\mathbf{x}); \mathbf{c}) - \hat{\mathbf{y}}) and pλ(y^)p_{\lambda}(\hat{\mathbf{y}}), where δ(⋅)\delta(\cdot) denotes Dirac’s delta. To clearly see that, let us write it down step-by-step:

CE[q(y^)∥pλ(y^)]=−∑y^q(y^)ln⁡pλ(y^)(8.6)\mathrm{CE} \left[ q(\hat{\mathbf{y}}) \| p_{\lambda}(\hat{\mathbf{y}}) \right] = - \sum_{\hat{\mathbf{y}}} q(\hat{\mathbf{y}}) \ln p_{\lambda}(\hat{\mathbf{y}}) \tag{8.6} =−∑y^pdata(x) δ(Q(fe,ϕ(x);c)−y^)ln⁡pλ(y^)(8.7)= - \sum_{\hat{\mathbf{y}}} p_{data}(\mathbf{x}) \, \delta(Q(f_{e,\phi}(\mathbf{x}); \mathbf{c}) - \hat{\mathbf{y}}) \ln p_{\lambda}(\hat{\mathbf{y}}) \tag{8.7} =−1N∑n=1Nln⁡pλ(Q(fe,ϕ(xn);c)).(8.8)= - \frac{1}{N} \sum_{n=1}^{N} \ln p_{\lambda} \left( Q(f_{e,\phi}(\mathbf{x}_n); \mathbf{c}) \right). \tag{8.8}

Eventually, we can write the training objective explicitly, replacing expectations with sums:

L(θ,ϕ,λ,c)=1N∑n=1N(xn−fd,θ(Q(fe,ϕ(xn);c)))2+\mathcal{L}(\theta, \phi, \lambda, \mathbf{c}) = \frac{1}{N} \sum_{n=1}^{N} \left( \mathbf{x}_n - f_{d,\theta} \left( Q \left( f_{e,\phi}(\mathbf{x}_n); \mathbf{c} \right) \right) \right)^2 + +βN∑n=1N[−ln⁡pλ(Q(fe,ϕ(xn);c))].(8.9)+ \frac{\beta}{N} \sum_{n=1}^{N} \left[ -\ln p_{\lambda} \left( Q \left( f_{e,\phi}(\mathbf{x}_n); \mathbf{c} \right) \right) \right]. \tag{8.9}

In the training objective, we have a sum of distortion and rate. Please note that during training, we do not need to use entropy coding at all. However, it is necessary if we want to use neural compression in practice.

Additionally, it is beneficial to discuss how the bits per pixel (bpp) is calculated. The definition of the bpp is the total size in bits of the encoder output divided by the total size in pixels of the encoder input. In our case, the encoder returns a code of size MM and each value is mapped to one of KK values (let us assume that K=2κK = 2^{\kappa}). As a result, we can represent the quantized code using indices, i.e., integers. Since we have KK possible integers, we can use κ\kappa bits to represent each of them. As a result, the code is described by κ×M\kappa \times M bits. In other words, we can use a uniform distribution 8.4 Neural Compression: Components

with probability equal 1/(κ×M)1/(\kappa \times M) that gives the bpp equal −log⁡2(1/(κ×M))/D-\log_2(1/(\kappa \times M))/D. However, we can improve this score by using entropy coding. As a result, we can use the rate value and divide it by the size of the image, DD, to obtain the bpp, i.e., −log⁡2p(y^)/D-\log_2 p(\hat{y})/D.

class NeuralCompressor(nn.Module):
def __init__(self, encoder, decoder, entropy_coding,
quantizer, beta=1., detaching=False):
super(NeuralCompressor, self).__init__()
print('Neural Compressor by JT.')
# we
self.encoder = encoder
self.decoder = decoder
self.entropy_coding = entropy_coding
self.quantizer = quantizer
# beta determines how strongly we focus on compression
# against reconstruction quality
self.beta = beta
# We can detach inputs to the rate, then we learn rate
# and distortion separately
self.detaching = detaching
def forward(self, x, reduction='avg'):
# encoding
#--non-quantized values
z = self.encoder(x)
#--quantizing
quantizer_out = self.quantizer(z)
# decoding
x_rec = self.decoder(quantizer_out[2])
# Distortion (e.g., MSE)
Distortion = torch.mean(torch.pow(x - x_rec, 2), 1)
# Rate: we use the entropy coding here
Rate = torch.mean(self.entropy_coding(quantizer_out[0],
quantizer_out[2]), 1)
# Objective
objective = Distortion + self.beta * Rate
if reduction == 'sum':
return objective.sum(), Distortion.sum(), Rate.sum()
else:
return objective.mean(), Distortion.mean(), Rate.mean()

Listing 8.5 A neural compression class

[!visual-conversion] Real training curves plus real image/reconstruction/sample grids — photographic/data content. Cropped from page 194. source_page: pages/page-194.png | visual_type: training curves + image grid

dgm-fig-8.5-final-outcomes.png Fig. 8.5 An example of outcomes after the training: (a) A distortion curve. (b) A rate curve. (c) Real images (left columns) and their reconstructions (middle column), and samples from the autoregressive entropy coder (right column)

To conclude the description of the neural compressor, the whole compression procedure consists of the following steps, assuming that the model has been trained already:

  1. Encode the input image, y=fe,ϕ(x)\mathbf{y} = f_{e,\phi}(\mathbf{x}).
  2. Quantize the code, y^=Q(y^;c)\hat{\mathbf{y}} = Q(\hat{\mathbf{y}}; \mathbf{c}).
  3. Turn the quantized code y^\hat{\mathbf{y}} into a bitstream using pλ(y^)p_{\lambda}(\hat{\mathbf{y}}) and, e.g., arithmetic encoding.
  4. Sent the bits.
  5. Decode bits into y^\hat{\mathbf{y}} using pλ(y^)p_{\lambda}(\hat{\mathbf{y}}) and, e.g., arithmetic decoding.
  6. Decode y^\hat{\mathbf{y}}, x^=fd,θ(y^)\hat{\mathbf{x}} = f_{d,\theta}(\hat{\mathbf{y}}).

Example In a separate file (see https://github.com/jmtomczak/intro_dgm), you can find the implementation of the presented neural compressor and play around with it. For instance, you can get the following results (for β=1\beta = 1) as in Fig. 8.5.

Interestingly, since the entropy coder is also a deep generative model, we can sample from it. In Fig. 8.5c, there are four samples presented. They indicate that the model indeed can learn the data distribution of the quantized codes!

8.5 What’s Next?

Neural compression is a fascinating field. Utilizing neural networks for compression opens new possibilities for developing new coding schemes. Neural compression achieved comparable or (sometimes) better results than standard codecs on image compression [20], however, there is still room for improvement in video compression or audio compression even though recent attempts are very promising [21, 22]. There are many interesting research directions I missed here. I highly recommend taking a look at a nice overview of neural compression methods [20]. Lastly, I want to highlight that here we used the deep autoregressive generative model; however, we can use other deep generative models (e.g., flows, VAEs).

References

  1. Facebook. Facebook reports fourth quarter and full year 2020 results.

  2. Rashid Ansari, Christine Guillemot, and Nasir Memon. Jpeg and jpeg2000. In The Essential Guide to Image Processing, pages 421–461. Elsevier, 2009.

  3. Zixiang Xiong and Kannan Ramchandran. Wavelet image compression. In The Essential Guide to Image Processing, pages 463–493. Elsevier, 2009.

  4. Yann LeCun, Yoshua Bengio, and Geoffrey Hinton. Deep learning. nature, 521(7553):436–444, 2015.

  5. Jürgen Schmidhuber. Deep learning in neural networks: An overview. Neural networks, 61:85–117, 2015.

  6. Lionel Gueguen, Alex Sergeev, Ben Kadlec, Rosanne Liu, and Jason Yosinski. Faster neural networks straight from jpeg. Advances in Neural Information Processing Systems, 31:3933–3944, 2018.

  7. Lucas Theis, Wenzhe Shi, Andrew Cunningham, and Ferenc Huszár. Lossy image compression with compressive autoencoders. arXiv preprint arXiv:1703.00395, 2017.

  8. Eirikur Agustsson, Fabian Mentzer, Michael Tschannen, Lukas Cavigelli, Radu Timofte, Luca Benini, and Luc Van Gool. Soft-to-hard vector quantization for end-to-end learning compressible representations. In Proceedings of the 31st International Conference on Neural Information Processing Systems, pages 1141–1151, 2017.

  9. Johannes Ballé, David Minnen, Saurabh Singh, Sung Jin Hwang, and Nick Johnston. Variational image compression with a scale hyperprior. In International Conference on Learning Representations, 2018.

  10. Amirhossein Habibian, Ties van Rozendaal, Jakub M Tomczak, and Taco S Cohen. Video compression with rate-distortion autoencoders. In Proceedings of the IEEE/CVF International Conference on Computer Vision, pages 7033–7042, 2019.

  11. Fabian Mentzer, Eirikur Agustsson, Michael Tschannen, Radu Timofte, and Luc Van Gool. Conditional probability models for deep image compression. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, pages 4394–4402, 2018.

  1. David Minnen, Johannes Ballé, and George Toderici. Joint autoregressive and hierarchical priors for learned image compression. arXiv preprint arXiv:1809.02736, 2018.

  2. Claude Elwood Shannon. A mathematical theory of communication. The Bell system technical journal, 27(3):379–423, 1948.

  3. Yibo Yang, Robert Bamler, and Stephan Mandt. Improving inference for neural image compression. Advances in Neural Information Processing Systems, 33, 2020.

  4. Fabian Mentzer, George D Toderici, Michael Tschannen, and Eirikur Agustsson. High-fidelity generative image compression. Advances in Neural Information Processing Systems, 33, 2020.

  5. David Salomon. Data compression: the complete reference. Springer Science & Business Media, 2004.

  6. LJ Karam. Lossless image compression. In Al Bovik, editor, The Essential Guide to Image Processing. Elsevier Academic Press, 2009.

  7. Pierre Moulin. Multiscale image decompositions and wavelets. In The essential guide to image processing, pages 123–142. Elsevier, 2009.

  8. Zhou Wang, Ero P Simoncelli, and Alan C Bovik. Multiscale structural similarity for image quality assessment. In The Thirty-Seventh Asilomar Conference on Signals, Systems & Computers, 2003, volume 2, pages 1398–1402. IEEE, 2003.

  9. Johannes Ballé, Philip A Chou, David Minnen, Saurabh Singh, Nick Johnston, Eirikur Agustsson, Sung Jin Hwang, and George Toderici. Nonlinear transform coding. IEEE Journal of Selected Topics in Signal Processing, 15(2):339–353, 2020.

  10. Adam Golinski, Reza Pourreza, Yang Yang, Guillaume Sautiere, and Taco S Cohen. Feedback recurrent autoencoder for video compression. In Proceedings of the Asian Conference on Computer Vision, 2020.

  11. Yang Yang, Guillaume Sautière, J Jon Ryu, and Taco S Cohen. Feedback recurrent autoencoder. In ICASSP 2020-2020 IEEE International Conference on Acoustics, Speech and Signal Processing (ICASSP), pages 3347–3351. IEEE, 2020.