A flow-based generative model is a generative model used in machine learning that explicitly models a probability distribution by leveraging normalizing flow,[1][2][3] 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 autoencoders (VAEs), generative adversarial networks (GANs), or diffusion models, 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^{-1}_i 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|
Learning probability distributions by differentiating such log Jacobians originated in the Infomax (maximum likelihood) approach to ICA,[4] which forms a single-layer (K=1) flow-based model. Relatedly, the single layer precursor of conditional generative flows appeared in.[5]
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,[6] RealNVP,[7] and Glow.[8]
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.[9]
A pseudocode for training normalizing flows is as follows:[10]
- INPUT. dataset
x_{1:n}, normalizing flow modelf_\theta(\cdot), p_0. - SOLVE.
\max_\theta \sum_j \log p_\theta(x_j)by gradient descent - RETURN.
\hat\theta
Variants
Planar Flow
The earliest example.[11] Fix some activation function h, and let \theta = (u, w, b) with the appropriate dimensions, then
x = f_\theta(z) = z + u h(\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 \R^{2n} be even-dimensional, and split them in the middle.[6] 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:[7]
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^n_{i=1} 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,[8] 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 \R^n is defined as the following stochastic process:[12]
\begin{align}
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{align}
where \mu_i: \R^{i-1} \to \R and \sigma_i: \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{align}
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{align}
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.[13]
Continuous Normalizing Flow (CNF)
Instead of constructing flow by function composition, another approach is to formulate the flow as a continuous-time dynamic.[14][15] 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:[14]
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:[14]
\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.[16] 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":[17][18]
Given any matrixUsually, the random vector is sampled fromW\in \R^{n\times n}, and any randomu\in \R^nwithE[uu^T] = I, we haveE[u^T W u] = tr(W). (Proof: expand the expectation directly.)
N(0, I) (normal distribution) or \{\pm n^{-1/2}\}^n (Rademacher distribution).
When f is implemented as a neural network, neural ODE methods[19] 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".[20]
Any homeomorphism of \R^n can be approximated by a neural ODE operating on \R^{2n+1}, proved by combining Whitney embedding theorem for manifolds and the universal approximation theorem for neural networks.[21]
To regularize the flow f, one can impose regularization losses. The paper [17] 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.
Flows on manifolds
When a probabilistic flow transforms a distribution on an m-dimensional smooth manifold embedded in \R^n, where m<n, and where the transformation is specified as a function, \R^n\to\R^n, the scaling factor between the source and transformed PDFs is not given by the naive computation of the determinant of the n\text{-by-}n Jacobian (which is zero), but instead by the determinant(s) of one or more suitably defined m\text{-by-}m matrices. This section is an interpretation of the tutorial in the appendix of Sorrenson et al.(2023),[22] where the more general case of non-isometrically embedded Riemann manifolds is also treated. Here we restrict attention to isometrically embedded manifolds.
As running examples of manifolds with smooth, isometric embedding in \R^n we shall use:
- The unit hypersphere:
\mathbb S^{n-1}=\{\mathbf x\in\R^n:\mathbf x'\mathbf x=1\}, where flows can be used to generalize e.g. Von Mises-Fisher or uniform spherical distributions. - The simplex interior:
\Delta^{n-1}=\{\mathbf p=(p_1,\dots,p_n)\in\R^n:p_i>0, \sum_ip_i=1\}, wheren-way categorical distributions live; and where flows can be used to generalize e.g. Dirichlet, or uniform simplex distributions.
As a first example of a spherical manifold flow transform, consider the normalized linear transform, which radially projects onto the unit sphere the output of an invertible linear transform, parametrized by the n\text{-by-}n invertible matrix \mathbf M:
f_\text{lin}(\mathbf x; \mathbf M) = \frac{\mathbf{Mx}}{\lVert\mathbf{Mx}\rVert}
In full Euclidean space, f_\text{lin}:\R^n\to\R^n is not invertible, but if we restrict the domain and co-domain to the unit sphere, then f_\text{lin}:\mathbb S^{n-1}\to\mathbb S^{n-1} is invertible (more specifically it is a bijection and a homeomorphism and a diffeomorphism), with inverse f_\text{lin}(\cdot\,;\mathbf M^{-1}). The Jacobian of f_\text{lin}:\R^n\to\R^n, at \mathbf y=f_\text{lin}(\mathbf x;\mathbf M) is \lVert\mathbf{Mx}\rVert^{-1}(\mathbf I_n -\mathbf{yy}')\mathbf M, which has rank n-1 and determinant of zero; while as explained here, the factor (see subsection below) relating source and transformed densities is: \lVert\mathbf{Mx}\rVert^{-n}\left|\operatorname{det}\mathbf M\right|.
Differential volume ratio
For m<n, let \mathcal M\subset\R^n be an m-dimensional manifold with a smooth, isometric embedding into \R^n. Let f:\R^n\to\R^n be a smooth flow transform with range restricted to \mathcal M. Let \mathbf x\in\mathcal M be sampled from a distribution with density P_X. Let \mathbf y=f(\mathbf x), with resultant (pushforward) density P_Y. Let U\subset\mathcal M be a small, convex region containing \mathbf x and let V=f(U) be its image, which contains \mathbf y; then by conservation of probability mass:
P_X(\mathbf x)\operatorname{volume}(U)\approx P_Y(\mathbf y)\operatorname{volume}(V)
where volume (for very small regions) is given by Lebesgue measure in m-dimensional tangent space. By making the regions infinitessimally small, the factor relating the two densities is the ratio of volumes, which we term the differential volume ratio.
To obtain concrete formulas for volume on the m-dimensional manifold, we construct U by mapping an m-dimensional rectangle in (local) coordinate space to the manifold via a smooth embedding function: \R^m\to\R^n. At very small scale, the embedding function becomes essentially linear so that U is a parallelotope (multidimensional generalization of a parallelogram). Similarly, the flow transform, f becomes linear, so that the image, V=f(U) is also a parallelotope. In \R^m, we can represent an m-dimensional parallelotope with an m\text{-by-}m matrix whose column-vectors are a set of edges (meeting at a common vertex) that span the paralellotope. The volume is given by the absolute value of the determinant of this matrix. If more generally (as is the case here), an m-dimensional paralellotope is embedded in \R^n, it can be represented with a (tall) n\text{-by-}m matrix, say \mathbf V. Denoting the parallelotope as /\mathbf V\!/, its volume is then given by the square root of the Gram determinant:
\operatorname{volume}/\mathbf V\!/=\sqrt{\left|\operatorname{det}(\mathbf V'\mathbf V)\right|}
In the sections below, we show various ways to use this volume formula to derive the differential volume ratio.
Simplex flow
As a first example, we develop expressions for the differential volume ratio of a simplex flow, \mathbf q=f(\mathbf p), where \mathbf p, \mathbf q\in\mathcal M=\Delta^{n-1}. Define the embedding function:
e:\tilde\mathbf p=(p_1\dots,p_{n-1})\mapsto\mathbf p=(p_1\dots,p_{n-1},1-\sum_{i=1}^{n-1}p_i)
which maps a conveniently chosen, (n-1)-dimensional representation, \tilde\mathbf p, to the embedded manifold. The n\text{-by-}(n-1) Jacobian is
\mathbf E = \begin{bmatrix}
\mathbf{I}_{n-1} \\
-\boldsymbol{1}'
\end{bmatrix}.
To define U, the differential volume element at the transformation input (\mathbf p\in\Delta^{n-1}), we start with a rectangle in \tilde\mathbf p-space, having (signed) differential side-lengths, dp_1, \dots, dp_{n-1} from which we form the square diagonal matrix \mathbf D, the columns of which span the rectangle. At very small scale, we get U=e(\mathbf D)=/\mathbf{ED}\!/, with:
\operatorname{volume}(U) = \sqrt{\left|\operatorname{det}(\mathbf{DE}'\mathbf{ED})\right|} = \sqrt{\left|\operatorname{det}(\mathbf E'\mathbf E)\right|}\, \left|\operatorname{det}\mathbf D)\right| =\sqrt n\prod_{i=1}^{n-1} \left|dp_i\right|
To understand the geometric interpretation of the factor \sqrt{n}, see the example for the 1-simplex in the diagram at right.
The differential volume element at the transformation output (\mathbf q\in\Delta^{n-1}), is the parallelotope, V=f(U)=/\mathbf{F_pED}\!/, where \mathbf{F_p} is the n\text{-by-}n Jacobian of f at \mathbf p=e(\tilde\mathbf p). Its volume is:
\operatorname{volume}(V) = \sqrt{\left|\operatorname{det}(\mathbf{DE}'\mathbf{ F_p}'\mathbf{F_pED})\right|} = \sqrt{\left|\operatorname{det}(\mathbf E'\mathbf{F_p}'\mathbf{F_pE})\right|}\, \left|\operatorname{det}\mathbf D)\right|
so that the factor \left|\operatorname{det}\mathbf D)\right| cancels in the volume ratio, which can now already be numerically evaluated. It can however be rewritten in a sometimes more convenient form by also introducing the representation function, r:\mathbf p\mapsto\tilde\mathbf p, which simply extracts the first (n-1) components. The Jacobian is \mathbf R=\begin{bmatrix}\mathbf I_n&\boldsymbol0\end{bmatrix}. Observe that, since e\circ r\circ f=f, the chain rule for function composition gives: \mathbf{ERF_p}=\mathbf{F_p}. By plugging this expansion into the above Gram determinant and then refactoring it as a product of determinants of square matrices, we can extract the factor \sqrt{\left|\operatorname{det}(\mathbf E'\mathbf E)\right|}=\sqrt n, which now also cancels in the ratio, which finally simpifies to the determinant of the Jacobian of the "sandwiched" flow transformation, r\circ f\circ e:
R^\Delta_f(\mathbf p)=\frac{\operatorname{volume}(V)}{\operatorname{volume}(U)} = \left|\operatorname{det}(\mathbf{RF_pE})\right|
which, if \mathbf p\sim P_\mathbf P, can be used to derive the pushforward density after a change of variables, \mathbf q = f(\mathbf p):
P_{\mathbf Q}(\mathbf q) = \frac{P_{\mathbf P}(\mathbf p)}{R^\Delta_f(\mathbf p)}\,,\;\text{where}\;\; \mathbf p=f^{-1}(\mathbf q)
This formula is valid only because the simplex is flat and the Jacobian, \mathbf E is constant. The more general case for curved manifolds is discussed below, after we present two concrete examples of simplex flow transforms.
Simplex calibration transform
A calibration transform, f_\text{cal}:\Delta^{n-1}\to\Delta^{n-1}, which is sometimes used in machine learning for post-processing of the (class posterior) outputs of a probabilistic n-class classifier,[23][24] uses the softmax function to renormalize categorical distributions after scaling and translation of the input distributions in log-probability space. For \mathbf p, \mathbf q\in\Delta^{n-1} and with parameters, a\ne0 and \mathbf c\in\R^n the transform can be specified as:
\mathbf q=f_\text{cal}(\mathbf p; a, \mathbf c) = \operatorname{softmax}(a^{-1}\log\mathbf p+\mathbf c)\;\iff\; \mathbf p=f^{-1}_\text{cal}(\mathbf q; a, \mathbf c) = \operatorname{softmax}(a\log\mathbf q-a\mathbf c)
where the log is applied elementwise. After some algebra the differential volume ratio can be expressed as:
R^\Delta_\text{cal}(\mathbf p; a, \mathbf c) = \left|\operatorname{det}(\mathbf{RF_pE})\right| = \left|a\right|^{1-n}\prod_{i=1}^n\frac{q_i}{p_i}
- This result can also be obtained by factoring the density of the SGB distribution,[25] which is obtained by sending Dirichlet variates through
f_\text{cal}.
While calibration transforms are most often trained as discriminative models, the reinterpretation here as a probabilistic flow allows also the design of generative calibration models based on this transform. When used for calibration, the restriction a>0 can be imposed to prevent direction reversal in log-probability space. With the additional restriction \mathbf c=\boldsymbol0, this transform (with discriminative training) is known in machine learning as temperature scaling.
Generalized calibration transform
The above calibration transform can be generalized to f_\text{gcal}:\Delta^{n-1}\to\Delta^{n-1}, with parameters \mathbf c\in\R^n and \mathbf A n\text{-by-}n invertible:[26]
\mathbf q = f_\text{gcal}(\mathbf p;\mathbf A,\mathbf c) = \operatorname{softmax}(\mathbf A\log\mathbf p + \mathbf c)\,,\;\text{subject to}\; \mathbf{A1}=\lambda\mathbf1
where the condition that \mathbf A has \mathbf1 as an eigenvector ensures invertibility by sidestepping the information loss due to the invariance: \operatorname{softmax}(\mathbf x+\alpha\mathbf1)=\operatorname{softmax}(\mathbf x). Note in particular that \mathbf A=\lambda\mathbf I_n is the only allowed diagonal parametrization, in which case we recover f_\text{cal}(\mathbf p;\lambda^{-1},\mathbf c), while (for n>2) generalization is possible with non-diagonal matrices. The inverse is:
\mathbf p = f_\text{gcal}^{-1}(\mathbf q;\mathbf A, \mathbf c) = f_\text{gcal}(\mathbf q;\mathbf A^{-1}, -\mathbf A^{-1}\mathbf c)\,,\;\text{where}\; \mathbf{A1}=\lambda\mathbf1\Longrightarrow\mathbf{A}^{-1}\mathbf1=\lambda^{-1}\mathbf1
The differential volume ratio is:
R^\Delta_\text{gcal}(\mathbf p;\mathbf A,\mathbf c) =\frac{\left|\operatorname{det}(\mathbf A)\right|}{|\lambda|}\prod_{i=1}^n\frac{q_i}{p_i}
If f_\text{gcal} is to be used as a calibration transform, further constraint could be imposed, for example that \mathbf A be positive definite, so that (\mathbf{Ax})'\mathbf x>0, which avoids direction reversals. (This is one possible generalization of a>0 in the f_\text{cal} parameter.)
For n=2, a>0 and \mathbf A positive definite, then f_\text{cal} and f_\text{gcal} are equivalent in the sense that in both cases, \log\frac{p_1}{p_2}\mapsto\log\frac{q_1}{q_2} is a straight line, the (positive) slope and offset of which are functions of the transform parameters. For n>2, f_\text{gcal} does generalize f_\text{cal}.
It must however be noted that chaining multiple f_\text{gcal} flow transformations does not give a further generalization, because:
f_\text{gcal}(\cdot\,;\mathbf A_1,\mathbf c_1) \circ f_\text{gcal}(\cdot\,;\mathbf A_2,\mathbf c_2) = f_\text{gcal}(\cdot\,;\mathbf A_1\mathbf A_2,\mathbf c_1+\mathbf A_1\mathbf c_2)
In fact, the set of f_\text{gcal} transformations form a group under function composition. The set of f_\text{cal} transformations form a subgroup.
Also see: Dirichlet calibration,[27] which generalizes f_\text{gcal}, by not placing any restriction on the matrix, \mathbf A, so that invertibility is not guaranteed. While Dirichlet calibration is trained as a discriminative model, f_\text{gcal} can also be trained as part of a generative calibration model.
Differential volume ratio for curved manifolds
Consider a flow, \mathbf y=f(\mathbf x) on a curved manifold, for example \mathbb S^{n-1} which we equip with the embedding function, e that maps a set of (n-1) angular spherical coordinates to \mathbb S^{n-1}. The Jacobian of e is non-constant and we have to evaluate it at both input (\mathbf {E_x}) and output (\mathbf {E_y}). The same applies to r, the representation function that recovers spherical coordinates from points on \mathbb S^{n-1}, for which we need the Jacobian at the output (\mathbf{R_y}). The differential volume ratio now generalizes to:
R_f(\mathbf x) = \left|\operatorname{det}(\mathbf{R_yF_xE_x})\right|\,\frac{\sqrt{\left|\operatorname{det}(\mathbf E_\mathbf y'\mathbf{E_y})\right|}}{\sqrt{\left|\operatorname{det}(\mathbf E_\mathbf x'\mathbf{E_x})\right|}}
For geometric insight, consider \mathbf S^2, where the spherical coordinates are co-latitude, \theta\in[0,\pi] and longitude, \phi\in[0,2\pi). At \mathbf x = e(\theta,\phi), we get \sqrt{\left|\operatorname{det}(\mathbf E_\mathbf x'\mathbf{E_x})\right|}=\sin\theta, which gives the radius of the circle at that latitude (compare e.g. polar circle to equator). The differential volume (surface area on the sphere) is: \sin\theta\,d\theta\,d\phi.
The above derivation for R_f is fragile in the sense that when using fixed functions e,r, there may be places where they are not well-defined, for example at the poles of the 2-sphere where longitude is arbitrary. This problem is sidestepped (using standard manifold machinery) by generalizing to local coordinates (charts), where in the vicinities of \mathbf x,\mathbf y\in\mathcal M, we map from local m-dimensional coordinates to \R^n and back using the respective function pairs e_{\mathbf x}, r_{\mathbf x} and e_{\mathbf y}, r_{\mathbf y}. We continue to use the same notation for the Jacobians of these functions (\mathbf{E_x}, \mathbf{E_y}, \mathbf{R_y}), so that the above formula for R_f remains valid.
We can however, choose our local coordinate system in a way that simplifies the expression for R_f and indeed also its practical implementation.[22] Let \pi:\mathcal P\to\R^n be a smooth idempotent projection (\pi\circ\pi=\pi) from the projectible set, \mathcal P\subseteq\R^n, onto the embedded manifold. For example:
- The positive orthant of
\R^nis projected onto the simplex as:\pi(\mathbf z)=\bigl(\sum_{i=1}^n z_i\bigr)^{-1}\mathbf z - Non-zero vectors in
\R^nare projected onto the unit sphere as:\pi(\mathbf z)=\bigl(\sum_{i=1}^n z^2_i\bigr)^{-\frac12}\mathbf z
For every \mathbf x\in\mathcal M, we require of \pi that its n\text{-by-}n Jacobian, \boldsymbol{\Pi_x} has rank m (the manifold dimension), in which case \boldsymbol{\Pi_x} is an idempotent linear projection onto the local tangent space (orthogonal for the unit sphere: \mathbf I_n-\mathbf{xx}'; oblique for the simplex: \mathbf I_n-\boldsymbol{x1}'). The columns of \boldsymbol{\Pi_x} span the m-dimensional tangent space at \mathbf x. We use the notation, \mathbf{T_x} for any n\text{-by-}m matrix with orthonormal columns (\mathbf T_{\mathbf x}'\mathbf{T_x}=\mathbf I_m) that span the local tangent space. Also note: \boldsymbol{\Pi_x}\mathbf{T_x}=\mathbf{T_x}. We can now choose our local coordinate embedding function, e_\mathbf x:\R^m\to\R^n:
e_\mathbf x(\tilde x) = \pi(\mathbf x + \mathbf{T_x\tilde x})\,, \text{with Jacobian:}\,\mathbf{E_x}=\mathbf{T_x}\,\text{at}\,\tilde\mathbf x=\mathbf0.
Since the Jacobian is injective (full rank: m), a local (not necessarily unique) left inverse, say r^*_\mathbf x with Jacobian \mathbf R^*_\mathbf x, exists such that r^*_\mathbf x(e_\mathbf x(\tilde x))=\tilde x and \mathbf R^*_\mathbf x\mathbf{T_x}=\mathbf I_m. In practice we do not need the left inverse function itself, but we do need its Jacobian, for which the above equation does not give a unique solution. We can however enforce a unique solution for the Jacobian by choosing the left inverse as, r_\mathbf x:\R^n\to\R^m:
r_\mathbf x(\mathbf z) = r^*_\mathbf x(\pi(\mathbf z))\,,\text{with Jacobian:}\, \mathbf{R_x}=\mathbf T_\mathbf x'
We can now finally plug \mathbf{E_x}=\mathbf{T_x} and \mathbf{R_y}=\mathbf T_\mathbf y' into our previous expression for R_f, the differential volume ratio, which because of the orthonormal Jacobians, simplifies to:[28]
R_f(\mathbf x) = \left|\operatorname{det}(\mathbf{T_y}'\mathbf{F_xT_x})\right|
Practical implementation
For learning the parameters of a manifold flow transformation, we need access to the differential volume ratio, R_f, or at least to its gradient w.r.t. the parameters. Moreover, for some inference tasks, we need access to R_f itself. Practical solutions include:
- Sorrenson et al.(2023)[22] give a solution for computationally efficient stochastic parameter gradient approximation for
\log R_f. - For some hand-designed flow transforms,
R_fcan be analytically derived in closed form, for example the above-mentioned simplex calibration transforms. Further examples are given below in the section on simple spherical flows. - On a software platform equipped with linear algebra and automatic differentiation,
R_f(\mathbf x) = \left|\operatorname{det}(\mathbf{T_y}'\mathbf{F_xT_x})\right|can be automatically evaluated, given access to only\mathbf x, f, \pi.[29] But this is expensive for high-dimensional data, with at least\mathcal O(n^3)computational costs. Even then, the slow automatic solution can be invaluable as a tool for numerically verifying hand-designed closed-form solutions.
Simple spherical flows
In machine learning literature, various complex spherical flows formed by deep neural network architectures may be found.[22] In contrast, this section compiles from statistics literature the details of three very simple spherical flow transforms, with simple closed-form expressions for inverses and differential volume ratios. These flows can be used individually, or chained, to generalize distributions on the unit sphere, \mathbb S^{n-1}. All three flows are compositions of an invertible affine transform in \R^n, followed by radial projection back onto the sphere. The flavours we consider for the affine transform are: pure translation, pure linear and general affine. To make these flows fully functional for learning, inference and sampling, the tasks are:
- To derive the inverse transform, with suitable restrictions on the parameters to ensure invertibility.
- To derive in simple closed form the differential volume ratio,
R_f.
An interesting property of these simple spherical flows is that they don't make use of any non-linearities apart from the radial projection. Even the simplest of them, the normalized translation flow, can be chained to form perhaps surprisingly flexible distributions.
Normalized translation flow
The normalized translation flow, f_\text{trans}:\mathbb S^{n-1}\to\mathbb S^{n-1}, with parameter \mathbf c\in\R^n, is given by:
\mathbf y = f_\text{trans}(\mathbf x;\mathbf c) =\frac{\mathbf x + \mathbf c}{\lVert\mathbf x + \mathbf c\rVert}\,, \;\text{where}\;\lVert\mathbf c\rVert < 1
The inverse function may be derived by considering, for \ell>0: \mathbf y=\ell^{-1}(\mathbf x+\mathbf c) and then using \mathbf x'\mathbf x=1 to get a quadratic equation to recover \ell, which gives:
\mathbf x = f^{-1}_\text{trans}(\mathbf y;\mathbf c) = \ell\mathbf y - \mathbf c\,,\text{where}\; \ell = \mathbf y'\mathbf c +\sqrt{(\mathbf y'\mathbf c)^2+1-\mathbf c'\mathbf c}
from which we see that we need \lVert\mathbf c\rVert < 1 to keep \ell real and positive for all \mathbf y\in\mathbb S^{n-1}. The differential volume ratio is given (without derivation) by Boulerice & Ducharme(1994) as:[30]
R_\text{trans}(\mathbf x;\mathbf c) = \frac{1+\mathbf x'\mathbf c}{\lVert\mathbf x +\mathbf c\rVert^n}
This can indeed be verified analytically:
- By a laborious manipulation of
R_f(\mathbf x) = \left|\operatorname{det}(\mathbf{T_y}'\mathbf{F_xT_x})\right|. - By setting
\mathbf M=\mathbf I_ninR_\text{aff}(\mathbf x;\mathbf M, \mathbf c), which is given below.
Finally, it is worth noting that f_\text{trans} and f^{-1}_\text{trans} do not have the same functional form.
Normalized linear flow
The normalized linear flow, f_\text{lin}:\mathbb S^{n-1}\to\mathbb S^{n-1}, where parameter \mathbf M is an invertible n\text{-by-}n matrix, is given by:
\mathbf y = f_\text{lin}(\mathbf x;\mathbf M) =\frac{\mathbf{Mx}}{\lVert\mathbf{Mx}\rVert} \;\iff\; \mathbf x = f^{-1}_\text{lin}(\mathbf y;\mathbf M) = f_\text{lin}(\mathbf y;\mathbf M^{-1}) =\frac{\mathbf{M^{-1}y}}{\lVert\mathbf{M^{-1}y}\rVert}
The differential volume ratio is:
R_\text{lin}(\mathbf x; \mathbf M) = \frac{\left|\operatorname{det}\mathbf M\right|} {\lVert\mathbf{Mx}\rVert^n}
This result can be derived indirectly via the Angular central Gaussian distribution (ACG),[31] which can be obtained via normalized linear transform of either Gaussian, or uniform spherical variates. The first relationship can be used to derive the ACG density by a marginalization integral over the radius; after which the second relationship can be used to factor out the differential volume ratio. For details, see ACG distribution.
Normalized affine flow
The normalized affine flow, f_\text{aff}:\mathbb S^{n-1}\to\mathbb S^{n-1}, with parameters \mathbf c\in\R^n and \mathbf M, n\text{-by-}n invertible, is given by:
f_\text{aff}(\mathbf x;\mathbf M, \mathbf c) =\frac{\mathbf{Mx} + \mathbf c}{\lVert\mathbf{Mx} + \mathbf c\rVert}\,, \;\text{where}\;\lVert\mathbf{M^{-1}c}\rVert < 1
The inverse function, derived in a similar way to the normalized translation inverse is:
\mathbf x = f^{-1}_\text{aff}(\mathbf y;\mathbf M,\mathbf c) = \mathbf M^{-1}(\ell\mathbf y - \mathbf c)\,,\text{where}\; \ell = \frac{\mathbf y'\mathbf{Wc} +\sqrt{(\mathbf y'\mathbf{Wc})^2+\mathbf y'\mathbf{Wy}(1-\mathbf c'\mathbf{Wc})}}{\mathbf y'\mathbf{Wy}}
where \mathbf W=(\mathbf{MM}')^{-1}. The differential volume ratio is:
R_\text{aff}(\mathbf x; \mathbf M, \mathbf c) =R_\text{lin}(\mathbf x; \mathbf M+\mathbf c\mathbf x') = \frac{\left|\operatorname{det}\mathbf M\right|(1+\mathbf x'\mathbf{M^{-1}c})} {\lVert\mathbf{Mx+c}\rVert^n}
The final RHS numerator was expanded from \operatorname{det}(\mathbf M + \mathbf{cx}') by the matrix determinant lemma. Recalling R_f(\mathbf x)=\left|\operatorname{det}(\mathbf T_\mathbf y'\mathbf{F_xT_x})\right|, the equality between R_\text{aff} and R_\text{lin} holds because not only:
\mathbf x'\mathbf x=1\;\Longrightarrow\;\mathbf y = f_\text{aff}(\mathbf x; \mathbf{M,c})=f_\text{lin}(\mathbf x; \mathbf{M+cx}')
but also, by orthogonality of \mathbf x to the local tangent space:
\mathbf x'\mathbf{T_x}=\boldsymbol0\;\Longrightarrow\;\mathbf F_\mathbf x^\text{aff}\mathbf{T_x} = \mathbf F_\mathbf x^\text{lin}\mathbf{T_x}
where \mathbf F_\mathbf x^\text{lin}=\lVert\mathbf{Mx}+\mathbf c\rVert^{-1}(\mathbf I_n-\mathbf{yy}')(\mathbf{M+cx}') is the Jacobian of f_\text{lin} differentiated w.r.t. its input, but not also w.r.t. its parameter.
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.[32]
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).[33] Some hypotheses were formulated to explain this phenomenon, among which the typical set hypothesis,[34] estimation issues when training models,[35] or fundamental issues due to the entropy of the data distributions.[36]
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.[37]
Applications
Flow-based generative models have been applied on a variety of modeling tasks, including:
- Audio generation[38]
- Image generation[8]
- Molecular graph generation[39]
- Point-cloud modeling[40]
- Video generation[41]
- Lossy image compression[32]
- Anomaly detection[42]
References
- ^ Tabak, Esteban G. & Vanden-Eijnden, Eric (2010). "Density estimation by dual ascent of the log-likelihood". Communications in Mathematical Sciences. 8 (1): 217–233. doi:10.4310/CMS.2010.v8.n1.a11
- ^ Tabak, Esteban G. & Turner, Cristina V. (2012). "A family of nonparametric density estimation algorithms". Communications on Pure and Applied Mathematics. 66 (2): 145–164. doi:10.1002/cpa.21423. hdl:11336/8930. S2CID 17820269
- ^ Papamakarios, George; Nalisnick, Eric; Jimenez Rezende, Danilo; Mohamed, Shakir; Bakshminarayanan, Balaji (2021). "Normalizing flows for probabilistic modeling and inference". Journal of Machine Learning Research. 22 (1): 2617–2680. arXiv:1912.02762
- ^ Bell, A. J.; Sejnowski, T. J. (1995). "An information-maximization approach to blind separation and blind deconvolution". Neural Computation. **7** (6): 1129–1159. doi:10.1162/neco.1995.7.6.1129.
- ^ Roth, Z.; Baram, Y. (1996). "Multidimensional density shaping by sigmoids". IEEE Transactions on Neural Networks. **7** (5): 1291–1298. doi:10.1109/72.536322.
- ^ Dinh, Laurent; Krueger, David; Bengio, Yoshua (2014). "NICE: Non-linear Independent Components Estimation". arXiv:1410.8516
- ^ Dinh, Laurent; Sohl-Dickstein, Jascha; Bengio, Samy (2016). "Density estimation using Real NVP". arXiv:1605.08803
- ^ Kingma, Diederik P. & Dhariwal, Prafulla (2018). "Glow: Generative Flow with Invertible 1x1 Convolutions". arXiv:1807.03039
- ^ Papamakarios, George; Nalisnick, Eric; Rezende, Danilo Jimenez; Shakir, Mohamed; Balaji, Lakshminarayanan (March 2021). "Normalizing Flows for Probabilistic Modeling and Inference". Journal of Machine Learning Research. 22 (57): 1–64. arXiv:1912.02762
- ^ Kobyzev, Ivan; Prince, Simon J.D.; Brubaker, Marcus A. (November 2021). "Normalizing Flows: An Introduction and Review of Current Methods". IEEE Transactions on Pattern Analysis and Machine Intelligence. 43 (11): 3964–3979. arXiv:1908.09257. Bibcode:2021ITPAM..43.3964K. doi:10.1109/TPAMI.2020.2992934. ISSN 1939-3539. PMID 32396070. S2CID 208910764
- ^ Danilo Jimenez Rezende & Mohamed, Shakir (2015). "Variational Inference with Normalizing Flows". arXiv:1505.05770
- ^ Papamakarios, George; Pavlakou, Theo; Murray, Iain (2017). "Masked Autoregressive Flow for Density Estimation". Advances in Neural Information Processing Systems. 30. Curran Associates, Inc. arXiv:1705.07057
- ^ Kingma, Durk P; Salimans, Tim; Jozefowicz, Rafal; Chen, Xi; Sutskever, Ilya; Welling, Max (2016). "Improved Variational Inference with Inverse Autoregressive Flow". Advances in Neural Information Processing Systems. 29. Curran Associates, Inc. arXiv:1606.04934
- ^ Grathwohl, Will; Chen, Ricky T. Q.; Bettencourt, Jesse; Sutskever, Ilya; Duvenaud, David (2018). "FFJORD: Free-form Continuous Dynamics for Scalable Reversible Generative Models". arXiv:1810.01367
- ^ Lipman, Yaron; Chen, Ricky T. Q.; Ben-Hamu, Heli; Nickel, Maximilian; Le, Matt (2022-10-01). "Flow Matching for Generative Modeling". arXiv:2210.02747
- ^ Grathwohl, Will; Chen, Ricky T. Q.; Bettencourt, Jesse; Sutskever, Ilya; Duvenaud, David (2018-10-22). "FFJORD: Free-form Continuous Dynamics for Scalable Reversible Generative Models". arXiv:1810.01367
- ^ Finlay, Chris; Jacobsen, Joern-Henrik; Nurbekyan, Levon; Oberman, Adam (2020-11-21). "How to Train Your Neural ODE: the World of Jacobian and Kinetic Regularization". International Conference on Machine Learning. PMLR. arXiv:2002.02798
- ^ Hutchinson, M.F. (January 1989). "A Stochastic Estimator of the Trace of the Influence Matrix for Laplacian Smoothing Splines". Communications in Statistics - Simulation and Computation. 18 (3): 1059–1076. doi:10.1080/03610918908812806. ISSN 0361-0918
- ^ Chen, Ricky T. Q.; Rubanova, Yulia; Bettencourt, Jesse; Duvenaud, David K. (2018). Neural Ordinary Differential Equations. Advances in Neural Information Processing Systems. Vol. 31. Curran Associates, Inc. arXiv:1806.07366
- ^ Dupont, Emilien; Doucet, Arnaud; Teh, Yee Whye (2019). "Augmented Neural ODEs". Advances in Neural Information Processing Systems. 32. Curran Associates, Inc.
- ^ Zhang, Han; Gao, Xi; Unterman, Jacob; Arodz, Tom (2019-07-30). "Approximation Capabilities of Neural ODEs and Invertible Residual Networks". arXiv:1907.12998
- ^ Sorrenson, Peter; Draxler, Felix; Rousselot, Armand; Hummerich, Sander; Köthe, Ullrich (2023). "Learning Distributions on Manifolds with Free-Form Flows". arXiv:2312.09852
- ^ Brümmer, Niko & van Leeuwen, D. A. (2006). On calibration of language recognition scores. Proceedings of IEEE Odyssey: The Speaker and Language Recognition Workshop. pp. 1–8. doi:10.1109/ODYSSEY.2006.248106
- ^ Ferrer, Luciana & Ramos, Daniel (2024). "Evaluating Posterior Probabilities: Decision Theory, Proper Scoring Rules, and Calibration". arXiv:2408.02841
- ^ Graf, Monique (2019). "The Simplicial Generalized Beta distribution - R-package SGB and applications". Libra. Retrieved 26 May 2025.
- ^ Brümmer, Niko (18 October 2010). Measuring, refining and calibrating speaker and language information extracted from speech (PhD thesis). Stellenbosch, South Africa: Department of Electrical & Electronic Engineering, University of Stellenbosch.
- ^ Meelis Kull, Miquel Perelló‑Nieto, Markus Kängsepp, Telmo Silva Filho, Hao Song, Peter A. Flach (28 October 2019). "Beyond temperature scaling: Obtaining well-calibrated multiclass probabilities with Dirichlet calibration". arXiv:1910.12656
- ^ The tangent matrices are not unique: if
\mathbf Thas orthonormal columns and\mathbf Qis an orthogonal matrix, then\mathbf{TQ}also has orthonormal columns that span the same subspace; it is easy to verify that\left|\operatorname{det}(\mathbf{T_y}'\mathbf{F_xT_x})\right|is invariant to such transformations of the tangent representatives. - ^ With PyTorch:
from torch.linalg import qr from torch.func import jacrev def logRf(pi, m, f, x): y = f(x) Fx, PI = jacrev(f)(x), jacrev(pi) Tx, Ty = [qr(PI(z)).Q[:,:m] for z in (x,y)] return (Ty.T @ Fx @ Tx).slogdet().logabsdet - ^ Boulerice, Bernard & Ducharme, Gilles R. (1994). "Decentered Directional Data". Annals of the Institute of Statistical Mathematics. 46 (3): 573–586. doi:10.1007/BF00773518
- ^ Tyler, David E (1987). "Statistical analysis for the angular central Gaussian distribution on the sphere". Biometrika. 74 (3): 579–589. doi:10.2307/2336697. JSTOR 2336697
- ^ Helminger, Leonhard; Djelouah, Abdelaziz; Gross, Markus; Schroers, Christopher (2020). "Lossy Image Compression with Normalizing Flows". arXiv:2008.10486
- ^ Nalisnick, Eric; Matsukawa, Teh; Zhao, Yee Whye; Song, Zhao (2018). "Do Deep Generative Models Know What They Don't Know?". arXiv:1810.09136v3
- ^ Nalisnick, Eric; Matsukawa, Teh; Zhao, Yee Whye; Song, Zhao (2019). "Detecting Out-of-Distribution Inputs to Deep Generative Models Using Typicality". arXiv:1906.02994
- ^ Zhang, Lily; Goldstein, Mark; Ranganath, Rajesh (2021). "Understanding Failures in Out-of-Distribution Detection with Deep Generative Models". Proceedings of Machine Learning Research. 139: 12427–12436. PMC 9295254. PMID 35860036
- ^ Caterini, Anthony L. & Loaiza-Ganem, Gabriel (2022). "Entropic Issues in Likelihood-Based OOD Detection". pp. 21–26. arXiv:2109.10794
- ^ Behrmann, Jens; Vicol, Paul; Wang, Kuan-Chieh; Grosse, Roger; Jacobsen, Jörn-Henrik (2020). "Understanding and Mitigating Exploding Inverses in Invertible Neural Networks". arXiv:2006.09347
- ^ Ping, Wei; Peng, Kainan; Gorur, Dilan; Lakshminarayanan, Balaji (2019). "WaveFlow: A Compact Flow-based Model for Raw Audio". arXiv:1912.01219
- ^ Shi, Chence; Xu, Minkai; Zhu, Zhaocheng; Zhang, Weinan; Zhang, Ming; Tang, Jian (2020). "GraphAF: A Flow-based Autoregressive Model for Molecular Graph Generation". arXiv:2001.09382
- ^ Yang, Guandao; Huang, Xun; Hao, Zekun; Liu, Ming-Yu; Belongie, Serge; Hariharan, Bharath (2019). "PointFlow: 3D Point Cloud Generation with Continuous Normalizing Flows". arXiv:1906.12320
- ^ Kumar, Manoj; Babaeizadeh, Mohammad; Erhan, Dumitru; Finn, Chelsea; Levine, Sergey; Dinh, Laurent; Kingma, Durk (2019). "VideoFlow: A Conditional Flow-Based Model for Stochastic Video Generation". arXiv:1903.01434
- ^ Rudolph, Marco; Wandt, Bastian; Rosenhahn, Bodo (2021). "Same Same But DifferNet: Semi-Supervised Defect Detection with Normalizing Flows". arXiv:2008.12577