# Continuous Normalizing Flows

Now, we study a single layer neural network that can estimate the density p_x of a variable of interest x by re-parameterizing a base variable z with known density p_z through the Neural Network model passed to the layer.

## Copy-Pasteable Code

Before getting to the explanation, here's some code to start with. We will follow a full explanation of the definition and training process:

using Flux, DiffEqFlux, DifferentialEquations, Optimization, OptimizationFlux,
OptimizationOptimJL, Distributions

nn = Flux.Chain(
Flux.Dense(1, 3, tanh),
Flux.Dense(3, 1, tanh),
) |> f32
tspan = (0.0f0, 1.0f0)

ffjord_mdl = FFJORD(nn, tspan, Tsit5())

# Training
data_dist = Normal(6.0f0, 0.7f0)
train_data = Float32.(rand(data_dist, 1, 100))

function loss(θ)
logpx, λ₁, λ₂ = ffjord_mdl(train_data, θ)
-mean(logpx)
end

optf = Optimization.OptimizationFunction((x, p) -> loss(x), adtype)
optprob = Optimization.OptimizationProblem(optf, ffjord_mdl.p)

res1 = Optimization.solve(optprob,
maxiters = 100)

optprob2 = Optimization.OptimizationProblem(optf, res1.u)
res2 = Optimization.solve(optprob2,
Optim.LBFGS(),
allow_f_increases=false)

# Evaluation
using Distances

actual_pdf = pdf.(data_dist, train_data)
learned_pdf = exp.(ffjord_mdl(train_data, res2.u))
train_dis = totalvariation(learned_pdf, actual_pdf) / size(train_data, 2)

# Data Generation
ffjord_dist = FFJORDDistribution(FFJORD(nn, tspan, Tsit5(); p=res2.u))
new_data = rand(ffjord_dist, 100)
1×100 Matrix{Float32}:
0.498427  1.61841  -2.48128  1.35943  …  -2.13918  -1.85586  -2.42816

## Step-by-Step Explanation

We can use DiffEqFlux.jl to define, train and output the densities computed by CNF layers. In the same way as a neural ODE, the layer takes a neural network that defines its derivative function (see  for a reference). A possible way to define a CNF layer, would be:

using Flux, DiffEqFlux, DifferentialEquations, Optimization, OptimizationFlux,
OptimizationOptimJL, Distributions

nn = Flux.Chain(
Flux.Dense(1, 3, tanh),
Flux.Dense(3, 1, tanh),
) |> f32
tspan = (0.0f0, 10.0f0)

ffjord_mdl = FFJORD(nn, tspan, Tsit5())
(::FFJORD{Chain{Tuple{Dense{typeof(tanh), Matrix{Float32}, Vector{Float32}}, Dense{typeof(tanh), Matrix{Float32}, Vector{Float32}}}}, Vector{Float32}, Nothing, Optimisers.Restructure{Chain{Tuple{Dense{typeof(tanh), Matrix{Float32}, Vector{Float32}}, Dense{typeof(tanh), Matrix{Float32}, Vector{Float32}}}}, NamedTuple{(:layers,), Tuple{Tuple{NamedTuple{(:weight, :bias, :σ), Tuple{Int64, Int64, Tuple{}}}, NamedTuple{(:weight, :bias, :σ), Tuple{Int64, Int64, Tuple{}}}}}}}, Distributions.MvNormal{Float32, PDMats.PDiagMat{Float32, Vector{Float32}}, Vector{Float32}}, Tuple{Float32, Float32}, Tuple{OrdinaryDiffEq.Tsit5{typeof(OrdinaryDiffEq.trivial_limiter!), typeof(OrdinaryDiffEq.trivial_limiter!), Static.False}}, Base.Pairs{Symbol, Union{}, Tuple{}, NamedTuple{(), Tuple{}}}}) (generic function with 1 method)

where we also pass as an input the desired timespan for which the differential equation that defines log p_x and z(t) will be solved.

### Training

First, let's get an array from a normal distribution as the training data. Note that we want the data in Float32 values to match how we have setup the neural network weights and the state space of the ODE.

data_dist = Normal(6.0f0, 0.7f0)
train_data = Float32.(rand(data_dist, 1, 100))
1×100 Matrix{Float32}:
5.84153  5.47328  5.45282  4.47089  …  7.37738  5.76655  5.65471  5.2723

Now we define a loss function that we wish to minimize

function loss(θ)
logpx, λ₁, λ₂ = ffjord_mdl(train_data, θ)
-mean(logpx)
end
loss (generic function with 1 method)

In this example, we wish to choose the parameters of the network such that the likelihood of the re-parameterized variable is maximized. Other loss functions may be used depending on the application. Furthermore, the CNF layer gives the log of the density of the variable x, as one may guess from the code above.

We then train the neural network to learn the distribution of x.

Here we showcase starting the optimization with ADAM to more quickly find a minimum, and then honing in on the minimum by using LBFGS.

adtype = Optimization.AutoZygote()
optf = Optimization.OptimizationFunction((x, p) -> loss(x), adtype)
optprob = Optimization.OptimizationProblem(optf, ffjord_mdl.p)

res1 = Optimization.solve(optprob,
maxiters = 100)
u: 10-element Vector{Float32}:
0.35768273
0.6532577
-0.36470369
1.0084485
-0.5481732
-0.98420316
-0.59132
0.57647246
0.5942154
0.050896317

We then complete the training using a different optimizer starting from where ADAM stopped.

optprob2 = Optimization.OptimizationProblem(optf, res1.u)
res2 = Optimization.solve(optprob2,
Optim.LBFGS(),
allow_f_increases=false)
u: 10-element Vector{Float32}:
0.3583046
0.65137064
-0.36533615
1.008624
-0.5490396
-0.98437876
-0.59863776
0.5697303
0.6015334
0.043416973

### Evaluation

For evaluating the result, we can use totalvariation function from Distances.jl. First, we compute densities using actual distribution and FFJORD model. then we use a distance function.

using Distances

actual_pdf = pdf.(data_dist, train_data)
learned_pdf = exp.(ffjord_mdl(train_data, res2.u))
train_dis = totalvariation(learned_pdf, actual_pdf) / size(train_data, 2)
0.45398125f0

### Data Generation

What's more, we can generate new data by using FFJORD as a distribution in rand.

ffjord_dist = FFJORDDistribution(FFJORD(nn, tspan, Tsit5(); p=res2.u))
new_data = rand(ffjord_dist, 100)
1×100 Matrix{Float32}:
5.82036  5.2114  5.06331  6.00076  …  5.13125  5.61825  6.18785  4.90977

 Grathwohl, Will, Ricky TQ Chen, Jesse Bettencourt, Ilya Sutskever, and David Duvenaud. "Ffjord: Free-form continuous dynamics for scalable reversible generative models." arXiv preprint arXiv:1810.01367 (2018).