RBIG warm start for coupling flows
What fit_rbig_coupling hands to a coupling flow, and what it is worth on held-out data once both starts get the same budget
05 · RBIG warm start for coupling flows¶
Part 4 started a diagonal flow from a greedy RBIG fit and found that the start buys time but, with a fair learning rate, not a better model on held-out data. fit_rbig_coupling does the same for a coupling flow. Its warm start is often credited to the conditioners’ zero readout, which makes each coupling a diagonal marginal map at the start. Since notebook 00 we know that every coupling in gauss_flows starts with a zero readout, so the readout is not what the warm start adds. The warm-start example shows the coupling warm start’s likelihood, pushforward and samples before training; here we ask what it adds, and what that is worth on held-out data.
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, Key
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_maps.bijections import MixtureGaussianCDFCoupling
from gauss_flows_models.inference import fit_rbig_coupling, 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 data are those of Part 4: two moons with noise of standard deviation 0.08, standardised, split into training rows and held-out rows. The notebook runs in float32, the precision fit_rbig_coupling works in.
# 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¶
fit_rbig_coupling builds layers, each a PCA frame (3) followed by two MixtureGaussianCDFCoupling layers with a flip after each, so that each coordinate is active once per layer. Each conditioner is an MLP of width 64 and depth 2, and the greedy fit sets the bias of its last layer to the 8-component mixture that EM fits to the active coordinate, as fit_rbig fits its marginals. Like fit_rbig, it also builds a trainable base (gauss_flows#256), which we swap for a fixed ; the base starts there, so the swap changes no density.
# today (gauss_flows)
# K = 4 layers of a PCA frame and two mixture couplings, the readout biases fitted by EM
greedy_flow: Transformed = fit_rbig_coupling(
jnp.asarray(train_points), jr.key(0), n_layers=4, 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,))
)
# the 20 blocks of the warm start, in the density direction
warm_blocks: list = list(warm_flow.bijection.bijection.bijections)
print(
[type(block).__name__ for block in warm_blocks[:5]],
f"... {len(warm_blocks)} blocks",
)['FixedRotation', 'MixtureGaussianCDFCoupling', 'Flip', 'MixtureGaussianCDFCoupling', 'Flip'] ... 20 blocks
For comparison we keep the warm start’s frames and flips and put a fresh coupling of the same size in place of each fitted one. A fresh coupling is the identity (notebook 00), so this fresh start is the PCA frames alone. Part 4 found that frozen frames alone are worth almost nothing before training and neither help nor harm after it, so it differs from the warm start in what matters only by what the couplings hold.
# one key per block, for the fresh couplings
block_keys: jax.Array = jr.split(jr.key(1), len(warm_blocks))
# today (gauss_flows)
# the warm blocks with every coupling replaced by a fresh one of the same size
fresh_blocks: list = [
MixtureGaussianCDFCoupling(key, shape=(2,), n_components=8)
if isinstance(block, MixtureGaussianCDFCoupling)
else block
for block, key in zip(warm_blocks, block_keys, strict=True)
]
# today (equinox)
# the warm start's frames and flips, fresh couplings
fresh_flow: Transformed = eqx.tree_at(
lambda flow: flow.bijection.bijection.bijections, warm_flow, fresh_blocks
)The fresh start cannot be trained as it is. Its zero readout gives all eight mixture components of a coupling the same parameters, so every component gets the same gradient and they stay identical through training, and the coupling trains as an affine one (gauss_flows#265). We break the symmetry as notebook 00 does, moving every weight of each fresh coupling by a normal draw of standard deviation 0.1, and call the result the cold start. The nudge moves the readout weight off zero too, so the cold start is neither the identity nor a marginal map.
# Shapes: leaf = the weight arrays of the layer
# user
# φ ← φ + 0.1 ε with ε ~ N(0, I), for every weight of the layer
def perturb_weights(
layer: eqx.Module, key: jax.Array, scale: float = 0.1
) -> eqx.Module:
"""The layer with every floating-point weight moved by scale times a normal draw."""
# today (equinox)
# the weight arrays φ, with every other field of the layer set to None
weights: eqx.Module = eqx.filter(layer, eqx.is_inexact_array)
# today (jax)
# the weight arrays as a flat list, and how to rebuild the tree
leaves: list[jax.Array]
treedef: jax.tree_util.PyTreeDef
leaves, treedef = jax.tree.flatten(weights)
# one key per weight array, (leaf)
keys: Key[jax.Array, " leaf"] = jr.split(key, len(leaves))
# φ + scale ε, one array per leaf
moved: list[jax.Array] = [
leaf + scale * jr.normal(leaf_key, leaf.shape, leaf.dtype)
for leaf, leaf_key in zip(leaves, keys, strict=True)
]
return eqx.combine(jax.tree.unflatten(treedef, moved), layer)# one key per block, for the perturbations
nudge_keys: jax.Array = jr.split(jr.key(2), len(fresh_blocks))
# user
# every fresh coupling with its weights moved by 0.1 ε
cold_blocks: list = [
perturb_weights(block, key)
if isinstance(block, MixtureGaussianCDFCoupling)
else block
for block, key in zip(fresh_blocks, nudge_keys, strict=True)
]
# today (equinox)
# the cold start: the warm start's frames and flips, perturbed fresh couplings
cold_flow: Transformed = eqx.tree_at(
lambda flow: flow.bijection.bijection.bijections, warm_flow, cold_blocks
)# Shapes: train (N_t) = 3,000; held_out (N_v) = 1,000
# today (gauss_flows)
# −(1/N) ∑ₙ log p_x(xₙ), on training and held-out rows
for name, flow in [("warm", warm_flow), ("fresh", fresh_flow), ("cold", cold_flow)]:
print(
f"{name}: NLL {float(negative_log_likelihood(flow, train_points)):.3f} on training rows, {float(negative_log_likelihood(flow, held_points)):.3f} held out"
)warm: NLL 2.023 on training rows, 2.094 held out
fresh: NLL 2.839 on training rows, 2.834 held out
cold: NLL 5.606 on training rows, 5.634 held out
Before training, the warm start has a negative log-likelihood of 2.023 nats on the training rows and 2.094 held out. On the training rows that is the value of the diagonal flow that fit_rbig builds with four layers; held out the diagonal flow has 2.100, and notebook 06 traces the difference to three held-out rows. The fresh start has 2.839 and 2.834: a rotation followed by identities leaves standardised data where they are, and their negative log-likelihood under is nats in two dimensions. The nudge costs the cold start almost three nats: its eight couplings, each moved a little off the identity, compound to 5.606 on the training rows and 5.634 held out.
2. The warm start is a marginal map¶
The last layer of a conditioner is affine: with the output of the MLP’s last hidden layer, it returns
where has one row per parameter of the transformer and is its bias. The warm and fresh starts have : the fresh couplings by the default of gauss_flows, the warm ones because fit_rbig_coupling writes only the bias. Then for every , and the block of the coupling’s Jacobian below the diagonal (3), , is zero. We check that from outside: one function runs the blocks of a flow in the density direction and, at each coupling, takes the median of over a set of points.
# Shapes: coupling = the 8 couplings of a flow
PerCoupling = Float[ArrayLike, " coupling"]
# user
# median over points of |∂z_B/∂x_A| at each coupling, at the points that reach it, (coupling)
def cross_slopes(flow: Transformed, points: SampleState) -> PerCoupling:
"""The typical cross-derivative of every coupling of ``flow``."""
# the medians, one entry per coupling
medians: list = []
# x₀ = x, (sample, state)
state: SampleState = jnp.asarray(points)
for block in flow.bijection.bijection.bijections:
if isinstance(block, MixtureGaussianCDFCoupling):
# today (jax)
# J = ∂z/∂x of the coupling at every point, (sample, latent, state)
jacobians: Float[ArrayLike, "sample latent state"] = jax.vmap(
jax.jacfwd(block.transform)
)(state)
medians.append(float(jnp.median(jnp.abs(jacobians[:, 1, 0]))))
# today (flowjax)
# the block's map, (sample, state)
state = jax.vmap(block.transform)(state)
return np.array(medians)for name, flow in [("warm", warm_flow), ("fresh", fresh_flow), ("cold", cold_flow)]:
# user
# median |∂z_B/∂x_A| of each coupling on the training rows, (coupling)
slopes: PerCoupling = cross_slopes(flow, train_points)
print(f"{name}: {np.round(slopes, 4)}")warm: [0. 0. 0. 0. 0. 0. 0. 0.]
fresh: [0. 0. 0. 0. 0. 0. 0. 0.]
cold: [0.0492 0.1007 0.1204 0.1398 0.1192 0.1014 0.2727 0.0739]
Every cross-derivative of the warm and fresh starts is zero, so both are diagonal flows: each coupling is a marginal map on its active coordinate. What the warm start adds is in , the EM mixtures; the fresh start’s bias gives eight copies of , the identity. The nudged cold start has median cross-slopes of 0.05 to 0.27, so it starts as a weak coupling flow rather than a diagonal one. Notebook 06 checks that the warm start is the diagonal flow of fit_rbig, layer by layer.
3. The same budget at three learning rates¶
The training loop is that of Part 4: pipekit-train on the mean negative log-likelihood (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. The frozen PCA frames stay out of the optimiser.
# 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}
# 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)# 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, history: History) -> TrainingLoop:
"""A training loop for ``flow`` with the shared settings."""
# 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=1,
**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
) -> tuple[Transformed, PerEpoch, PerEpoch]:
"""Train ``flow`` at peak rate ``peak`` with the shared settings."""
# 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, history).run()
return trained_op.module, *epoch_losses(history)We train the warm and cold starts at peak rates of 10-3, and 10-2. The six runs take about six minutes.
# the peak learning rates both starts are trained at
peaks: list = [1e-3, 3e-3, 1e-2]
# the two starts
starts: dict = {"warm": warm_flow, "cold": cold_flow}
# user
# the runs by start and peak rate: θ after training, training losses, held-out losses
runs: dict = {
(name, peak): train_flow(flow, peak)
for name, flow in starts.items()
for peak in peaks
}print("NLL after epoch 1 held out | after epoch 30 held out (training)")
for peak in peaks:
print(
f"peak {peak:.0e}: "
+ " ".join(
f"{name} {runs[(name, peak)][2][0]:.3f} | {runs[(name, peak)][2][-1]:.3f} ({runs[(name, peak)][1][-1]:.3f})"
for name in starts
)
)NLL after epoch 1 held out | after epoch 30 held out (training)
peak 1e-03: warm 1.861 | 1.887 (1.449) cold 3.123 | 1.651 (1.540)
peak 3e-03: warm 1.718 | 2.173 (1.386) cold 2.125 | 1.669 (1.534)
peak 1e-02: warm 1.693 | 1.981 (1.389) cold 1.893 | 1.676 (1.530)
fig, axes = plt.subplots(1, 2, figsize=(13, 4.4))
epochs = np.arange(1, 31)
colours = {"warm": "C1", "cold": "C0"}
styles = {1e-3: ":", 3e-3: "--", 1e-2: "-"}
for (name, peak), (_, _, held_losses) in runs.items():
axes[0].plot(
epochs,
held_losses,
color=colours[name],
ls=styles[peak],
lw=2,
label=f"{name}, peak {peak:.0e}",
)
for name in starts:
axes[1].plot(
peaks,
[runs[(name, peak)][2][-1] for peak in peaks],
"o-",
color=colours[name],
lw=2,
label=f"{name}, held out",
)
axes[1].plot(
peaks,
[runs[(name, peak)][1][-1] for peak in peaks],
"s--",
color=colours[name],
lw=1.5,
label=f"{name}, training",
)
axes[0].set(xlabel="epoch", ylabel="held-out NLL (nats)", ylim=(1.5, 2.6))
axes[1].set(
xscale="log", xlabel="peak learning rate", ylabel="NLL after training (nats)"
)
for ax in axes:
ax.legend(fontsize=8)
style_ax(ax)
fig.tight_layout()
plt.show()
Figure 1:Left: the held-out negative log-likelihood per epoch of the warm start (orange) and the cold start (blue), at peak learning rates of 10⁻³ (dotted), 3 × 10⁻³ (dashed) and 10⁻² (solid). Right: the final training (dashed) and held-out (solid) negative log-likelihood against the peak learning rate.
The warm start leads early: after one epoch its held-out loss is 1.69 to 1.86 nats against the cold start’s 1.89 to 3.12, and the left panel shows it near its best within the first few epochs, a level the cold start reaches only around epoch 14. It does not stay there. From about epoch 14 the warm runs’ held-out loss climbs while their training loss keeps falling, and after 30 epochs they end at 1.887, 2.173 and 1.981 nats held out (at 10-3, and 10-2) with 1.39 to 1.45 on the training rows. The cold runs end at 1.651, 1.669 and 1.676 held out with 1.53 to 1.54 on the training rows. On the training rows the warm start is better at every rate; on held-out data it is worse by 0.24 to 0.50 nats at every rate. The warm start spends its head start on fitting the 3,000 training rows ever more closely, and the budget that is fair to the cold start is too long for it; Part 4’s diagonal warm start bought time but not a better held-out model, and the coupling warm start, with 46,804 parameters to the diagonal flow’s 212, pays for the same time with overfitting.
4. Training switches the conditioners on¶
We measure the cross-derivatives of the warm and cold starts again after training, at a peak rate of 10-3.
for name in starts:
# user
# median |∂z_B/∂x_A| of each coupling after training at 10⁻³, (coupling)
slopes: PerCoupling = cross_slopes(runs[(name, 1e-3)][0], train_points)
print(f"{name}, trained: {np.round(slopes, 3)}")warm, trained: [0.055 0.052 0.056 0.055 0.068 0.107 0.157 0.166]
cold, trained: [0.118 0.299 0.489 0.14 0.396 0.366 0.738 0.286]
Training moves off zero in the warm start and further from it in the cold one, so neither is a marginal map. The warm start’s median cross-slopes stay small, from 0.052 to 0.166 and largest in the last two couplings, while the cold start’s grow from 0.05 to 0.27 before training to 0.12 to 0.74 after it. The warm conditioners barely leave the diagonal flow they started as; the cold ones, with nothing fitted to keep, use their copied coordinate far more.
Recap¶
| Piece | Equation | In code |
|---|---|---|
| the warm start | (3), (2) | fit_rbig_coupling, base swapped for StandardNormal((2,)) |
| the conditioner’s readout | (1) | zero weight in every fresh coupling; fit_rbig_coupling writes the bias |
| a zero readout gives a marginal map | (3) | cross_slopes, from jax.jacfwd(block.transform) |
| breaking the mixture components’ symmetry | perturb_weights, a normal draw of standard deviation 0.1 on every weight (gauss_flows#265) | |
| training at a fair learning rate | (1) | pipekit-train’s TrainingLoop, three peak rates, held-out rows |
Next. The warm start is a diagonal flow until training. Notebook 06 checks that the warm start is exactly the diagonal flow of fit_rbig, layer by layer, and finds where that fails today.