RBIG as a warm start
What a greedy RBIG fit hands to a trainable flow, and what it is worth once both starts get the same budget and a fair learning rate
01 · RBIG as a warm start¶
Notebook 00 found that a greedy RBIG fit is quick and that a trained flow generalises better. The obvious combination is to start training from the greedy fit. fit_rbig returns a FlowJax Transformed distribution whose blocks are all trainable except its rotations, so it can go straight into the training loop of notebook 00. This notebook asks what that start hands over and what it is worth. The warm-start example shows the start itself (its likelihood before training, its pushforward and its samples) and trains both starts at one learning rate; here we compare them on held-out data, with a learning rate chosen for each.
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 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 sklearn.datasets import make_moons
from gauss_flows_docs.environment import watermark
from gauss_flows_docs.plotting import 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
As in notebook 00 the notebook runs in float32, because fit_rbig cannot run with float64 turned on today, a bug in gauss_flows (gauss_flows#247). The data are the same: 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. What the warm start hands over¶
We build both starts with layers of 8-component mixture marginals. The cold start is gaussianization_flow with a fixed standard-normal base, as notebook 00 recommends. The warm start is fit_rbig on the training rows. fit_rbig also builds a trainable base, the defect notebook 00 found (gauss_flows#256), and unlike the factory it has no base_dist argument, so we swap the base for a fixed one with eqx.tree_at. Its base starts at , so the swap changes no density, only what training may move.
# today (gauss_flows)
# the cold start: 8 layers of a random mixture marginal and a Householder rotation, fixed 𝒩(0, I) base
cold_flow: Transformed = gaussianization_flow(
jr.key(0), n_dims=2, n_layers=8, n_components=8, base_dist=StandardNormal((2,))
)
# today (gauss_flows)
# the greedy fit: 8 layers of a PCA rotation and a mixture marginal fitted by EM
greedy_flow: Transformed = fit_rbig(
jnp.asarray(train_points), n_layers=8, n_components=8, random_state=0
)
# today (equinox)
# the warm start: the greedy fit with its base swapped for a fixed 𝒩(0, I)
warm_flow: Transformed = eqx.tree_at(
lambda flow: flow.base_dist, greedy_flow, StandardNormal((2,))
)A small function counts the numbers each flow holds and how many of them the optimiser may move. Rotations wrapped in paramax.NonTrainable stay out of the optimiser, as in Part 2.
# 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
# the numbers a flow holds, and those outside a NonTrainable wrapper
def count_numbers(flow: Transformed) -> tuple[int, int]:
"""Total and trainable array sizes of ``flow``."""
# today (equinox)
# every array of the flow
all_arrays: list = jax.tree.leaves(eqx.filter(flow, eqx.is_inexact_array))
# today (equinox)
# the arrays left once the frozen leaves are dropped
free_arrays: list = jax.tree.leaves(
eqx.filter(
jax.tree.map(
lambda leaf: None if is_frozen(leaf) else leaf, flow, is_leaf=is_frozen
),
eqx.is_inexact_array,
)
)
return sum(a.size for a in all_arrays), sum(a.size for a in free_arrays)# the cold layer stack, run in the density direction by Invert
cold_stack: eqx.Module = cold_flow.bijection.bijection
# the warm layer stack, run in the density direction by Invert
warm_stack: eqx.Module = warm_flow.bijection.bijection
print(
f"cold: {type(cold_flow.bijection).__name__}({type(cold_stack).__name__}(...)), one layer {[type(block).__name__ for block in cold_stack.bijection.bijections]} run 8 times"
)
print(
f"warm: {type(warm_flow.bijection).__name__}({type(warm_stack).__name__}(...)), first blocks {[type(block).__name__ for block in warm_stack.bijections[:2]]} of {len(warm_stack.bijections)}"
)
for name, flow in [("cold", cold_flow), ("warm", warm_flow)]:
total: int
free: int
# user
# the numbers of the flow, all and trainable
total, free = count_numbers(flow)
print(f"{name}: {total} numbers, {free} trainable, {total - free} frozen")cold: Invert(Scan(...)), one layer ['MixtureGaussianCDF', 'HouseholderRotation'] run 8 times
warm: Invert(Chain(...)), first blocks ['FixedRotation', 'MixtureGaussianCDF'] of 16
cold: 416 numbers, 416 trainable, 0 frozen
warm: 416 numbers, 384 trainable, 32 frozen
The two starts are not the same flow. The cold flow runs each layer as a marginal map followed by a trainable Householder rotation (2), stored once and run by Scan. The warm flow is a Chain of 16 blocks that runs the PCA frame (3) of the current state first and the marginal map after it, which is how fit_rbig fits them, so the two compositions are
with the same number of numbers in each, 416. In the warm flow the 32 numbers of the eight frames are frozen: training moves only the mixture marginals. The warm start therefore hands over two things, the EM fit of every marginal and a set of rotations that training will never change. The source of this tutorial checks that the two starts share a structure by comparing the name of the outer bijection, which is Invert for both; the layers inside differ.
How far apart the starts are shows in their negative log-likelihood before training.
# Shapes: train (N_t) = 3,000; held_out (N_v) = 1,000
# today (gauss_flows)
# −(1/N) ∑ₙ log p_x(xₙ), the mean negative log-likelihood, on training and held-out rows
for name, flow in [("greedy", greedy_flow), ("warm", warm_flow), ("cold", cold_flow)]:
print(
f"{name:6s}: NLL {float(negative_log_likelihood(flow, train_points)):6.3f} on training rows, {float(negative_log_likelihood(flow, held_points)):6.3f} held out"
)greedy: NLL 1.926 on training rows, 2.430 held out
warm : NLL 1.926 on training rows, 2.430 held out
cold : NLL 16.254 on training rows, 16.276 held out
The warm start begins at the greedy fit’s likelihood, about 14 nats per point better than the cold start, which the swap of base left unchanged. It also begins with the greedy fit’s overfitting: half a nat between its training and held-out rows, the gap notebook 00 found.
2. The comparison as the source ran it¶
The training loop is notebook 00’s: pipekit-train on (1), Adam with gradients clipped to a global norm of 1 on a one-cycle cosine learning rate, 3,000 steps of 512 rows in 30 epochs, with the held-out loss after each epoch. Only the peak learning rate changes from run to run, so the optimiser is built from it.
# 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}
# user
# Adam on a one-cycle rate that peaks at `peak`, with the gradient clipped to a global norm of 1
def one_cycle_adam(peak: float) -> dict:
"""pipekit-train's optimiser settings for one peak learning rate."""
# today (optax)
# the learning rate of each step: up to the peak, then down to almost zero
schedule: optax.Schedule = optax.cosine_onecycle_schedule(
transition_steps=3000, peak_value=peak
)
return {"name": "adam", "lr": schedule, "clip_norm": 1.0}# 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,
}# Shapes: epoch = 30 epochs of 100 steps; step = 100 steps 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, one row 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
# a pipekit-train loop that fits the flow at peak rate `peak` and logs into the history
def build_loop(
flow: Transformed, peak: float, seed: int, history: History
) -> TrainingLoop:
"""A training loop for ``flow`` with the shared settings; ``seed`` sets the batch order."""
# today (pipekit)
# the flow as a trainable model, frozen leaves masked out
model_op = EquinoxModelOp(
flow, trainable=jax.tree.map(eqx.is_inexact_array, flow, is_leaf=is_frozen)
)
return TrainingLoop(
model_op,
train_data,
optimizer_config=one_cycle_adam(peak),
callbacks=(history,),
seed=seed,
**loop_settings,
)# user
# θ after 3,000 steps from `flow` at peak rate `peak`, with the per-epoch training and held-out losses
def train_flow(
flow: Transformed, peak: float, seed: int = 1
) -> tuple[Transformed, PerEpoch, PerEpoch]:
"""Train ``flow`` at peak rate ``peak``; ``seed`` sets the batch order."""
# today (pipekit)
# the training and held-out losses of the run
history = History()
# today (pipekit)
# θ after 3,000 steps, held by the model op
trained_op: EquinoxModelOp
trained_op, _ = build_loop(flow, peak, seed, history).run()
return trained_op.module, *epoch_losses(history)The source trains the cold start at a peak learning rate of and the warm start at 10-3, a smaller rate so that training does not throw away the greedy fit.
# user
# the cold start at the source's peak rate of 3 × 10⁻³, (epoch), (epoch)
source_cold: Transformed
source_cold_train: PerEpoch
source_cold_held: PerEpoch
source_cold, source_cold_train, source_cold_held = train_flow(cold_flow, 3e-3)
# user
# the warm start at the source's peak rate of 10⁻³, (epoch), (epoch)
source_warm: Transformed
source_warm_train: PerEpoch
source_warm_held: PerEpoch
source_warm, source_warm_train, source_warm_held = train_flow(warm_flow, 1e-3)for name, train_losses, held_losses in [
("cold, peak 3e-3", source_cold_train, source_cold_held),
("warm, peak 1e-3", source_warm_train, source_warm_held),
]:
print(
f"{name}: NLL after epoch 1 {held_losses[0]:.3f} held out; after epoch 30 {train_losses[-1]:.3f} on training rows, {held_losses[-1]:.3f} held out"
)cold, peak 3e-3: NLL after epoch 1 15.462 held out; after epoch 30 1.886 on training rows, 1.901 held out
warm, peak 1e-3: NLL after epoch 1 2.406 held out; after epoch 30 1.599 on training rows, 1.852 held out
fig, ax = plt.subplots(figsize=(7.5, 4.4))
epochs = np.arange(1, 31)
ax.plot(epochs, source_cold_train, color="C0", lw=2, label="cold, peak 3e-3")
ax.plot(epochs, source_cold_held, color="C0", lw=2, ls="--")
ax.plot(epochs, source_warm_train, color="C1", lw=2, label="warm, peak 1e-3")
ax.plot(epochs, source_warm_held, color="C1", lw=2, ls="--")
ax.axhline(
float(negative_log_likelihood(greedy_flow, held_points)),
color="0.5",
lw=1.5,
label="greedy, held out",
)
ax.set(xlabel="epoch", ylabel="negative log-likelihood (nats)", ylim=(1.4, 3.0))
ax.legend()
style_ax(ax)
plt.show()
Figure 1:The comparison as the source ran it: the training (solid) and held-out (dashed) negative log-likelihood per epoch of the cold start at a peak learning rate of 3 × 10⁻³ (blue) and the warm start at 10⁻³ (orange). The grey line is the greedy fit on the held-out rows.
At these settings the warm start wins, as the source reports: after 3,000 steps it is at 1.852 nats held out against the cold start’s 1.901, and at 1.599 against 1.886 on the training rows. The source reports log-likelihoods on its training data (in float64, with all of its 3,000 points used for training) of -1.66 for the warm start, -1.98 for the cold one and -1.96 for the greedy fit; ours on the training rows are -1.599, -1.886 and -1.926, the same order. What the training rows alone hide is the warm start’s gap between training and held-out loss, a quarter of a nat (1.599 against 1.852), where the cold start’s is 0.015. The two starts also had different learning rates, so this comparison cannot say how much of the difference is the start.
3. The same budget and a fair learning rate¶
A learning rate chosen for one start is not a fair setting for the other, so we train each start at the same four peak rates, from 10-3 to 10-1, for the same 3,000 steps, and keep each start’s best held-out result.
A third start separates the two things the warm start hands over. It keeps the warm flow’s frozen PCA frames and replaces its EM marginals with the cold flow’s random initial ones, so it has the frames without the marginal fit. The cold flow stores its layers stacked along a leading axis inside Scan; indexing that axis gives the layers one at a time, a trick the next notebook uses to look inside a trained flow.
# Shapes: the cold flow's arrays carry a leading layer axis of length K = 8
# today (equinox)
# the arrays of the cold layer, stacked over layers, and the rest of the layer
stacked_arrays: eqx.Module
layer_rest: eqx.Module
stacked_arrays, layer_rest = eqx.partition(cold_stack.bijection, eqx.is_inexact_array)
# today (equinox)
# the initial mixture marginal of each cold layer, taken out of the stack
cold_marginals: list = [
eqx.combine(
jax.tree.map(lambda array: array[k], stacked_arrays), layer_rest
).bijections[0]
for k in range(8)
]Each of these goes in place of a warm marginal.
# the warm blocks with every marginal (the odd positions) replaced by a cold one
frame_blocks: list = list(warm_stack.bijections)
frame_blocks[1::2] = cold_marginals
# today (equinox)
# the frames-only start: frozen PCA frames, random mixture marginals
frames_flow: Transformed = eqx.tree_at(
lambda flow: flow.bijection.bijection.bijections, warm_flow, frame_blocks
)
print(
f"frames-only start: NLL {float(negative_log_likelihood(frames_flow, train_points)):.3f} on training rows, {float(negative_log_likelihood(frames_flow, held_points)):.3f} held out"
)frames-only start: NLL 15.984 on training rows, 15.968 held out
The frames alone are worth almost nothing before training: the frames-only start begins close to the cold one. We now train the three starts at the four peak rates; the warm run at 10-3 is the one from section 2. The twelve runs take several minutes.
# the peak learning rates every start is trained at
peaks: list = [1e-3, 1e-2, 3e-2, 1e-1]
# the three starts
starts: dict = {"cold": cold_flow, "warm": warm_flow, "frames only": frames_flow}
# the runs by start and peak rate: θ after training, training losses, held-out losses
# the warm run at 10⁻³ is reused from section 2
runs: dict = {("warm", 1e-3): (source_warm, source_warm_train, source_warm_held)}
for start_name, start_flow in starts.items():
for peak in peaks:
if (start_name, peak) not in runs:
# user
# the start trained for 3,000 steps at this peak rate
runs[(start_name, peak)] = train_flow(start_flow, peak)print("held-out NLL after 3,000 steps (training NLL in brackets)")
print("peak " + "".join(f"{start_name:>18s}" for start_name in starts))
for peak in peaks:
print(
f"{peak:<8.0e}"
+ "".join(
f"{runs[(name, peak)][2][-1]:>9.3f} ({runs[(name, peak)][1][-1]:.3f})"
for name in starts
)
)
# the peak with the lowest final held-out loss, for each start
best_peak: dict = {
name: min(peaks, key=lambda peak: runs[(name, peak)][2][-1]) for name in starts
}
print(f"best peak per start: {best_peak}")held-out NLL after 3,000 steps (training NLL in brackets)
peak cold warm frames only
1e-03 2.076 (2.055) 1.852 (1.599) 2.118 (2.095)
1e-02 1.716 (1.712) 1.763 (1.561) 1.783 (1.761)
3e-02 1.659 (1.628) 1.694 (1.559) 1.675 (1.619)
1e-01 1.673 (1.603) 1.680 (1.574) 1.639 (1.590)
best peak per start: {'cold': 0.03, 'warm': 0.1, 'frames only': 0.1}
fig, axes = plt.subplots(1, 2, figsize=(13, 4.4))
colours = {"cold": "C0", "warm": "C1", "frames only": "C2"}
for name in starts:
axes[0].plot(
peaks,
[runs[(name, peak)][2][-1] for peak in peaks],
"o-",
color=colours[name],
lw=2,
label=name,
)
axes[1].plot(
epochs,
runs[(name, best_peak[name])][2],
color=colours[name],
lw=2,
label=f"{name}, peak {best_peak[name]:.0e}",
)
for ax in axes:
ax.axhline(
float(negative_log_likelihood(greedy_flow, held_points)),
color="0.5",
lw=1.5,
label="greedy",
)
style_ax(ax)
axes[0].set(
xscale="log",
xlabel="peak learning rate",
ylabel="held-out NLL after training (nats)",
)
axes[1].set(xlabel="epoch", ylabel="held-out NLL (nats)", ylim=(1.5, 3.0))
axes[0].legend()
axes[1].legend()
fig.tight_layout()
plt.show()
Figure 2:Left: the held-out negative log-likelihood after 3,000 steps against the peak learning rate, for the cold start (blue), the warm start (orange) and the frames-only start (green); the grey line is the greedy fit. Right: the held-out loss per epoch of each start at its best peak rate.
Every start does best at a higher peak rate than the source used: the cold start at (1.659), the warm and frames-only starts at 10-1 (1.680 and 1.639). The warm start is far ahead at 10-3, where the others are still far from their best after 3,000 steps, but its lead is gone by 10-2, and at each start’s best rate the three end within 0.04 nats of each other. What the warm start keeps is its early lead, seen on the right: it is below the greedy fit from the first epoch, while the cold start needs four epochs to get there. It also keeps the largest gap between its training and held-out loss at every peak rate, from 0.25 nats at 10-3 to 0.11 at 10-1; the cold start’s is between 0.004 and 0.07, and the frames-only start’s between 0.02 and 0.06.
How much of the difference between the best runs is noise? We train the cold and warm starts at their best peak rates twice more, with other batch orders.
# start → the final held-out loss of the batch orders 1, 2 and 3 at the best peak rate
repeats: dict = {}
for name in ["cold", "warm"]:
# user
# the final held-out loss of two more runs, each with its own batch order
more_runs: list = [
train_flow(starts[name], best_peak[name], seed=seed)[2][-1] for seed in [2, 3]
]
repeats[name] = [runs[(name, best_peak[name])][2][-1], *more_runs]
print(
f"{name}, peak {best_peak[name]:.0e}: held-out NLL {np.round(repeats[name], 3)}, mean {np.mean(repeats[name]):.3f}"
)cold, peak 3e-02: held-out NLL [1.659 1.67 1.661], mean 1.663
warm, peak 1e-01: held-out NLL [1.68 1.685 1.665], mean 1.676
Changing only the batch order moves the cold start’s result by up to 0.011 nats and the warm start’s by up to 0.020. Every cold run ends below the warm runs’ mean, and the means differ by 0.013 nats. With a fair learning rate and the same budget, the warm start does not end better than the cold start on held-out data; here it ends a little worse. The frames-only start’s 1.639 is a single run, 0.02 nats below the best cold run, so we read it as showing that the frozen frames do no harm, not that they help. What the warm start buys is time: a good model after one epoch, and the right answer at a learning rate too small for a cold start.
4. What training leaves of the greedy fit¶
The greedy fit overfits because EM gives its mixtures narrow components, fitted to the training rows of each layer. We compare the component scales of (2) in the greedy fit with those after training, for the warm and cold starts at their best peak rates.
# Shapes: component (M) = 8 per coordinate and layer
# user
# the scales σ_m of every mixture component in a flow, flattened
def component_scales(flow: Transformed) -> Float[ArrayLike, " component"]:
"""All mixture-component scales of ``flow``, over layers and coordinates."""
# today (paramax)
# the flow with every parametrised leaf unwrapped to its value
plain_flow: Transformed = paramax.unwrap(flow)
# every array that holds mixture scales: one per warm block, one stacked array for the cold Scan
scale_arrays: list = [
block.scales
for block in jax.tree.leaves(
plain_flow, is_leaf=lambda leaf: hasattr(leaf, "scales")
)
if hasattr(block, "scales")
]
return np.concatenate([np.ravel(array) for array in scale_arrays])# user
# the cold start trained at its best peak rate
best_cold: Transformed = runs[("cold", best_peak["cold"])][0]
# user
# the warm start trained at its best peak rate
best_warm: Transformed = runs[("warm", best_peak["warm"])][0]
for name, flow in [
("greedy", greedy_flow),
("warm, trained", best_warm),
("cold, initial", cold_flow),
("cold, trained", best_cold),
]:
# user
# σ_m over all components, (component)
scales: Float[ArrayLike, " component"] = component_scales(flow)
print(
f"{name:14s}: {scales.size} scales, median {np.median(scales):.3f}, 10% quantile {np.quantile(scales, 0.1):.3f}"
)greedy : 128 scales, median 0.215, 10% quantile 0.159
warm, trained : 128 scales, median 0.488, 10% quantile 0.218
cold, initial : 128 scales, median 0.698, 10% quantile 0.698
cold, trained : 128 scales, median 0.640, 10% quantile 0.255
EM leaves the greedy fit’s components narrow, with a median scale of 0.215 against 0.698 for every component of the cold start before training. Training widens them, but the warm start’s stay narrower than the cold start’s: a median of 0.488 against 0.640, and a 10% quantile of 0.218 against 0.255. That is consistent with the larger gap between the warm start’s training and held-out loss: the warm start keeps part of the greedy fit’s adaptation to the training rows.
# 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)
)# today (flowjax)
# log p_x on the grid for the greedy fit and the two trained starts, (test) each
grid_logp: dict = {
name: np.asarray(jax.vmap(flow.log_prob)(grid_points))
for name, flow in [
("greedy", greedy_flow),
("cold, trained", best_cold),
("warm, trained", best_warm),
]
}
print(
"grid points where log p_x is minus infinity: "
+ ", ".join(
f"{name} {int(np.isneginf(values).sum())}" for name, values in grid_logp.items()
)
)grid points where log p_x is minus infinity: greedy 156, cold, trained 0, warm, trained 0
The greedy fit’s log-density is at 156 of the 14,400 grid points, the NaN that MixtureGaussianCDF returns far in a mixture’s tail (gauss_flows#248), as in notebook 00. Neither trained flow has any. The figure clips the log-density at -6.
fig, axes = plt.subplots(1, 3, figsize=(15, 4.8), sharey=True)
# one set of log-density levels for all panels, from −6 up
levels = np.linspace(-6, max(values.max() for values in grid_logp.values()), 19)
for ax, (name, values) in zip(axes, grid_logp.items()):
ax.contourf(
grid_axis,
grid_axis,
np.clip(values, -6, None).reshape(120, 120),
levels=levels,
cmap="viridis",
)
ax.set(title=name, 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 fit (left), the cold start trained at its best peak rate (centre) and the warm start trained at its best peak rate (right), on one colour scale clipped at −6.
Both trained flows follow the two moons, which the greedy fit does not. The cold start’s density is smooth and leaves some mass in the gap at the right-hand end of the moons. The warm start’s bands are narrower, with a few small islands of mass off the moons and sharp seams across the bands near and .
Recap¶
| Piece | Equation | In code |
|---|---|---|
| the two starts, block by block | (1) | gaussianization_flow against fit_rbig |
| the warm start’s frozen frames | (3) | FixedRotation, paramax.NonTrainable |
| a fixed base for the warm start | (3) | eqx.tree_at on base_dist (gauss_flows#256) |
| training each start | (1) | train_flow, one_cycle_adam |
a layer taken out of a Scan | eqx.partition, index the leading axis, eqx.combine | |
| the components EM leaves narrow | (2) | component_scales |
Next. Every comparison so far read one number, the likelihood of the whole flow. The next notebook opens the flows up and follows the data through them one block at a time.