Conditioner architectures
The network that reads the passive half: what it holds, how its size changes the fit, and what bounding its log-scales does to training
02 · Conditioner architectures¶
A coupling layer has two parts: the transformer (notebook 01) and the conditioner , which reads the passive half and returns the transformer’s parameters, (1). The transformer is what makes the log-determinant a cheap sum; the conditioner decides how each coordinate’s map changes with the others, which is where a coupling flow’s modelling power comes from Papamakarios et al., 2021. In gauss_flows the conditioner is an equinox.nn.MLP sized by nn_width and nn_depth, and it returns the parameters of the whole active half at once. This notebook fixes the transformer, a mixture CDF with components, and studies the conditioner.
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.bijections import Chain, Flip, Invert
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 gauss_flows_docs.environment import watermark
from gauss_flows_docs.plotting import style_ax, use_compact_figures
from gauss_flows_maps.bijections import HouseholderRotation, MixtureGaussianCDFCoupling
from gauss_flows_models.inference import negative_log_likelihood
jax.config.update("jax_enable_x64", True)
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_maps")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_maps: 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
1. Inside one coupling layer¶
We build one MixtureGaussianCDFCoupling on , with the default conditioner of notebook 01 (width 32, depth 2), and list its weight arrays.
# Shapes: state (D_x) = 2; passive (D_A) = 1; active (D_B) = 1
# today (gauss_flows)
# a mixture-CDF coupling with M = 8 and a width-32, depth-2 MLP as c_φ
probe = MixtureGaussianCDFCoupling(
jr.key(0), shape=(2,), n_components=8, nn_width=32, nn_depth=2
)
# today (equinox)
# the weight arrays of the layer
probe_weights: list = jax.tree.leaves(eqx.filter(probe, eqx.is_inexact_array))
for weight in probe_weights:
print(f"weight array of shape {weight.shape}")
print(f"{sum(weight.size for weight in probe_weights)} weights in all")weight array of shape (32, 1)
weight array of shape (32,)
weight array of shape (32, 32)
weight array of shape (32,)
weight array of shape (24, 32)
weight array of shape (24,)
1912 weights in all
The six arrays are the weights and biases of a three-layer MLP, , and they are all the weights the layer has: the transformer holds none of its own. The MLP reads the one passive coordinate and returns 24 numbers, the weights, means and log-scales of the mixture that maps the one active coordinate. The form of the map is fixed; how it reacts to the passive coordinate is whatever this network can represent, so the fit should follow the network’s size.
2. The size of the conditioner¶
We fit flows that differ only in the conditioner’s width, on the two-arm spiral of notebook 01: training rows and held-out rows.
# Shapes: sample (N) = 4,000; train (N_t) = 3,000; held_out (N_v) = 1,000
PerSample = Float[ArrayLike, " sample"]
# the position along an arm, t ~ U(0.5, 3.5), (sample)
arm_position: PerSample = rng.uniform(0.5, 3.5, 4000)
# the arm of each point, ±1, (sample, 1)
arm_sign: Float[ArrayLike, "sample 1"] = (rng.integers(0, 2, 4000) * 2 - 1)[:, None]
# (t cos 2.5t, t sin 2.5t) on one of the two arms, (sample, state)
spiral: Float[ArrayLike, "sample state"] = arm_sign * np.column_stack(
[
arm_position * np.cos(2.5 * arm_position),
arm_position * np.sin(2.5 * arm_position),
]
)
# the spiral plus noise of standard deviation 0.08, (sample, state)
raw: Float[ArrayLike, "sample state"] = spiral + 0.08 * rng.standard_normal((4000, 2))SampleState = Float[ArrayLike, "sample state"]
# x = (raw − x̄) / s, (sample, state)
samples: SampleState = (raw - raw.mean(axis=0)) / raw.std(axis=0)
# 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:]]The flows have three blocks of a rotation and two mixture-CDF couplings with a flip between them, as in notebook 01; only the conditioner’s width and the log-scale bound change. The rotation is a HouseholderRotation with random vectors, since its default vectors are all equal (gauss_flows#239), and the base is a fixed standard normal. A fresh mixture-CDF coupling has all eight components equal, and because its conditioner’s last layer starts at zero they stay equal through training, so the layer trains as an affine coupling (gauss_flows#265); until that is fixed, make_coupling moves every weight of each fresh layer by 0.1 times a standard-normal draw with perturb_weights.
# Shapes: reflection = 2 Householder vectors
# user
# Q = H₂ H₁, with random Householder vectors
def random_rotation(key: Key[ArrayLike, ""]) -> HouseholderRotation:
"""A 2-D HouseholderRotation with two random reflections."""
# today (gauss_flows)
# Q = H₂ H₁, with the default vectors
rotation = HouseholderRotation(n_reflections=2, shape=(2,))
# vᵢ ~ N(0, I), (reflection, state)
reflections: Float[ArrayLike, "reflection state"] = jr.normal(
key, rotation.params.shape
)
# Q with the random vᵢ in place of the defaults
return eqx.tree_at(lambda r: r.params, rotation, reflections)# Shapes: leaf = the weight arrays of a layer
# user
# φ ← φ + scale · ε 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)# user
# a mixture-CDF coupling with M = 8, a conditioner of the given width and depth 2, and log-scales in [−b, b], with φ ← φ + 0.1 ε
def make_coupling(
key: Key[ArrayLike, ""], width: int, bound: float
) -> MixtureGaussianCDFCoupling:
"""A 2-D mixture-CDF coupling with the given conditioner width and log-scale bound, its symmetry broken."""
# today (gauss_flows)
# the fresh coupling layer
layer = MixtureGaussianCDFCoupling(
key,
shape=(2,),
n_components=8,
nn_width=width,
nn_depth=2,
log_scale_bound=bound,
)
# user
# φ ← φ + 0.1 ε, so the components differ
return perturb_weights(layer, jr.fold_in(key, 1), scale=0.1)A flow stacks three blocks of them.
# user
# three blocks of Q, C₁, a flip, C₂ and a flip back, with mixture-CDF couplings
def build_flow(
key: Key[ArrayLike, ""], width: int = 32, bound: float = 5.0
) -> Transformed:
"""A flow of three mixture-CDF coupling blocks with the given conditioner width."""
# the bijections of the flow, in the density direction
blocks: list = []
# three blocks, each with a key for its rotation and one for each coupling
for rotation_key, first_key, second_key in jr.split(key, (3, 3)):
# user
# Q, then C₁, a flip, C₂ and a flip back
blocks += [
random_rotation(rotation_key),
make_coupling(first_key, width, bound),
Flip(shape=(2,)),
make_coupling(second_key, width, bound),
Flip(shape=(2,)),
]
return Transformed(StandardNormal((2,)), Invert(Chain(blocks)))Training is that of notebook 01 with 1,200 steps: pipekit-train on the mean negative log-likelihood (1), Adam on a one-cycle cosine rate peaking at , and the gradient clipped to a global norm of 1. We also keep the training loss of every step.
# 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}# Shapes: step = 1,200 training steps; epoch = 12 epochs of 100 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=1200, peak_value=3e-3
)
# today (pipekit)
# the settings every run shares
loop_settings: dict = {
"optimizer_config": {"name": "adam", "lr": schedule, "clip_norm": 1.0},
"val_dataset": ArrayDataset(held_points, ()),
"task": FlowNLL(),
"max_steps": 1200,
"steps_per_epoch": 100,
"eval_every_n_steps": 100,
"log_every_n_steps": 100,
"batch_size": 512,
"seed": 1,
}# 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)One function trains a flow and returns it with its training losses.
# user
# θ after 1,200 Adam steps on 𝓛(θ), and the training loss of every step, (step)
def train_flow(flow: Transformed) -> tuple[Transformed, Float[ArrayLike, " step"]]:
"""Train ``flow`` with the shared settings."""
# today (pipekit)
# the training and held-out losses of the run
history = History()
# today (pipekit)
# θ after 1,200 steps, held by the model op
trained_op: EquinoxModelOp
trained_op, _ = TrainingLoop(
EquinoxModelOp(
flow, trainable=jax.tree.map(eqx.is_inexact_array, flow, is_leaf=is_frozen)
),
ArrayDataset(train_points, ()),
callbacks=(history,),
**loop_settings,
).run()
return trained_op.module, np.array(
[metrics["loss"] for _, metrics in history.train]
)# Shapes: width = 5 conditioner widths
# the widths of the conditioner, (width)
widths: list = [4, 8, 16, 32, 64]
# user
# one trained flow and its training loss per width
width_runs: dict = {
width: train_flow(build_flow(jr.key(0), width=width)) for width in widths
}For each width we count the flow’s weights and give the mean negative log-likelihood on the training rows and, on the held-out rows, the median, the mean and the worst row.
PerHeldOut = Float[ArrayLike, " held_out"]
# user
# −log p_x(xₙ) of every held-out row, (held_out)
def held_out_nll(flow: Transformed) -> PerHeldOut:
"""The negative log-likelihood of each held-out row."""
# today (flowjax)
# log p_x(xₙ) of each held-out row, (held_out)
held_logp: PerHeldOut = jax.vmap(flow.log_prob)(jnp.asarray(held_points))
return -np.asarray(held_logp)
# user
# the number of weights of a flow
def count_weights(flow: Transformed) -> int:
"""The number of floating-point weights in ``flow``."""
return sum(
weight.size
for weight in jax.tree.leaves(eqx.filter(flow, eqx.is_inexact_array))
)# user
# −log p_x(xₙ) of every held-out row, (held_out) per width
held_by_width: dict = {
width: held_out_nll(flow) for width, (flow, _) in width_runs.items()
}
# today (gauss_flows)
# 𝓛 = −(1/N_t) ∑ₙ log p_x(xₙ) on the training rows, per width
train_by_width: dict = {
width: float(negative_log_likelihood(flow, jnp.asarray(train_points)))
for width, (flow, _) in width_runs.items()
}
# user
# the number of weights of each flow
weights_by_width: dict = {
width: count_weights(flow) for width, (flow, _) in width_runs.items()
}
for width in widths:
# −log p_x(xₙ) of the held-out rows of this width, (held_out)
held: PerHeldOut = held_by_width[width]
print(
f"width {width:2d}: {weights_by_width[width]:6d} weights, NLL {train_by_width[width]:.3f} on training rows; held out: median {np.median(held):.3f}, mean {held.mean():.3f}, worst {held.max():.1f}"
)width 4: 900 weights, NLL 2.435 on training rows; held out: median 2.436, mean 2.505, worst 24.8
width 8: 1836 weights, NLL 2.185 on training rows; held out: median 2.383, mean 2.261, worst 11.8
width 16: 4284 weights, NLL 1.599 on training rows; held out: median 1.474, mean 1.648, worst 9.5
width 32: 11484 weights, NLL 1.519 on training rows; held out: median 1.429, mean 1.579, worst 9.2
width 64: 35100 weights, NLL 1.376 on training rows; held out: median 1.362, mean 1.443, worst 7.9
fig, ax = plt.subplots(figsize=(12, 5))
weight_counts: list = [weights_by_width[width] for width in widths]
ax.plot(
weight_counts,
[train_by_width[width] for width in widths],
"o-",
label="training rows, mean",
)
ax.plot(
weight_counts,
[np.median(held_by_width[width]) for width in widths],
"s-",
label="held-out rows, median",
)
for width in widths:
ax.annotate(
f"width {width}",
(weights_by_width[width], train_by_width[width]),
textcoords="offset points",
xytext=(6, 6),
)
ax.set(
xscale="log", xlabel="weights of the flow", ylabel="negative log-likelihood (nats)"
)
ax.legend()
style_ax(ax)
fig.tight_layout()
plt.show()
Figure 1:The negative log-likelihood of flows that differ only in the width of their conditioners, against their number of weights: the mean over the training rows and the median over the held-out rows.
The fit improves with the conditioner’s width, while the transformer and the depth stay the same: from 2.44 to 1.38 nats on the training rows, and from 2.44 to 1.36 nats for the median held-out row. Most of the gain comes between width 8 and width 16, where the held-out median drops from 2.38 to 1.47; after that it keeps falling, more slowly, to 1.43 at width 32 and 1.36 at width 64 (35,100 weights), with 1,200 steps. The worst held-out row costs between 7.9 and 24.8 nats, so no single row moves the held-out mean far: it stays within 0.18 nats of the median at every width.
3. Bounding the log-scales¶
Among the conditioner’s outputs are the log-scales of the mixture components. MixtureGaussianCDFCoupling passes each raw output through , so every component’s scale stays in , with = log_scale_bound (5 by default). A tight bound keeps a bad batch from pushing a scale to an extreme; a loose one lets components become very narrow. We train the width-32 flow with and and compare with the default.
# user
# one trained flow and its training loss per bound, with b = 5 taken from the width sweep
bound_runs: dict = {
3.0: train_flow(build_flow(jr.key(0), bound=3.0)),
5.0: width_runs[32],
50.0: train_flow(build_flow(jr.key(0), bound=50.0)),
}
for bound, (flow, step_losses) in bound_runs.items():
# user
# −log p_x(xₙ) of every held-out row, (held_out)
held: PerHeldOut = held_out_nll(flow)
print(
f"b = {bound:4.0f}: peak training loss {step_losses.max():.1f}, final NLL {float(negative_log_likelihood(flow, jnp.asarray(train_points))):.3f} on training rows, held-out median {np.median(held):.3f}"
)b = 3: peak training loss 3.4, final NLL 1.525 on training rows, held-out median 1.461
b = 5: peak training loss 3.8, final NLL 1.519 on training rows, held-out median 1.429
b = 50: peak training loss 17.8, final NLL 1.860 on training rows, held-out median 1.825
fig, ax = plt.subplots(figsize=(12, 5))
for bound, (_, step_losses) in bound_runs.items():
ax.plot(step_losses, lw=1, alpha=0.8, label=f"b = {bound:.0f}")
ax.set(xlabel="step", ylabel="training loss (nats)", ylim=(1.5, 8))
ax.legend()
style_ax(ax)
fig.tight_layout()
plt.show()
Figure 2:The training loss of every step for the width-32 flow with the log-scales bounded at b = 3, 5 and 50.
With and the runs train alike: each has its highest loss at the start (3.4 and 3.8 nats) and ends at 1.53 and 1.52 nats on the training rows, with held-out medians 1.46 and 1.43. With the run also has its highest loss at the start, 17.8 nats, then spikes now and then until about step 800, and ends behind, at 1.86 nats on the training rows and 1.83 for the held-out median. Part of that is the start: each log-scale is , and the three flows share their keys, so the same perturbation of the conditioner’s weights gives log-scales ten times larger with than with . With one run per setting we cannot separate the start from the bound, only say that the loose bound cost fit here and the two tighter ones did not differ.
4. The conditioner is the part that changes with the data¶
Everything above used an MLP because the data are unstructured vectors. The coupling contract does not care what is, so the conditioner is the place to put the structure of the data, and the later parts of this curriculum do so:
| Data | Conditioner | Where |
|---|---|---|
| vectors | an MLP | here |
| a context, such as a class or an observation | the context joined to the passive half | Part 7 |
| sequences | a network that reads only past values | Part 11 |
| images and spatial fields | a convolutional network, which keeps the spatial layout | Part 12 |
| space-time fields | a network over frames, or over space and time separately | Part 13 |
The triangular Jacobian and the cheap inverse stay the same; only the network that reads changes.
Recap¶
| Knob | Effect here |
|---|---|
| the conditioner holds every weight | its size is the coupling’s size |
| conditioner width | wider fitted better, on the training rows and on the median held-out row, up to width 64, most between widths 8 and 16 |
log_scale_bound | and trained alike; started far higher and fitted worst |
| the conditioner’s architecture | where later parts put the structure of the data |
The transformer sets what shape a coordinate’s map can take; the conditioner sets how that shape follows the rest of the data.
Next. A coupling layer transforms only its active half, so which coordinates are active, and how that changes from layer to layer, matters. Notebook 03 looks at masks.
- 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.