Three ways to condition a flow
A conditional Gaussianizer maps every slice p(x | y) to the same N(0, I); the context y can enter at the base, in the couplings, or through a modulation wrapped around any layer
00 · Three ways to condition a flow¶
Every flow of Parts 4 to 6 learned one density . Here the flow’s parameters become functions of a context , so one model holds a whole family of densities Winkler et al., 2019, and its map sends every slice of that family to the same : a conditional Gaussianizer. Training, sampling and the log-determinant are unchanged; what changes is where the context enters. The conditional-flow example fits the same four variants (no context, the base, the couplings, both) on two moons and ranks them on the training rows; here we rank them on held-out rows, add the Conditioner wrapper as a fifth, ask how Gaussian each class’s latent is, test the rule of thumb on a pair of crescents that differ only by a shift, and look inside the conditioning layers.
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
from flowjax.bijections import Chain, Flip, Identity, Invert, Scan
from flowjax.distributions import StandardNormal, Transformed
from jaxtyping import ArrayLike, Float
from pipekit_train import ArrayDataset, 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 (
DATA_COLOR,
LATENT_COLOR,
SCATTER_KW,
style_ax,
use_compact_figures,
)
from gauss_flows_maps.bijections import RQSplineCoupling
from gauss_flows_maps.conditioning import (
AffineModulation,
ConcatConditioner,
Conditioner,
HyperLinear,
pack_time_control,
zero_readout,
)
from gauss_flows_models.distributions import ConditionalDiagGaussian
from gauss_flows_models.inference import negative_log_likelihood
from gauss_flows_models.info_theory import gaussian_kl_divergence
jax.config.update("jax_enable_x64", True)
np.set_printoptions(precision=3, suppress=True)
# 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. Class-conditional two moons¶
The two moons of Parts 4 and 5, but this time we keep the label make_moons returns: for the upper crescent and for the lower one. The context is the one-hot label , so , and each slice is one crescent. The two crescents differ in position and in shape, since the lower one is the upper one turned upside down.
# Shapes: sample (N) = 3,000; state (D_x) = 2; context (D_y) = 2
SampleState = Float[ArrayLike, "sample state"]
SampleContext = Float[ArrayLike, "sample context"]
# today (sklearn)
# x ~ two moons with noise 0.06, and the crescent y ∈ {0, 1} of each point, (sample, state), (sample)
raw_points: SampleState
labels: Float[ArrayLike, " sample"]
raw_points, labels = make_moons(n_samples=3000, noise=0.06, random_state=0)
# x̄, the mean of each coordinate, (state)
moons_mean: Float[ArrayLike, " state"] = raw_points.mean(axis=0)
# s, the standard deviation of each coordinate, (state)
moons_std: Float[ArrayLike, " state"] = raw_points.std(axis=0)
# x ← (x − x̄) / s, coordinate by coordinate, (sample, state)
moons_points: SampleState = (raw_points - moons_mean) / moons_std
# y = onehot(y), (sample, context)
moons_contexts: SampleContext = np.eye(2)[labels]A fixed shuffle holds out 600 rows; every flow trains on the other 2,400.
# Shapes: train (N_t) = 2,400; held_out (N_v) = 600
# a fixed permutation of the rows, (sample)
row_order: Float[ArrayLike, " sample"] = np.random.default_rng(0).permutation(3000)
# user
# the training rows and the held-out rows of one dataset
def split_rows(points: SampleState, contexts: SampleContext) -> dict:
"""The first 2,400 shuffled rows for training and the last 600 held out."""
# the indices of the training rows, (train)
train_rows: Float[ArrayLike, " train"] = row_order[:2400]
# the indices of the held-out rows, (held_out)
held_rows: Float[ArrayLike, " held_out"] = row_order[2400:]
return {
"train": (points[train_rows], contexts[train_rows]),
"held_out": (points[held_rows], contexts[held_rows]),
}
# user
# the moons, split once
moons_data: dict = split_rows(moons_points, moons_contexts)
print({part: rows[0].shape for part, rows in moons_data.items()}){'train': (2400, 2), 'held_out': (600, 2)}
fig, ax = plt.subplots(figsize=(5, 4.5))
for label, color in ((0, DATA_COLOR), (1, LATENT_COLOR)):
in_class: Float[ArrayLike, " sample"] = labels == label
ax.scatter(
*moons_points[in_class].T, color=color, label=f"y = {label}", **SCATTER_KW
)
ax.set(xlabel="x₁", ylabel="x₂", title="two moons by label", aspect="equal")
ax.legend()
style_ax(ax)
fig.tight_layout()
plt.show()
Figure 1:Two moons coloured by the crescent each point belongs to. The label is the context: each slice p(x | y) is one crescent.
2. Where the context can enter¶
Write for the flow’s map from data to latent at context . For each fixed it is a bijection, so the change of variables holds slice by slice:
where is the Jacobian of in alone. The context can enter in three places.
The base can depend on it. ConditionalDiagGaussian is a diagonal Gaussian whose mean and standard deviations come from a small network of the context:
The couplings can read it. A coupling’s conditioner already reads the passive half (Part 5); RQSplineCoupling(cond_dim=D_y) also gives it the context, so the spline of the active half changes shape from one context to another:
The Jacobian stays triangular, so the log-determinant is still a sum. Any other layer can be wrapped. Conditioner takes a bijection that cannot read a context (a rotation, a normalisation, or here the identity) and modulates its output feature by feature, which adds to its log-determinant:
This is FiLM, feature-wise linear modulation, and it is also how ConditionalDiagGaussian makes its mean and scale: both use AffineModulation, whose readout starts at zero so that and for every context. We compare five flows that differ only in where the context goes:
| flow | base | couplings | data side | what the context can change |
|---|---|---|---|---|
| none | unconditional | nothing: it fits the mixture of both crescents | ||
| base | (2) | unconditional | an affine map of the latent per context | |
| coupling | (3) | the shape of every coupling’s spline | ||
| both | (2) | (3) | both | |
| wrapper | unconditional | (4) on the identity | an affine map of the data per context |
Every flow has four rational-quadratic spline couplings Durkan et al., 2019 with 8 bins on and a two-layer conditioner of width 64, with a flip after each so both coordinates are transformed. The four blocks share one type, so they are built at once with eqx.filter_vmap and applied in turn by FlowJax’s Scan.
# Shapes: layer = 4 coupling blocks
# user
# f = (Π ∘ f₄) ∘ … ∘ (Π ∘ f₁) in the density direction, each fₖ a spline coupling, θ = c_φ(x_A) or c_φ(x_A, y)
def coupling_stack(key: jax.Array, context_dim: int | None) -> Scan:
"""Four spline couplings, each followed by a flip, reading the context if ``context_dim`` is set."""
# user
# one block: a spline coupling, then Π, which swaps the two coordinates
def block(block_key: jax.Array) -> Chain:
# today (gauss_flows)
# z_B = T_θ(x_B) with an 8-bin spline, θ = c_φ(x_A) or c_φ(x_A, y)
coupling = RQSplineCoupling(
block_key, shape=(2,), n_bins=8, interval=4.0, cond_dim=context_dim
)
# today (flowjax)
# the coupling, then Π
return Chain([coupling, Flip((2,))])
# today (equinox)
# the four blocks stacked on a leading axis
blocks: Chain = eqx.filter_vmap(block)(jr.split(key, 4))
# today (flowjax)
# the blocks applied in turn
return Scan(blocks)conditional_flow assembles one of the five flows. FlowJax’s Transformed runs its bijection in the sampling direction, so the density-direction map is wrapped in Invert, as in Part 5.
# user
# p(x | y) of one of the five flows
def conditional_flow(kind: str, key: jax.Array) -> Transformed:
"""The flow called ``kind``: none, base, coupling, both or wrapper."""
# one key for the couplings, the base and the wrapper
keys: jax.Array = jr.split(key, 3)
# user
# f, the four couplings, reading y for coupling and both
density_map: Scan = coupling_stack(
keys[0], 2 if kind in ("coupling", "both") else None
)
if kind == "wrapper":
# today (gauss_flows, flowjax)
# h' = γ(y) ⊙ x + β(y), then f
density_map = Chain(
[Conditioner(keys[2], inner=Identity((2,)), cond_dim=2), density_map]
)
# today (flowjax)
# p_z(z) = 𝒩(0, I)
base = StandardNormal((2,))
if kind in ("base", "both"):
# today (gauss_flows)
# p_z(z | y) = 𝒩(β(y), diag γ(y)²)
base = ConditionalDiagGaussian(keys[1], event_shape=(2,), cond_dim=2)
# today (flowjax)
# p(x | y) by the change of variables, f run forwards for the density
return Transformed(base, Invert(density_map))Each of the three conditional pieces starts where it would be without the context: the couplings’ readouts start at zero (zero_readout, Part 5), and AffineModulation starts at , . With an even number of flips, every fresh flow is then the identity map with a standard-normal base, whatever the context. We check it on the training rows.
# the names of the five flows
FLOW_KINDS: tuple = ("none", "base", "coupling", "both", "wrapper")
# user
# the five fresh flows, with one key for all
fresh_flows: dict = {kind: conditional_flow(kind, jr.key(11)) for kind in FLOW_KINDS}
# the training rows and their contexts, (train, state), (train, context)
train_points: Float[ArrayLike, "train state"]
train_contexts: Float[ArrayLike, "train context"]
train_points, train_contexts = moons_data["train"]
# today (flowjax)
# 𝒩(0, I) on the plane
standard_normal = StandardNormal((2,))
# today (flowjax)
# log 𝒩(x; 0, I) of each training row, (train)
standard_log_density: Float[ArrayLike, " train"] = standard_normal.log_prob(
train_points
)# user
# the number of floating-point weights of a module
def weight_count(module: eqx.Module) -> int:
"""How many floating-point numbers ``module`` holds."""
# today (equinox)
# the floating-point leaves of the module
leaves: list = jax.tree.leaves(eqx.filter(module, eqx.is_inexact_array))
return sum(leaf.size for leaf in leaves)
for kind, flow in fresh_flows.items():
# today (flowjax)
# log p(x | y) of each training row, (train)
log_density: Float[ArrayLike, " train"] = flow.log_prob(
train_points, train_contexts
)
# max over the rows of |log p(x | y) − log 𝒩(x; 0, I)|
gap: float = float(jnp.abs(log_density - standard_log_density).max())
print(f"{kind:>8}: {weight_count(flow):6,} weights, max gap {gap:.1e}") none: 24,432 weights, max gap 1.3e-15
base: 29,044 weights, max gap 3.1e-08
coupling: 24,944 weights, max gap 1.3e-15
both: 29,556 weights, max gap 3.1e-08
wrapper: 29,044 weights, max gap 1.3e-15
Every fresh flow is the identity with a standard-normal base. Three agree with to 10-15; the two with a conditional base differ by , because ConditionalDiagGaussian keeps in float32 when float64 is switched on after the import, as it is here (gauss_flows#272). The context costs few weights: the conditional base and the wrapper each add 4,612 to the 24,432 of the couplings, and the conditional couplings add 512, one more input to each conditioner’s first layer per context coordinate.
3. Training all five¶
Every flow minimises the same loss, the mean negative conditional log-likelihood of a batch, by (1). negative_log_likelihood takes the batch’s contexts as its condition, so the task is the one of Part 4 with the context passed through.
Scalar = Float[ArrayLike, ""]
# user
# pipekit-train's task: the conditional 𝓛(θ) of one batch
class ConditionalNLL:
"""pipekit-train's task: the mean negative conditional log-likelihood of a batch."""
# user
# 𝓛(θ) = −(1/N_b) ∑ₙ log p(xₙ | yₙ; θ), also logged
def loss_fn(self, flow, batch, key):
# the points of the batch and their contexts, (batch, state), (batch, context)
batch_points: Float[ArrayLike, "batch state"]
batch_contexts: Float[ArrayLike, "batch context"]
batch_points, batch_contexts = batch
# today (gauss_flows)
# −(1/N_b) ∑ₙ log p(xₙ | yₙ; θ)
loss: Scalar = negative_log_likelihood(
flow, batch_points, condition=batch_contexts
)
return loss, {"loss": loss}Each run takes 2,000 Adam steps of 256 rows on a one-cycle cosine rate that peaks at , with the gradient clipped to a global norm of 1.
# Shapes: step = 2,000 training steps; batch (N_b) = 256
# today (optax)
# the learning rate of each step: up to 5 × 10⁻³, then down to almost zero
schedule: optax.Schedule = optax.cosine_onecycle_schedule(
transition_steps=2000, peak_value=5e-3
)
# the settings every run shares
loop_settings: dict = {
"optimizer_config": {"name": "adam", "lr": schedule, "clip_norm": 1.0},
"task": ConditionalNLL(),
"max_steps": 2000,
"steps_per_epoch": 100,
"log_every_n_steps": 100,
"batch_size": 256,
"seed": 1,
}# user
# θ after 2,000 Adam steps on 𝓛(θ)
def train_flow(flow: Transformed, data: dict) -> Transformed:
"""Train every floating-point array of ``flow`` on the training rows of ``data``."""
# 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 training rows, with their contexts as the targets
train_set = ArrayDataset(*data["train"])
# today (pipekit)
# θ after 2,000 steps, held by the model op
trained_op: EquinoxModelOp
trained_op, _ = TrainingLoop(model_op, train_set, **loop_settings).run()
return trained_op.module# user
# the five flows trained on the moons
moons_flows: dict = {
kind: train_flow(flow, moons_data) for kind, flow in fresh_flows.items()
}
# user
# −(1/N_v) ∑ₙ log p(xₙ | yₙ) on the held-out rows
def held_out_nll(flow: Transformed, data: dict) -> float:
"""The mean negative conditional log-likelihood of the held-out rows."""
# today (gauss_flows)
# 𝓛 on the held-out rows and their contexts
return float(
negative_log_likelihood(
flow, data["held_out"][0], condition=data["held_out"][1]
)
)
# user
# the held-out NLL of each flow
moons_nll: dict = {
kind: held_out_nll(flow, moons_data) for kind, flow in moons_flows.items()
}
for kind, value in moons_nll.items():
print(f"{kind:>8}: held-out NLL {value:.3f} nats") none: held-out NLL 1.374 nats
base: held-out NLL 0.659 nats
coupling: held-out NLL 0.663 nats
both: held-out NLL 0.666 nats
wrapper: held-out NLL 1.234 nats
The held-out rows are the same for every flow, so the standard error of a difference between two flows comes from the row-by-row differences of their log-densities, which is much smaller than the spread of either.
PerHeldOut = Float[ArrayLike, " held_out"]
# user
# the mean of log p_a(xₙ | yₙ) − log p_b(xₙ | yₙ) over the held-out rows, and its standard error
def paired_gap(
flow_a: Transformed, flow_b: Transformed, data: dict
) -> tuple[float, float]:
"""How many nats ``flow_b`` beats ``flow_a`` by on the held-out rows, and the standard error."""
# the held-out rows and their contexts, (held_out, state), (held_out, context)
held_points: Float[ArrayLike, "held_out state"]
held_contexts: Float[ArrayLike, "held_out context"]
held_points, held_contexts = data["held_out"]
# today (flowjax)
# log p_b(xₙ | yₙ) − log p_a(xₙ | yₙ), (held_out)
gaps: PerHeldOut = flow_b.log_prob(held_points, held_contexts)
gaps = gaps - flow_a.log_prob(held_points, held_contexts)
return float(gaps.mean()), float(gaps.std() / np.sqrt(len(gaps)))Here is how much better the base-conditioned flow does than each of the others on the moons.
for kind in ("coupling", "both", "wrapper"):
# user
# how much better base does than this flow, and the standard error
gap: float
error: float
gap, error = paired_gap(moons_flows[kind], moons_flows["base"], moons_data)
print(f"base against {kind:>8}: {gap:+.3f} ± {error:.3f} nats per row")base against coupling: +0.003 ± 0.008 nats per row
base against both: +0.007 ± 0.007 nats per row
base against wrapper: +0.575 ± 0.017 nats per row
The flow with no context is far behind, at 1.374 nats against 0.659 to 0.666 for the three that read the context through the base or the couplings. The gap of 0.715 nats is close to , which is what the label is worth here: the two crescents do not overlap and are equally likely, so where one has density the marginal is half of . The wrapper recovers only part of it, at 1.234 nats.
The base, the couplings and both tie: the base is ahead of the couplings by 0.003 ± 0.008 nats per row and of both by 0.007 ± 0.007, within one standard error, and ahead of the wrapper by 0.575 ± 0.017. The conditional-flow example trains differently (5,000 rows with less noise, a constant rate and early stopping, in float32), and its run puts the base-only flow well behind the coupling flow on its training rows (-0.816 against -0.440 nats; its training keys change from one execution to the next, gauss_flows#274). On these rows and with this schedule the base keeps up.
Sampling runs each flow the other way: draw , then . We draw 1,000 points for each label from each flow.
# Shapes: test = 1,000 draws per label
# user
# x = f⁻¹(z; y) with z ~ p_z(· | y), for each label
def draws_by_label(flow: Transformed, key: jax.Array) -> list:
"""1,000 draws from ``flow`` for each of the two labels."""
# the draws of each label
draws: list = []
for label in (0, 1):
# y = onehot(label), (context)
context: Float[ArrayLike, " context"] = jnp.eye(2)[label]
# today (flowjax)
# 1,000 draws at y, (test, state)
samples: Float[ArrayLike, "test state"] = flow.sample(
jr.fold_in(key, label), (1000,), condition=context
)
draws.append(samples)
return drawsfig, axes = plt.subplots(2, 5, figsize=(15, 6.4), sharex=True, sharey=True)
for column, (kind, flow) in enumerate(moons_flows.items()):
for label, samples in enumerate(draws_by_label(flow, jr.key(100))):
ax = axes[label, column]
ax.scatter(
*train_points[train_contexts[:, label] == 1].T, color="0.75", **SCATTER_KW
)
ax.scatter(
*np.asarray(samples).T,
color=(DATA_COLOR, LATENT_COLOR)[label],
**SCATTER_KW,
)
ax.set(
xlim=(-2.5, 2.5),
ylim=(-2.5, 2.5),
aspect="equal",
title=f"{kind}, y = {label}",
)
style_ax(ax)
fig.tight_layout()
plt.show()
Figure 2:Draws of each trained flow for each label (colour) over the training rows of that label (grey). The flow with no context draws both crescents for both labels; base, coupling and both put the draws of each label on its crescent; the wrapper adds a branch across the other crescent.
The draws tell the same story. With no context, each label gets both crescents. The base, the couplings and both put each label’s draws on its own crescent and nowhere else. The wrapper can only move and stretch the data before one shared map, and it cannot turn the upper crescent into the lower one, so each label gets its crescent plus a branch across the other.
4. How Gaussian is each slice?¶
A conditional Gaussianizer should send each slice to , not only the mixture of all of them. For the flows with a conditional base, the latent follows (2), so we standardise it first; for the others the latent is already the standardised one:
For each label we send its held-out rows through, fit a Gaussian to the by their sample mean and covariance, and measure that Gaussian’s KL divergence from with gaussian_kl_divergence. It is zero when the first two moments match and says nothing about higher ones, so it is a floor on how far each slice is from the target.
# user
# z̃ = (f(x; y) − β(y)) ⊘ γ(y) for each row, with β = 0 and γ = 1 for a standard-normal base
def standardised_latents(
flow: Transformed, points: SampleState, contexts: SampleContext
) -> SampleState:
"""The latent of each row, standardised by the base when the base is conditional."""
# today (flowjax)
# z = f(x; y), (sample, latent)
latents: Float[ArrayLike, "sample latent"] = jax.vmap(flow.bijection.inverse)(
points, contexts
)
if not isinstance(flow.base_dist, ConditionalDiagGaussian):
return latents
# today (gauss_flows)
# γ(y) and β(y) of each row, (sample, latent), (sample, latent)
scales: Float[ArrayLike, "sample latent"]
shifts: Float[ArrayLike, "sample latent"]
scales, _, shifts = jax.vmap(flow.base_dist.modulation.modulation)(contexts)
return (latents - shifts) / scalesThe KL of a slice is then a closed form in the sample moments of its standardised latent.
LatentMatrix = Float[ArrayLike, "latent latent"]
# user
# KL[𝒩(m̂_z̃, Σ̂_z̃) ‖ 𝒩(0, I)] for the rows of one label
def slice_kl(flow: Transformed, points: SampleState, contexts: SampleContext) -> float:
"""KL[𝒩(m̂_z̃, Σ̂_z̃) ‖ 𝒩(0, I)] of the standardised latent of the rows of one label."""
# user
# z̃ of each row, (sample, latent)
latents: Float[ArrayLike, "sample latent"] = standardised_latents(
flow, points, contexts
)
# Σ̂_z̃, the sample covariance divided by N, (latent, latent)
covariance: LatentMatrix = jnp.cov(latents.T, bias=True)
# today (gauss_flows)
# KL[𝒩(m̂_z̃, Σ̂_z̃) ‖ 𝒩(0, I)]
divergence: Scalar = gaussian_kl_divergence(
latents.mean(axis=0), covariance, jnp.zeros(2), jnp.eye(2)
)
return float(divergence)# user
# the KL of each label's held-out slice, for each flow
def slice_kls(flows: dict, data: dict) -> dict:
"""The two slice KLs of every flow, on the held-out rows of ``data``."""
# the held-out rows and their contexts, (held_out, state), (held_out, context)
held_points: Float[ArrayLike, "held_out state"]
held_contexts: Float[ArrayLike, "held_out context"]
held_points, held_contexts = data["held_out"]
# the held-out rows of each label
label_rows: list = [held_contexts[:, label] == 1 for label in (0, 1)]
# user
# the KL of the slice of each label, for each flow
return {
kind: [
slice_kl(flow, held_points[rows], held_contexts[rows])
for rows in label_rows
]
for kind, flow in flows.items()
}# user
# the slice KLs of the moons flows
moons_kls: dict = slice_kls(moons_flows, moons_data)
for kind, (upper, lower) in moons_kls.items():
print(
f"{kind:>8}: KL of the y = 0 slice {upper:.3f}, of the y = 1 slice {lower:.3f} nats"
) none: KL of the y = 0 slice 0.487, of the y = 1 slice 0.486 nats
base: KL of the y = 0 slice 0.006, of the y = 1 slice 0.005 nats
coupling: KL of the y = 0 slice 0.008, of the y = 1 slice 0.007 nats
both: KL of the y = 0 slice 0.007, of the y = 1 slice 0.005 nats
wrapper: KL of the y = 0 slice 0.159, of the y = 1 slice 0.169 nats
The flow with no context leaves each slice 0.49 nats from : it Gaussianizes the mixture of the two crescents, so each one lands on its own part of the target. Reading the context through the base, the couplings or both brings both slices within 0.008 nats of in their first two moments, and the wrapper leaves 0.16 and 0.17 nats. The latents show why conditioning only the base is enough here: the unconditional map is free to send the two crescents to two separate blobs, and and centre and scale each one. A base that reads the context acts after a nonlinear map, so it does not force one shape on both labels.
held_points, held_contexts = moons_data["held_out"]
panels = (
(
"none: z = f(x)",
jax.vmap(moons_flows["none"].bijection.inverse)(held_points, held_contexts),
),
(
"base: z = f(x)",
jax.vmap(moons_flows["base"].bijection.inverse)(held_points, held_contexts),
),
(
"base: z̃, standardised by the base",
standardised_latents(moons_flows["base"], held_points, held_contexts),
),
)
angles = np.linspace(0.0, 2.0 * np.pi, 200)
fig, axes = plt.subplots(1, 3, figsize=(13, 4.4), sharex=True, sharey=True)
for ax, (title, latents) in zip(axes, panels, strict=True):
for label, color in ((0, DATA_COLOR), (1, LATENT_COLOR)):
rows = held_contexts[:, label] == 1
ax.scatter(
*np.asarray(latents[rows]).T,
color=color,
label=f"y = {label}",
**SCATTER_KW,
)
for radius in (1.0, 2.0):
ax.plot(
radius * np.cos(angles), radius * np.sin(angles), color="k", ls="--", lw=1
)
ax.set(title=title, xlabel="z₁", aspect="equal", xlim=(-4, 4), ylim=(-4, 4))
style_ax(ax)
axes[0].legend()
fig.tight_layout()
plt.show()
Figure 3:Held-out rows of each label sent through the flow with no context and through the base-conditioned flow, before (left two) and after (right) the standardisation by β(y) and γ(y), with the circles of radius 1 and 2 of N(0, I).
On the left, the flow with no context shares between the labels: the upper crescent fills the upper half of the disc and the lower crescent the lower half, so neither slice is centred, and that is the 0.49 nats of each. In the middle, the base-conditioned map sends the two crescents to two compact blobs far apart, one near and one near , each narrower than the unit circle. On the right, the standardisation by and moves both blobs onto the same disc, where the two labels overlap.
5. A context that only shifts¶
The usual rule of thumb is to condition the base when the context moves the density and the couplings when it changes its shape. We test it on two crescents of the same shape: the label-1 crescent is the label-0 crescent moved by in the raw coordinates, standardised with the moons’ own mean and scale so that both datasets share one frame.
# today (sklearn)
# 6,000 fresh two-moons points and their labels, (sample, state), (sample)
fresh_points: SampleState
fresh_labels: Float[ArrayLike, " sample"]
fresh_points, fresh_labels = make_moons(n_samples=6000, noise=0.06, random_state=1)
# the first 3,000 upper-crescent points, (sample, state)
upper_points: SampleState = fresh_points[fresh_labels == 0][:3000]
# y alternates between 0 and 1, (sample)
shift_labels: Float[ArrayLike, " sample"] = np.arange(3000) % 2
# x + y (1, −0.5), standardised with the moons' mean and scale, (sample, state)
shifted_points: SampleState = (
upper_points + np.outer(shift_labels, [1.0, -0.5]) - moons_mean
) / moons_std
# user
# the shifted pair, split with the same rows
shift_data: dict = split_rows(shifted_points, np.eye(2)[shift_labels])# user
# the five flows trained on the shifted pair, with the same start as on the moons
shift_flows: dict = {
kind: train_flow(flow, shift_data) for kind, flow in fresh_flows.items()
}
# user
# the held-out NLL of each
shift_nll: dict = {
kind: held_out_nll(flow, shift_data) for kind, flow in shift_flows.items()
}
# user
# the two slice KLs of each
shift_kls: dict = slice_kls(shift_flows, shift_data)
for kind in FLOW_KINDS:
print(
f"{kind:>8}: held-out NLL {shift_nll[kind]:.3f} nats, slice KLs {shift_kls[kind][0]:.3f} and {shift_kls[kind][1]:.3f}"
) none: held-out NLL 1.360 nats, slice KLs 0.126 and 0.228
base: held-out NLL 0.722 nats, slice KLs 0.010 and 0.021
coupling: held-out NLL 0.700 nats, slice KLs 0.005 and 0.013
both: held-out NLL 0.689 nats, slice KLs 0.007 and 0.017
wrapper: held-out NLL 0.682 nats, slice KLs 0.007 and 0.008
for kind in ("base", "coupling", "both"):
# user
# how much better the wrapper does than this flow, and the standard error
gap: float
error: float
gap, error = paired_gap(shift_flows[kind], shift_flows["wrapper"], shift_data)
print(f"wrapper against {kind:>8}: {gap:+.3f} ± {error:.3f} nats per row")wrapper against base: +0.040 ± 0.016 nats per row
wrapper against coupling: +0.018 ± 0.017 nats per row
wrapper against both: +0.007 ± 0.015 nats per row
The wrapper beats the base by 0.040 ± 0.016 nats per row, two and a half standard errors; against the couplings (0.018 ± 0.017) and both (0.007 ± 0.015) it is within about one.
These standard errors cover the choice of held-out rows, not the training run. To see whether the order survives a different start, we train the base and coupling flows on the moons, and the base and wrapped flows on the shifted pair, a second time from a second key.
# user
# base and coupling on the moons, from a second start
second_moons: dict = {
kind: train_flow(conditional_flow(kind, jr.key(12)), moons_data)
for kind in ("base", "coupling")
}
# user
# base and wrapper on the shifted pair, from a second start
second_shift: dict = {
kind: train_flow(conditional_flow(kind, jr.key(12)), shift_data)
for kind in ("base", "wrapper")
}# user
# how much better base does than coupling on the moons
moons_gap: float
moons_error: float
moons_gap, moons_error = paired_gap(
second_moons["coupling"], second_moons["base"], moons_data
)
# user
# how much better the wrapper does than base on the shifted pair
shift_gap: float
shift_error: float
shift_gap, shift_error = paired_gap(
second_shift["base"], second_shift["wrapper"], shift_data
)
print(f"moons: base against coupling {moons_gap:+.3f} ± {moons_error:.3f} nats per row")
print(
f"shifted pair: wrapper against base {shift_gap:+.3f} ± {shift_error:.3f} nats per row"
)moons: base against coupling +0.005 ± 0.007 nats per row
shifted pair: wrapper against base +0.055 ± 0.016 nats per row
Here the order changes. The wrapper, which can move the data by a shift that depends on the label before the shared map, does best at 0.682 nats, and the base does worst of the four that read the context, at 0.722 nats; the couplings and both sit in between. The paired differences say which gaps are real.
fig, axes = plt.subplots(1, 2, figsize=(9, 4.2), sharex=True, sharey=True)
for ax, kind in zip(axes, ("base", "wrapper"), strict=True):
ax.scatter(*shift_data["train"][0].T, color="0.75", **SCATTER_KW)
for label, samples in enumerate(draws_by_label(shift_flows[kind], jr.key(200))):
ax.scatter(
*np.asarray(samples).T,
color=(DATA_COLOR, LATENT_COLOR)[label],
label=f"y = {label}",
**SCATTER_KW,
)
ax.set(title=kind, xlabel="x₁", aspect="equal")
style_ax(ax)
axes[0].legend()
fig.tight_layout()
plt.show()
Figure 4:Draws of the base-conditioned flow (left) and of the wrapped flow (right) for each label of the shifted pair, over the training rows (grey).
Both flows put each label on its own crescent; they differ at the ends, where the base-conditioned flow bends the right end of the upper crescent inwards and runs the left end of the lower one further down than the data. A second start repeats both comparisons: on the moons the base and the couplings tie again (0.005 ± 0.007 nats per row), and on the shifted pair the wrapper beats the base again (0.055 ± 0.016). So the rule “condition the base for shifts” holds for shifts of the latent, not of the data. A shift of the data is a shift of the latent only when the map commutes with translations, which a spline flow does not; the layer that models a shift of the data is a modulation on the data side, the wrapper.
6. The conditioning layers¶
Three layers in gauss_flows.conditioning turn an activation and a context into a conditioned activation, the pieces from which the conditional layers above are built. ConcatConditioner appends the context and applies one linear layer; AffineModulation is the FiLM of (4) Perez et al., 2018; HyperLinear is a hypernetwork that generates the weights and bias of a whole linear layer from the context:
They differ in what the context may change: concatenation only shifts the pre-activation by , FiLM rescales and shifts each feature, and the hypernetwork changes the whole matrix. We build each for features with a context of (the label here) and of (an embedding), count its parameters, and measure how far it starts from the identity on 100 random activations.
# Shapes: feature (D_h) = 64; test = 100 random activations
# user
# the three layers for D_h = 64 and a context of size D_y
def conditioning_layers(context_dim: int) -> dict:
"""``ConcatConditioner``, ``AffineModulation`` and ``HyperLinear`` with fresh weights."""
return {
# today (gauss_flows)
# h' = W [h; y] + b
"concatenation": ConcatConditioner.init(64, context_dim, key=jr.key(2)),
# today (gauss_flows)
# h' = γ(y) ⊙ h + β(y)
"FiLM": AffineModulation.init(64, context_dim, key=jr.key(2)),
# today (gauss_flows)
# h' = W(y) h + b(y)
"hypernetwork": HyperLinear.init(64, 64, context_dim, key=jr.key(2)),
}# h ~ 𝒩(0, I), (test, feature)
activations: Float[ArrayLike, "test feature"] = jr.normal(jr.key(0), (100, 64))
for context_dim in (2, 64):
# y ~ 𝒩(0, I), (test, context)
contexts: Float[ArrayLike, "test context"] = jr.normal(
jr.key(1), (100, context_dim)
)
# user
# the three layers for this D_y
layers: dict = conditioning_layers(context_dim)
for name, layer in layers.items():
# h' of each activation, (test, feature)
outputs: Float[ArrayLike, "test feature"] = jax.vmap(layer)(
activations, contexts
)
# max over activations and features of |h' − h|
change: float = float(jnp.abs(outputs - activations).max())
print(
f"D_y = {context_dim:>2}, {name:>13}: {weight_count(layer):7,} weights, max |h' - h| = {change:.2f}"
)D_y = 2, concatenation: 4,288 weights, max |h' - h| = 0.00
D_y = 2, FiLM: 384 weights, max |h' - h| = 0.00
D_y = 2, hypernetwork: 12,480 weights, max |h' - h| = 4.74
D_y = 64, concatenation: 8,256 weights, max |h' - h| = 0.00
D_y = 64, FiLM: 8,320 weights, max |h' - h| = 0.00
D_y = 64, hypernetwork: 270,400 weights, max |h' - h| = 4.35
At the start, concatenation and FiLM return their input exactly for every context: concatenation starts at , and FiLM at , . The hypernetwork does not start at the identity: it starts its generated layer at the variance of a fresh linear layer, so it moves every activation, here by up to 4.7. Their sizes grow differently with the context. Concatenation costs weights per context coordinate on top of a layer (4,288 at , 8,256 at ), FiLM per context coordinate and nothing else but a bias (384 and 8,320), and the hypernetwork per context coordinate (12,480 and 270,400), the price of letting the context change the whole matrix.
The conditional pieces of the flows above use two of the three. A conditional coupling concatenates: RQSplineCoupling(cond_dim=2) appends the context to the passive half before its conditioner’s first layer, which we can read off the layer’s input size.
# today (gauss_flows)
# a conditional coupling of the moons flows
moons_coupling: RQSplineCoupling = RQSplineCoupling(jr.key(0), shape=(2,), cond_dim=2)
# today (equinox)
# the first layer of its conditioner c_φ(x_A, y)
first_layer: eqx.nn.Linear = moons_coupling._coupling.conditioner.layers[0]
print(f"input size of c_φ: {first_layer.in_features} = D_A + D_y = 1 + 2")input size of c_φ: 3 = D_A + D_y = 1 + 2
The base and the wrapper modulate: ConditionalDiagGaussian and Conditioner both hold an AffineModulation, and so do GINCoupling and ContinuousAffineCoupling. Every one starts as the identity because its readout starts at zero weight, which is what zero_readout does to any eqx.nn.Linear or eqx.nn.MLP: the readout returns its bias for every input, and the weight still gets a gradient from the first step.
# today (equinox)
# a two-layer network ℝ² → ℝ³ with fresh weights
network: eqx.nn.MLP = eqx.nn.MLP(2, 3, width_size=16, depth=2, key=jr.key(4))
# today (gauss_flows)
# the same network with its readout g(e) = 0 · W e + 1
started: eqx.nn.MLP = zero_readout(network, bias=1.0)
# the outputs of the fresh network for the 2,400 training contexts, (train, 3)
fresh_outputs: Float[ArrayLike, "train 3"] = jax.vmap(network)(train_contexts)
# the outputs after zero_readout, (train, 3)
started_outputs: Float[ArrayLike, "train 3"] = jax.vmap(started)(train_contexts)
print(
f"fresh network, spread of the outputs over contexts: {float(fresh_outputs.std(axis=0).max()):.3f}"
)
print(f"after zero_readout: every output is {np.unique(np.asarray(started_outputs))}")fresh network, spread of the outputs over contexts: 0.079
after zero_readout: every output is [1.]
A context need not be a label. A continuous context, a time with an optional control vector, is packed into one condition by pack_time_control, which is how MatrixExponential in Part 6 takes its time; any of the layers above then reads it as .
# today (gauss_flows)
# y = (t, u) for t = 0.5 and a control u = (1, −1), (3)
time_context: Float[ArrayLike, " 3"] = pack_time_control(0.5, jnp.array([1.0, -1.0]))
# today (gauss_flows)
# a fresh wrapper that reads it, h' = γ(y) ⊙ x + β(y)
timed_wrapper: Conditioner = Conditioner(jr.key(5), inner=Identity((2,)), cond_dim=3)
print(
f"y = {np.asarray(time_context)}; fresh wrapper at x = (1, 2): {np.asarray(timed_wrapper.transform(jnp.array([1.0, 2.0]), time_context))}"
)y = [ 0.5 1. -1. ]; fresh wrapper at x = (1, 2): [1. 2.]
Recap¶
| Piece | Equation | In code |
|---|---|---|
| the conditional change of variables | (1) | negative_log_likelihood(flow, x, condition=y) |
| a conditional base, a Gaussian per context | (2) | ConditionalDiagGaussian(key, event_shape, cond_dim) |
| a conditional coupling, a spline per context | (3) | RQSplineCoupling(key, shape, cond_dim=D_y) |
| a modulation around any unconditional layer | (4) | Conditioner(key, inner=g, cond_dim) |
| how Gaussian each slice is | (5) | gaussian_kl_divergence of the moment-matched Gaussian |
| concatenation, FiLM and a hypernetwork | (6) | ConcatConditioner, AffineModulation, HyperLinear |
| a start at the identity | zero_readout | |
| a continuous context | pack_time_control(t, u) |
On these two datasets the rule of thumb needs restating. A context that changes the shape of the density can be read by the base as well as by the couplings, because the base acts after a nonlinear map. A context that shifts the data is modelled best by a modulation on the data side, and worst, of the conditional flows, by the base.
Next. Notebook 01 moves to a continuous context, makes the marginal CDFs depend on it, and checks that the conditional density it learns is calibrated.
- Winkler, C., Worrall, D. E., Hoogeboom, E., & Welling, M. (2019). Learning Likelihoods with Conditional Normalizing Flows. arXiv Preprint arXiv:1912.00042.
- Durkan, C., Bekasov, A., Murray, I., & Papamakarios, G. (2019). Neural Spline Flows. Advances in Neural Information Processing Systems (NeurIPS).
- Perez, E., Strub, F., de Vries, H., Dumoulin, V., & Courville, A. (2018). FiLM: Visual Reasoning with a General Conditioning Layer. Proceedings of the AAAI Conference on Artificial Intelligence.