Skip to content
ImagineWorld

Flow-Based Models

node_idnode-book_deep-generative-modeling_chapter-03-flow-based-models
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num3
chapter_titleFlow-Based Models
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 3 Flow-Based Models

3.1 Flows for Continuous Random Variables

3.1.1 Introduction

So far, we have discussed a class of deep generative models that model the distribution p(x)p(\mathbf{x}) directly in an autoregressive manner. The main advantage of ARMs is that they can learn long-range statistics and, in a consequence, powerful density estimators. However, their drawback is that they are parameterized in an autoregressive manner, hence, sampling is rather a slow process. Moreover, they lack a latent representation, therefore, it is not obvious how to manipulate their internal data representation that makes it less appealing for tasks like compression or metric learning. In this chapter, we present a different approach to direct modeling of p(x)p(\mathbf{x}). However, before we start our considerations, we will discuss a simple example.

Example 3.1 Let us take a random variable z∈Rz \in \mathbb{R} with π(z)=N(z∣0,1)\pi(z) = \mathcal{N}(z|0, 1). Now, we consider a new random variable after applying some linear transformation to zz, namely x=0.75z+1x = 0.75z + 1. Now the question is the following:

What is the distribution of xx, p(x)p(x)?

We can guess the solution by using properties of Gaussians, or dig in our memory about the change of variables formula to calculate this distribution, that is:

p(x)=π(z=f−1(x))∣∂f−1(x)∂x∣,(3.1)p(x) = \pi \left( z = f^{-1}(x) \right) \left| \frac{\partial f^{-1}(x)}{\partial x} \right|, \tag{3.1}

where ff is an invertible function (a bijection). What does it mean? It means that the function maps one point to another, distinctive point, and we can always invert the function to obtain the original point.

© 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_3

[!visual-conversion] Simple geometric bijection diagram (two sets, points joined 1:1 by lines) — the exact pairing shown is illustrative/arbitrary (the point is that a bijection exists, not which specific permutation), so an ASCII rendering carries the relationship 1:1. Converted from Fig. 3.1, page 034. Caption restored from the sidebar original (OCR had dropped the first 1–2 characters of each wrapped margin line: “ijection”→“bijection”, “1 the”→“in the”, “recisely”→“precisely”).

(blue set) (purple set)
____ __
/ \ / \
| o------------------o | |
| \ \--------/-----o |
| o \--/ / \ \
| \-------/ / \__ |
\ o___/--- \ /
\____/ \/

Fig. 3.1 An example of a bijection where for each point in the blue set there is precisely one corresponding point in the purple set (and vice versa) In Fig. 3.1, we have an example of a bijection. Notice that volumes of the domains do not need to be the same! Keep it in mind and think about it in the context of ∣∂f−1(x)∂x∣\left|\frac{\partial f^{-1}(x)}{\partial x}\right|.

Coming back to our example, we have

f(z)=0.75z+1,(3.2)f(z) = 0.75z + 1, \tag{3.2}

and the inverse of ff is

f−1(x)=x−10.75.(3.3)f^{-1}(x) = \frac{x - 1}{0.75}. \tag{3.3}

Then, the derivative of the change of volume is

∣∂f−1(x)∂x∣=43.(3.4)\left|\frac{\partial f^{-1}(x)}{\partial x}\right| = \frac{4}{3}. \tag{3.4}

Putting all information so far together yields

p(x)=π(z=x−10.75)43=12π⋅0.752exp⁡{−(x−1)2/0.752}.(3.5)p(x) = \pi \left(z = \frac{x - 1}{0.75}\right) \frac{4}{3} = \frac{1}{\sqrt{2\pi \cdot 0.75^2}} \exp\left\{-(x - 1)^2 / 0.75^2\right\}. \tag{3.5}

We immediately realize that we end up with the Gaussian distribution again:

p(x)=N(x∣1,0.75).(3.6)p(x) = \mathcal{N}(x|1, 0.75). \tag{3.6}

Moreover, we see that the part ∣∂f−1(x)∂x∣\left|\frac{\partial f^{-1}(x)}{\partial x}\right| is responsible to normalize the distribution π(z)\pi(z) after applying the transformation ff. In other words, ∣∂f−1(x)∂x∣\left|\frac{\partial f^{-1}(x)}{\partial x}\right| counteracts a possible change of volume caused by ff. ■

First of all, this example indicates that we can calculate a new distribution of a continuous random variable by applying a known bijective transformation ff to a 29

random variable with a known distribution, z∼p(z)z \sim p(z). The same holds for multiple variables x,z∈RD\mathbf{x}, \mathbf{z} \in \mathbb{R}^D:

p(x)=p(z=f−1(x))∣∂f−1(x)∂x∣,(3.7)p(\mathbf{x}) = p \left( \mathbf{z} = f^{-1}(\mathbf{x}) \right) \left| \frac{\partial f^{-1}(\mathbf{x})}{\partial \mathbf{x}} \right|, \tag{3.7}

where:

∣∂f−1(x)∂x∣=∣det⁡Jf−1(x)∣(3.8)\left| \frac{\partial f^{-1}(\mathbf{x})}{\partial \mathbf{x}} \right| = \left| \det \mathbf{J}_{f^{-1}}(\mathbf{x}) \right| \tag{3.8}

is the Jacobian matrix Jf−1\mathbf{J}_{f^{-1}} that is defined as follows:

Jf−1=[∂f1−1∂x1⋯∂f1−1∂xD⋮⋱⋮∂fD−1∂x1⋯∂fD−1∂xD].(3.9)\mathbf{J}_{f^{-1}} = \begin{bmatrix} \frac{\partial f_1^{-1}}{\partial x_1} & \cdots & \frac{\partial f_1^{-1}}{\partial x_D} \\ \vdots & \ddots & \vdots \\ \frac{\partial f_D^{-1}}{\partial x_1} & \cdots & \frac{\partial f_D^{-1}}{\partial x_D} \end{bmatrix}. \tag{3.9}

Moreover, we can also use the inverse function theorem that yields

∣Jf−1(x)∣=∣Jf(x)∣−1.(3.10)\left| \mathbf{J}_{f^{-1}}(\mathbf{x}) \right| = \left| \mathbf{J}_f(\mathbf{x}) \right|^{-1}. \tag{3.10}

Since ff is invertible, we can use the inverse function theorem to rewrite (3.7) as follows:

p(x)=p(z=f−1(x))∣Jf(x)∣−1.(3.11)p(\mathbf{x}) = p \left( \mathbf{z} = f^{-1}(\mathbf{x}) \right) \left| \mathbf{J}_f(\mathbf{x}) \right|^{-1}. \tag{3.11}

To get some insight into the role of the Jacobian-determinant, take a look at Fig. 3.2. Here, there are three cases of invertible transformations that play around with a uniform distribution defined over a square.

In the case on top, the transformation turns a square into a rhombus without changing its volume. As a result, the Jacobian-determinant of this transformation is 1. Such transformations are called volume-preserving. Notice that the resulting distribution is still uniform and since there is no change of volume, it is defined over the same volume as the original one, thus, the color is the same.

In the middle, the transformation shrinks the volume, therefore, the resulting uniform distribution is “denser” (a darker color in Fig. 3.2). Additionally, the Jacobian-determinant is smaller than 1.

In the last situation, the transformation enlarges the volume, hence, the uniform distribution is defined over a larger area (a lighter color in Fig. 3.2). Since the volume is larger, the Jacobian-determinant is larger than 1.

Notice that shifting operator is volume-preserving. To see that imagine adding an arbitrary value (e.g., 5) to all points of the square. Does it change the volume? Not at all! Thus, the Jacobian-determinant equals 1.

[!visual-conversion] Simple geometric figure (square under three invertible transforms, with axes and a |J_f(x)| label per row) — labels and shape relationships transcribe 1:1 to ASCII; the density/color cue is already explained in the surrounding prose. Converted from Fig. 3.2, page 036. Caption restored from the sidebar original (OCR-dropped leading characters per wrapped line).

|J_f(x)| = 1 (volume-preserving)
y y
| [■] --- f ---> | /■/ (rhombus, same area)
| <--- f⁻¹--- | / /
+------------> x +------------> x
|J_f(x)| = 0.5 (shrinks the area — denser / darker)
y y
| [■] --- f ---> | [▪] (smaller square)
| <--- f⁻¹--- |
+------------> x +------------> x
|J_f(x)| = 1.5 (enlarges the area — sparser / lighter)
y y
| [■] --- f ---> | [█████] (larger square)
| <--- f⁻¹--- | [█████]
+------------> x +------------> x

Fig. 3.2 Three examples of invertible transformations: (top) a volume-preserving bijection, (middle) a bijection that shrinks the original area, (bottom) a bijection that enlarges the original area

[!visual-conversion] Schematic density-curve diagram (three sketched distributions linked by forward/inverse transformation arrows) — no real data, labels and relationships transcribe 1:1 to ASCII. Converted from Fig. 3.3, page 037.

/\ __/\_ _/\_/\_
/ \ f1 / \ f2 / \
__/ \__ ---> __/ \__ ---> _/ \_
<--- <---
0 0 0
"latent" space pixel space

