Flowification: Everything is a Normalizing Flow
Anonymous Author(s)
AffiliationAddress email
Abstract
We develop a method that can be used to turn any multi-layer perceptron or convolutional network into a normalizing flow.
In some cases this requires the additionof uncorrelated noise to the model but in the simplest case no additional parameters.
The techniques we develop can be applied to a broad range of transformations. Converting standard models to normalizing flows allows the same architectures tobe used for a wide range of tasks.
Our models also allow existing density estimationtechniques to be combined with high performance feature extractors and for theexact likelihood to be calculated.
In contrast to standard density estimation techniques that require specific architectures and specialized knowledge, our approachcan leverage design knowledge from other domains and is a step closer to therealization of general purpose architectures.
We investigate the efficacy of linearand convolutional layers for the task of density estimation on standard datasets.
Ourresults suggest standard layers lack something fundamental that other normalizingflows do not.
Introduction
Density estimation techniques have proven effective on a wide variety of downstream tasks suchas sample generation and anomaly detection [1–6].
Normalizing flows and autoregressive modelsperform very well at density estimation but do not easily scale to large dimensions [2, 7, 8] and have tosatisfy strict design constraints to ensure efficient computation of their Jacobian and inverse.
Advancesin other areas of machine learning cannot be utilized as flow architectures because they are nottypically seen as being invertible, this restricts the application of highly optimized architectures frommany domains to density estimation and the use of the likelihood for diagnosing these architectures.
Methods using standard convolutions and residual layers for density estimation have been developedfor architectures with specific properties [9–12].
These methods do not provide a recipe for convertinggeneral architectures into flows.
There is no known correspondence between normalizing flows andthe operations defined by linear and convolutional layers.
In this paper we show that a large proportion of machine learning models can be trained as normalizingflows.
The forward pass of these models remains unchanged up to the addition of uncorrelated noise.
To demonstrate our formulation works we consider fully connected layers, convolutions and residualconnections as examples.
The code used for these experiments will be made publicly available.
The contributions of this paper include:
• In §3.1 we show that linear layers induce densities as augmented normalizing flows [13]with the multi-scale architecture used in RealNVPs [3].
We also show how these layers can be viewed as funnels [14] to increase their expressivity.
We term this process flowification .
• In §3.2 we argue that most ML architectures can be decomposed into simple buildingblocks that are easy to flowify.
As an example, we work out the details for 2-dimensionalconvolutional layers and residual blocks.• In §4 we flowify convolutional networks and train them as normalizing flows using thelikelihood.
This demonstrates that models built from standard layers can be used for densityestimation directly.
Background
Flows A complex probability distribution { p ( x ) | x ∈ X } can be constructed from a simple basedensity 1 { p ( z ) | z ∈ Z } and a diffeomorphism between X and Z , f : X → Z .
The likelihood ofany given x is then given by p ( x ) = p ( f ( x )) | det ( J fx ) | , where J fx is the Jacobian of f evaluatedat x .
Thus, the log-likelihoods of the two densities are related by an additive term, which will bereferred to as the likelihood contribution V ( x, z ) [15].
Normalizing flows [1] chain many invertiblemaps that are tuned to maximize the (log-)likelihood of the data.
A lot of development has gone intoconstructing flexible invertible layers with easy to calculate Jacobians where both the forward andinverse passes are fast to compute [2–4, 16, 17].
As the function f must be invertible it is required to preserve the dimension of the data.
This limitsthe expressivity of f and makes it expensive to model high dimensional data distributions.
To reducethese issues several works have studied dimension altering variants of flows [13, 15, 18–21].
Reducing the dimensionality A simple method for altering the dimension of a flow is totake the output of an intermediate layer z ′ and split it into two pieces z ′
= { z ′ 1 , z ′ 2 } .
Multiscale architectures [3] match one of these pieces directly to the base density and apply furthertransformations to the other.
Funnels [14] model z ′ 2 as being dependent on z ′ 1 and work withp ( z ′ )
=
p ( f ′ ( z ′ 1 )) p ( z ′ 2 | f ′ ( z 1 ))
| det J f ′ z ′ 1 | where f ′ can be any computational graph for which thelikelihood contribution can be calculated.
The conditional distribution can be a trainable densityand z ′ 1 is modelled with additional layers.
It is useful to think of this factorization as a dimensionreducing mechanism from dim( z ′ ) to dim( z ′ 1 ) .
Increasing the dimensionality Dimension increasing flow layers can improve a models flexibility,as demonstrated by augmented normalizing flows [13].
To increase the dimensionality, x is embeddedinto a larger dimensional space and data independent noise u is added to the embedding to obtain adistribution with support of nonzero measure.
This noise addition is similar to dequantization [3, 22],but is orthogonal to the distribution of x and increases its dimension.
It is important to note thatthe augmentation x
(cid:55)→ ( x, u ) increases the dimension from dim x to dim x + dim u .
Under anaugmentation the likelihood of x can be estimated using
[Equation]
[Equation]
In practice, we estimate this expectation value by sampling u everytime we pass a datapoint throughthe network.
This means the integral is estimated with a single monte carlo sample as in surVAEs [15].
Flowification
Suppose F is a network architecture with parameter space Θ .
Then for any choice of θ ∈ Θ thenetwork with parameters θ realizes a function F θ : R D → R C for some D and C .
Similarly, anormalizing flow model P is a parametric distribution on some R A and for any choice of γ from theirparameter space Γ they define a density function P γ on R A .
In this work we show that a large classof neural network architectures F can be thought of as a flow model by constructing a map
[Equation]
architectures [Equation] This embedding of F θ to its flowification F P θ ′ :
R D + N → R D + N and a base distribution define adensity on R D for some N ≥ 0 .
In the simplest case θ ′ =
θ . For every θ the expectation value of theforward pass of any layer of P coincides with the output of the same layer of F P θ for all input vectors.
It is in this sense that we claim that a large fraction of machine learning models are normalizingflows.
Terminology In what follows we will work with conditional distributions such as p ( z | x ) and it willbe practical to think of them as "stochastic functions" p : x (cid:55)→ z , that take an input x and producean output z ∼ p ( z | x ) .
Conversely, we can think of a function f : x (cid:55)→ z as the Dirac δ -distributionf
( z | x ) =
δ ( z − f ( x )) .
These definitions allow us to have a unified notation for deterministic and"stochastic functions" and we can talk about them in the same language.
Consequently, when we say"stochastic function", it will include deterministic functions as a corner case.
Depending on if f andf − 1 are deterministic or stochastic, we can talk about left, right or two-sided inverses.
We will becareful to always be precise about this.
We recommend [15] for a more detailed discussion on thistopic.
Method In the following we consider the standard building blocks of machine learning architecturesand enrich them by defining (stochastic-)inverse functions and calculating the likelihood contributionof each layer.
Treating each layer separately allows density estimation models to be built throughcomposition [15].
This stochastic inverse can use the funnel approach, in which case additionalparameters are required to model the inverse, or the multi-scale approach, in which case no additionalparameters are required.
For simplicity we will only consider conditional densities in the inverseas this is more general, but it is not necessary for the definitions to be correct.
We will refer tothis process as flowification and the enriched layers as flowified , non-flowified layers will be calledstandard layers .
Flowified layers can then be seen as a being simultaneously
• Flow layers that are invertible, their likelihood contribution is known and therefore can beused to train the model to maximize the likelihood.
• Standard layers that can be trained with losses other than the likelihood, but for which the
likelihood can be calculated after this training with fixed weights in the forward direction.
3.1 Linear Layers
Let L W,b : R n → R m denote the the linear layer of a neural network with parameters defined by aweight matrix W ∈ R m × n and bias b ∈ R m .
Formally, L W,b is defined as the affine function
[Equation]
[Equation]
Definition 1.
Let ϕ ( z | x ) : R n → R m be a stochastic function.
We say that ϕ is linear in expectationif there exists W ∈ R m × n and b ∈ R m such that for any x ∈ R n the expected value of ϕ coincideswith the application of L W,b
[Equation]
Similarly, we say that a stochastic function ψ ( z | x ) is convolutional in expectation if the expectation 109 E z ∼ ψ ( z | x ) [ z ] is given by a convolutional layer.
In this section we flowify linear layers, by which we mean we construct of a pair of stochasticfunctions, a forward L ( z | x ) : R n → R m and an inverse L − 1 ( x | z ) : R m → R n such that the forwardis linear in expectation and is compatible with the inverse in a way that will be made precise in thefollowing paragraphs.
Note that the inverse need not be conditioned on z and therefore does notnecessarily increase the number of parameters in the model.
SVD parametrization
To build a flowified linear layer, the first step is to parametrize the weight matrices by the singularvalue decomposition (SVD).
This involves writing W ∈ R m × n as a product W =
V Σ U , where
U ∈ R n × n is orthogonal, Σ ∈ R m × n is diagonal and V ∈
R m × m is orthogonal.
This parametrizationis particularly useful for our purposes because the orthogonal transformations are easily invertibleand don’t contribute to the likelihood and the non-invertible piece of the transformation is localizedto Σ .
Parametrizing U and V
We generate elements of the special orthogonal group SO ( d ) by applyingthe matrix-exponential to elements of the Lie algebra so ( d ) of skew-symmetric matrices.
Weparametrize so ( d ) and perform gradient descent there.
As the Lie-algebra is a vector space, this issignificantly easier than working directly with SO ( d ) .
See Appendix B for details.
Parametrizing Σ
The matrix Σ is of shape m × n containing the singular values on the maindiagonal.
We ensure maximal rank of Σ , by parameterizing the logarithm of the main diagonal, thisway all singular values are greater than 0.
It is important to note that this parametrization is not without loss of generality.
In particular,it does not include matrices of non-maximal rank nor orientation reversing ones, where either
U ∈ O ( n ) \ SO ( n ) or
V ∈ O ( m ) \ SO ( m ) .
This implementation detail does not change thegeneral perspective we provide of linear layers as normalizing flows, and instead simplifies theimplementation of flowified layers.
Decreasing the dimension
Definition 2.
We call the tuple ( L ( z | x ) , L − 1 ( x | z ))
a dimension decreasing flowified linear layer if
L is dimension decreasing, linear in expectation and the following conditions are satisfied
(i)
The forward is deterministic, given by L ( z | x ) =
L W,b ( x ) .
(ii)
The network is right-invertible, L ◦ L − 1 = id z .(iii)
The likelihood contribution of L can be exactly computed.
To flowify dimension decreasing linear layers, we define the forward function L as a standard linearlayer with parameters W and b ,
[Equation]
Since W is parametrized by the SVD decomposition, W = V Σ U , we need to invert V, U and Σseparately.
As V and U are rotations, they are inverible in the usual sense.
To construct a stochasticinverse to Σ , we think of it as a funnel[14] and use a neural network p inv (( Ux ) ( m :) | Σ
Ux ) thatmodels the dropped n − m coordinates as a function of the non-dropped m coordinates.
Again, thisis not required to calculate the likelihood under the model, even a fixed distribution could be used,but introducing some trainable parameters significantly improves the performance of the flow thatis defined by the layer.
We use Σ − 1 to denote this stochastic inverse to Σ .
The stochastic inversefunction L − 1 can then be written as
[Equation]
Since the rotations don’t contribute to the log-likelihood, the likelihood of data under a dimensiondecreasing flowified linear layer is
[Equation]
Augment
Augment
SVD SVD (1a) Mutli-scale flow with a base density p ( z, z ′ 2 ) . Augment
Augment
SVD SVD a where log Σ denotes the sum of the logarithms of the diagonal elements of Σ .
Theorem 3.
The above choices for L and L − 1 define a dimension decreasing flowified linear layer.
Sketch of proof.
The definition of the forward pass (5) makes the forward pass linear in expectationand satisfies (i) by definition.
Unpacking the definitions and decomposing W into its SVD formyields right-invertibility (ii) which in turn implies that the likelihood contribution can be exactlycomputed (iii).
When the inverse density is not made to be conditional the above ideas can be visualized as a standardmulti-scale flow architecture [3] as shown in Fig. 1b.
Increasing the dimension
Definition 4.
We define the Moore-Penrose pseudoinverse L + W,b of a linear layer L W,b : R n → R mas the affine transformation R m → R n
[Equation]
where W + denotes the Moore-Penrose pseudoinverse of the matrix W .
Definition 5.
We call the tuple ( L ( z | x ) , L − 1 ( x | z ))
a dimension increasing flowified linear layer if
L is dimension increasing, linear in expectation and the following conditions are satisfied
(iv) The inverse L − 1 is deterministic, given by L − 1 ( x | z )
=
L + W,b ( z ) .
(v) The network is left-invertible, L − 1 ◦ L
= id x
(vi) The likelihood contribution of L can be bounded from below.
To construct dimension increasing flowified linear layers, we rely again on the SVD parametrizationwhere the only nontrivial component is Σ .
In this case Σ is a dimension increasing operation and wethink of it as an augmentation step [13] composed with diagonal scaling.
To augment, we samplem − n coordinates from a distribution U with zero mean and then apply a scaling in m dimensions.
The likelihood contribution is then given by
[Equation]
where log Σ denotes the sum of the logarithms of the m scaling parameters.
The inverse function
L − 1 is the composition of the inverse rotations, the inverse scaling and the dropping of the sampledcoordinates.
Theorem 6.
The above choices for L and L − 1 define a dimension increasing flowified linear layer.
Sketch of proof.
The augmentation step [13] results in a lower bound on the likelihood contribution,implying (vi).
Since E u ∼ U = 0 , the augmentation does not influence the expected value of z , i.e. theforward pass is linear in expectation.
Simple calculations using the SVD decomposition then implyboth (iv) and (v).
Preserving the dimension
Dimension preserving layers are a corner case of both of the above scenarios, where padding andsampling are not needed in either direction and the layer is non-stochastically invertible.
All thisimplies (i),(ii),(iii),(iv) and (v).
3.2 Convolutional layers
Convolutions can be seen as a dimension increasing coordinate repetition followed by a matrixmultiplication with weight sharing.
In the previous section we worked out the details of matrixmultiplication.
We begin this section with the details of coordinate repetition after which we put thepieces together to build a flowified convolutional layer.
In Appendix D we describe an alternativeapproach relying on the Fourier transform.
Repeating coordinates In this paragraph we focus on the N -fold repetition of a single scalarcoordinate x .
This significantly simplifies notation, but the technique generalizes in an obvious way.
Intuitively, the idea is to expand the one dimensional volume to N dimensions by first embeddingand then increasing the volume of the embedding such that we have control over the volume in the N − 1 directions complementary to the embedding.
We have seen in §2 that the operation
[Equation]
has likelihood contribution E u [ − log p ( u )] .
Now, we can apply any N -dimensional rotation R Nwhich maps (1 , 0 ) to 1 √ N (1 , 1 ) to obtain
[Equation]
Note that this rotation does not contribute to the likelihood.
Finally, we apply a diagonal scaling in Ndimensions with factor √ N such that
[Equation]
12) where the final scaling has likelihood contribution N log( √ N ) =
( N/ 2) log N and x is now repeated
N times.
The overall contribution to the likelihood of the embedding (12) is
[Equation]
By construction, the padding distribution R N (0 , √ N u ) is orthogonal to the diagonal embeddingx
[Equation]
( x, ..., x ) of the data distribution.
The inverse function is given by the projection to the diagonalembedding,
[Equation]
General architectures Now that the likelihood contribution of arbitrary linear layers and coordinaterepetition has been computed it is possible to flowify more general architectures such as convolutionsand residual connections.
It is important to add that just because an architecture works well for certaintasks, it is not clear if it’s flowified version will perform well at density estimation.
Decomposing convolutional layers To flowify convolutional layers, we decompose it as a sequenceof building blocks that are easy to flowify separately.
A standard convolutional layer performs thefollowing sequence of steps:
Padding of the input image with zeros to increase it’s size.
Unfolding of the padded image into tiles.
This step replicates the data according to the
kernel size and stride.3.
Applying a linear layer.
Finally, we apply the same linear layer to each of the tiles produced
in the previous step.
The outputs then correspond to the pixels of the output image.
Flowification Steps 1 and 3 are already flowified, i.e. their likelihood contribution is computed and an inverse is constructed, in §3.1.
We denote their flowification with Pad and Linear , respectively.
Step 2 fits into the discussion of the previous paragraph of repeating coordinates, where both its inverse (14) and its likelihood contribution (13) are given.
We will denote this operation by Unfold .
Definition 7.
Let Linear , Unfold and Pad be as above and define C and C − 1 be the following stochastic functions
[Equation]
call the resulting layer ( C , C − 1 ) a flowified convolutional layer .
Augment
SVD SVD
A flowified convolutional layer ( C , C − 1 ) is then convolutional in expectation (Definition 1), i.e. thereexists a convolutional layer C θ with parameters θ such that
[Equation]
[Equation]
The flowification of a convolution without padding can be seen in Fig.
The Unfold operation isimplemented as coordinate duplication and Linear is a flowified linear layer parameterized by the
SVD.
Activation functions Functions that are surjective onto R and invertible fit well in our frameworkas they can be used out of the box without any modifications.
In our experiments we use LeakyReLUand rational-quadratic splines [4] as activations functions.
Non-invertible activations can also be usedwhen equipped with additional densities [15].
Residual connections Residual connections can be seen as coordinate duplication followed by twoseparate computational graphs { f 1 , f 2 } that are the recombined with a sum.
The sum can be invertedby defining a density over one of the summands p ( f 1 ( x + u ) | f 1 ( x + u ) , f 2 ( x 2 )) and sampling fromthis density, which will also define the likelihood contribution.
Then if the likelihood contributioncan be calculated for each individual computational graph the likelihood of the total operation can becalculated [15].
Experiments
In this section we flowify convolutional architectures and train them to maximize the likelihoodof image data.
We use the MNIST [23] and CIFAR10 [24] datasets in our experiments with thestandard training and test splits.
The data is uniformly dequantized as required to train on imagedata [25, 26].
The network for both datasets consists of convolutional layers followed by dense layers.
The exact architectures can be found in Appendix C. The flowified layers sample from U ( − a/ 2 , a/ 2)for dimension increasing operations where a is a per-layer trainable parameter.
We use RQ-splines [4]with 8 knots and a tail bound of 2 as activation functions, where the same function is applied peroutput node.
Importantly, we don’t use existing flow layers in the forward pass of our layers, nor anydata-dependent operations such as couplings unless we explicitly say so.
The results of the density modelling can be seen in Table.
The samples in the left column of Fig.
3are generated by sampling from a standard gaussian in the latent space and taking the expected outputof the inverse in every layer.
The images in the right column use the same latent samples as the leftcolumn but also sample from the distribution defined by the inverse pass of the layers.
To minimize the number of augmentation steps that occur in each model we define architectures withsimilar numbers of parameters but with non-overlapping kernels in the convolutional layers.
As seen [Table]
in Table. 1 these models perform significantly better.
This suggests that the augmentation step costsmore in terms of likelihood than it provides in terms of increased expressivity. The samples from thismodel are shown in Fig. and are slightly improved in terms of visual quality which is a reflection oftheir improved modelling of the density.
Related Work
Several works have developed methods that allow standard layers to be made invertible, but theseapproaches restrict the space of the models, whereas we consider networks in their full generality.
Invertible ResNets [9, 10] require that each residual block has a Lipschitz constant less than one, buteven with this restriction they attain competitive results on both classification and density estimation.
The same Lipschitz constraint can also be applied to other networks [11].
In these architectures themulti-scale architecture used in RealNVPs [3] is not leveraged, and so no information is discardedby the model.
It is unclear why this approach outperforms flowified layers, as shown in Table.
1,but it could be due to the preservation of information through the model, the very large number of parameters that are used in these approaches, the restricted subspace of the models, or somecombination of these three.
It can also be shown that convolutions with the same number of input and output channels can be madeinvertible [12].
These layers perform poorly at the task of density estimation and are outperformedby flowified layers.
This is likely due to the increased expressivity that comes from consideringa larger space of architectures.
There have been several works that develop convolution inspiredinvertible transformations [27–29], but these architectures consider restricted transformations tomaintain invertibility.
Future Work and Conlusion
Our experiments suggest that flowified convolutional networks do not match the density estimationperformance of similarly sized normalizing flows.
A possible explanation is that the dimensionreducing steps discard information that is still structured and more expressive layers are necessaryto transform the distributions before reducing the dimensionality.
Possibly the main limitation isthe fact that unlike flow layers the forward passes of standard linear and convolutional layers arenot data-dependent.
This is reinforced by the fact that the entanglement capability typically used inflows also appears in attention mechanisms, which have been shown to excel at capturing complexstatistical structures [30–32].
With further development – such as increased capacity given to the inverse density, or data dependentparameters in the forward pass – standard architectures could become good density estimators intheir own right and allow for general purpose models to be developed.
The focus of this work wason using standard layers for density estimation, but it is possible that designing data dependentvariants of standard layers that are more flow-like could improve their performance on tasks suchas classification and regression.
The flowification procedure provides a useful means for designingsuch models, and demonstrates that standard architectures can be considered a subset of normalizingflows, a correspondence that has not previously been demonstrated.
Checklist
For all authors...
(a) Do the main claims made in the abstract and introduction accurately reflect the paper’s contributions and scope? [Yes] (b) Did you describe the limitations of your work?
{+[Yes] See 
 (c) Did you discuss any potential negative societal impacts+} of your work? [N/A] (d) Have you read the ethics review guidelines and ensured that your paper conforms to
