Mask design for coupling flows
A coupling layer touches only its active half, so the mask has to change from layer to layer for every coordinate to be both transformed and used as context
03 · Mask design for coupling flows¶
A coupling layer (1) transforms its active half and copies its passive half (notebook 00). One layer can therefore change only half of the coordinates, and a stack whose layers all use the same split, the same mask, never changes the passive coordinates at all, however deep it is. The mask decides which coordinates are passive, and changing it from layer to layer is what lets a stack of couplings transform every coordinate: each one has to be transformed in some layers and condition the others in the rest.
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.random as jr
import matplotlib.pyplot as plt
import numpy as np
import optax
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 scipy import stats
from sklearn.datasets import make_moons
from gauss_flows_docs.environment import watermark
from gauss_flows_docs.plotting import (
GAUSS_KW,
standard_normal_pdf,
style_ax,
use_compact_figures,
)
from gauss_flows_maps.bijections import 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_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 the two moons of Part 4, standardised and split into training rows and held-out rows, here in float64.
# 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, (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:]]1. The same mask in every layer¶
Write (1) for a stack of coupling layers. If every layer has the same passive half , each copies to its output, and so does the stack:
The flow’s latent then keeps the passive coordinates’ data marginal, and the base scores them as if they were already standard normal. One function builds a stack of mixture-CDF couplings, with or without a flip of the two coordinates after each layer; the flip is the subject of section 2.
# Shapes: layer = K = 4 coupling layers
# user
# f = f_K ∘ … ∘ f_1 with mixture-CDF couplings, optionally a flip Π after each, and an 𝒩(0, I) base
def coupling_stack(key: jax.Array, alternate: bool) -> Transformed:
"""Four mixture-CDF couplings in the density direction, flipped between layers if asked."""
# the layers in the density direction x → z
layers: list = []
for layer_key in jr.split(key, 4):
# today (gauss_flows)
# z_B = Φ⁻¹(F_θ(x_B)) with an 8-component mixture, θ = c_φ(x_A)
layers.append(
MixtureGaussianCDFCoupling(
layer_key, shape=(2,), n_components=8, nn_width=32, nn_depth=2
)
)
if alternate:
# today (flowjax)
# Π, which swaps the two coordinates
layers.append(Flip((2,)))
# today (flowjax)
# p_x(x) = 𝒩(f(x); 0, I) |det J_f(x)|, with f run forwards for the density
return Transformed(StandardNormal((2,)), Invert(Chain(layers)))A fresh coupling is the identity (notebook 00), so both stacks start as the identity and only training can tell them apart. A fresh mixture-CDF coupling has a second problem: its zero readout gives all eight components the same parameters, every component then gets the same gradient, and the layer trains as an affine coupling, a bug in gauss_flows (gauss_flows#265). We break that symmetry by moving every weight of a stack by , with drawn for each weight, before training, with the helper of notebook 00.
# Shapes: leaf = the weight arrays of the flow
# user
# φ ← φ + 0.1 ε with ε ~ N(0, I), for every weight of the flow
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)The training follows Part 4: pipekit-train runs Adam on the mean negative log-likelihood (1), with a one-cycle cosine learning rate peaking at and the gradient clipped to a global norm of 1, for 2,000 steps on batches of 512 rows.
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 = 2,000 training steps; batch (N_b) = 512
# 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=2000, peak_value=3e-3
)
# today (pipekit)
# the held-out rows, with no targets
held_data = ArrayDataset(held_points, ())
# the settings every run shares
loop_settings: dict = {
"optimizer_config": {"name": "adam", "lr": schedule, "clip_norm": 1.0},
"val_dataset": held_data,
"task": FlowNLL(),
"max_steps": 2000,
"steps_per_epoch": 100,
"eval_every_n_steps": 100,
"log_every_n_steps": 100,
"batch_size": 512,
"seed": 1,
}# user
# θ after 2,000 Adam steps on 𝓛(θ)
def train_flow(flow: Transformed) -> Transformed:
"""Train every floating-point array of ``flow`` with the shared settings."""
# today (pipekit)
# the flow as a trainable model, every floating-point array trained
model_op = EquinoxModelOp(flow, trainable=eqx.is_inexact_array)
# today (pipekit)
# the loop over the training rows, which have no targets
loop = TrainingLoop(
model_op,
ArrayDataset(train_points, ()),
callbacks=(History(),),
**loop_settings,
)
# today (pipekit)
# θ after 2,000 steps, held by the model op
trained_op: EquinoxModelOp
trained_op, _ = loop.run()
return trained_op.moduleWe train the fixed-mask stack and map the held-out rows to the latent.
# user
# four couplings that all copy the first coordinate, their weights moved by 0.1 ε
fixed_initial: Transformed = perturb_weights(
coupling_stack(jr.key(0), alternate=False), jr.key(7)
)
# user
# the fixed-mask stack, trained
fixed_flow: Transformed = train_flow(fixed_initial)
LatentPoints = Float[ArrayLike, "held_out latent"]
# today (flowjax)
# zₙ = f(xₙ) for the held-out rows, (held_out, latent)
fixed_latent: LatentPoints = np.asarray(
jax.vmap(fixed_flow.bijection.inverse)(held_points)
)
print(
f"first latent coordinate equal to the first data coordinate: {np.array_equal(fixed_latent[:, 0], held_points[:, 0])}"
)
print(f"held-out NLL: {float(negative_log_likelihood(fixed_flow, held_points)):.3f}")first latent coordinate equal to the first data coordinate: True
held-out NLL: 1.840
After 2,000 steps the first latent coordinate is still the first data coordinate, exactly, as (1) says. The excess kurtosis (2), which is 0 for a normal, shows what that costs: the first data coordinate of two moons is flatter than a normal, and the stack passes it on unchanged.
# user
# the variance and the excess kurtosis γ₂ of each latent coordinate
def describe(name: str, points: LatentPoints) -> None:
"""Print the variance and excess kurtosis of each coordinate of ``points``."""
# today (scipy)
# γ₂,d of each coordinate, (latent)
kurtosis: Float[ArrayLike, " latent"] = stats.kurtosis(points, axis=0)
print(
f"{name}: variances {np.round(points.var(axis=0), 3)}, excess kurtosis {np.round(kurtosis, 3)}"
)
# user
# the data's held-out rows
describe("data ", held_points)
# user
# the fixed-mask latent
describe("fixed-mask latent", fixed_latent)data : variances [1.026 0.963], excess kurtosis [-0.919 -1.171]
fixed-mask latent: variances [1.026 0.999], excess kurtosis [-0.919 0.15 ]
2. Flipping the coordinates between layers¶
The fix is to change the mask from layer to layer. With a permutation of the coordinates after each coupling, here the flip that swaps the two, a coordinate that is passive in one layer is active in the next:
A permutation has , so it adds nothing to the log-determinant (4) and has no parameters: the two stacks have exactly the same parameters, and differ only in which coordinates each coupling transforms.
# today (equinox)
# the trainable numbers of the fixed-mask stack
fixed_count: int = sum(
leaf.size
for leaf in jax.tree.leaves(eqx.filter(fixed_initial, eqx.is_inexact_array))
)
# user
# four couplings with a flip after each, their weights moved by the same 0.1 ε
flipped_initial: Transformed = perturb_weights(
coupling_stack(jr.key(0), alternate=True), jr.key(7)
)
# today (equinox)
# the trainable numbers of the flipped stack
flipped_count: int = sum(
leaf.size
for leaf in jax.tree.leaves(eqx.filter(flipped_initial, eqx.is_inexact_array))
)
print(f"trainable numbers: fixed mask {fixed_count}, flipped {flipped_count}")trainable numbers: fixed mask 7648, flipped 7648
We train the flipped stack with the same settings.
# user
# the flipped stack, trained
flipped_flow: Transformed = train_flow(flipped_initial)
# today (flowjax)
# zₙ = f(xₙ) for the held-out rows, (held_out, latent)
flipped_latent: LatentPoints = np.asarray(
jax.vmap(flipped_flow.bijection.inverse)(held_points)
)# user
# the flipped stack's latent
describe("flipped latent ", flipped_latent)
for name, flow in [("fixed mask", fixed_flow), ("flipped ", flipped_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"
)flipped latent : variances [1.018 0.994], excess kurtosis [-0.103 -0.041]
fixed mask: NLL 1.734 on training rows, 1.840 held out
flipped : NLL 1.549 on training rows, 1.641 held out
fig, axes = plt.subplots(1, 2, figsize=(12, 4.4), sharey=True)
line = np.linspace(-3.5, 3.5, 200)
for ax, points, title, color in [
(axes[0], fixed_latent, "fixed mask", "C3"),
(axes[1], flipped_latent, "flipped between layers", "C2"),
]:
ax.hist(
points[:, 0],
bins=50,
density=True,
color=color,
alpha=0.7,
label="first latent coordinate",
)
ax.plot(line, standard_normal_pdf(line), **GAUSS_KW, label="N(0, 1)")
ax.set(title=title, xlabel="first latent coordinate")
ax.legend()
style_ax(ax)
axes[0].set_ylabel("density")
fig.tight_layout()
plt.show()
Figure 1:Histograms of the first latent coordinate of the held-out rows, against the standard normal density (dashed). With a fixed mask (left) it is the first data coordinate, flat-topped and bumpy; with a flip between layers (right) it is close to the normal.
With the same parameters, flipping the coordinates between layers brings the first latent coordinate close to a standard normal, with an excess kurtosis of −0.10 against the data’s −0.92, and lowers the held-out negative log-likelihood from 1.84 to 1.64 nats. The gap is modest in two dimensions because the fixed-mask stack still models the second coordinate given the first, and loses only the first coordinate’s marginal; with more coordinates, a fixed mask leaves half of them unmodelled. Changing the mask is not a refinement: without it, a coupling flow cannot model part of its input at all.
3. The mask families¶
Which split to use depends on the structure of the data Dinh et al., 2017. For a vector, the channel-wise mask splits the coordinates into a first and a second half, and a permutation between layers changes the split; coupling_gaussianization_flow puts a flip after each coupling when and a random permutation otherwise. For an image, neighbouring pixels are strongly correlated, so a checkerboard mask makes every active pixel’s neighbours passive, and each transformed pixel is conditioned on its surroundings. The figure shows the three patterns; image flows come later in the curriculum.
fig, axes = plt.subplots(1, 3, figsize=(16.5, 4.4))
channel_mask = np.repeat((np.arange(8) >= 4)[None, :].astype(float), 2, axis=0)
axes[0].imshow(channel_mask, cmap="coolwarm", vmin=0, vmax=1, aspect="auto")
axes[0].set(
title="channel-wise, a vector", xlabel="coordinate", xticks=range(8), yticks=[]
)
checkerboard = np.indices((8, 8)).sum(axis=0) % 2
axes[1].imshow(checkerboard, cmap="coolwarm", vmin=0, vmax=1)
axes[1].set(title="checkerboard, an image", xticks=[], yticks=[])
layer_masks = np.array([[0, 0, 1, 1], [1, 1, 0, 0], [0, 0, 1, 1]])
axes[2].imshow(layer_masks, cmap="coolwarm", vmin=0, vmax=1, aspect="auto")
axes[2].set(
title="flipped after each layer",
xlabel="coordinate",
ylabel="layer",
xticks=range(4),
yticks=range(3),
)
fig.tight_layout()
plt.show()
Figure 2:Masks, with passive coordinates (copied, the conditioner’s input) in blue and active coordinates (transformed) in red. Left: a channel-wise mask on 8 coordinates. Centre: a checkerboard mask on an 8 × 8 image. Right: a channel-wise mask on 4 coordinates over three layers, flipped after each, so every coordinate is active in some layer.
Recap¶
| Piece | Equation | In code |
|---|---|---|
| a fixed mask copies the passive half through the whole stack | (1) | couplings chained with no permutation |
| a permutation between layers changes the mask | (2) | Flip for , Permute otherwise |
| a permutation costs nothing | (4) | no parameters, log-determinant 0 |
| channel-wise and checkerboard masks | (1) | vectors and images |
| training | (1) | pipekit-train’s TrainingLoop on negative_log_likelihood |
Next. With the pattern, the transformers, the conditioners and the masks in hand, notebook 04 compares coupling flows with the diagonal flows of Part 4 at matched parameter counts.
- Dinh, L., Sohl-Dickstein, J., & Bengio, S. (2017). Density Estimation using Real NVP. International Conference on Learning Representations (ICLR).