Fig. 3.3 An example of transforming a unimodal distribution (the latent space) to a multimodal distribution (the data space, e.g., the pixel space) through a series of invertible transformations fif_i

ln⁡p(x)=ln⁡N(z0=f−1(x)∣0,I)−∑i=1Kln⁡∣Jfi(zi−1)∣.(3.14)\ln p(\mathbf{x}) = \ln \mathcal{N}\left(\mathbf{z}_0 = f^{-1}(\mathbf{x})|0, \mathbf{I}\right) - \sum_{i=1}^{K} \ln \left|\mathbf{J}_{f_i}(\mathbf{z}_{i-1})\right|. \tag{3.14}

Interestingly, we see that the first part, namely ln⁡N(z0=f−1(x)∣0,I)\ln \mathcal{N}\left(\mathbf{z}_0 = f^{-1}(\mathbf{x})|0, \mathbf{I}\right), corresponds to the Mean Square Error loss function between 0 and f−1(x)f^{-1}(\mathbf{x}) plus a constant. The second part, ∑i=1Kln⁡∣Jfi(zi−1)∣\sum_{i=1}^{K} \ln \left|\mathbf{J}_{f_i}(\mathbf{z}_{i-1})\right|, as in our example, ensures that the distribution is properly normalized. However, since it penalizes the change of volume (take a look again at the example above!), we can think of it as a kind of a regularizer for the invertible transformations {fi}\{f_i\}.

Once we have laid down the foundations of the change of variables for expressing density functions, now we must face two questions:

  • How to model the invertible transformations?
  • What is the difficulty here?

The answer to the first question could be neural networks because they are flexible and easy-to-train. However, we cannot take any neural network because of two reasons. First, the transformation must be invertible, thus, we must pick an invertible neural network. Second, even if a neural network is invertible, we face a problem of calculating the second part of (3.14), i.e., ∑i=1Kln⁡∣Jfi(zi−1)∣\sum_{i=1}^{K} \ln \left|\mathbf{J}_{f_i}(\mathbf{z}_{i-1})\right|, that is non-trivial and computationally intractable for an arbitrary sequence of invertible transformations. As a result, we seek for such neural networks that are both invertible and the logarithm of a Jacobian-determinant is (relatively) easy to calculate. The resulting model that consists of invertible transformations (neural networks) with tractable Jacobian-determinants is referred to as normalizing flows or flow-based models.

There are various possible invertible neural networks with tractable Jacobian-determinants, e.g., Planar Normalizing Flows [1], Sylvester Normalizing Flows [3], Residual Flows [4, 5], Invertible DenseNets [6]. However, here we focus on a very important class of models: RealNVP, Real-valued Non-Volume Preserving flows [7] that serve as a starting point for many other flow-based generative models (e.g., GLOW [8]).

3.1.3 Building Blocks of RealNVP

3.1.3.1 Coupling Layers

The main component of RealNVP is a coupling layer. The idea behind this transformation is the following. Let us consider an input to the layer that is divided into two parts: x=[xa,xb]\mathbf{x} = [\mathbf{x}_a, \mathbf{x}_b]. The division into two parts could be done by dividing the vector x\mathbf{x} into x1:d\mathbf{x}_{1:d} and xd+1:D\mathbf{x}_{d+1:D} or according to a more sophisticated manner, e.g., a checkerboard pattern [7]. Then, the transformation is defined as follows:

ya=xa(3.15)\mathbf{y}_a = \mathbf{x}_a \tag{3.15} yb=exp⁡(s(xa))⊙xb+t(xa),(3.16)\mathbf{y}_b = \exp \left( s \left( \mathbf{x}_a \right) \right) \odot \mathbf{x}_b + t \left( \mathbf{x}_a \right), \tag{3.16}

where s(⋅)s(\cdot) and t(⋅)t(\cdot) are arbitrary neural networks called scaling and transition, respectively.

This transformation is invertible by design, namely:

xb=(yb−t(ya))⊙exp⁡(−s(ya))(3.17)\mathbf{x}_b = \left( \mathbf{y}_b - t \left( \mathbf{y}_a \right) \right) \odot \exp \left( -s \left( \mathbf{y}_a \right) \right) \tag{3.17} xa=ya.(3.18)\mathbf{x}_a = \mathbf{y}_a. \tag{3.18}

Importantly, the logarithm of the Jacobian-determinant is easy to calculate, because:

J=[Id×d0d×(D−d)∂yb∂xadiag(exp⁡(s(xa)))](3.19)\mathbf{J} = \begin{bmatrix} \mathbf{I}_{d \times d} & \mathbf{0}_{d \times (D-d)} \\ \frac{\partial \mathbf{y}_b}{\partial \mathbf{x}_a} & \mathrm{diag} \left( \exp \left( s \left( \mathbf{x}_a \right) \right) \right) \end{bmatrix} \tag{3.19}

that yields

det⁡(J)=∏j=1D−dexp⁡(s(xa)j)=exp⁡(∑j=1D−ds(xa)j).(3.20)\det(\mathbf{J}) = \prod_{j=1}^{D-d} \exp \left( s \left( \mathbf{x}_a \right)_j \right) = \exp \left( \sum_{j=1}^{D-d} s \left( \mathbf{x}_a \right)_j \right). \tag{3.20}

Eventually, coupling layers seem to be flexible and powerful transformations with tractable Jacobian-determinants! However, we process only half of the input, therefore, we must think of an appropriate additional transformation a coupling layer could be combined with.

3.1.3.2 Permutation Layers

A simple yet effective transformation that could be combined with a coupling layer is a permutation layer. Since permutation is volume-preserving, i.e., its Jacobian-

[!visual-conversion] Node/flow diagram (coupling layer + permutation layer, forward and inverse passes) — relationships and labels transcribe 1:1 to Mermaid. Converted from Fig. 3.4, page 041.

graph LR
    subgraph A["(a) Forward pass"]
        xa1((x_a)) --> ya((y_a))
        xa1 --> f1["f"]
        xb1((x_b)) --> f1
        f1 --> yb((y_b))
        ya --> zb1((z_b))
        yb --> za1((z_a))
    end
graph RL
    subgraph B["(b) Inverse pass"]
        za2((z_a)) --> yb2((y_b))
        zb2((z_b)) --> ya2((y_a))
        ya2 --> xa2((x_a))
        ya2 --> f2["f⁻¹"]
        yb2 --> f2
        f2 --> xb2((x_b))
    end

Fig. 3.4 A combination of a coupling layer and a permutation layer that transforms [xa,xb][\mathbf{x}_a, \mathbf{x}_b] to [za,zb][\mathbf{z}_a, \mathbf{z}_b]. (a) A forward pass through the block. (b) An inverse pass through the block

[!visual-conversion] Simple 2×2 grid figure (probability mass at points vs. spread over square regions, under uniform dequantization — meaning the four regions are equal, so there’s no color gradient being lost here). Converted to ASCII from Fig. 3.5, page 041.

(left) probability mass at points (right) mass spread over square areas
y y
| o o | [■■][■■]
| | [■■][■■]
| o o | [■■][■■]
| | [■■][■■]
+------------------> x +------------------> x

Fig. 3.5 A schematic representation of the uniform dequantization for two binary random variables: (left) the probability mass is assigned to points, (right) after the uniform dequantization, the probability mass is assigned to square areas. Colors correspond to probability values

determinant is equal to 1, we can apply it each time after the coupling layer. For instance, we can reverse the order of variables.

An example of an invertible block, i.e., a combination of a coupling layer with a permutation layer is schematically presented in Fig. 3.4.

3.1.3.3 Dequantization

As discussed so far, flow-based models assume that x\mathbf{x} is a vector of real-valued random variables. However, in practice, many objects are discrete. For instance, images are typically represented as integers taking values in {0,1,…,255}D\{0, 1, \dots, 255\}^D. In [9], it has been outlined that adding a uniform noise, u∈[−0.5,0.5]D\mathbf{u} \in [-0.5, 0.5]^D, to original data, y∈{0,1,…,255}D\mathbf{y} \in \{0, 1, \dots, 255\}^D, allows applying density estimation to x=y+u\mathbf{x} = \mathbf{y} + \mathbf{u}. This procedure is known as uniform dequantization. Recently, there were different schema of dequantization proposed, you can read more on that in [10].

An example for two binary random variables and the uniform dequantization is depicted in Fig. 3.5. After adding u∈[−0.5,0.5]2\mathbf{u} \in [-0.5, 0.5]^2 to each discrete value, we obtain a continuous space and now probabilities originally associated with volumeless points are “spread” across small square regions.

3.1.4 Flows in Action!

Let us turn math into a code! We will first discuss the log-likelihood function (i.e., the learning objective) and how mathematical formulas correspond to the code. First, it is extremely important to know what is our learning objective, i.e., the log-likelihood function. In the example, we use coupling layers as described earlier, together with permutation layers. Then, we can plug the logarithm of the Jacobian-determinant for the coupling layers (for the permutation layers it is equal to 1, so ln⁡(1)=0\ln(1) = 0) in Eq. (3.14) that yields

