# Flow-based generative model

A flow-based generative model is a generative model used in machine learning that explicitly models a probability distribution by leveraging normalizing flow, which is a statistical method using the change-of-variable law of probabilities to transform a simple distribution into a complex one.
The direct modeling of likelihood provides many advantages. For example, the negative log-likelihood can be directly computed and minimized as the loss function. Additionally, novel samples can be generated by sampling from the initial distribution, and applying the flow transformation.
In contrast, many alternative generative modeling methods such as variational autoencoder (VAE) and generative adversarial network do not explicitly represent the likelihood function.

## Method

Let $z_{0}$ be a (possibly multivariate) random variable with distribution $p_{0}(z_{0})$.
For $i=1,...,K$, let $z_{i}=f_{i}(z_{i-1})$ be a sequence of random variables transformed from $z_{0}$. The functions $f_{1},...,f_{K}$ should be invertible, i.e. the inverse function $f_{i}^{-1}$ exists. The final output $z_{K}$ models the target distribution.
The log likelihood of $z_{K}$ is (see derivation):
    $\log p_{K}(z_{K})=\log p_{0}(z_{0})-\sum _{i=1}^{K}\log \left|\det {\frac {df_{i}(z_{i-1})}{dz_{i-1}}}\right|$
To efficiently compute the log likelihood, the functions $f_{1},...,f_{K}$ should be easily invertible, and the determinants of their Jacobians should be simple to compute. In practice, the functions $f_{1},...,f_{K}$ are modeled using deep neural networks, and are trained to minimize the negative log-likelihood of data samples from the target distribution. These architectures are usually designed such that only the forward pass of the neural network is required in both the inverse and the Jacobian determinant calculations. Examples of such architectures include NICE, RealNVP, and Glow.

### Derivation of log likelihood

Consider $z_{1}$ and $z_{0}$. Note that $z_{0}=f_{1}^{-1}(z_{1})$.
By the change of variable formula, the distribution of $z_{1}$ is:
    $p_{1}(z_{1})=p_{0}(z_{0})\left|\det {\frac {df_{1}^{-1}(z_{1})}{dz_{1}}}\right|$
Where $\det {\frac {df_{1}^{-1}(z_{1})}{dz_{1}}}$ is the determinant of the Jacobian matrix of $f_{1}^{-1}$.
By the inverse function theorem:
    $p_{1}(z_{1})=p_{0}(z_{0})\left|\det \left({\frac {df_{1}(z_{0})}{dz_{0}}}\right)^{-1}\right|$
By the identity $\det(A^{-1})=\det(A)^{-1}$ (where $A$ is an invertible matrix), we have:
    $p_{1}(z_{1})=p_{0}(z_{0})\left|\det {\frac {df_{1}(z_{0})}{dz_{0}}}\right|^{-1}$
The log likelihood is thus:
    $\log p_{1}(z_{1})=\log p_{0}(z_{0})-\log \left|\det {\frac {df_{1}(z_{0})}{dz_{0}}}\right|$
In general, the above applies to any $z_{i}$ and $z_{i-1}$. Since $\log p_{i}(z_{i})$ is equal to $\log p_{i-1}(z_{i-1})$ subtracted by a non-recursive term, we can infer by induction that:
    $\log p_{K}(z_{K})=\log p_{0}(z_{0})-\sum _{i=1}^{K}\log \left|\det {\frac {df_{i}(z_{i-1})}{dz_{i-1}}}\right|$

## Training method

As is generally done when training a deep learning model, the goal with normalizing flows is to minimize the Kullback–Leibler divergence between the model's likelihood and the target distribution to be estimated. Denoting $p_{\theta }$ the model's likelihood and $p^{*}$ the target distribution to learn, the (forward) KL-divergence is:
    $D_{\text{KL}}[p^{*}(x)\|p_{\theta }(x)]=-\mathop {\mathbb {E} } _{p^{*}(x)}[\log p_{\theta }(x)]+\mathop {\mathbb {E} } _{p^{*}(x)}[\log p^{*}(x)]$
The second term on the right-hand side of the equation corresponds to the entropy of the target distribution and is independent of the parameter $\theta$ we want the model to learn, which only leaves the expectation of the negative log-likelihood to minimize under the target distribution. This intractable term can be approximated with a Monte-Carlo method by importance sampling. Indeed, if we have a dataset $\{x_{i}\}_{i=1}^{N}$ of samples each independently drawn from the target distribution $p^{*}(x)$, then this term can be estimated as:
    $-{\hat {\mathop {\mathbb {E} } }}_{p^{*}(x)}[\log p_{\theta }(x)]=-{\frac {1}{N}}\sum _{i=0}^{N}\log p_{\theta }(x_{i})$
Therefore, the learning objective
    ${\underset {\theta }{\operatorname {arg\,min} }}\ D_{\text{KL}}[p^{*}(x)\|p_{\theta }(x)]$
is replaced by
    ${\underset {\theta }{\operatorname {arg\,max} }}\ \sum _{i=0}^{N}\log p_{\theta }(x_{i})$
