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¶
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 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.
import subprocess
import sys
try:
import google.colab # noqa: F401
IN_COLAB = True
except ImportError:
IN_COLAB = False
if IN_COLAB:
repo = "git+https://github.com/jejjohnson/gauss_flows@main"
subprocess.run(
[
sys.executable,
"-m",
"pip",
"install",
"-q",
f"gauss-flows-maps @ {repo}#subdirectory=packages/gauss-flows-maps",
f"gauss-flows-models @ {repo}#subdirectory=packages/gauss-flows-models",
f"gauss-flows-docs[notebooks] @ {repo}#subdirectory=docs",
],
check=True,
)import warnings
warnings.filterwarnings("ignore", message=r".*IProgress.*")
import time
import equinox as eqx
import jax
import jax.numpy as jnp
import jax.random as jr
import matplotlib.pyplot as plt
import numpy as np
import optax
import paramax
from flowjax.distributions import StandardNormal, Transformed
from jaxtyping import ArrayLike, Float
from pipekit_train import ArrayDataset, History, TrainingLoop
from pipekit_train.backends.equinox import EquinoxModelOp
from scipy import stats
from sklearn.datasets import make_moons
from gauss_flows_docs.environment import watermark
from gauss_flows_docs.plotting import (
SCATTER_KW,
style_ax,
use_compact_figures,
)
from gauss_flows_models.flows import gaussianization_flow
from gauss_flows_models.inference import fit_rbig, negative_log_likelihood
rng = np.random.default_rng(0)
# Figures are stored as palette PNGs to keep the notebook small.
use_compact_figures()
watermark("jax", "numpy", "optax", "flowjax", "pipekit_train", "gauss_flows_models")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 points of two moons with noise of standard deviation 0.08, standardised per coordinate and split into training rows and held-out rows.
# Shapes: sample (N) = 4,000; state (D_x) = 2; train (N_t) = 3,000; held_out (N_v) = 1,000
SampleState = Float[ArrayLike, "sample state"]
# today (scikit-learn)
# two interleaved half circles with noise of standard deviation 0.08, (sample, state)
raw: SampleState
raw, _ = make_moons(n_samples=4000, noise=0.08, random_state=0)
# x = (raw − x̄) / s, in float32, (sample, state)
samples: SampleState = ((raw - raw.mean(axis=0)) / raw.std(axis=0)).astype(np.float32)
# a random order of the rows, (sample)
order: Float[ArrayLike, " sample"] = rng.permutation(4000)
# the training rows, (train, state)
train_points: Float[ArrayLike, "train state"] = samples[order[:3000]]
# the held-out rows, (held_out, state)
held_points: Float[ArrayLike, "held_out state"] = samples[order[3000:]]1. The objective, term by term¶
gaussianization_flow builds the stack of Part 3 with trainable blocks: 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.
# today (gauss_flows)
# f_θ, 8 layers of an 8-component mixture marginal and a Householder rotation
initial_flow: Transformed = gaussianization_flow(
jr.key(0), n_dims=2, n_layers=8, n_components=8
)
# the layer stack, run in the density direction by Invert
layer_stack: eqx.Module = initial_flow.bijection.bijection
# today (equinox)
# every trainable array of the flow
trainable_arrays: list = jax.tree.leaves(eqx.filter(initial_flow, eqx.is_inexact_array))
print(
f"bijection: {type(initial_flow.bijection).__name__}({type(layer_stack).__name__}(...))"
)
print(
f"one layer: {[type(block).__name__ for block in layer_stack.bijection.bijections]}"
)
print(f"base distribution: {type(initial_flow.base_dist).__name__}")
print(f"trainable numbers: {sum(array.size for array in trainable_arrays)}")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 the one log_prob uses. With a standard-normal base, , so the objective splits into two terms,
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.
# Shapes: train (N_t) = 3,000; latent (D_x) = 2
PerTrain = Float[ArrayLike, " train"]
# today (flowjax)
# zₙ = f_θ(xₙ) and log |det J_f(xₙ)|, (train, latent), (train)
initial_latent: Float[ArrayLike, "train latent"]
initial_logdet: PerTrain
initial_latent, initial_logdet = jax.vmap(initial_flow.bijection.inverse_and_log_det)(
train_points
)
# today (flowjax)
# log p_z(zₙ), (train)
initial_base: PerTrain = jax.vmap(initial_flow.base_dist.log_prob)(initial_latent)
# today (flowjax)
# log p_x(xₙ), (train)
initial_logp: PerTrain = jax.vmap(initial_flow.log_prob)(train_points)print(f"mean log p_z(z) : {float(initial_base.mean()):+.3f}")
print(f"mean log |det J| : {float(initial_logdet.mean()):+.3f}")
print(
f"largest |sum - log_prob|: {float(jnp.abs(initial_base + initial_logdet - initial_logp).max()):.1e}"
)
print(f"initial NLL : {-float(initial_logp.mean()):.3f}")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 with , whose Jacobian is . On it the objective is
The base term alone is smallest at , which maps every point to the origin. The log-determinant term, , grows without bound as , and setting the derivative to zero gives , which is 1 for standardised data. We evaluate both terms on a range of .
# Shapes: scale = 200 values of κ
PerScale = Float[ArrayLike, " scale"]
# κ from 0.05 to 3, (scale)
scales: PerScale = np.linspace(0.05, 3.0, 200)
# (1/N) ∑ₙ ‖xₙ‖²
mean_square: float = float((train_points**2).sum(axis=1).mean())
# κ² (1/N) ∑ₙ ‖xₙ‖² / 2 + (D_x/2) log 2π, the base term, (scale)
scale_base: PerScale = 0.5 * scales**2 * mean_square + np.log(2 * np.pi)
# −D_x log κ, the log-determinant term, (scale)
scale_logdet: PerScale = -2 * np.log(scales)
# 𝓛(κ), (scale)
scale_loss: PerScale = scale_base + scale_logdet
print(
f"(1/N) sum ||x_n||^2 = {mean_square:.3f}, best kappa = {scales[np.argmin(scale_loss)]:.3f}, L at best = {scale_loss.min():.3f}"
)(1/N) sum ||x_n||^2 = 2.003, best kappa = 0.999, L at best = 2.839
fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(scales, scale_base, color="C0", lw=2, label="base term")
ax.plot(scales, scale_logdet, color="C1", lw=2, label="log-determinant term")
ax.plot(scales, scale_loss, color="k", lw=2, label="objective")
ax.axvline(1.0, color="k", ls="--", lw=1)
ax.set(xlabel="scale κ", ylabel="nats per point", ylim=(-3, 8))
ax.legend()
style_ax(ax)
plt.show()
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.
# Shapes: batch (N_b) = 512
Scalar = Float[ArrayLike, ""]
# user
# pipekit-train's task: 𝓛(θ) on one batch
class FlowNLL:
"""pipekit-train's task: the mean negative log-likelihood of a batch."""
# user
# 𝓛(θ) = −(1/N_b) ∑ₙ log p_x(xₙ; θ), also logged
def loss_fn(self, flow, batch, key):
# the points of the batch; its targets are empty, (batch, state)
batch_points: Float[ArrayLike, "batch state"]
batch_points, _ = batch
# today (gauss_flows)
# −(1/N_b) ∑ₙ log p_x(xₙ; θ)
loss: Scalar = negative_log_likelihood(flow, batch_points)
return loss, {"loss": loss}The optimiser follows the source of this tutorial: Adam with a one-cycle cosine learning rate, which warms up to a peak of 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.
# Shapes: step = 3,000 training steps
# today (optax)
# the learning rate of each step: up to 3 × 10⁻³, then down to almost zero
schedule: optax.Schedule = optax.cosine_onecycle_schedule(
transition_steps=3000, peak_value=3e-3
)
# Adam on the one-cycle rate, with the gradient clipped to a global norm of 1
clipped_adam: dict = {"name": "adam", "lr": schedule, "clip_norm": 1.0}
# the same without the clip
plain_adam: dict = {"name": "adam", "lr": schedule}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.
# Shapes: epoch = 30 epochs of 100 steps
# today (pipekit)
# the training rows, with no targets
train_data = ArrayDataset(train_points, ())
# today (pipekit)
# the held-out rows, with no targets
held_data = ArrayDataset(held_points, ())
# the settings every run shares
loop_settings: dict = {
"val_dataset": held_data,
"task": FlowNLL(),
"max_steps": 3000,
"steps_per_epoch": 100,
"eval_every_n_steps": 100,
"log_every_n_steps": 100,
"batch_size": 512,
"seed": 1,
}Two small functions build a loop for a flow and run it.
# user
# True on a paramax.NonTrainable leaf, which stays out of the optimiser
def is_frozen(leaf) -> bool:
"""Whether ``leaf`` is wrapped as non-trainable."""
return isinstance(leaf, paramax.NonTrainable)
# user
# a pipekit-train loop that fits the flow with the optimiser and logs into the history
def build_loop(flow: Transformed, optimizer: dict, history: History) -> TrainingLoop:
"""A training loop for ``flow`` with the shared settings."""
# today (equinox)
# True on each trainable array of the flow
trainable: eqx.Module = jax.tree.map(eqx.is_inexact_array, flow, is_leaf=is_frozen)
# today (pipekit)
# the flow as a trainable model with its mask
model_op = EquinoxModelOp(flow, trainable=trainable)
return TrainingLoop(
model_op,
train_data,
optimizer_config=optimizer,
callbacks=(history,),
**loop_settings,
)# user
# θ after 3,000 Adam steps on 𝓛(θ), the loss history, and the training time in seconds
def train_flow(
flow: Transformed, optimizer: dict
) -> tuple[Transformed, History, float]:
"""Train ``flow`` with ``optimizer`` and time the run."""
# today (pipekit)
# the training and held-out losses of the run
history = History()
# user
# the loop for this flow and optimiser
loop: TrainingLoop = build_loop(flow, optimizer, history)
# the clock before training
start: float = time.perf_counter()
# today (pipekit)
# θ after 3,000 steps, held by the model op
trained_op: EquinoxModelOp
trained_op, _ = loop.run()
return trained_op.module, history, time.perf_counter() - startWe train the flow as the factory builds it.
# user
# the factory's flow after training, with clipping
default_flow: Transformed
default_history: History
default_seconds: float
default_flow, default_history, default_seconds = train_flow(initial_flow, clipped_adam)The history holds the training loss of every step and the held-out loss of every epoch. We average the training loss per epoch.
PerEpoch = Float[ArrayLike, " epoch"]
# user
# the mean training loss of each epoch and the held-out loss after it, (epoch), (epoch)
def epoch_losses(history: History) -> tuple[PerEpoch, PerEpoch]:
"""Per-epoch training and held-out losses of a 3,000-step run."""
# the training loss of every step, as one row of 100 steps per epoch, (epoch, step)
step_losses: Float[ArrayLike, "epoch step"] = np.array(
[metrics["loss"] for _, metrics in history.train]
).reshape(30, 100)
# the held-out loss after each epoch, (epoch)
held_losses: PerEpoch = np.array([metrics["loss"] for _, metrics in history.eval])
return step_losses.mean(axis=1), held_losses
# user
# the factory flow's losses, (epoch), (epoch)
default_train: PerEpoch
default_held: PerEpoch
default_train, default_held = epoch_losses(default_history)
print(
f"NLL: {-float(initial_logp.mean()):.3f} before training, {default_train[-1]:.3f} on training rows and {default_held[-1]:.3f} held out after, {default_seconds:.0f} s"
)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 , and the joint test of Part 3, the largest Kolmogorov–Smirnov distance over projections (3).
# Shapes: direction (J) = 64; draw = 50
# αⱼ, 64 angles evenly spread over [0, π), (direction)
angles: Float[ArrayLike, " direction"] = np.linspace(0, np.pi, 64, endpoint=False)
# unit directions eⱼ = (cos αⱼ, sin αⱼ), (direction, state)
directions: Float[ArrayLike, "direction state"] = np.column_stack(
[np.cos(angles), np.sin(angles)]
)
# user
# KS_max = maxⱼ supₜ |F̂_{N,j}(t) − Φ(t)|
def projection_ks(points: Float[ArrayLike, "held_out latent"]) -> float:
"""The largest Kolmogorov-Smirnov distance of a projection of ``points`` to N(0, 1)."""
# eⱼᵀ zₙ, (held_out, direction)
projections: Float[ArrayLike, "held_out direction"] = (
np.asarray(points) @ directions.T
)
return max(stats.kstest(projections[:, j], "norm").statistic for j in range(64))
# user
# the 95% quantile of KS_max for 50 draws of 1,000 points from 𝒩(0, I)
null_threshold: float = np.quantile(
[projection_ks(rng.standard_normal((1000, 2))) for _ in range(50)], 0.95
)
print(f"KS_max of 1,000 standard-normal points, 95% quantile: {null_threshold:.3f}")KS_max of 1,000 standard-normal points, 95% quantile: 0.053
LatentPoints = Float[ArrayLike, "held_out latent"]
# today (flowjax)
# zₙ = f_θ(xₙ) of the trained flow for the held-out rows, (held_out, latent)
default_latent: LatentPoints = np.asarray(
jax.vmap(default_flow.bijection.inverse)(held_points)
)
# today (paramax)
# the trained base distribution, its parameters unwrapped
default_base: eqx.Module = paramax.unwrap(default_flow.base_dist)
print(
f"latent mean {np.round(default_latent.mean(axis=0), 3)}, variances {np.round(default_latent.var(axis=0), 3)}, KS_max {projection_ks(default_latent):.3f}"
)
print(
f"base location {np.round(np.asarray(default_base.loc), 3)}, scale {np.round(np.asarray(default_base.scale), 3)}"
)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 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 and scale are trainable arrays, and training moved them to the values printed above. A trainable base is an extra affine layer in disguise,
so the density of the data is as good as before, but the Gaussianized point is , not . Anything that reads 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.
# today (gauss_flows)
# f_θ with the same layers and a fixed 𝒩(0, I) base
fixed_flow_initial: Transformed = gaussianization_flow(
jr.key(0), n_dims=2, n_layers=8, n_components=8, base_dist=StandardNormal((2,))
)
# user
# the fixed-base flow after training, with clipping
fixed_flow: Transformed
fixed_history: History
fixed_seconds: float
fixed_flow, fixed_history, fixed_seconds = train_flow(fixed_flow_initial, clipped_adam)Its losses, and its latent on the held-out rows:
# user
# the fixed-base flow's losses, (epoch), (epoch)
fixed_train: PerEpoch
fixed_held: PerEpoch
fixed_train, fixed_held = epoch_losses(fixed_history)
# today (flowjax)
# zₙ = f_θ(xₙ) of the trained flow for the held-out rows, (held_out, latent)
fixed_latent: LatentPoints = np.asarray(
jax.vmap(fixed_flow.bijection.inverse)(held_points)
)
print(
f"NLL {fixed_train[-1]:.3f} on training rows and {fixed_held[-1]:.3f} held out, {fixed_seconds:.0f} s"
)
print(
f"latent mean {np.round(fixed_latent.mean(axis=0), 3)}, variances {np.round(fixed_latent.var(axis=0), 3)}, KS_max {projection_ks(fixed_latent):.3f}"
)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 and variances near 1. Its 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.
# user
# the fixed-base flow after training, without clipping
unclipped_flow: Transformed
unclipped_history: History
unclipped_seconds: float
unclipped_flow, unclipped_history, unclipped_seconds = train_flow(
fixed_flow_initial, plain_adam
)
# user
# the unclipped flow's losses, (epoch), (epoch)
unclipped_train: PerEpoch
unclipped_held: PerEpoch
unclipped_train, unclipped_held = epoch_losses(unclipped_history)
# the training loss of every step with clipping, (step)
clipped_steps: Float[ArrayLike, " step"] = np.array(
[metrics["loss"] for _, metrics in fixed_history.train]
)
# the training loss of every step without clipping, (step)
unclipped_steps: Float[ArrayLike, " step"] = np.array(
[metrics["loss"] for _, metrics in unclipped_history.train]
)print(
f"with clipping : held-out NLL {fixed_held[-1]:.3f}, first step loss {clipped_steps[0]:.3f}, largest {clipped_steps.max():.3f}, any NaN {bool(np.isnan(clipped_steps).any())}"
)
print(
f"without clipping: held-out NLL {unclipped_held[-1]:.3f}, first step loss {unclipped_steps[0]:.3f}, largest {unclipped_steps.max():.3f}, any NaN {bool(np.isnan(unclipped_steps).any())}"
)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.
fig, axes = plt.subplots(1, 3, figsize=(16.5, 4.4))
epochs = np.arange(1, 31)
axes[0].plot(epochs, default_train, color="C1", lw=2, label="factory base")
axes[0].plot(epochs, default_held, color="C1", lw=2, ls="--")
axes[0].plot(epochs, fixed_train, color="C0", lw=2, label="fixed base")
axes[0].plot(epochs, fixed_held, color="C0", lw=2, ls="--")
axes[0].set(xlabel="epoch", ylabel="negative log-likelihood (nats)", ylim=(1.5, 4.0))
axes[0].legend()
axes[1].plot(
np.arange(3000), [float(schedule(step)) for step in range(3000)], color="k", lw=2
)
axes[1].set(xlabel="step", ylabel="learning rate")
axes[2].scatter(
default_latent[:, 0],
default_latent[:, 1],
color="C1",
label="factory base",
**SCATTER_KW,
)
axes[2].scatter(
fixed_latent[:, 0], fixed_latent[:, 1], color="C0", label="fixed base", **SCATTER_KW
)
axes[2].set(
xlim=(-4, 4),
ylim=(-4, 4),
xlabel="first latent coordinate",
ylabel="second latent coordinate",
)
axes[2].set_aspect("equal")
axes[2].legend()
for ax in axes:
style_ax(ax)
fig.tight_layout()
plt.show()
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.
# the clock before fitting
start: float = time.perf_counter()
# today (gauss_flows)
# 8 greedy layers of a PCA rotation and an 8-component mixture fitted by EM
greedy_flow: Transformed = fit_rbig(
jnp.asarray(train_points), n_layers=8, n_components=8, random_state=0
)
# seconds spent fitting
greedy_seconds: float = time.perf_counter() - start
PerHeld = Float[ArrayLike, " held_out"]
# today (flowjax)
# log p_x(xₙ) of the greedy fit on the training rows, (train)
greedy_train_logp: PerTrain = np.asarray(jax.vmap(greedy_flow.log_prob)(train_points))
# today (flowjax)
# log p_x(xₙ) of the greedy fit on the held-out rows, (held_out)
greedy_held_logp: PerHeld = np.asarray(jax.vmap(greedy_flow.log_prob)(held_points))
# today (flowjax)
# log p_x(xₙ) of the trained flow on the training rows, (train)
fixed_train_logp: PerTrain = np.asarray(jax.vmap(fixed_flow.log_prob)(train_points))
# today (flowjax)
# log p_x(xₙ) of the trained flow on the held-out rows, (held_out)
fixed_held_logp: PerHeld = np.asarray(jax.vmap(fixed_flow.log_prob)(held_points))print(
f"greedy RBIG : NLL {-greedy_train_logp.mean():.3f} on training rows, {-greedy_held_logp.mean():.3f} held out, {greedy_seconds:.0f} s to fit"
)
print(
f"trained flow: NLL {-fixed_train_logp.mean():.3f} on training rows, {-fixed_held_logp.mean():.3f} held out, {fixed_seconds:.0f} s to train"
)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.
# Shapes: line = 120 points along each axis; test = 120 × 120 grid points
# 120 points from −2.5 to 2.5, (line)
grid_axis: Float[ArrayLike, " line"] = np.linspace(-2.5, 2.5, 120)
# the 120 × 120 grid over [−2.5, 2.5]², as rows, (test, state)
grid_points: Float[ArrayLike, "test state"] = (
np.stack(np.meshgrid(grid_axis, grid_axis), axis=-1)
.reshape(-1, 2)
.astype(np.float32)
)
PerTest = Float[ArrayLike, " test"]
# today (flowjax)
# log p_x on the grid for the greedy fit, (test)
greedy_grid: PerTest = np.asarray(jax.vmap(greedy_flow.log_prob)(grid_points))
# today (flowjax)
# log p_x on the grid for the trained flow, (test)
fixed_grid: PerTest = np.asarray(jax.vmap(fixed_flow.log_prob)(grid_points))
print(
f"grid points where log p_x is minus infinity: greedy {int(np.isneginf(greedy_grid).sum())} of {greedy_grid.size}, trained {int(np.isneginf(fixed_grid).sum())}"
)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 . 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.
fig, axes = plt.subplots(1, 2, figsize=(11, 4.8), sharey=True)
# one set of log-density levels for both panels, from −6 up
levels = np.linspace(-6, max(greedy_grid.max(), fixed_grid.max()), 19)
for ax, grid_logp, title in [
(axes[0], greedy_grid, "greedy RBIG"),
(axes[1], fixed_grid, "trained flow"),
]:
ax.contourf(
grid_axis,
grid_axis,
np.clip(grid_logp, -6, None).reshape(120, 120),
levels=levels,
cmap="viridis",
)
ax.set(title=title, xlabel="first coordinate")
ax.set_aspect("equal")
axes[0].set_ylabel("second coordinate")
fig.tight_layout()
plt.show()
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¶
| Piece | Equation | In 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.
- 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.