ln⁡p(x)=ln⁡N(z0=f−1(x)∣0,I)−∑i=1K(∑j=1D−dsk(xak)j),(3.21)\ln p(\mathbf{x}) = \ln \mathcal{N}\left(\mathbf{z}_0 = f^{-1}(\mathbf{x}) | \mathbf{0}, \mathbf{I}\right) - \sum_{i=1}^{K} \left( \sum_{j=1}^{D-d} s_k \left( \mathbf{x}_a^k \right)_j \right), \tag{3.21}

where sks_k is the scale network in the kk-th coupling layer, and xak\mathbf{x}_a^k denotes the input to the kk-th coupling layer. Notice that exp⁡\exp in the log-Jacobian-determinant is cancelled by applying the logarithm.

Let us think again about the learning objective from the implementation perspective. First, we definitely need to obtain z\mathbf{z} by calculating f−1(x)f^{-1}(\mathbf{x}), and then we can calculate ln⁡N(z0=f−1(x)∣0,I)\ln \mathcal{N}(\mathbf{z}_0 = f^{-1}(\mathbf{x}) | \mathbf{0}, \mathbf{I}). That is actually easy, and we get

ln⁡N(z0=f−1(x)∣0,I)=−const−12∥f−1(x)∥2,(3.22)\ln \mathcal{N}\left(\mathbf{z}_0 = f^{-1}(\mathbf{x}) | \mathbf{0}, \mathbf{I}\right) = -\text{const} - \frac{1}{2} \| f^{-1}(\mathbf{x}) \|^2, \tag{3.22}

where const=D2ln⁡(2π)\text{const} = \frac{D}{2} \ln (2\pi) is the normalizing constant of the standard Gaussian, and 12∥f−1(x)∥2=MSE(0,f−1(x))\frac{1}{2} \| f^{-1}(\mathbf{x}) \|^2 = \text{MSE}(0, f^{-1}(\mathbf{x})).

Alright, now we should look into the second part of the objective, i.e., the log-Jacobian-determinants. As we can see, we have a sum over transformations, and for each coupling layer, we consider only the outputs of the scale nets. Hence, the only thing we must remember during implementing the coupling layers is to return not only output but also the outcome of the scale layer too.

3.1.5 Code

Now, we have all components to implement our own RealNVP! Below, there is a code with a lot of comments that should help to understand every single line of it. The full code (with auxiliary functions) that you can play with is available here: https://github.com/jmtomeczak/intro_dgm.

class RealNVP(nn.Module):
def __init__(self, nets, nett, num_flows, prior, D=2,
dequantization=True):
super(RealNVP, self).__init__()
# Well, it's always good to brag about yourself.
print('RealNVP by JT.')
# We need to dequantize discrete data. This attribute is
# used during training to dequantize integer data.
self.dequantization = dequantization
# An object of a prior (here: torch.distribution of
# multivariate normal distribution)
self.prior = prior
# A module list for translation networks
self.t = torch.nn.ModuleList([nett() for _ in range(num_flows)])
# A module list for scale networks
self.s = torch.nn.ModuleList([nets() for _ in range(num_flows)])
# The number of transformations, in our equations it is
# denoted by K.
self.num_flows = num_flows
# The dimensionality of the input. It is used for
# sampling.
self.D = D
# This is the coupling layer, the core of the RealNVP model.
def coupling(self, x, index, forward=True):
# x: input, either images (for the first transformation)
# or outputs from the previous transformation
# index: it determines the index of the transformation
# forward: whether it is a pass from x to y (forward=True)
# , or from y to x (forward=False)
# We chunk the input into two parts: x_a, x_b
(xa, xb) = torch.chunk(x, 2, 1)
# We calculate s(xa), but without exp!
s = self.s[index](xa)
# We calculate t(xa)
t = self.t[index](xa)
# Calculate either the forward pass (x -> z) or the
# inverse pass (z -> x)
# Note that we use the exp here!
if forward:
#yb = f^{-1}(x)
yb = (xb - t) * torch.exp(-s)
else:
#xb = f(y)
yb = torch.exp(s) * xb + t
# We return the output y = [ya, yb], but also s for
# calculating the log-Jacobian-determinant
return torch.cat((xa, yb), 1), s
# An implementation of the permutation layer
def permute(self, x):
# Simply flip the order.
return x.flip(1)
def f(self, x):
# This is a function that calculates the full forward pass through the coupling+permutation layers.
# We initialize the log-Jacobian-det
log_det_J, z = x.new_zeros(x.shape[0]), x
# We iterate through all layers
for i in range(self.num_flows):
# First, do coupling layer,
z, s = self.coupling(z, i, forward=True)
# then permute.
z = self.permute(z)
# To calculate the log-Jacobian-determinant of the sequence of transformations we sum over all of them.
# As a result, we can simply accumulate individual log-Jacobian determinants.
log_det_J = log_det_J - s.sum(dim=1)
# We return both z and the log-Jacobian-determinant, because we need z to feed in to the logarithm of the Norma;
return z, log_det_J
def f_inv(self, z):
# The inverse path: from z to x.
# We apply all transformations in the reversed order.
x = z
for i in reversed(range(self.num_flows)):
x = self.permute(x)
x, _ = self.coupling(x, i, forward=False)
# Since we use this function for sampling, we don't need to return anything else than x.
return x
def forward(self, x, reduction='avg'):
# This function is essential for PyTorch.
# First, we calculate the forward part: from x to z, and also we need the log-Jacobian-determinant.
z, log_det_J = self.f(x)
# We can use either sum or average as the output.
# Either way, we calculate the learning objective: self.prior.log_prob(z) + log_det_J.
# NOTE: Mind the minus sign! We need it, because, by default, we consider the minimization problem,
# but normally we look for the maximum likelihood estimate. Therefore, we use:
# max F(x) <=> min -F(x)
if reduction == 'sum':
return -(self.prior.log_prob(z) + log_det_J).sum()
else:
return -(self.prior.log_prob(z) + log_det_J).mean()
def sample(self, batchSize):
# First, we sample from the prior, z ~ p(z) = Normal(z|0,1)
z = self.prior.sample((batchSize, self.D))
z = z[:, 0, :]
# Second, we go from z to x.
x = self.f_inv(z)
return x.view(-1, self.D)

Listing 3.1 An example of an implementation of RealNVP

