Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

NLL training of a Gaussianization flow

The rotation and marginal blocks of RBIG, fitted together by maximum likelihood instead of one at a time

00 · NLL training of a Gaussianization flow

Open In Colab

Part 3 fitted RBIG greedily: each layer was fitted once, to the data as the layers before it left them, and never revisited. A parametric Gaussianization flow uses the same architecture, a stack of marginal maps and rotations, but treats the parameters θ\theta of every block as free and fits them all together by maximum likelihood, the recipe that defines normalizing flows Papamakarios et al., 2021. The objective is the mean negative log-likelihood (1), with the density of a deep flow (5) in place of the one-dimensional one.

Python implementation: CPython
Python version       : 3.13.12
IPython version      : 9.12.0

jax               : 0.12.1
numpy             : 2.4.3
optax             : 0.2.8
flowjax           : 19.1.0
pipekit_train     : 0.3.4
gauss_flows_models: 0.3.1

Compiler    : Clang 21.1.4 
OS          : Linux
Release     : 6.8.0-1044-azure
Machine     : x86_64
Processor   : x86_64
CPU cores   : 16
Architecture: 64bit

The notebook runs in float32, the precision users get by default. Float64 would suit the log-determinants, but fit_rbig in section 3 cannot run with it turned on today, a bug in gauss_flows (gauss_flows#247).

The data are N=4000N = 4000 points of two moons with noise of standard deviation 0.08, standardised per coordinate and split into Nt=3000N_t = 3000 training rows and Nv=1000N_v = 1000 held-out rows.

1. The objective, term by term

gaussianization_flow builds the stack of Part 3 with trainable blocks: K=8K = 8 layers, each a Gaussian-mixture CDF marginal map (2) followed by a Householder rotation (2), and a base distribution. We build one and look at what it holds.

bijection: Invert(Scan(...))
one layer: ['MixtureGaussianCDF', 'HouseholderRotation']
base distribution: Normal
trainable numbers: 420

The eight layers are stored once, stacked along a leading axis, and run by FlowJax’s Scan; Invert makes the data-to-latent direction z=fθ(x)\vect{z} = f_\theta(\vect{x}) the one log_prob uses. With a standard-normal base, log⁡pz(z)=−12∥z∥2−Dx2log⁡2π\log p_z(\vect{z}) = -\frac{1}{2} \Vert \vect{z} \Vert^2 - \frac{D_x}{2} \log 2\pi, so the objective splits into two terms,

L(θ)=1N∑n=1N(12∥fθ(xn)∥2+Dx2log⁡2π)−1N∑n=1Nlog⁡∣det⁡Jfθ(xn)∣\mathcal{L}(\theta) = \frac{1}{N} \sum_{n=1}^{N} \left( \frac{1}{2} \Vert f_\theta(\vect{x}_n) \Vert^2 + \frac{D_x}{2} \log 2\pi \right) - \frac{1}{N} \sum_{n=1}^{N} \log \vert \det \mat{J}_{f_\theta}(\vect{x}_n) \vert

where the first sum is the base term, small when the data land near the origin of the latent, and the second is the log-determinant term, which rewards a map that spreads the data out. We compute both for the untrained flow and check that they add up to log_prob.

mean log p_z(z)        : -1.852
mean log |det J|       : -14.402
largest |sum - log_prob|: 0.0e+00
initial NLL            : 16.254

The two terms add up to log_prob exactly, so (1) is the loss the optimiser sees. The untrained flow pays mostly through its log-determinant: its random mixtures squeeze the data, and the log-determinant term charges 14.4 nats per point for it.

Why both terms are needed shows on the simplest map there is, a scaling fκ(x)=κxf_\kappa(\vect{x}) = \kappa \vect{x} with κ>0\kappa > 0, whose Jacobian is κI\kappa \mat{I}. On it the objective is

L(κ)=κ22N∑n=1N∥xn∥2+Dx2log⁡2π−Dxlog⁡κ\mathcal{L}(\kappa) = \frac{\kappa^2}{2N} \sum_{n=1}^{N} \Vert \vect{x}_n \Vert^2 + \frac{D_x}{2} \log 2\pi - D_x \log \kappa

The base term alone is smallest at κ=0\kappa = 0, which maps every point to the origin. The log-determinant term, −Dxlog⁡κ-D_x \log \kappa, grows without bound as κ→0\kappa \to 0, and setting the derivative to zero gives κ2=NDx/∑n∥xn∥2\kappa^2 = N D_x / \sum_n \Vert \vect{x}_n \Vert^2, which is 1 for standardised data. We evaluate both terms on a range of κ\kappa.

(1/N) sum ||x_n||^2 = 2.003, best kappa = 0.999, L at best = 2.839
<Figure size 700x400 with 1 Axes>

Figure 1:The two terms of the objective on a scaling of the data by κ. The base term (blue) falls as κ shrinks the data towards the origin; the log-determinant term (orange) rises without bound, and their sum is smallest at κ = 1 for standardised data.

2. Training with pipekit-train

The flow is an Equinox module, so pipekit-train can fit it. Its task is (1) on one batch, through negative_log_likelihood.

The optimiser follows the source of this tutorial: Adam with a one-cycle cosine learning rate, which warms up to a peak of 3×10−33 \times 10^{-3} and anneals to almost zero, and the gradient clipped to a global norm of 1. We keep a copy without the clip for a check further down.

The rest of the loop is the same for every run: the training and held-out rows, the task, and 3,000 steps of 512 rows in 30 epochs of 100 steps, with one log line and one held-out evaluation per epoch.

Two small functions build a loop for a flow and run it.

We train the flow as the factory builds it.

The history holds the training loss of every step and the held-out loss of every epoch. We average the training loss per epoch.

NLL: 16.254 before training, 1.879 on training rows and 1.899 held out after, 39 s

The flow is trained, but is its latent a standard normal? We map the held-out rows and read off the mean and the variances of z\vect{z}, and the joint test of Part 3, the largest Kolmogorov–Smirnov distance KSmax⁡\mathrm{KS}_{\max} over projections (3).

KS_max of 1,000 standard-normal points, 95% quantile: 0.053
latent mean [-0.976  0.947], variances [0.302 0.339], KS_max 0.651
base location [-0.971  0.983], scale [0.547 0.585]

It is not. The latent sits around (−0.98,0.95)(-0.98, 0.95) with variances of about 0.3, far outside the null band, because the base distribution trained too. gaussianization_flow builds its base as FlowJax’s Normal, whose location μz\gvect{\mu}_z and scale σz\gvect{\sigma}_z are trainable arrays, and training moved them to the values printed above. A trainable base is an extra affine layer in disguise,

log⁡N(z;μz,diag(σz2))=log⁡N((z−μz)/σz;0,I)−∑d=1Dxlog⁡σz,d\log \mathcal{N}(\vect{z}; \gvect{\mu}_z, \mathrm{diag}(\gvect{\sigma}_z^2)) = \log \mathcal{N}((\vect{z} - \gvect{\mu}_z) / \gvect{\sigma}_z; \vect{0}, \mat{I}) - \sum_{d=1}^{D_x} \log \sigma_{z,d}

so the density of the data is as good as before, but the Gaussianized point is (z−μz)/σz(\vect{z} - \gvect{\mu}_z) / \gvect{\sigma}_z, not z\vect{z}. Anything that reads z\vect{z} as a standard normal (a test of the latent, an entropy or a total correlation read off it) is then wrong. This is a defect in gauss_flows (gauss_flows#256): the Gaussianization factories and fit_rbig should build the fixed StandardNormal. Until they do, pass base_dist=StandardNormal((2,)), which the factory accepts.

Its losses, and its latent on the held-out rows:

NLL 1.886 on training rows and 1.901 held out, 38 s
latent mean [-0.02  -0.067], variances [0.992 0.977], KS_max 0.074

The held-out likelihood is the same to the second decimal, as (3) says it must be, and now the latent itself has mean near 0\vect{0} and variances near 1. Its KSmax⁡\mathrm{KS}_{\max} is still above the null quantile: the eight layers have not finished the job at this budget.

The source of this tutorial credits the gradient clipping with keeping the early, high-learning-rate steps from diverging. We check by training the fixed-base flow again without it.

with clipping   : held-out NLL 1.901, first step loss 16.245, largest 16.281, any NaN False
without clipping: held-out NLL 1.915, first step loss 16.245, largest 16.281, any NaN False

Here clipping changes nothing that matters: in neither run does a step’s loss rise more than a few hundredths of a nat above the first step’s or turn NaN, and the two end within a few hundredths of a nat of each other. On this small, standardised problem the clip does not decide the outcome; whether it does for deeper flows or rougher data is not tested here.

<Figure size 1650x440 with 3 Axes>

Figure 2:Left: the training (solid) and held-out (dashed) negative log-likelihood per epoch for the factory’s flow and the fixed-base flow, which overlap. Centre: the one-cycle cosine learning rate. Right: held-out points mapped by each trained flow; the factory’s flow (orange) puts them off the origin with a small spread, the fixed-base flow (blue) around the origin with unit spread.

3. Iterative against parametric

The same architecture can be fitted two ways. fit_rbig fits it greedily, as in Part 3, with a PCA rotation and a mixture marginal fitted by EM per layer, in closed form and without gradients. The trained flow fits all layers together by gradient descent. We fit RBIG with the same number of layers and components on the training rows, and compare both on the training and held-out rows.

greedy RBIG : NLL 1.926 on training rows, 2.430 held out, 15 s to fit
trained flow: NLL 1.883 on training rows, 1.901 held out, 38 s to train

The source of this tutorial says the trained flow matches the greedy fit. On held-out data it does better, by about half a nat per point. On the training rows the two are close, so the greedy fit overfits: its held-out NLL is half a nat worse than its training NLL, against two hundredths for the trained flow. Both took seconds here, though timings on a shared machine vary from run to run; the greedy fit needs no gradients and no learning rate, and the trained flow needs both. The densities show the difference.

grid points where log p_x is minus infinity: greedy 156 of 14400, trained 0

In the corners of the grid the greedy fit’s log-density is −∞-\infty. That is not a real zero of the density: MixtureGaussianCDF’s log-space probit returns NaN far in a mixture’s tail, and the greedy layers push points just outside the data that far out, a bug in gauss_flows (gauss_flows#248). The figure clips the log-density at -6, so those points take the lowest colour.

<Figure size 1100x480 with 2 Axes>

Figure 3:The log-density of the greedy RBIG fit (left) and of the trained flow (right), on one colour scale clipped at −6. The greedy fit has bright ridges and spots, some off the moons, such as the diagonal ridge across the gap between them; the trained flow is smooth and follows the two moons, with some mass left in the gap.

Recap

PieceEquationIn code
the density of a deep flow(5)flow.log_prob
the objective, base and log-determinant terms(1), (1)negative_log_likelihood, bijection.inverse_and_log_det
why the log-determinant stops shrinkage(2)scale_base, scale_logdet
the factory(2), (2)gaussianization_flow, Invert(Scan(Chain([MixtureGaussianCDF, HouseholderRotation])))
a trainable base is an affine layer(3)pass base_dist=StandardNormal((2,))
training(1)pipekit-train’s TrainingLoop, Adam, one-cycle cosine schedule, clip_norm
a joint test of the latent(3)projection_ks
greedy against trained(5)fit_rbig against train_flow

Next. The greedy fit is quick and the trained flow generalises better. The next notebook combines them: it starts the trainable flow from the greedy fit and trains from there.

References
  1. Papamakarios, G., Nalisnick, E., Rezende, D. J., Mohamed, S., & Lakshminarayanan, B. (2021). Normalizing Flows for Probabilistic Modeling and Inference. Journal of Machine Learning Research, 22(57), 1–64.