The transformer menu for coupling
Affine, mixture CDF, deep sigmoid and rational-quadratic spline: the one-dimensional maps a coupling layer can wrap, and what each buys
01 · The transformer menu for coupling¶
Notebook 00 showed that a coupling layer (1) keeps its triangular Jacobian and its cheap inverse whatever its transformer is, as long as acts on each active coordinate on its own and is monotone. The transformer and the conditioner are separate choices. This notebook keeps the conditioner fixed, an MLP of width 32 and depth 2, and goes through the four transformers of gauss_flows:
| Transformer | Inverse | Layer | |
|---|---|---|---|
| affine | (2) | closed form | AffineCoupling, as in RealNVP Dinh et al., 2017 |
| mixture CDF | with the mixture CDF (2) | bisection | MixtureGaussianCDFCoupling |
| deep sigmoid | (1) | bisection | DeepSigmoidCoupling |
| rational-quadratic spline | (2) | closed form (4) | RQSplineCoupling, as in neural spline flows Durkan et al., 2019 |
The deep sigmoid is the single-layer sigmoidal transformer of neural autoregressive flows Huang et al., 2018: a positive-slope line plus sigmoid steps,
where is the logistic sigmoid, are scales and slopes, and are shifts. Each term is increasing, so is monotone.
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 AbstractBijection, 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 SCATTER_KW, style_ax, use_compact_figures
from gauss_flows_maps.bijections import (
AffineCoupling,
DeepSigmoidCoupling,
HouseholderRotation,
MixtureGaussianCDFCoupling,
RQSplineCoupling,
)
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. Each transformer is a map of one coordinate¶
We work in two dimensions, : the first coordinate is passive and the second active. Every layer gets the same conditioner, an MLP of width 32 and depth 2; the mixture and the deep sigmoid use components, the spline 8 bins on .
# Shapes: state (D_x) = 2; passive (D_A) = 1; active (D_B) = 1
# today (gauss_flows)
# the four transformers, each with its layer class and its options
transformers: dict = {
"affine": (AffineCoupling, {}),
"mixture CDF": (MixtureGaussianCDFCoupling, {"n_components": 8}),
"deep sigmoid": (DeepSigmoidCoupling, {"n_components": 8}),
"RQ spline": (RQSplineCoupling, {"n_bins": 8, "interval": 4.0}),
}
# user
# a coupling layer on D_x = 2 with the named transformer and a width-32, depth-2 MLP as c_φ
def make_coupling(name: str, key: Key[ArrayLike, ""]) -> AbstractBijection:
"""A fresh 2-D coupling layer with the named transformer."""
layer_class: type
options: dict
# the layer class and the options of the named transformer
layer_class, options = transformers[name]
# today (gauss_flows)
# the layer, with a width-32, depth-2 MLP as c_φ
return layer_class(key, shape=(2,), nn_width=32, nn_depth=2, **options)A fresh coupling’s conditioner returns the transformer’s initial parameters for every input (notebook 00). We fix the passive coordinate at , sweep the active one and read off .
# Shapes: test = 200 values of the active coordinate
PerTestPoint = Float[ArrayLike, " test"]
# x_B on [−3, 3], (test)
active_values: PerTestPoint = np.linspace(-3, 3, 200)
# the points (x_A, x_B) with x_A = 0.7, (test, state)
sweep_points: Float[ArrayLike, "test state"] = np.column_stack(
[np.full(200, 0.7), active_values]
)
# user
# z_B = T_θ(x_B) at x_A = 0.7, the active output of the layer along the sweep, (test)
def active_map(layer: AbstractBijection) -> PerTestPoint:
"""The layer's active output along the sweep."""
return np.asarray(jax.vmap(layer.transform)(jnp.asarray(sweep_points))[:, 1])# user
# max |T_θ(x_B) − x_B| of each fresh layer along the sweep
for name in transformers:
# user
# z_B = T_θ(x_B) of the fresh layer, (test)
fresh_map: PerTestPoint = active_map(make_coupling(name, jr.key(3)))
print(
f"{name:12s}: max |z_B - x_B| = {np.abs(fresh_map - active_values).max():.3f}"
)affine : max |z_B - x_B| = 0.000
mixture CDF : max |z_B - x_B| = 0.000
deep sigmoid: max |z_B - x_B| = 7.621
RQ spline : max |z_B - x_B| = 0.000
Three of the fresh layers are the identity. The deep sigmoid is not: its initial parameters are and , so a fresh layer maps to , which adds up to to every active coordinate. This is deliberate (the layer’s source says its initial transformer is not the identity map), and training moves it like any other start.
To see the shapes a trained transformer can take, we move every weight of each layer by a random amount, as in notebook 00, and measure how far each map is from its best straight line.
# Shapes: leaf = the weight arrays of a layer
# user
# φ ← φ + 0.3 ε with ε ~ N(0, I), for every weight of the layer
def perturb_weights(
layer: eqx.Module, key: jax.Array, scale: float = 0.3
) -> 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
# z_B = T_θ(x_B) of each layer with random weights, (test) per transformer
random_maps: dict = {
name: active_map(perturb_weights(make_coupling(name, jr.key(3)), jr.key(4)))
for name in transformers
}
# user
# max |T_θ(x_B) − (a x_B + b)|, the distance from the least-squares line a x_B + b
for name, random_map in random_maps.items():
# a x_B + b, the least-squares line through the map, (test)
line: PerTestPoint = np.polyval(
np.polyfit(active_values, random_map, 1), active_values
)
print(
f"{name:12s}: distance from a straight line {np.abs(random_map - line).max():.3f}"
)affine : distance from a straight line 0.000
mixture CDF : distance from a straight line 0.597
deep sigmoid: distance from a straight line 1.326
RQ spline : distance from a straight line 0.691
The affine transformer is a straight line to machine precision: a coupling with an affine transformer can only scale and shift a coordinate. The mixture CDF and the spline bend into smooth monotone curves, and the deep sigmoid bends most, from a start that already sits far from the identity. All four stay increasing, as they must to be invertible.
2. The family of maps the conditioner can choose from¶
The conditioner reads and returns , so as moves the layer sweeps a whole family of one-dimensional maps. That family, not one map, is what a single layer can express. For the affine transformer it is a family of lines (the conditioner picks a slope and an intercept); for the spline it is a family of monotone curves.
# Shapes: context = 7 values of the passive coordinate
# x_A on [−2, 2], (context)
passive_values: Float[ArrayLike, " context"] = np.linspace(-2, 2, 7)
# user
# z_B = T_{θ(x_A)}(x_B) for every x_A, (context, test)
def map_family(layer: AbstractBijection) -> Float[ArrayLike, "context test"]:
"""The layer's active output along the sweep, one row per passive value."""
# the maps, one row per value of x_A
rows: list = []
for passive in passive_values:
# the points (x_A, x_B) at this x_A, (test, state)
points: Float[ArrayLike, "test state"] = np.column_stack(
[np.full(200, passive), active_values]
)
rows.append(np.asarray(jax.vmap(layer.transform)(jnp.asarray(points))[:, 1]))
return np.stack(rows)The affine panel is a sheaf of straight lines, so non-linear dependence between coordinates can only be built up over many stacked layers. In the spline panel each value of gives a different curve, so one layer can already make a non-linear, context-dependent change. That is the case for expressive transformers: they need fewer layers.
3. Fitting a spiral with two coupling blocks¶
We make this concrete on a two-arm spiral, standardised, with training rows and held-out rows. With only two coupling blocks, the transformer, not the depth, decides the fit.
# 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:]]Each block is a rotation followed by two couplings with a flip between them, so both coordinates are transformed once per block. The rotation is a HouseholderRotation with random vectors, since its default vectors are all equal and it would start as the identity (gauss_flows#239). The base is a fixed standard normal.
# 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)A fresh mixture-CDF or deep-sigmoid coupling has all its components equal, and because its conditioner’s last layer starts at zero they stay equal through training: the mixture CDF trains as one Gaussian, which is an affine map, and the deep sigmoid as a line plus one sigmoid, with its units unable to move apart (gauss_flows#265); until that is fixed we move every weight of those two layers by 0.1 times a standard-normal draw with perturb_weights before training, and leave the affine and spline layers as they are.
# user
# C, with φ ← φ + 0.1 ε for the transformers whose fresh components are equal (gauss_flows#265)
def make_trainable_coupling(name: str, key: Key[ArrayLike, ""]) -> AbstractBijection:
"""The named coupling, with its symmetry broken for the mixture CDF and the deep sigmoid."""
# user
# the fresh layer
layer: AbstractBijection = make_coupling(name, key)
if name in ("mixture CDF", "deep sigmoid"):
# user
# φ ← φ + 0.1 ε, so the components differ
return perturb_weights(layer, jr.fold_in(key, 1), scale=0.1)
return layer# user
# f = (flip ∘ C₂ ∘ flip ∘ C₁ ∘ Q)₂ ∘ (flip ∘ C₂ ∘ flip ∘ C₁ ∘ Q)₁, with a standard-normal base
def build_flow(name: str, key: Key[ArrayLike, ""]) -> Transformed:
"""A flow of two coupling blocks with the named transformer."""
# the bijections of the flow, in the density direction
blocks: list = []
# two blocks, each with a key for its rotation and one for each coupling
for rotation_key, first_key, second_key in jr.split(key, (2, 3)):
# user
# Q, then C₁, a flip, C₂ and a flip back
blocks += [
random_rotation(rotation_key),
make_trainable_coupling(name, first_key),
Flip(shape=(2,)),
make_trainable_coupling(name, second_key),
Flip(shape=(2,)),
]
return Transformed(StandardNormal((2,)), Invert(Chain(blocks)))Training follows Part 4: pipekit-train fits the mean negative log-likelihood (1) with Adam on a one-cycle cosine rate peaking at , the gradient clipped to a global norm of 1, for 1,500 steps of 512 rows.
# 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,500 training steps; epoch = 15 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=1500, 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": 1500,
"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)
# user
# θ after 1,500 Adam steps on 𝓛(θ)
def train_flow(flow: Transformed) -> Transformed:
"""Train ``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 training loop of this flow
loop = TrainingLoop(
EquinoxModelOp(flow, trainable=trainable),
ArrayDataset(train_points, ()),
callbacks=(History(),),
**loop_settings,
)
# today (pipekit)
# θ after 1,500 steps, held by the model op
trained_op: EquinoxModelOp
trained_op, _ = loop.run()
return trained_op.module# user
# one trained flow of two coupling blocks per transformer
trained_flows: dict = {
name: train_flow(build_flow(name, jr.key(0))) for name in transformers
}We compare the mean negative log-likelihood on the training rows and on the held-out rows, and also the median over the held-out rows, which one badly fitted point cannot move.
# user
# −log p_x(xₙ) of every held-out row, per transformer, (held_out) each
held_nll: dict = {
name: -np.asarray(jax.vmap(flow.log_prob)(jnp.asarray(held_points)))
for name, flow in trained_flows.items()
}
for name, flow in trained_flows.items():
# today (gauss_flows)
# 𝓛 = −(1/N_t) ∑ₙ log p_x(xₙ) on the training rows
train_loss: Scalar = negative_log_likelihood(flow, jnp.asarray(train_points))
print(
f"{name:12s}: NLL {float(train_loss):.3f} on training rows, {held_nll[name].mean():.3f} held out (median {np.median(held_nll[name]):.3f}, worst {held_nll[name].max():.1f})"
)affine : NLL 2.418 on training rows, 2.518 held out (median 2.403, worst 28.6)
mixture CDF : NLL 1.620 on training rows, 1.695 held out (median 1.605, worst 9.2)
deep sigmoid: NLL 2.388 on training rows, 2.433 held out (median 2.379, worst 8.3)
RQ spline : NLL 1.541 on training rows, 1.595 held out (median 1.527, worst 6.3)
The spline fits best, with 1.54 nats on the training rows and 1.60 held out, and the mixture CDF comes close behind, with 1.62 and 1.70. The deep sigmoid (2.39 and 2.43) and the affine transformer (2.42 and 2.52) end about 0.8 nats behind them. Every flow has a few held-out rows it fits much worse than the rest (the worst column, from 6.3 nats for the spline to 28.6 for the affine flow), which is why we also give the median.
The densities show the difference between the transformers at a glance.
# Shapes: test = 120 × 120 grid points
# one axis of the grid, (test)
grid_axis: Float[ArrayLike, " test"] = np.linspace(-2.5, 2.5, 120)
# the grid points, (test, state)
grid_points: Float[ArrayLike, "test state"] = np.stack(
np.meshgrid(grid_axis, grid_axis), axis=-1
).reshape(-1, 2)
# today (flowjax)
# p_x on the grid for each trained flow, (test) per transformer
grid_density: dict = {
name: np.exp(np.asarray(jax.vmap(flow.log_prob)(jnp.asarray(grid_points))))
for name, flow in trained_flows.items()
}With two blocks, the spline and the mixture CDF put their mass on the two arms. The affine and deep-sigmoid flows fill a disc around the spiral and catch only parts of the outer arm. An affine map of each coordinate is a line, so its flow needs more blocks to follow the arms; the deep sigmoid can bend (the random-weight maps above), yet with two blocks and 1,500 steps its flow does not follow them either.
Recap¶
| Transformer | Map of one coordinate | Inverse | Here |
|---|---|---|---|
| affine (2) | a line | closed form | the cheapest; needs depth for non-linear dependence |
| mixture CDF (2) | a smooth monotone curve | bisection | close behind the spline, once its weights are moved off their symmetric start (gauss_flows#265) |
| deep sigmoid (1) | a line plus sigmoid steps | bisection | does not start as the identity; also needs its weights moved (gauss_flows#265), and ends close to the affine transformer here |
| rational-quadratic spline (2) | a piecewise rational-quadratic curve | closed form (4) | the best fit with two blocks |
The transformer sets what shape one coordinate’s map can take. The other half of a coupling layer, the conditioner, sets how that shape changes with the passive coordinates.
Next. Notebook 02 keeps the transformer fixed and changes the conditioner: its size, the bound on the log-scales it returns, and the networks that later parts put in its place.
- Dinh, L., Sohl-Dickstein, J., & Bengio, S. (2017). Density Estimation using Real NVP. International Conference on Learning Representations (ICLR).
- Durkan, C., Bekasov, A., Murray, I., & Papamakarios, G. (2019). Neural Spline Flows. Advances in Neural Information Processing Systems (NeurIPS).
- Huang, C.-W., Krueger, D., Lacoste, A., & Courville, A. (2018). Neural Autoregressive Flows. International Conference on Machine Learning (ICML).