# The number of flows
num_flows = 8
# Neural networks for a single transformation (a single flow).
nets = lambda: nn.Sequential(nn.Linear(D//2, M), nn.LeakyReLU(),
nn.Linear(M, M), nn.LeakyReLU(),
nn.Linear(M, D//2), nn.Tanh())
nett = lambda: nn.Sequential(nn.Linear(D//2, M), nn.LeakyReLU(),
nn.Linear(M, M), nn.LeakyReLU(),
nn.Linear(M, D//2))
# For the prior, we can use the built-in PyTorch distribution.
prior = torch.distributions.MultivariateNormal(torch.zeros(D),
torch.eye(D))
# Init of the RealNVP. Please note that we need to dequantize the
# data (i.e., uniform dequantization).
model = RealNVP(nets, nett, num_flows, prior, D=D, dequantization
=True)

Listing 3.2 An example of networks

Et voilà! Now we are ready to run the full code. After training our RealNVP, we should obtain results resembling those in Fig. 3.6.

[!visual-conversion] Real generated-digit image grids plus a real training validation curve — photographic/data content. Cropped from page 045. source_page: pages/page-045.png | visual_type: image grid + training curve

dgm-fig-3.6-realnvp-outcomes.png Fig. 3.6 An example of outcomes after the training: (a) Randomly selected real images. (b) Unconditional generations from the RealNVP. (c) The validation curve during training

3.1.6 Is It All? Really?

Yes and no. Yes in the sense it is the minimalistic example of an implementation of the RealNVP. No, because there are many improvements over the instance of the RealNVP presented here, namely:

  • Factoring-out [7]: During the forward pass (from x to z), we can split the variables and proceed with processing only a subset of them. This could help to parameterize the base distribution by using the outputs of intermediate layers. In other words, we can obtain an autoregressive base distribution.

  • Rezero trick [11]: Introducing additional parameters to the coupling layer, e.g., y_b = exp(αs(x_a)) ⊙ x_b + βt(x_a) and α, β are initialized with 0’s. This helps to ensure that the transformations act as identity maps in the beginning. It is shown in [12] that this trick helps to learn better transformations by maintaining information about the input through all layers in the beginning of the training process.

  • Masking or Checkerboard pattern [7]: We can use a checkerboard pattern instead of dividing an input into two parts like [x_{1:D/2}, x_{D/2+1:D}]. This encourages learning local statistics better.

  • Squeezing [7]: We can also play around with “squeezing” some dimensions. For instance, an image that consists of C channels, width W, and height H could be turned into 4C channels, width W/2, and height H/2.

  • Learnable base distributions: instead of using a standard Gaussian base distribution, we can consider another model for that, e.g., an autoregressive model.

  • Invertible 1x1 convolution [8]: A fixed permutation could be replaced with a (learned) invertible 1x1 convolution as in the GLOW model [8].

  • Variational dequantization [13]: We can also pick a different dequantization scheme, e.g., variational dequantization. This allows to obtain much better scores. However, it is not for free because it leads to a lower bound to the log-likelihood function.

Moreover, there are many new fascinating research directions! I will name them here and point to papers where you can find more details:

  • Data compression with flows [14]: Flow-based models are perfect candidates for compression since they allow to calculate the exact likelihood. Ho et al. [14] proposed a scheme that allows to use flows in the bit-back-like compression scheme.

  • Conditional flows [15–17]: Here, we present the unconditional RealNVP. However, we can use a flow-based model for conditional distributions. For instance, we can use the conditioning as an input to the scale network and the translation network.

  • Variational inference with flows [1, 3, 18–21]: Conditional flow-based models could be used to form a flexible family of variational posteriors. Then, the lower bound to the log-likelihood function could be tighter. We will come back to that in Chap. 4, Sect. 4.4.2.

  • Integer discrete flows [12, 22, 23]: Another interesting direction is a version of the RealNVP for integer-valued data. We will explain this idea in Sect. 3.2.
  • Flows on manifolds [24]: Typically, flow-based models are considered in the Euclidean space. However, they could be considered in non-Euclidean spaces, resulting in new properties of (partially) invertible transformations.
  • Flows for ABC [25]: Approximate Bayesian Computation (ABC) assumes that the posterior over quantities of interest is intractable. One possible approach to mitigate this issue is to approximate it using flow-based models, e.g., masked autoregressive flows [26], as presented in [25].

Many other interesting information on flow-based models could be found in a fantastic review by Papamakarios et al. [27].

3.1.7 ResNet Flows and DenseNet Flows

ResNet Flows [4, 5]

In the previous sections, we have discussed flow-based models with a pre-designed architectures (i.e., blocks consisting of coupling layers and permutation layers) that allow easy calculation of the Jacobian-determinant. However, we can take a different approach and think of how we can approximate the Jacobian-determinant for an almost arbitrary architecture. And, additionally, what kind of requirements we must impose to make the architecture invertible.

In [4], the authors consider widely used residual neural networks (ResNets) and construct an invertible ResNet layer which is only constrained in Lipschitz continuity. A ResNet is defined as: F(x)=x+g(x)F(x) = x + g(x), where gg is modeled by a (convolutional) neural network and FF represents a ResNet layer which is in general not invertible. However, gg is constructed in such a way that it satisfies the Lipschitz constant being strictly lower than 1, Lip(g)<1\text{Lip}(g) < 1, by using spectral normalization of [28, 29]:

Lip(g)<1,if∣∣Wi∣∣2<1,(3.23)\text{Lip}(g) < 1, \quad \text{if} \quad ||W_i||_2 < 1, \tag{3.23}

where ∣∣⋅∣∣2|| \cdot ||_2 is the ℓ2\ell_2 matrix norm. Then Lip(g)=K<1\text{Lip}(g) = K < 1 and Lip(F)<1+K\text{Lip}(F) < 1 + K. Only in this specific case the Banach fixed-point theorem holds and ResNet layer FF has a unique inverse. As a result, the inverse can be approximated by fixed-point iterations [4].

To estimate the log-determinant is, especially for high-dimensional spaces, computationally intractable due to expensive computations. Since ResNet blocks have a constrained Lipschitz constant, the logarithm of the Jacobian-determinant is cheaper to compute, tractable, and approximated with guaranteed convergence [4]:

ln⁡p(x)=ln⁡p(f(x))+tr(∑k=1∞(−1)k+1k[Jg(x)]k),(3.24)\ln p(x) = \ln p(f(x)) + \mathrm{tr} \left( \sum_{k=1}^{\infty} \frac{(-1)^{k+1}}{k} [J_g(x)]^k \right), \tag{3.24}

where Jg(x)J_g(x) is the Jacobian of gg at xx that satisfies ∣∣Jg∣∣<1||J_g|| < 1. The Skilling-Hutchinson trace estimator [30, 31] is used to compute the trace at a lower cost than to fully compute the trace of the Jacobian. Residual Flows [5] use an improved method to estimate the power series at an even lower cost with an unbiased estimator based on “Russian roulette” of [32]. Intuitively, the method estimates the infinite sum of the power series by evaluating a finite amount of terms. In return, this leads to less computation of terms compared to invertible residual networks. To avoid derivative saturation, which occurs when the second derivative is zero in large regions, the LipSwish activation is proposed [4].

DenseNet Flows [6]

Since it is possible to formulate a flow for a ResNet architecture, a natural question is whether it could be accomplished for densely connected networks (DensNets) [33]. In [6], it was shown that indeed it is possible!

The main component of DenseNet flows is a DenseBlock that is defined as a function F:Rd→RdF : \mathbb{R}^d \to \mathbb{R}^d with F(x)=x+g(x)F(x) = x + g(x), where gg consists of dense layers {hi}i=1n\{h_i\}_{i=1}^n. Note that an important modification to make the model invertible is to output x+g(x)x + g(x), whereas a standard DenseBlock would only output g(x)g(x). The function gg is expressed as follows:

g(x)=hn+1∘hn∘⋯∘h1(x),(3.25)g(x) = h_{n+1} \circ h_n \circ \cdots \circ h_1(x), \tag{3.25}

where hn+1h_{n+1} represents a 1×11 \times 1 convolution to match the output size of Rd\mathbb{R}^d. A layer hih_i consists of two parts concatenated to each other. The upper part is a copy of the input signal. The lower part consists of the transformed input, where the transformation is a multiplication of (convolutional) weights WiW_i with the input signal, followed by a non-linearity ϕ\phi having Lip(ϕ)≤1\mathrm{Lip}(\phi) \le 1, such as ReLU, ELU, LipSwish, or tanh. As an example, a dense layer h2h_2 can be composed as follows:

h1(x)=[xϕ(W1x)],h2(h1(x))=[h1(x)ϕ(W2h1(x))].(3.26)h_1(x) = \begin{bmatrix} x \\ \phi(W_1 x) \end{bmatrix}, \quad h_2(h_1(x)) = \begin{bmatrix} h_1(x) \\ \phi(W_2 h_1(x)) \end{bmatrix}. \tag{3.26}

The DenseNet flows [6] rely on the same techniques for approximating the Jacobian-determinant as in the ResNet flows. The main difference between the DenseNet flows and the ResNet flows lies in normalizing weights so that the Lipschitz constant of the transformation is smaller than 1 and, thus, the transformation is invertible. Formally, to satisfy Lip(g)<1\mathrm{Lip}(g) < 1, we need to enforce Lip(hi)<1\mathrm{Lip}(h_i) < 1 for all nn layers, since Lip(g)≤Lip(hn+1)⋅⋯⋅Lip(h1)\mathrm{Lip}(g) \le \mathrm{Lip}(h_{n+1}) \cdot \cdots \cdot \mathrm{Lip}(h_1). Therefore, we first need to determine the Lipschitz constant for a dense layer hih_i. We know that a function ff is K-Lipschitz if for all points vv and ww the following holds:

dY(f(v),f(w))≤KdX(v,w),(3.27)d_Y(f(v), f(w)) \leq K d_X(v, w), \tag{3.27}

where we assume that the distance metrics dX=dY=dd_X = d_Y = d are chosen to be the ℓ2\ell_2-norm. Further, let two functions f1f_1 and f2f_2 be concatenated in hh:

hv=[f1(v)f2(v)],hw=[f1(w)f2(w)],(3.28)h_v = \begin{bmatrix} f_1(v) \\ f_2(v) \end{bmatrix}, \quad h_w = \begin{bmatrix} f_1(w) \\ f_2(w) \end{bmatrix}, \tag{3.28}

where function f1f_1 is the upper part and f2f_2 is the lower part. We can now find an analytical form to express a limit on KK for the dense layer in the form of Eq. (3.27):

d(hv,hw)2=d(f1(v),f1(w))2+d(f2(v),f2(w))2,d(h_v, h_w)^2 = d(f_1(v), f_1(w))^2 + d(f_2(v), f_2(w))^2, d(hv,hw)2≤(K12+K22)d(v,w)2,(3.29)d(h_v, h_w)^2 \leq (K_1^2 + K_2^2) d(v, w)^2, \tag{3.29}

where we know that the Lipschitz constant of hh consist of two parts, namely Lip(f1)=K1\text{Lip}(f_1) = K_1 and Lip(f2)=K2\text{Lip}(f_2) = K_2. Therefore, the Lipschitz constant of layer hh can be expressed as

Lip(h)=(K12+K22).(3.30)\text{Lip}(h) = \sqrt{(K_1^2 + K_2^2)}. \tag{3.30}

With spectral normalization of Eq. (3.23), we know that we can enforce (convolutional) weights WiW_i to be at most 1-Lipschitz. Hence, for all nn dense layers we apply the spectral normalization on the lower part which locally enforces Lip(f2)=K2<1\text{Lip}(f_2) = K_2 < 1. Further, since we enforce each layer hih_i to be at most 1-Lipschitz and we start with h1h_1, where f1(x)=xf_1(x) = x, we know that Lip(f1)=1\text{Lip}(f_1) = 1. Therefore, the Lipschitz constant of an entire layer can be at most Lip(h)=12+12=2\text{Lip}(h) = \sqrt{1^2 + 1^2} = \sqrt{2}, thus dividing by this limit enforces each layer to be at most 1-Lipschitz. To read more about DenseNet flows and further improvements, please see the original paper [6].

3.2 Flows for Discrete Random Variables

3.2.1 Introduction

While discussing flow-based models in the previous section, we presented them as density estimators, namely models that represent stochastic dependencies among continuous random variables. We introduced the change of variables formula that helps to express a random variable by transforming it using invertible maps (bijections) ff to a random variable with a known probability density function. Formally, it is defined as follows:

p(x)=p(v=f−1(x))∣Jf(x)∣−1,(3.31)p(\mathbf{x}) = p\left(\mathbf{v} = f^{-1}(\mathbf{x})\right) \left| \mathbf{J}_f(\mathbf{x}) \right|^{-1}, \tag{3.31}

[!visual-conversion] Simple geometric shape-transformation diagram (circle↔square, circle↔line) — transcribes 1:1 to ASCII. Converted from Fig. 3.7, page 050.

A B
y ○ <==> □ y ○ <=X=> ―
| (circle) (square) | (circle) (line segment)
+----------> x +----------> x
homeomorphic (both directions) non-homeomorphic (X: circle → line
cannot be inverted back to a circle)

Fig. 3.7 Examples of: (a) homeomorphic spaces, and (b) non-homeomorphic spaces. The red cross indicates it is impossible to invert the transformation

where Jf(x)\mathbf{J}_f(\mathbf{x}) is the Jacobian of ff at x\mathbf{x}.

However, there are potential issues with such an approach. First of all, in many problems (e.g., image processing) the considered random variables (objects) are discrete. For instance, images typically take values in {0,1,…,255}⊂Z\{0, 1, \dots, 255\} \subset \mathbb{Z}. In order to apply flows, we must apply dequantization [10] that results in a lower bound to the original probability distribution.

A continuous space possesses various potential pitfalls. One of them is that if we a transformation is a bijection (as in flows), not all continuous deformations are possible. It is tightly connected with topology and, more precisely, homeomorphisms, i.e., a continuous function between topological spaces that has a continuous inverse function, and diffeomorphisms, i.e., invertible functions that map one differentiable manifold to another such that both the function and its inverse are smooth. It is not crucial to know topology, but a curious reader may take a detour and read on that, it is definitely a fascinating field and I wish to know more about it! Anyway, let us consider three examples.

Imagine we want to transform a square into a circle (Fig. 3.7a). It is possible to find a homeomorphism (i.e., a bijection) that turns the square into the circle and back. Imagine you have a hammer and an iron square. If you start hitting the square infinitely many times, you can get an iron circle. Then, you can do it “backward” to get the square back. I know, it is unrealistic but hey, we are talking about math here!

However, if we consider a line segment and a circle (Fig. 3.7b), the situation is a bit more complicated. It is possible to transform the line segment into a circle, but not the other way around. Why? Because while transforming the circle to the line segment, it is unclear which point of the circle corresponds to the beginning (or the end) of the line segment. That is why we cannot invert the transformation!

[!visual-conversion] Topological ring→ball diagram — the figure’s point hinges on a subtle detail (the transformed ring has a break, with a visible “trace” connecting the inner ball to the gap, showing how probability mass continuity is maintained). Misrepresenting that detail in ASCII would misstate the exact topological point being made, so cropped rather than approximated. source_page: pages/page-051.png | visual_type: topology diagram

dgm-fig-3.8-ring-to-ball.png Fig. 3.8 An example of “replacing” a ring (in blue) with a ball (in magenta)

Another example that I really like, and which is closer to the potential issues of continuous flows, is transforming a ring into a ball as in Fig. 3.8. The goal is to replace the blue ring with the magenta ball. In order to make the transformation bijective, while transforming the blue ring in place of the magenta ball, we must ensure that the new magenta “ring” is in fact “broken” so that the new blue “ball” can get inside! Again, why? If the magenta ring is not broken, then we cannot say how the blue ball got inside that destroys bijectivity! In the language of topology, it is impossible because the two spaces are non-homeomorphic.

Alright, but how this affects the flow-based models? I hope that some of you asked this question, or maybe even imagined possible cases where this might hinder learning flows. In general, I would say it is fine, and we should not look for faults where there is none or almost none. However, if you work with flows that require dequantization, then you can spot cases like the one in Fig. 3.9. In this simple example, we have two discrete random variables that after uniform dequantization have two regions with equal probability mass, and the remaining two regions with zero probability mass [10]. After training a flow-based model, we have a density estimator that assigns non-zero probability mass where the true distribution has zero density! Moreover, the transformation in the flow must be a bijection, therefore, there is a continuity between the two squares (see Fig. 3.9, right). Where did we see that? Yes, in Fig. 3.8! We must know how to invert the transformation, thus, there must be a “trace” of how the probability mass moves between the regions.

Again, we can ask ourselves if it is bad. Well, I would say not really, but if we think of a case with more random variables, and there is always some little error here and there, this causes a probability mass leakage that could result in a far-from-perfect model. And, overall, the model could err in proper probability assignment.

3.2.2 Flows in R\mathbb{R} or Maybe Rather in Z\mathbb{Z}?

Before we consider any specific cases and discuss discrete flows, first we need to answer whether there is a change of variables formula for discrete random variables. The answer, fortunately, is yes! Let us consider x∈XD\mathbf{x} \in \mathcal{X}^D where X\mathcal{X} is a discrete space,

[!visual-conversion] Shaded-region heatmap-style plot — the fuzziness of the right panel’s edges (probability leaking outside the true support) is the figure’s entire point; a table/ASCII rendering can’t carry a soft gradient. Cropped from page 052. source_page: pages/page-052.png | visual_type: shaded density plot

dgm-fig-3.9-dequantized-vs-flow.png Fig. 3.9 An example of uniformly dequantized discrete random variables (left) and a flow-based model (right). Notice that in these examples, the true distribution assigns equal probability mass to the two regions in orange, and zero probability mass to the remaining two regions (in black). However, the flow-based model assigns probability mass outside the original non-zero probability regions

e.g., X={0,1}X = \{0, 1\} or X=ZX = \mathbb{Z}. Then the change of variables takes the following form:

p(x)=π(z0=f−1(x)),(3.32)p(\mathbf{x}) = \pi \left( \mathbf{z}_0 = f^{-1}(\mathbf{x}) \right), \tag{3.32}

where ff is an invertible transformation and π(⋅)\pi(\cdot) is a base distribution. Immediately we can spot a “missing” Jacobian-determinant. This is correct! Why? Because now we live in the discrete world where the probability mass is assigned to points that are “shapeless” and the bijection cannot change the volume. Thus, the Jacobian-determinant is always equal to 1! That seems to be good news, isn’t it? We can take any bijective transformations and we do not need to bother about the Jacobian. That is obviously true, however, we need to remember that the output of the transformation must be still discrete, i.e., z∈XDz \in \mathcal{X}^D. As a result, we cannot use any arbitrary invertible neural network. We will discuss it in a minute, however, before we do that, it is worth discussing the expressivity of discrete flows.

Let us assume that we have an invertible transformation f:XD→XDf : \mathcal{X}^D \to \mathcal{X}^D. Moreover, we have X={0,1}X = \{0, 1\}. As noted by Papamakarios et al. [27], a discrete flow can only permute probability masses. Since there is no Jacobian (or, rather, the Jacobian-determinant is equal to 1), there is no chance to decrease or increase the probability for specific values. We depict it in Fig. 3.10. You can easily imagine the situation as the space is the Rubik’s cube and your hands are the flows. If you record your moves, you can always play the video backward, thus, it is invertible. However, you can only shuffle the colors around! As a result, we do not gain anything by

[!visual-conversion] Color-coded probability grid (shading encodes probability magnitude per cell) — cannot be read off reliably from a grayscale scan or transcribed without asserting values I can’t verify. Cropped from page 053. source_page: pages/page-053.png | visual_type: shaded grid / heatmap

dgm-fig-3.10-discrete-flow-2x2.png Fig. 3.10 An example of a discrete flow for two binary random variables. Colors represent various probabilities (i.e., the sum of all squares is 1)

[!visual-conversion] Color-coded probability grid (5×5, extended space) — same reasoning as Fig. 3.10: shading is the encoded quantitative content. Cropped from page 053. source_page: pages/page-053.png | visual_type: shaded grid / heatmap

dgm-fig-3.11-discrete-flow-5x5.png Fig. 3.11 An example of a discrete flow for two binary random variables but in the extended space. Colors represent various probabilities (i.e., the sum of all squares is 1)

applying the discrete flow, and learning the discrete flow is equivalent to learning the base distribution π\pi.^1 So we are back to square one.

However, as pointed out by van den Berg et al. [12], the situation looks differently if we consider an extended space (or infinite space like Z\mathbb{Z}). The discrete flow can still only shuffle the probabilities, but now it can re-organize them in such a way that the probabilities can be factorized! In other words, it can help the base distribution to be a product of marginals, π(z)=∏d=1Dπd(zd∣θd)\pi(\mathbf{z}) = \prod_{d=1}^{D} \pi_d(\mathbf{z}_d|\theta_d), and the dependencies among variables are now encoded in the invertible transformations. An example of this case is presented in Fig. 3.11. We refer to [12] for a more thorough discussion with an appropriate lemma.

This is amazing information! It means that building a flow-based model in the discrete space makes sense. Now we can think of how to build an invertible neural network in discrete spaces and we have it!

[1] Well, this is not entirely true, we can still learn some correlations but it is definitely highly limited.

3.2.3 Integer Discrete Flows

We know now that it makes sense to work with discrete flows and that they are viable as long as we use extended spaces or infinite spaces like Z\mathbb{Z}. However, the question is how to formulate an invertible transformation (or rather: an invertible neural network) that will output discrete values.

Hoogeboom et al. [22] proposed to focus on integers since they can be seen as discretized continuous values. As such, we consider coupling layers [7] and modify them accordingly. Let us remind ourselves the definition of bipartite coupling layers for x∈RD\mathbf{x} \in \mathbb{R}^D:

ya=xa(3.33)\mathbf{y}_a = \mathbf{x}_a \tag{3.33} yb=exp⁡(s(xa))⊙xb+t(xa),(3.34)\mathbf{y}_b = \exp\left(s\left(\mathbf{x}_a\right)\right) \odot \mathbf{x}_b + t\left(\mathbf{x}_a\right), \tag{3.34}

where s(⋅)s(\cdot) and t(⋅)t(\cdot) are arbitrary neural networks called scaling and transition, respectively.

Considering integer-valued variables, x∈ZD\mathbf{x} \in \mathbb{Z}^D, requires modifying this transformation. First, using scaling might be troublesome because multiplying by integers is still possible, but when we invert the transformation, we divide by integers, and dividing an integer by an integer does not necessarily result in an integer. Therefore, we must remove scaling just in case. Second, we use an arbitrary neural network for the transition. However, this network must return integers! Hoogeboom et al. [22] utilize a relatively simple trick, namely they say that we can round the output of t(⋅)t(\cdot) to the closest integer. As a result, we add (in the forward) or subtract (in the inverse) integers from integers that is perfectly fine. (the outcome is still integer-valued.) Eventually, we get the following bipartite coupling layer:

ya=xa(3.35)\mathbf{y}_a = \mathbf{x}_a \tag{3.35} yb=xb+⌊t(xa)⌋,(3.36)\mathbf{y}_b = \mathbf{x}_b + \left\lfloor t\left(\mathbf{x}_a\right) \right\rfloor, \tag{3.36}

where ⌊⋅⌋\lfloor \cdot \rfloor is the rounding operator. An inquisitive reader could ask at this point whether the rounding operator still allows using the backpropagation algorithm. In other words, whether the rounding operator is differentiable. The answer is no, but [22] showed that using the straight-through estimator (STE) of a gradient is sufficient. As a side note, the STE in this case uses the rounding in the forward pass of the network, ⌊t(xa)⌋\lfloor t\left(\mathbf{x}_a\right) \rfloor, but it utilizes t(xa)t\left(\mathbf{x}_a\right) in the backward pass (to calculate gradients). van den Berg et al. [12] further indicated that indeed the STE works well and the bias does not hinder training too much. The implementation of the rounding operator using the STE is presented below.

  1. We need to turn torch.round (i.e., the rounding operator) into a differentiable function. For this purpose, we use the rounding in the forward pass, but the original input for the backward pass. This is nothing else than the STE.

    Section titled “We need to turn torch.round (i.e., the rounding operator) into a differentiable function. For this purpose, we use the rounding in the forward pass, but the original input for the backward pass. This is nothing else than the STE.”
  2. class RoundStraightThrough(torch.autograd.Function):
def __init__(self):
super().__init__()
@staticmethod
def forward(ctx, input):
rounded = torch.round(input, out=None)
return rounded
@staticmethod
def backward(ctx, grad_output):
grad_input = grad_output.clone()
return grad_input

Listing 3.3 An implementation of the rounding operator using the STE

In [23] it has been shown how to generalize invertible transformations like bipartite coupling layers, among others, namely (Xi:jX_{i:j} denotes a subset of XX corresponding to variables from the ii-th dimension to the jj-th dimension, xi:jx_{i:j}, we assume that X1:0=∅X_{1:0} = \emptyset and Xn+1:n=∅X_{n+1:n} = \emptyset):

Proposition 3.1 ([23]) Let us take x,y∈Xx, y \in X. If binary transformations ∘\circ and ▹\triangleright have inverses ∙\bullet and ◃\triangleleft, respectively, and g2,…,gDg_2, \dots, g_D and f1,…,fDf_1, \dots, f_D are arbitrary functions, where gi:X1:i−1→Xig_i : X_{1:i-1} \to X_i, fi:X1:i−1×Xi+1:n→Xif_i : X_{1:i-1} \times X_{i+1:n} \to X_i, then the following transformation from xx to yy:

y1=x1∘f1(∅,x2:D)y_1 = x_1 \circ f_1(\emptyset, x_{2:D}) y2=(g2(y1)▹x2)∘f2(y1,x3:D)y_2 = (g_2(y_1) \triangleright x_2) \circ f_2(y_1, x_{3:D}) ⋯\cdots yd=(gd(y1:d−1)▹xd)∘fd(y1:d−1,xd+1:D)y_d = (g_d(y_{1:d-1}) \triangleright x_d) \circ f_d(y_{1:d-1}, x_{d+1:D}) ⋯\cdots yD=(gD(y1:D−1)▹xD)∘fD(y1:D−1,∅)y_D = (g_D(y_{1:D-1}) \triangleright x_D) \circ f_D(y_{1:D-1}, \emptyset)

is invertible.

Proof In order to inverse yy to xx we start from the last element to obtain the following:

xD=gD(y1:D−1)◃(yD∙fD(y1:D−1,∅)) .x_D = g_D(y_{1:D-1}) \triangleleft (y_D \bullet f_D(y_{1:D-1}, \emptyset)) \,.

Then, we can proceed with next expressions in the decreasing order (i.e., from D−1D-1 to 1) to eventually obtain

xD−1=gD−1(y1:D−2)◃(yD−1∙fD−1(y1:D−2,xD))x_{D-1} = g_{D-1}(y_{1:D-2}) \triangleleft (y_{D-1} \bullet f_{D-1}(y_{1:D-2}, x_D)) ⋯\cdots xd=gd(y1:d−1)←(yd∙fd(y1:d−1,xd+1:D))x_d = g_d(y_{1:d-1}) \leftarrow (y_d \bullet f_d(y_{1:d-1}, x_{d+1:D})) ⋯\cdots x2=g2(y1)←(y2∙f2(y1,x3:D))x_2 = g_2(y_1) \leftarrow (y_2 \bullet f_2(y_1, x_{3:D})) x1=y1∙f1(∅,x2:D).x_1 = y_1 \bullet f_1(\emptyset, x_{2:D}).

For instance, we can divide x\mathbf{x} into four parts, x=[xa,xb,xc,xd]\mathbf{x} = [\mathbf{x}_a, \mathbf{x}_b, \mathbf{x}_c, \mathbf{x}_d], and the following transformation (a quadripartite coupling layer) is invertible [23]:

ya=xa+[t(xb,xc,xd)](3.37)y_a = x_a + [t(x_b, x_c, x_d)] \tag{3.37} yb=xb+[t(ya,xc,xd)](3.38)y_b = x_b + [t(y_a, x_c, x_d)] \tag{3.38} yc=xc+[t(ya,yb,xd)](3.39)y_c = x_c + [t(y_a, y_b, x_d)] \tag{3.39} yd=xd+[t(ya,yb,yc)].(3.40)y_d = x_d + [t(y_a, y_b, y_c)]. \tag{3.40}

This new invertible transformation could be seen as a kind of autoregressive processing since yay_a is used to calculate yby_b, then both yay_a and yby_b are used for obtaining ycy_c and so on. As a result, we get a more powerful transformation than the bipartite coupling layer.

If we stick to a coupling layer, we need to remember to use a permutation layer to reverse the order of variables. Otherwise, some inputs would be only partially processed. This holds true for any coupling layer, either they are used for continuous flows or integer-valued flows.

The last component we need to think of is the base distribution. Similarly to flow-based models, we can use various tricks to boost the performance of the model. For instance, we can consider squeezing, factoring-out, and a mixture model for the base distribution [22]. However, in this section, we try to keep the model as simple as possible, therefore, we use the product of marginals as the base distribution. For images represented as integers, we use the following:

π(z)=∏d=1Dπd(zd)(3.41)\pi(\mathbf{z}) = \prod_{d=1}^{D} \pi_d(z_d) \tag{3.41} =∏d=1DDL(zd∣μd,νd),(3.42)= \prod_{d=1}^{D} \mathrm{DL}(z_d | \mu_d, \nu_d), \tag{3.42}

where πd(zd)=DL(zd∣μd,νd)\pi_d(z_d) = \mathrm{DL}(z_d | \mu_d, \nu_d) is the discretized logistic distribution that is defined as a difference of CDFs of the logistic distribution as follows [34]:

π(z)=sigm((z+0.5−μ)/ν)−sigm((z−0.5−μ)/ν),(3.43)\pi(z) = \mathrm{sigm}\left((z + 0.5 - \mu)/\nu\right) - \mathrm{sigm}\left((z - 0.5 - \mu)/\nu\right), \tag{3.43}

[!visual-conversion] Standard sigmoid/logistic-CDF curve with a marked bin — a well-defined mathematical function (given explicitly by the formula alongside it), so its shape transcribes 1:1 as ASCII without approximation risk. Converted from Fig. 3.12, page 057.

p(z)
1 |...........................................______
| ,---´
| ,-´ p(z) = CDF(z+0.5) − CDF(z−0.5)
| ,-´
| ,-´
| ,-´
| ,.-´
| ______.-´
0 +----------|--|----------------------------------> z
z−0.5 z+0.5
└──┬──┘
bin of size 1 (shaded area = its probability mass)

Fig. 3.12 An example of the discretized logistic distribution with μ=0\mu = 0 and ν=1\nu = 1. The magenta area on the y-axis corresponds to the probability mass of a bin of size 1

where μ∈R\mu \in \mathbb{R} and ν>0\nu > 0 denote the mean and the scale, respectively, sigm(⋅)\text{sigm}(\cdot) is the sigmoid function. Notice that this is equivalent to calculating the probability of zz falling into a bin of length 1, therefore, we add 0.5 in the first CDF and subtract 0.5 from the second CDF. An example of the discretized distribution is presented in Fig. 3.12 and the implementation follows. Interestingly, we can use this distribution to replace the Categorical distribution in Chap. 2, as it was done in [18]. We can even use a mixture of discretized logistic distribution to further improve the final performance [22, 35].

# This function implements the log of the discretized logistic distribution.
def log_integer_probability(x, mean, logscale):
scale = torch.exp(logscale)
logp = log_min_exp(
F.logsigmoid((x + 0.5 - mean) / scale),
F.logsigmoid((x - 0.5 - mean) / scale))
return logp

Listing 3.4 The logarithm of the discretized logistic distribution [34]

Eventually, our log-likelihood function takes the following form:

ln⁡p(x)=∑d=1Dln⁡DL(zd=f−1(x)∣μd,νd)(3.44)\ln p(\mathbf{x}) = \sum_{d=1}^{D} \ln \text{DL}(z_d = f^{-1}(\mathbf{x})|\mu_d, \nu_d) \tag{3.44} =∑d=1Dln⁡(sigm((zd+0.5−μd)νd)−sigm((zd−0.5−μd)νd)),(3.45)= \sum_{d=1}^{D} \ln \left( \text{sigm}\left( \frac{(z_d + 0.5 - \mu_d)}{\nu_d} \right) - \text{sigm}\left( \frac{(z_d - 0.5 - \mu_d)}{\nu_d} \right) \right), \tag{3.45}

here we make all μd\mu_d and vdv_d learnable parameters. Notice that vdv_d must be positive strictly larger than 0), therefore, in the implementation, we will consider the logarithm of the scale because taking exp of the log-scale ensures having strictly positive values.

Now, we have all components to implement our own Integer Discrete Flow (IDFs)! Below, there is a code with a lot of comments that should help to understand every single line of it.

# That's the class of the Integer Discrete Flows (IDFs).
# There are two options implemented:
# Option 1: The bipartite coupling layers as in (Hoogeboom et al
# , 2019).
# Option 2: A new coupling layer with 4 parts as in (Tomczak,
# 2021).
# We implement the second option explicitly, without any loop, so
# that it is very clear how it works.
class IDF(nn.Module):
def __init__(self, netts, num_flows, D=2):
super(IDF, self).__init__()
print('IDF by JT.')
# Option 1:
if len(netts) == 1:
self.t = torch.nn.ModuleList([netts[0]() for _ in
range(num_flows)])
self.idf_git = 1
# Option 2:
elif len(netts) == 4:
self.t_a = torch.nn.ModuleList([netts[0]() for _ in
range(num_flows)])
self.t_b = torch.nn.ModuleList([netts[1]() for _ in
range(num_flows)])
self.t_c = torch.nn.ModuleList([netts[2]() for _ in
range(num_flows)])
self.t_d = torch.nn.ModuleList([netts[3]() for _ in
range(num_flows)])
self.idf_git = 4
else:
raise ValueError('You can provide either 1 or 4
translation nets.')
# The number of flows (i.e., invertible transformations).
self.num_flows = num_flows
# The rounding operator
self.round = RoundStraightThrough.apply
# Initialization of the parameters of the base distribution.
# Notice they are parameters, so they are trained
# alongside the weights of neural networks.
self.mean = nn.Parameter(torch.zeros(1, D)) #mean
self.logscale = nn.Parameter(torch.ones(1, D)) #log-scale
# The dimensionality of the problem.
self.D = D
# The coupling layer.
def coupling(self, x, index, forward=True):
# Option 1:
if self.idf_git == 1:
(xa, xb) = torch.chunk(x, 2, 1)
if forward:
yb = xb + self.round(self.t[index](xa))
else:
yb = xb - self.round(self.t[index](xa))
return torch.cat((xa, yb), 1)
# Option 2:
elif self.idf_git == 4:
(xa, xb, xc, xd) = torch.chunk(x, 4, 1)
if forward:
ya = xa + self.round(self.t_a[index](torch.cat((xb, xc, xd), 1)))
yb = xb + self.round(self.t_b[index](torch.cat((ya, xc, xd), 1)))
yc = xc + self.round(self.t_c[index](torch.cat((ya, yb, xd), 1)))
yd = xd + self.round(self.t_d[index](torch.cat((ya, yb, yc), 1)))
else:
yd = xd - self.round(self.t_d[index](torch.cat((xa, xb, xc), 1)))
yc = xc - self.round(self.t_c[index](torch.cat((xa, xb, yd), 1)))
yb = xb - self.round(self.t_b[index](torch.cat((xa, yc, yd), 1)))
ya = xa - self.round(self.t_a[index](torch.cat((yb, yc, yd), 1)))
return torch.cat((ya, yb, yc, yd), 1)
# Similarly to RealNVP, we have also the permute layer.
def permute(self, x):
return x.flip(1)
# The main function of the IDF: forward pass from x to z.
def f(self, x):
z = x
for i in range(self.num_flows):
z = self.coupling(z, i, forward=True)
z = self.permute(z)
return z
# The function for inverting z to x.
def f_inv(self, z):
x = z
for i in reversed(range(self.num_flows)):
x = self.permute(x)
x = self.coupling(x, i, forward=False)
return x
# The PyTorch forward function. It returns the log-probability.
def forward(self, x, reduction='avg'):
z = self.f(x)
if reduction == 'sum':
return -self.log_prior(z).sum()
else:
return -self.log_prior(z).mean()
# The function for sampling:
# First we sample from the base distribution.
# Second, we invert z.
def sample(self, batchSize, intMax=100):
# sample z:
z = self.prior_sample(batchSize=batchSize, D=self.D, intMax=intMax)
# x = f^-1(z)
x = self.f_inv(z)
return x.view(batchSize, 1, self.D)
# The function for calculating the logarithm of the base distribution.
def log_prior(self, x):
log_p = log_integer_probability(x, self.mean, self.logscale)
return log_p.sum(1)
# A function for sampling integers from the base distribution.
def prior_sample(self, batchSize, D=2):
# Sample from logistic
y = torch.rand(batchSize, self.D)
# Here we use a property of the logistic distribution:
# In order to sample from a logistic distribution, first sample y ~ Uniform[0,1].
# Then, calculate log(y / (1.-y)), scale is with the scale, and add the mean.
x = torch.exp(self.logscale) * torch.log(y / (1. - y)) + self.mean
# And then round it to an integer.
return torch.round(x)

Listing 3.5 An example of networks

Below, we provide examples of neural networks that could be used to run the IDFs.

# The number of invertible transformations
num_flows = 8
# This variable defines whether we use:
# Option 1: 1 - the classic coupling layer proposed in (Hoogeboom et al., 2019)
# Option 2: 4 - the general invertible transformation in (Tomczak, 2021) with 4 partitions
idf_git = 1
if idf_git == 1:
nett = lambda: nn.Sequential(
nn.Linear(D//2, M), nn.LeakyReLU(),
nn.Linear(M, M), nn.LeakyReLU(),
nn.Linear(M, D//2))
netts = [nett]
elif idf_git == 4:
nett_a = lambda: nn.Sequential(
nn.Linear(3 * (D//4), M), nn.LeakyReLU(),
nn.Linear(M, M), nn.LeakyReLU(),
nn.Linear(M, D//4))
nett_b = lambda: nn.Sequential(
nn.Linear(3 * (D//4), M), nn.LeakyReLU(),
nn.Linear(M, M), nn.LeakyReLU(),
nn.Linear(M, D//4))
nett_c = lambda: nn.Sequential(
nn.Linear(3 * (D//4), M), nn.LeakyReLU(),
nn.Linear(M, M), nn.LeakyReLU(),
nn.Linear(M, D//4))
nett_d = lambda: nn.Sequential(
nn.Linear(3 * (D//4), M), nn.LeakyReLU(),
nn.Linear(M, M), nn.LeakyReLU(),
nn.Linear(M, D//4))
netts = [nett_a, nett_b, nett_c, nett_d]

[!visual-conversion] Real generated-digit image grids — photographic content. Cropped from page 062. source_page: pages/page-062.png | visual_type: image grid

dgm-fig-3.13-idf-outcomes.png Fig. 3.13 An example of outcomes after the training: (a) Randomly selected real images. (b) Unconditional generations from the IDF with bipartite coupling layers. (c) Unconditional generations from the IDF with quadripartite coupling layers

# Init IDF
model = IDF(netts, num_flows, D=D)
# Print the summary (like in Keras)
print(summary(model, torch.zeros(1, 64), show_input=False,
show_hierarchical=False))

Listing 3.6 An example of networks

And we are done, this is all we need to have! After running the code (take a look at: https://github.com/jmtomczak/intro_dgm) and training the IDFs, we should obtain results similar to those in Fig. 3.13.

3.2.5 What’s Next?

Similarly to our example of RealNVP, here we present rather a simplified implementation of IDFs. We can use many of the tricks presented in the section on RealNVP (see Sect. 3.1.6). On recent developments on IDFs, please see also [12].

Integer discrete flows have a great potential in data compression. Since IDFs learn the distribution p(x)p(\mathbf{x}) directly on the integer-valued objects, they are excellent candidates for lossless compression. As presented in [22], they are competitive with other codecs for lossless compression of images.

The paper by van den Berg et al. [12] further shows that the potential bias following from the STE of the gradients is not as dramatic as originally thought [22], and they can learn flexible distributions. This result suggests that IDFs require special attention, especially for real-life applications like data compression.

It seems that the next step would be to think of more powerful transformations for discrete variables, e.g., see [23], and developing powerful architectures. Another interesting direction is utilizing alternative learning algorithms in which gradients could be better estimated [36], or even replaced [37].

References

  1. Danilo Rezende and Shakir Mohamed. Variational inference with normalizing flows. In International Conference on Machine Learning, pages 1530–1538. PMLR, 2015.

  2. Oren Rippel and Ryan Prescott Adams. High-dimensional probability estimation with deep density models. arXiv preprint arXiv:1302.5125, 2013.

  3. Rianne Van Den Berg, Leonard Hasenclever, Jakub M Tomczak, and Max Welling. Sylvester normalizing flows for variational inference. In 34th Conference on Uncertainty in Artificial Intelligence 2018, UAI 2018, pages 393–402. Association For Uncertainty in Artificial Intelligence (AUAI), 2018.

  4. Jens Behrmann, Will Grathwohl, Ricky TQ Chen, David Duvenaud, and Jörn-Henrik Jacobsen. Invertible residual networks. In International Conference on Machine Learning, pages 573–582. PMLR, 2019.

  5. Ricky TQ Chen, Jens Behrmann, David Duvenaud, and Jörn-Henrik Jacobsen. Residual flows for invertible generative modeling. arXiv preprint arXiv:1906.02735, 2019.

  6. Yura Perugachi-Diaz, Jakub M Tomczak, and Sandjai Bhulai. Invertible DenseNets with concatenated LipSwish. Advances in Neural Information Processing Systems, 2021.

  7. Laurent Dinh, Jascha Sohl-Dickstein, and Samy Bengio. Density estimation using Real NVP. arXiv preprint arXiv:1605.08803, 2016.

  8. Diederik P Kingma and Prafulla Dhariwal. Glow: generative flow with invertible 1×1 convolutions. In Proceedings of the 32nd International Conference on Neural Information Processing Systems, pages 10236–10245, 2018.

  9. Lucas Theis, Aäron van den Oord, and Matthias Bethge. A note on the evaluation of generative models. arXiv preprint arXiv:1511.01844, 2015.

  10. Emiel Hoogeboom, Taco S Cohen, and Jakub M Tomczak. Learning discrete distributions by dequantization. arXiv preprint arXiv:2001.11235, 2020.

  11. Thomas Bachlechner, Bodhisattwa Prasad Majumder, Huanru Henry Mao, Garrison W Cottrell, and Julian McAuley. Rezero is all you need: Fast convergence at large depth. arXiv preprint arXiv:2003.04887, 2020.

  12. Rianne van den Berg, Alexey A Gritsenko, Mostafa Dehghani, Casper Kaae Sønderby, and Tim Salimans. Idf++: Analyzing and improving integer discrete flows for lossless compression. arXiv e-prints, pages arXiv–2006, 2020.

  13. Jonathan Ho, Xi Chen, Aravind Srinivas, Yan Duan, and Pieter Abbeel. Flow++: Improving flow-based generative models with variational dequantization and architecture design. In International Conference on Machine Learning, pages 2722–2730. PMLR, 2019.

  14. Jonathan Ho, Evan Lohn, and Pieter Abbeel. Compression with flows via local bits-back coding. arXiv preprint arXiv:1905.08500, 2019.

  15. Michał Stypułkowski, Kacper Kania, Maciej Zamorski, Maciej Ziȩba, Tomasz Trzciński, and Jan Chorowski. Representing point clouds with generative conditional invertible flow networks. arXiv preprint arXiv:2010.11087, 2020.

  16. Christina Winkler, Daniel Worrall, Emiel Hoogeboom, and Max Welling. Learning likelihoods with conditional normalizing flows. arXiv preprint arXiv:1912.00042, 2019.

  17. Valentin Wolf, Andreas Lugmayr, Martin Danelljan, Luc Van Gool, and Radu Timofte. DeFlow: Learning complex image degradations from unpaired data with conditional flows. arXiv preprint arXiv:2101.05796, 2021.

  18. Durk P Kingma, Tim Salimans, Rafal Jozefowicz, Xi Chen, Ilya Sutskever, and Max Welling. Improved variational inference with inverse autoregressive flow. Advances in Neural Information Processing Systems, 29:4743–4751, 2016.

  19. Emiel Hoogeboom, Victor Garcia Satorras, Jakub M Tomczak, and Max Welling. The convolution exponential and generalized Sylvester flows. arXiv preprint arXiv:2006.01910, 2020.

  20. Jakub M Tomczak and Max Welling. Improving variational auto-encoders using householder flow. arXiv preprint arXiv:1611.09630, 2016.

  1. Jakub M Tomczak and Max Welling. Improving variational auto-encoders using convex combination linear inverse autoregressive flow. arXiv preprint arXiv:1706.02326, 2017.

  2. Emiel Hoogeboom, Jorn WT Peters, Rianne van den Berg, and Max Welling. Integer discrete flows and lossless compression. arXiv preprint arXiv:1905.07376, 2019.

  3. Jakub M Tomczak. General invertible transformations for flow-based generative modeling. INNF+, 2021.

  4. Johann Brehmer and Kyle Cranmer. Flows for simultaneous manifold learning and density estimation. arXiv preprint arXiv:2003.13913, 2020.

  5. George Papamakarios, David Sterratt, and Iain Murray. Sequential neural likelihood: Fast likelihood-free inference with autoregressive flows. In The 22nd International Conference on Artificial Intelligence and Statistics, pages 837–848. PMLR, 2019.

  6. George Papamakarios, Theo Pavlakou, and Iain Murray. Masked autoregressive flow for density estimation. arXiv preprint arXiv:1705.07057, 2017.

  7. George Papamakarios, Eric Nalisnick, Danilo Jimenez Rezende, Shakir Mohamed, and Balaji Lakshminarayanan. Normalizing flows for probabilistic modeling and inference. arXiv preprint arXiv:1912.02762, 2019.

  8. Henry Gouk, Eibe Frank, Bernhard Pfahringer, and Michael Cree. Regularisation of neural networks by enforcing Lipschitz continuity. arXiv preprint arXiv:1804.04368, 2018.

  9. Takeru Miyato, Toshiki Kataoka, Masanori Koyama, and Yuichi Yoshida. Spectral normalization for generative adversarial networks. arXiv preprint arXiv:1802.05957, 2018.

  10. John Skilling. The eigenvalues of mega-dimensional matrices. In Maximum Entropy and Bayesian Methods, pages 455–466. Springer, 1989.

  11. Michael F Hutchinson. A stochastic estimator of the trace of the influence matrix for laplacian smoothing splines. Communications in Statistics-Simulation and Computation, 19(2):433–450, 1990.

  12. Herman Kahn. Use of different Monte Carlo sampling techniques. Proceedings of Symposium on Monte Carlo Methods, 1955.

  13. Gao Huang, Zhuang Liu, Laurens Van Der Maaten, and Kilian Q Weinberger. Densely connected convolutional networks. In IEEE Conference on Computer Vision and Pattern Recognition, 2017.

  14. Subrata Chakraborty and Dhruvajyoti Chakravarty. A new discrete probability distribution with integer support on (−∞,∞)(-\infty, \infty). Communications in Statistics-Theory and Methods, 45(2):492–505, 2016.

  15. Tim Salimans, Andrej Karpathy, Xi Chen, and Diederik P Kingma. PixelCNN++: Improving the PixelCNN with discretized logistic mixture likelihood and other modifications. arXiv preprint arXiv:1701.05517, 2017.

  16. Emile van Krieken, Jakub M Tomczak, and Annette ten Teije. Storchastic: A framework for general stochastic automatic differentiation. Advances in Neural Information Processing Systems, 2021.

  17. Niru Maheswaranathan, Luke Metz, George Tucker, Dami Choi, and Jascha Sohl-Dickstein. Guided evolutionary strategies: Augmenting random search with surrogate gradients. In International Conference on Machine Learning, pages 4264–4273. PMLR, 2019.