them? [Yes] If you are including theoretical results... (a) Did you state the full set of assumptions of all theoretical results?
{+[Yes] See 
 (b) Did you include complete proofs of all theoretical results? [No] We provided sketches of+} the proof, and as the results we present depend on well known results we think
further details are unnecessary and don’t help with the clarity of the paper. If you ran experiments... (a) Did you include the code, data, and instructions needed to reproduce the main exper-
imental results (either in the supplemental material or as a URL)? [Yes] The script used to run the experiments has been included and the instructions can be found
in the code.
(b) Did you specify all the training details (e g., data splits, hyperparameters,
how they were chosen)?
[Yes]
(c) Did you report error bars (e.g., with respect to the random seed after running exper- iments multiple times)? [No] This is not typically done on the benchmarks weconsidered.
(d) Did you include the total amount of compute and the type of resources used (e.g., typeof GPUs, internal cluster, or cloud provider)?
[Yes] See A.
If you are using existing assets (e g., code, data, models) or curating/releasing new assets...
(a) If your work uses existing assets, did you cite the creators?
[Yes] See A.
(b) Did you mention the license of the assets? [Yes] See A.
(c) Did you include any new assets either in the supplemental material or as a URL? [No] The tools we develop are contained in the paper, the code is included but is not
a new library that
should be widely adopted (d) Did you discuss whether and how consent was obtained from
people whose data you’re  using/curating? [N/A] (e) Did you discuss whether the data you are using/curating contains personally identifiable
information or offensive content?
[N/A]
If you used crowdsourcing or conducted research with human subjects... (a) Did you include the full text of instructions given to participants and screenshots, if applicable?
[N/A](b) Did you describe any potential participant risks, with links to Institutional Review Board (IRB) approvals, if applicable? [N/A]
(c) Did you include the estimated hourly wage paid to participants and the total amount
spent on participant compensation?
[N/A]
A
Flowification + NSF
Below are samples from an architecture combining flowified standard layers and NSF layers.
[Figure]
Experimental details
The models on CIFAR- 10 were trained for 600 epochs with a batch size of 256 and lasted 16-20hours.
The models on MNIST were trained for 200 epochs with the same batch size and lastedapproximately 2 hours.
Everything was implemented in PyTorch [33] and executed on a RTX 3090 GPU.
We also used weights and biases for experiment tracking [34] and the neural spline flows [35] packagefor the rational quadratic activation functions.
Both of these tools are available under an MIT license.
B Parametrizing rotations via the Lie algebra so ( d )
The Lie algebra so ( d ) of the rotation group SO ( d ) is the space of d × d skew-symmetric matrices [Equation]
Moreover, since SO ( d ) is connected and compact, the (matrix-)exponential map so ( d ) → SO ( d ) issurjective [36, Corollary 11.10], i.e. every rotation U ∈ SO
( d ) can be written as the exponential ofsome skew-symmetric X ∈ so ( d ) .
Motivated by this result, we propose to parametrize the Lie algebra so ( d ) , and use the exponentialmap to obtain rotations. Since the exponential map is differentiable, we can propagate gradients allthe way back to the Lie algebra and do gradient based optimization there.
Note that is significantly eases the optimization process. The reason for this is that the Lie group ofunitary transformations has non-trivial geometry and doing gradient descent is cumbersome on suchspaces.
On the other hand, the Lie algebra is a vector space, where gradient descent can shine.
Since PyTorch [33] has built-in support for the matrix exponential, random orthogonal transformationscan be generated with just a few lines of Python code:1 d
=# size of matrix 2 x = torch.randn(d,d) # random (d,d) matrix 3 S = x - x.T() # S is skew -symmetric 4 U = torch.matrix_exp(S) # U is a rotation
C Architectures
[Figure] .nn
as nn
[Figure]
flowification as ffn 3 4 model = nn.
Sequential( ffn.
Conv2D(in_c = 3, out_c = 27, kernel_size = 3, stride = 2), # ffn.ffn.
RqSpline(), ffn. Conv2D(in_c = 27, out_c = 48, kernel_size = 3, stride = 2), # ffn.
RqSpline(), ffn. Conv2D(in_c = 48, out_c = 72, kernel_size = 3, stride = 2), # ffn. RqSpline(), ffn.
Conv2D(in_c = 72, out_c = 96, kernel_size = 3, stride = 2), # ffn. RqSpline(), ffn.
Conv2D(in_c = 96, out_c = 128, kernel_size = 2, stride = 2), # ffn. RqSpline(), ffn.
Flatten(), ffn.
Linear(128, 128), ffn. RqSpline(), ffn. Linear(128, 128), ffn.
RqSpline(), ffn. Linear(128, 128), ffn. RqSpline(), ffn.
Linear(128, 128), ffn. RqSpline(), ffn. Linear(128, 128), ffn.
RqSpline(), ffn.
Linear(128, 128), ffn. RqSpline(), )
[Figure]
[Figure] = nn
[Figure]
( ffn.
Conv2D(in_c = 1, out_c = 4, kernel_size = 3, stride = 2), # ffn.
RqSpline(), ffn.
Conv2D(in_c = 4, out_c = 8, kernel_size = 3, stride = 2), # ffn.
RqSpline(), ffn.
Conv2D(in_c = 8, out_c = 12, kernel_size = 3, stride = 2), # ffn.
RqSpline(), ffn.
Flatten(), ffn.
Linear(108, 64), ffn.
Linear(64, 32), ffn.
Linear(32, 16), ffn.
Linear(16, 8), )
D Flowifying convolutions through the FFT
An alternative way of flowifing convolutional layers is through the convolution theorem which statesthat the Fourier-transformation diagonalizes convolutions.
In this section we sketch the idea anddiscuss the issues with it.
Fig.9 displays the Pytorch code for performing convolutions through the convolution theorem.
Line12 of the code shows that in the Fourier basis, we can perform convolution as follows; at eachfrequency we form the vector of dimension (# of in_channels) and apply a weight matrix of size (# ofin_channels) ×
(# of out_channels) to it.
If this weight matrix is parametrized by the SVD, we can guarantee its invertibility.
Since the FFT is also invertible, this construction should be a flowificationof the convolutional layer if we can also solve the following two issues:
If the weight matrix is parametrized in frequency domain,
(1) it’s inverse transform might not be real.
(2) it’s inverse transform might not be of the appropriate size (i
e. nonzero outside of the first (kernel_size)-many pixels).
The first of these is easy to solve with the symmetric parametrization induced by [Equation] where N is the length of the signal.
To deal with the second condition, a auxiliary loss term isintroduced that minimizes the terms that should be 0 .
Although the idea of FFT seems promising,this approach turns out be slower (probably due to the FFT), worse performing and more cumbersomethan the flowificaton presented in §3.2.
Fig.
10 shows some samples from a Fourier-flowifiedconvolutional network trained on MNIST.
{+in_channels , out_channels = 4, signal_length , kernel_size = 32, batch_size =
+}
K = torch.randn(out_channels , in_channels , kernel_size) x = torch.randn(batch_size , in_channels , signal_length) z1 = torch.nn.functional.conv1d(input=x, weight=K) 8x_ = torch.fft.fft(x, norm=’ortho’)
# pad kernel to match the length of x
K_ = torch.fft.fft(K.flip(-1), n=x.size()[-1], norm=’ortho’)
z_
= torch.einsum(’bix ,jix ->bjx’, (x_, K_))
z2 = torch.fft.ifft(z_, norm=’forward’)
{+z2 = z
+}
[:, :, (kernel_size -1):] 15print((z1-z2).abs().max().item())
# tensor (2.8610e-06)