In other words, minimizing the Kullback–Leibler divergence between the model's likelihood and the target distribution is equivalent to maximizing the model likelihood under observed samples of the target distribution.
A pseudocode for training normalizing flows is as follows:
* INPUT. dataset $x_{1:n}$, normalizing flow model $f_{\theta }(\cdot ),p_{0}$.
* SOLVE. $\max _{\theta }\sum _{j}\ln p_{\theta }(x_{j})$ by gradient descent
* RETURN. ${\hat {\theta }}$

## Variants
### Planar Flow

The earliest example. Fix some activation function $h$, and let $\theta =(u,w,b)$ with the appropriate dimensions, then$x=f_{\theta }(z)=z+uh(\langle w,z\rangle +b)$The inverse $f_{\theta }^{-1}$ has no closed-form solution in general.
The Jacobian is $|\det(I+h'(\langle w,z\rangle +b)uw^{T})|=|1+h'(\langle w,z\rangle +b)\langle u,w\rangle |$.
For it to be invertible everywhere, it must be nonzero everywhere. For example, $h=\tanh$ and $\langle u,w\rangle >-1$ satisfies the requirement.

### Nonlinear Independent Components Estimation (NICE)

Let $x,z\in \mathbb {R} ^{2n}$ be even-dimensional, and split them in the middle. Then the normalizing flow functions are$x={\begin{bmatrix}x_{1}\\x_{2}\end{bmatrix}}=f_{\theta }(z)={\begin{bmatrix}z_{1}\\z_{2}\end{bmatrix}}+{\begin{bmatrix}0\\m_{\theta }(z_{1})\end{bmatrix}}$where $m_{\theta }$ is any neural network with weights $\theta$.
$f_{\theta }^{-1}$ is just $z_{1}=x_{1},z_{2}=x_{2}-m_{\theta }(x_{1})$, and the Jacobian is just 1, that is, the flow is volume-preserving.
When $n=1$, this is seen as a curvy shearing along the $x_{2}$ direction.

### Real Non-Volume Preserving (Real NVP)

The Real Non-Volume Preserving model generalizes NICE model by:$x={\begin{bmatrix}x_{1}\\x_{2}\end{bmatrix}}=f_{\theta }(z)={\begin{bmatrix}z_{1}\\e^{s_{\theta }(z_{1})}\odot z_{2}\end{bmatrix}}+{\begin{bmatrix}0\\m_{\theta }(z_{1})\end{bmatrix}}$
Its inverse is $z_{1}=x_{1},z_{2}=e^{-s_{\theta }(x_{1})}\odot (x_{2}-m_{\theta }(x_{1}))$, and its Jacobian is $\prod _{i=1}^{n}e^{s_{\theta }(z_{1,})}$. The NICE model is recovered by setting $s_{\theta }=0$. Since the Real NVP map keeps the first and second halves of the vector $x$ separate, it's usually required to add a permutation $(x_{1},x_{2})\mapsto (x_{2},x_{1})$ after every Real NVP layer.

### Generative Flow (Glow)

In generative flow model, each layer has 3 parts:
* channel-wise affine transform$y_{cij}=s_{c}(x_{cij}+b_{c})$with Jacobian $\prod _{c}s_{c}^{HW}$.
* invertible 1x1 convolution$z_{cij}=\sum _{c'}K_{cc'}y_{cij}$with Jacobian $\det(K)^{HW}$. Here $K$ is any invertible matrix.
* Real NVP, with Jacobian as described in Real NVP.
The idea of using the invertible 1x1 convolution is to permute all layers in general, instead of merely permuting the first and second half, as in Real NVP.

### Masked autoregressive flow (MAF)

An autoregressive model of a distribution on $\mathbb {R} ^{n}$ is defined as the following stochastic process:
${\begin{aligned}x_{1}\sim &N(\mu _{1},\sigma _{1}^{2})\\x_{2}\sim &N(\mu _{2}(x_{1}),\sigma _{2}(x_{1})^{2})\\&\cdots \\x_{n}\sim &N(\mu _{n}(x_{1:n-1}),\sigma _{n}(x_{1:n-1})^{2})\\\end{aligned}}$where $\mu _{i}:\mathbb {R} ^{i-1}\to \mathbb {R}$ and $\sigma _{i}:\mathbb {R} ^{i-1}\to (0,\infty )$ are fixed functions that define the autoregressive model.
By the reparameterization trick, the autoregressive model is generalized to a normalizing flow:${\begin{aligned}x_{1}=&\mu _{1}+\sigma _{1}z_{1}\\x_{2}=&\mu _{2}(x_{1})+\sigma _{2}(x_{1})z_{2}\\&\cdots \\x_{n}=&\mu _{n}(x_{1:n-1})+\sigma _{n}(x_{1:n-1})z_{n}\\\end{aligned}}$The autoregressive model is recovered by setting $z\sim N(0,I_{n})$.
The forward mapping is slow (because it's sequential), but the backward mapping is fast (because it's parallel).
The Jacobian matrix is lower-diagonal, so the Jacobian is $\sigma _{1}\sigma _{2}(x_{1})\cdots \sigma _{n}(x_{1:n-1})$.
Reversing the two maps $f_{\theta }$ and $f_{\theta }^{-1}$ of MAF results in Inverse Autoregressive Flow (IAF), which has fast forward mapping and slow backward mapping.

### Continuous Normalizing Flow (CNF)

Instead of constructing flow by function composition, another approach is to formulate the flow as a continuous-time dynamic. Let $z_{0}$ be the latent variable with distribution $p(z_{0})$. Map this latent variable to data space with the following flow function:
    $x=F(z_{0})=z_{T}=z_{0}+\int _{0}^{T}f(z_{t},t)dt$
where $f$ is an arbitrary function and can be modeled with e.g. neural networks.
The inverse function is then naturally:
    $z_{0}=F^{-1}(x)=z_{T}+\int _{T}^{0}f(z_{t},t)dt=z_{T}-\int _{0}^{T}f(z_{t},t)dt$
And the log-likelihood of $x$ can be found as:
    $\log(p(x))=\log(p(z_{0}))-\int _{0}^{T}{\text{Tr}}\left[{\frac {\partial f}{\partial z_{t}}}\right]dt$
Since the trace depends only on the diagonal of the Jacobian $\partial _{z_{t}}f$, this allows "free-form" Jacobian. Here, "free-form" means that there is no restriction on the Jacobian's form. It is contrasted with previous discrete models of normalizing flow, where the Jacobian is carefully designed to be only upper- or lower-diagonal, so that the Jacobian can be evaluated efficiently.
The trace can be estimated by "Hutchinson's trick":
   Given any matrix $W\in \mathbb {R} ^{n\times n}$, and any random $u\in \mathbb {R} ^{n}$ with $E[uu^{T}]=I$, we have $E[u^{T}Wu]=tr(W)$. (Proof: expand the expectation directly.)
Usually, the random vector is sampled from $N(0,I)$ (normal distribution) or $\{\pm n^{-1/2}\}^{n}$ (Radamacher distribution).
When $f$ is implemented as a neural network, neural ODE methods would be needed. Indeed, CNF was first proposed in the same paper that proposed neural ODE.
There are two main deficiencies of CNF, one is that a continuous flow must be a homeomorphism, thus preserve orientation and ambient isotopy (for example, it's impossible to flip a left-hand to a right-hand by continuous deforming of space, and it's impossible to turn a sphere inside out, or undo a knot), and the other is that the learned flow $f$ might be ill-behaved, due to degeneracy (that is, there are an infinite number of possible $f$ that all solve the same problem).
By adding extra dimensions, the CNF gains enough freedom to reverse orientation and go beyond ambient isotopy (just like how one can pick up a polygon from a desk and flip it around in 3-space, or unknot a knot in 4-space), yielding the "augmented neural ODE".
Any homeomorphism of $\mathbb {R} ^{n}$ can be approximated by a neural ODE operating on $\mathbb {R} ^{2n+1}$, proved by combining Whitney embedding theorem for manifolds and the universal approximation theorem for neural networks.
To regularize the flow $f$, one can impose regularization losses. The paper proposed the following regularization loss based on optimal transport theory:$\lambda _{K}\int _{0}^{T}\left\|f(z_{t},t)\right\|^{2}dt+\lambda _{J}\int _{0}^{T}\left\|\nabla _{z}f(z_{t},t)\right\|_{F}^{2}dt$where $\lambda _{K},\lambda _{J}>0$ are hyperparameters. The first term punishes the model for oscillating the flow field over time, and the second term punishes it for oscillating the flow field over space. Both terms together guide the model into a flow that is smooth (not "bumpy") over space and time.

## Downsides

Despite normalizing flows success in estimating high-dimensional densities, some downsides still exist in their designs. First of all, their latent space where input data is projected onto is not a lower-dimensional space and therefore, flow-based models do not allow for compression of data by default and require a lot of computation. However, it is still possible to perform image compression with them.
Flow-based models are also notorious for failing in estimating the likelihood of out-of-distribution samples (i.e.: samples that were not drawn from the same distribution as the training set). Some hypotheses were formulated to explain this phenomenon, among which the typical set hypothesis, estimation issues when training models, or fundamental issues due to the entropy of the data distributions.
One of the most interesting properties of normalizing flows is the invertibility of their learned bijective map. This property is given by constraints in the design of the models (cf.: RealNVP, Glow) which guarantee theoretical invertibility. The integrity of the inverse is important in order to ensure the applicability of the change-of-variable theorem, the computation of the Jacobian of the map as well as sampling with the model. However, in practice this invertibility is violated and the inverse map explodes because of numerical imprecision.

## Applications

Flow-based generative models have been applied on a variety of modeling tasks, including:
* Audio generation
* Image generation
* Molecular graph generation
* Point-cloud modeling
* Video generation
* Lossy image compression
* Anomaly detection