Conditional density estimation
A continuous context y: one flow for a whole family of densities, checked slice by slice against the exact density, the standard normal and a calibration test
01 · Conditional density estimation¶
Every flow so far has learned one density . Many problems ask for a family of them, indexed by a context : a covariate, a sensor setting, a forcing. A conditional flow makes its map depend on the context, , keeps the standard-normal base, and so learns the whole family with one set of weights. Notebook 00 conditioned on a class label; here the context is continuous, and we ask two questions of the trained flow: is each slice right, and is it Gaussianized? A family whose exact density we know answers both, and a calibration test answers the second without it.
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 time
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, Scan
from flowjax.distributions import StandardNormal, Transformed
from jaxtyping import ArrayLike, Bool, Float
from pipekit_train import ArrayDataset, History, TrainingLoop
from pipekit_train.backends.equinox import EquinoxModelOp
from scipy import stats
from gauss_flows_docs.environment import watermark
from gauss_flows_docs.plotting import (
DATA_COLOR,
GAUSS_KW,
LATENT_COLOR,
SCATTER_KW,
style_ax,
use_compact_figures,
)
from gauss_flows_maps.bijections import RQSplineCoupling, RQSplineMarginal
from gauss_flows_maps.conditioning import Conditioner
from gauss_flows_models.inference import negative_log_likelihood
jax.config.update("jax_enable_x64", True)
np.set_printoptions(precision=3, suppress=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. A family that bends with the context¶
Draw in two dimensions and a context uniformly on , and set
At the two coordinates are independent Gaussians. As grows, follows an S-shaped curve in , rising for and falling for , so the context changes the spread of , its shape and its dependence on at once; the keeps the tails light. The map from to is triangular and invertible for every , so the exact conditional density follows from the change of variables of Part 0 (4):
with and . It is the reference every trained flow below is measured against.
# Shapes: sample (N) = rows of the family; context (D_y) = 1
SampleContext = Float[ArrayLike, "sample context"]
# user
# y ~ 𝒰(−1.5, 1.5) for each row, or one fixed y for all
def draw_contexts(count: int, fixed_y: float | None = None) -> SampleContext:
"""Draw ``count`` contexts, all equal to ``fixed_y`` if given."""
if fixed_y is None:
return rng.uniform(-1.5, 1.5, (count, 1))
return np.full((count, 1), fixed_y)The rows follow (1) at their contexts.
# Shapes: state (D_x) = 2
SampleState = Float[ArrayLike, "sample state"]
# user
# x₁ = 0.8 w₁, x₂ = 0.6 w₂ + 1.5 y tanh(1.2 w₁), with w ~ 𝒩(0, I)
def draw_family(
count: int, fixed_y: float | None = None
) -> tuple[SampleState, SampleContext]:
"""Draw ``count`` rows of the family and their contexts, at ``fixed_y`` if given."""
# user
# y for each row, (sample, context)
contexts: SampleContext = draw_contexts(count, fixed_y)
# w ~ 𝒩(0, I), (sample, state)
noise: SampleState = rng.standard_normal((count, 2))
# x₂ = 0.6 w₂ + 1.5 y tanh(1.2 w₁), (sample)
second: Float[ArrayLike, " sample"] = 0.6 * noise[:, 1] + 1.5 * contexts[
:, 0
] * np.tanh(1.2 * noise[:, 0])
return np.column_stack([0.8 * noise[:, 0], second]), contextsThe flows train on standardised coordinates. The mean and the standard deviation come from a pilot draw of 20,000 rows and stay fixed, so the exact density of a standardised row is (2) plus the log of the two standard deviations.
# Shapes: pilot = 20,000 rows that fix the standardisation
# user
# x from a pilot draw, (pilot, state)
pilot: Float[ArrayLike, "pilot state"] = draw_family(20_000)[0]
# m, the pilot's mean of each coordinate, (state)
centre: Float[ArrayLike, " state"] = pilot.mean(axis=0)
# s, the pilot's standard deviation of each coordinate, (state)
spread: Float[ArrayLike, " state"] = pilot.std(axis=0)
# user
# x̃ = (x − m) / s, the rows in standardised coordinates
def draw_standardised(
count: int, fixed_y: float | None = None
) -> tuple[SampleState, SampleContext]:
"""Draw ``count`` standardised rows of the family and their contexts."""
# user
# x and y, (sample, state), (sample, context)
points: SampleState
contexts: SampleContext
points, contexts = draw_family(count, fixed_y)
return (points - centre) / spread, contexts# Shapes: train (N_t) = 20,000 rows; held_out (N_v) = 2,000 rows
# user
# x̃ and y of the training rows, (train, state), (train, context)
train_points: Float[ArrayLike, "train state"]
train_contexts: Float[ArrayLike, "train context"]
train_points, train_contexts = draw_standardised(20_000)
# user
# x̃ and y of the held-out rows, (held_out, state), (held_out, context)
held_points: Float[ArrayLike, "held_out state"]
held_contexts: Float[ArrayLike, "held_out context"]
held_points, held_contexts = draw_standardised(2000)
print(
f"training rows {train_points.shape}, contexts {train_contexts.shape}; held-out rows {held_points.shape}"
)training rows (20000, 2), contexts (20000, 1); held-out rows (2000, 2)
The exact log-density of a standardised row inverts the standardisation and then (1).
PerSample = Float[ArrayLike, " sample"]
# user
# log p(x̃ | y) = log 𝒩(w₁) + log 𝒩(w₂) − log 0.8 − log 0.6 + ∑ᵢ log sᵢ
def exact_log_density(points: SampleState, contexts: SampleContext) -> PerSample:
"""The exact log-density of standardised ``points`` at their ``contexts``."""
# x = m + s x̃, (sample, state)
raw: SampleState = centre + spread * points
# w₁ = x₁ / 0.8, (sample)
first_noise: PerSample = raw[:, 0] / 0.8
# w₂ = (x₂ − 1.5 y tanh(1.2 w₁)) / 0.6, (sample)
second_noise: PerSample = (
raw[:, 1] - 1.5 * contexts[:, 0] * np.tanh(1.2 * first_noise)
) / 0.6
# log 𝒩(w₁) + log 𝒩(w₂) − log 0.8 − log 0.6 + ∑ᵢ log sᵢ, (sample)
return (
stats.norm.logpdf(first_noise)
+ stats.norm.logpdf(second_noise)
- np.log(0.48)
+ np.log(spread).sum()
)print(
f"exact NLL: training rows {-exact_log_density(train_points, train_contexts).mean():.4f}, held-out rows {-exact_log_density(held_points, held_contexts).mean():.4f} nats"
)exact NLL: training rows 2.2674, held-out rows 2.2901 nats
fig, ax = plt.subplots(figsize=(5.6, 5))
cloud = ax.scatter(
*np.asarray(train_points[:5000]).T,
c=np.asarray(train_contexts[:5000, 0]),
cmap="coolwarm",
s=6,
alpha=0.5,
edgecolors="none",
)
fig.colorbar(cloud, ax=ax, label="context $y$", fraction=0.046)
ax.set(
title="training rows coloured by $y$",
xlabel="$x_1$",
ylabel="$x_2$",
aspect="equal",
)
style_ax(ax)
plt.show()
Figure 1:5,000 of the standardised training rows, each coloured by its context y. At y near 0 the cloud is round; towards either end it bends into an S, upwards for positive y and downwards for negative y.
2. A conditional coupling flow¶
A conditional flow is a map that is invertible in for every context. The change of variables holds slice by slice:
where the Jacobian is taken in only; the context is an input, never transformed. Because the base is the same standard normal for every , a trained is a conditional Gaussianizer: it should send every slice to the same .
The couplings of Part 5 take the context as an extra input to their conditioner: RQSplineCoupling with cond_dim=1 concatenates to the copied half before the network computes the spline. We stack four of them, each followed by a Flip so the next one transforms the other coordinate. The four blocks share one type and differ only in their weights, so they are built at once with eqx.filter_vmap and applied in turn by FlowJax’s Scan. A fresh coupling is the identity, so training starts from .
# Shapes: block (K) = 4 coupling blocks
# user
# one block: a spline coupling that reads y, then a flip of the two coordinates
def coupling_block(key: jax.Array) -> Chain:
"""A conditional rational-quadratic spline coupling followed by a flip."""
# today (gauss_flows)
# x_B ↦ spline(x_B; c_φ(x_A, y)), 8 bins on [−5, 5], a 2 × 32 conditioner
coupling: RQSplineCoupling = RQSplineCoupling(
key, shape=(2,), n_bins=8, interval=5.0, cond_dim=1, nn_width=32, nn_depth=2
)
# today (flowjax)
# the coupling, then (x₁, x₂) ↦ (x₂, x₁)
return Chain([coupling, Flip((2,))])
# today (flowjax)
# four fresh blocks stacked on a leading axis
coupling_blocks: Chain = eqx.filter_vmap(coupling_block)(jr.split(jr.key(1), 4))# today (flowjax)
# p_x(x | y; θ), the blocks applied in turn on a standard-normal base
coupling_flow: Transformed = Transformed(StandardNormal((2,)), Scan(coupling_blocks))
# today (gauss_flows)
# the held-out NLL at the start, where f_θ is the identity
initial_nll: float = float(
negative_log_likelihood(coupling_flow, held_points, condition=held_contexts)
)
print(f"held-out NLL of the fresh flow: {initial_nll:.4f} nats")held-out NLL of the fresh flow: 2.8327 nats
Training is the maximum likelihood of Part 1 (1), as in Parts 4 to 6, with the context of each row passed to the flow as its condition. The task hands each batch’s contexts to negative_log_likelihood.
# Shapes: batch (N_b) = 256
Scalar = Float[ArrayLike, ""]
# user
# pipekit-train's task: 𝓛(θ) on one batch of rows and their contexts
class ConditionalNLL:
"""pipekit-train's task: the mean conditional negative log-likelihood of a batch."""
# user
# 𝓛(θ) = −(1/N_b) ∑ₙ log p_x(xₙ | yₙ; θ), also logged
def loss_fn(self, flow, batch, key):
# the rows 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(xₙ | yₙ; θ)
loss: Scalar = negative_log_likelihood(
flow, batch_points, condition=batch_contexts
)
return loss, {"loss": loss}Every run takes 3,000 Adam steps of 256 rows on a one-cycle cosine rate that peaks at , with the gradient clipped to a global norm of 5, and evaluates the held-out rows every 100 steps.
# Shapes: step = 3,000 training 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=3000, peak_value=3e-3
)
# user
# the settings every run shares
loop_settings: dict = {
"task": ConditionalNLL(),
"optimizer_config": {"name": "adam", "lr": schedule, "clip_norm": 5.0},
"val_dataset": ArrayDataset(held_points, held_contexts),
"max_steps": 3000,
"steps_per_epoch": 100,
"eval_every_n_steps": 100,
"log_every_n_steps": 100,
"batch_size": 256,
"seed": 1,
}# user
# θ̂ = argmin 𝓛(θ) on the training rows, with the losses of the run
def fit_flow(flow: Transformed) -> tuple[Transformed, History]:
"""Train ``flow`` on the training rows and their contexts."""
# today (pipekit)
# the losses of the run
history = History()
# today (pipekit)
# θ̂ after 3,000 steps, held by the model op
trained_op: EquinoxModelOp
trained_op, _ = TrainingLoop(
EquinoxModelOp(flow),
ArrayDataset(train_points, train_contexts),
callbacks=(history,),
**loop_settings,
).run()
return trained_op.module, history# the clock before training
start: float = time.perf_counter()
# user
# the trained coupling flow and its losses
coupling_fit: Transformed
coupling_history: History
coupling_fit, coupling_history = fit_flow(coupling_flow)
print(f"trained in {time.perf_counter() - start:.0f} s")
# user
# 𝓛 = −(1/N) ∑ₙ log p_x(xₙ | yₙ) of a flow on the given rows
def conditional_nll(
flow: Transformed, points: SampleState, contexts: SampleContext
) -> float:
"""The mean conditional negative log-likelihood of ``points`` under ``flow``."""
# today (gauss_flows)
# −(1/N) ∑ₙ log p_x(xₙ | yₙ)
return float(negative_log_likelihood(flow, points, condition=contexts))trained in 18 s
print(
f"coupling flow: training NLL {conditional_nll(coupling_fit, train_points, train_contexts):.4f}, held-out NLL {conditional_nll(coupling_fit, held_points, held_contexts):.4f} nats"
)
print(
f"exact density: training NLL {-exact_log_density(train_points, train_contexts).mean():.4f}, held-out NLL {-exact_log_density(held_points, held_contexts).mean():.4f} nats"
)coupling flow: training NLL 2.2568, held-out NLL 2.2992 nats
exact density: training NLL 2.2674, held-out NLL 2.2901 nats
fig, ax = plt.subplots(figsize=(7, 3.5))
ax.plot(
[step for step, _ in coupling_history.train],
[float(metrics["loss"]) for _, metrics in coupling_history.train],
color=DATA_COLOR,
alpha=0.5,
label="training batch",
)
ax.plot(
[step for step, _ in coupling_history.eval],
[float(metrics["loss"]) for _, metrics in coupling_history.eval],
"o-",
color=DATA_COLOR,
label="held out",
)
ax.axhline(
-exact_log_density(held_points, held_contexts).mean(),
color="k",
ls="--",
lw=1,
label="exact density, held out",
)
ax.set(xlabel="step", ylabel="NLL (nats per row)", ylim=(2.0, 3.2))
ax.legend()
style_ax(ax)
plt.show()
Figure 2:Training loss of each logged step (light) and held-out loss every 100 steps (dark), in nats per row, with the exact density’s held-out NLL dashed.
The fresh flow, the identity, scores 2.83 nats on the held-out rows. Training brings it to 2.299 nats, 0.009 above the exact density’s 2.290, in about 20 seconds; the held-out loss falls close to the exact value within the first few hundred steps and then barely moves. On the training rows the flow scores 2.257, 0.011 below the exact density on the same rows: it has fitted a little of the noise of its own sample, and not much more.
3. The learned density across the context¶
One trained flow gives for any in the training range. We evaluate it on a grid at five contexts and put each next to rows drawn from the family at the same context.
# Shapes: line = 70 points along each axis; test = 70 × 70 grid points
# 70 points on [−3.5, 3.5], (line)
grid_axis: Float[ArrayLike, " line"] = np.linspace(-3.5, 3.5, 70)
# the 70 × 70 grid on [−3.5, 3.5]², (test, state)
grid_points: Float[ArrayLike, "test state"] = np.stack(
np.meshgrid(grid_axis, grid_axis), axis=-1
).reshape(-1, 2)
# the five contexts of the sweep
sweep_contexts: tuple = (-1.2, -0.6, 0.0, 0.6, 1.2)
# user
# p_x(x | y) of a flow on the grid at one context, as a 70 × 70 image
def density_image(flow: Transformed, context: float) -> Float[ArrayLike, "line line"]:
"""The density of ``flow`` on the grid at ``context``."""
# today (flowjax)
# log p_x(x | y) at each grid point, (test)
grid_log_density: Float[ArrayLike, " test"] = flow.log_prob(
grid_points, jnp.array([context])
)
return np.exp(np.asarray(grid_log_density)).reshape(70, 70)fig, axes = plt.subplots(2, 5, figsize=(16, 6.6), sharex=True, sharey=True)
for column, context in enumerate(sweep_contexts):
slice_points: SampleState = draw_standardised(1500, context)[0]
axes[0, column].scatter(*np.asarray(slice_points).T, color=DATA_COLOR, **SCATTER_KW)
axes[1, column].pcolormesh(
grid_axis,
grid_axis,
density_image(coupling_fit, context),
cmap="viridis",
shading="auto",
)
axes[0, column].set(title=f"$y = {context:+.1f}$")
for ax in axes[:, column]:
ax.set(xlim=(-3.5, 3.5), ylim=(-3.5, 3.5), aspect="equal")
style_ax(ax)
axes[0, 0].set_ylabel("data")
axes[1, 0].set_ylabel("coupling flow")
plt.show()
Figure 3:Top: 1,500 rows of the family at each of five contexts. Bottom: the trained coupling flow’s density at the same contexts. One set of weights follows the bend in both directions and its absence at y = 0.
The flow bends its density in the direction the context asks for, more steeply as grows, and leaves it round and unbent at . Nothing in the architecture says the family is symmetric in ; the flow learned that from the data.
4. Every slice to the same standard normal¶
The density direction of the flow, bijection.inverse, is the map itself. We draw 1,500 fresh rows at each of three contexts, send them through it at their context, and read the moments of the latent as in Part 0: the mean, the standard deviation and the excess kurtosis (2) of each coordinate, and the correlation between the two.
SampleLatent = Float[ArrayLike, "sample latent"]
# user
# z = f_θ(x; y) for each row at its own context
def to_latent(
flow: Transformed, points: SampleState, contexts: SampleContext
) -> SampleLatent:
"""The latent of each row of ``points`` at its context."""
# today (flowjax)
# z = f_θ(x; y), each row at its context, (sample, latent)
return np.asarray(jax.vmap(flow.bijection.inverse)(points, contexts))
# the three contexts of the check
check_contexts: tuple = (-1.0, 0.0, 1.0)
# user
# 1,500 fresh rows at each context of the check
check_slices: dict = {
context: draw_standardised(1500, context) for context in check_contexts
}# user
# the mean, standard deviation and excess kurtosis of each latent coordinate, and their correlation
def report_moments(name: str, flow: Transformed) -> dict:
"""Print the moments of each check slice's latent under ``flow`` and return the latents."""
# user
# z = f_θ(x; y) of each check slice
latents: dict = {
context: to_latent(flow, *check_slices[context]) for context in check_contexts
}
for context, latent in latents.items():
print(
f"{name}, y = {context:+.0f}: mean {latent.mean(axis=0)}, std {latent.std(axis=0)}, excess kurtosis {stats.kurtosis(latent, axis=0)}, correlation {np.corrcoef(latent.T)[0, 1]:+.3f}"
)
return latents
# user
# the coupling flow's latent of each check slice
coupling_latents: dict = report_moments("coupling", coupling_fit)coupling, y = -1: mean [-0.042 0.026], std [0.976 0.989], excess kurtosis [0.118 0.174], correlation +0.035
coupling, y = +0: mean [ 0.008 -0.001], std [0.999 0.988], excess kurtosis [-0.002 -0.029], correlation +0.011
coupling, y = +1: mean [0.016 0.022], std [1.022 1.036], excess kurtosis [-0.105 -0.105], correlation -0.019
Three different slices land on one standard normal. The means are within 0.05 of zero, the standard deviations between 0.97 and 1.04, the excess kurtosis within 0.18 of zero (1.4 standard errors, ) and the correlation within 0.04 of zero (1.4 standard errors, ). That is what a sample of 1,500 standard-normal draws looks like.
5. A calibration test¶
The moments check three slices. A test that uses every held-out row, each at its own context, comes from the norm of the latent. If is exact, for every , so follows a distribution whatever the context, and its cumulative distribution function in two dimensions has a closed form. The probability integral transform of Part 1 (1) then gives
which is uniform on for a calibrated flow. Its empirical distribution function at a level is the coverage of the flow’s central region of probability , the disk mapped back through : a calibrated flow covers a fraction of the rows at every level, and at every context. A Kolmogorov-Smirnov test of against checks all levels at once.
# user
# ũ = 1 − exp(−‖z‖² / 2) of each held-out row at its context
def radial_pit(flow: Transformed) -> PerSample:
"""The probability integral transform of ‖z‖² for every held-out row."""
# user
# z = f_θ(x; y), (held_out, latent), (sample, latent)
held_latent: SampleLatent = to_latent(flow, held_points, held_contexts)
# ũ = 1 − exp(−‖z‖² / 2), (held_out)
return 1.0 - np.exp(-0.5 * np.sum(held_latent**2, axis=1))
# the nominal levels τ of the coverage table, (quantile)
levels: Float[ArrayLike, " quantile"] = np.array([0.5, 0.8, 0.9, 0.95])
# the three bands of |y|
context_bands: tuple = ((0.0, 0.5), (0.5, 1.0), (1.0, 1.5))# user
# coverage (1/N_v) ∑ₙ 𝟙[ũₙ ≤ τ] at each level, overall and in each band of |y|
def report_coverage(name: str, pit: PerSample) -> None:
"""Print the coverage of the held-out rows at each level, overall and by band."""
print(
f"{name}: coverage at τ = {levels}: {np.mean(pit[:, None] <= levels, axis=0)}"
)
for low, high in context_bands:
# the rows whose |y| is in the band, (held_out)
in_band: Bool[ArrayLike, " held_out"] = (np.abs(held_contexts[:, 0]) >= low) & (
np.abs(held_contexts[:, 0]) < high
)
print(
f" |y| in [{low}, {high}), {in_band.sum()} rows: {np.mean(pit[in_band, None] <= levels, axis=0)}"
)# user
# the coverage table and a Kolmogorov-Smirnov test of ũ against 𝒰(0, 1)
def report_calibration(name: str, flow: Transformed) -> PerSample:
"""Print the calibration of ``flow`` on the held-out rows and return their ũ."""
# user
# ũ of each held-out row, (held_out), (sample)
pit: PerSample = radial_pit(flow)
# user
# the coverage table
report_coverage(name, pit)
# today (scipy)
# sup |F̂(ũ) − ũ| and its p-value under 𝒰(0, 1)
ks_statistic: float
ks_pvalue: float
ks_statistic, ks_pvalue = stats.kstest(pit, "uniform")
print(
f" Kolmogorov-Smirnov against U(0, 1): statistic {ks_statistic:.4f}, p-value {ks_pvalue:.3g}"
)
return pit# user
# the coupling flow's calibration on the held-out rows, (sample)
coupling_pit: PerSample = report_calibration("coupling", coupling_fit)coupling: coverage at τ = [0.5 0.8 0.9 0.95]: [0.485 0.787 0.893 0.944]
|y| in [0.0, 0.5), 661 rows: [0.487 0.793 0.891 0.944]
|y| in [0.5, 1.0), 685 rows: [0.474 0.775 0.888 0.94 ]
|y| in [1.0, 1.5), 654 rows: [0.494 0.794 0.902 0.948]
Kolmogorov-Smirnov against U(0, 1): statistic 0.0248, p-value 0.169
The coupling flow covers 48.5%, 78.7%, 89.3% and 94.4% of the held-out rows at the levels 50%, 80%, 90% and 95%. With 2,000 rows the standard error of a coverage is at most 1.1 points, so every level is within 1.5 standard errors of its nominal value, and within 1.7 in each band of , where the standard error is up to 1.9 points. The Kolmogorov-Smirnov test does not reject uniformity (). The flow is calibrated across the whole range of the context, where the spread of grows with .
6. When elementwise maps are enough¶
A cheaper flow makes every map elementwise in : each coordinate gets its own one-dimensional Gaussianization whose shape depends on , . Its density factorises,
so it can fit the conditional marginal of each coordinate, its location, spread and shape at every , but it treats the coordinates as independent given the context. We build it from the marginal splines of Part 1: RQSplineMarginal takes no context, so each spline is wrapped in Conditioner, which follows it with a -dependent scale and shift of each coordinate, , read by a small network from . Four such layers in turn make the shape of each marginal map depend on as well. Like the couplings, a fresh wrapper starts as the identity.
# user
# one elementwise layer: a marginal spline g, then γ(y) ⊙ g(x) + β(y)
def marginal_block(key: jax.Array) -> Conditioner:
"""A marginal rational-quadratic spline with a context-dependent scale and shift."""
# today (gauss_flows)
# g(x)_d = spline_d(x_d), 8 bins on [−5, 5], the same for every y
spline: RQSplineMarginal = RQSplineMarginal(n_bins=8, shape=(2,), interval=5.0)
# today (gauss_flows)
# γ(y) ⊙ g(x) + β(y), with γ = 1 and β = 0 at the start
return Conditioner(key, inner=spline, cond_dim=1)
# today (flowjax)
# p_x(x | y; θ), four elementwise layers on a standard-normal base
marginal_flow: Transformed = Transformed(
StandardNormal((2,)), Scan(eqx.filter_vmap(marginal_block)(jr.split(jr.key(3), 4)))
)# user
# the trained elementwise flow and its losses
marginal_fit: Transformed
marginal_history: History
marginal_fit, marginal_history = fit_flow(marginal_flow)
for name, flow in (("elementwise", marginal_fit), ("coupling", coupling_fit)):
print(
f"{name:>11} flow: held-out NLL {conditional_nll(flow, held_points, held_contexts):.4f} nats"
)
print(
f"exact density: held-out NLL {-exact_log_density(held_points, held_contexts).mean():.4f} nats"
)elementwise flow: held-out NLL 2.7178 nats
coupling flow: held-out NLL 2.2992 nats
exact density: held-out NLL 2.2901 nats
# user
# the elementwise flow's latent of each check slice
marginal_latents: dict = report_moments("elementwise", marginal_fit)elementwise, y = -1: mean [-0.056 0.06 ], std [0.974 0.964], excess kurtosis [ 0.083 -0.025], correlation -0.797
elementwise, y = +0: mean [0.012 0.004], std [1.003 0.956], excess kurtosis [0.026 0.186], correlation +0.013
elementwise, y = +1: mean [0.013 0.018], std [1.021 1.018], excess kurtosis [-0.165 -0.097], correlation +0.801
angle: Float[ArrayLike, " test"] = np.linspace(0, 2 * np.pi, 200)
fig, axes = plt.subplots(2, 3, figsize=(12, 8), sharex=True, sharey=True)
for row, (name, latents) in zip(
axes,
(("coupling", coupling_latents), ("elementwise", marginal_latents)),
strict=True,
):
for ax, context in zip(row, check_contexts, strict=True):
ax.scatter(*latents[context].T, color=LATENT_COLOR, **SCATTER_KW)
for radius in (1.0, 2.0):
ax.plot(radius * np.cos(angle), radius * np.sin(angle), **GAUSS_KW)
ax.set(
title=f"{name}, $y = {context:+.0f}$",
xlim=(-3.6, 3.6),
ylim=(-3.6, 3.6),
aspect="equal",
)
style_ax(ax)
row[0].set_ylabel("$z_2$")
for ax in axes[1]:
ax.set_xlabel("$z_1$")
plt.show()
Figure 4:Fresh rows at three contexts mapped to the latent by the coupling flow (top) and the elementwise flow (bottom), with the circles of radius 1 and 2 of N(0, I). Every coupling slice is round; the elementwise slices at y = ±1 keep a tilt.
The elementwise flow scores 2.718 nats on the held-out rows, 0.43 nats worse than the exact density and only 0.11 better than the identity it started from. Its latent shows why. Each coordinate of each slice is Gaussianized as well as the coupling flow’s: the standard deviations are between 0.95 and 1.03 and the excess kurtosis within 0.19 of zero. But the correlation of the two coordinates is -0.80 at and +0.80 at : the dependence the context puts between and passes straight through, because no map of one coordinate can read the other. At , where the family’s coordinates are independent, the correlation is 0.01 and the elementwise flow is as good as the coupling flow.
# user
# the elementwise flow's calibration on the held-out rows, (sample)
marginal_pit: PerSample = report_calibration("elementwise", marginal_fit)elementwise: coverage at τ = [0.5 0.8 0.9 0.95]: [0.544 0.79 0.883 0.934]
|y| in [0.0, 0.5), 661 rows: [0.514 0.797 0.89 0.943]
|y| in [0.5, 1.0), 685 rows: [0.547 0.787 0.876 0.927]
|y| in [1.0, 1.5), 654 rows: [0.57 0.787 0.884 0.934]
Kolmogorov-Smirnov against U(0, 1): statistic 0.0762, p-value 1.51e-10
fig, axes = plt.subplots(1, 2, figsize=(10, 3.6), sharey=True)
for ax, (name, pit) in zip(
axes, (("coupling", coupling_pit), ("elementwise", marginal_pit)), strict=True
):
ax.hist(pit, bins=20, range=(0, 1), density=True, color=LATENT_COLOR, alpha=0.7)
ax.axhline(1.0, color="k", ls="--", lw=1)
ax.set(title=f"{name} flow", xlabel="$\\tilde{u}$")
style_ax(ax)
axes[0].set_ylabel("density")
plt.show()
Figure 5:Histograms of ũ for the 2,000 held-out rows under each flow, in 20 bins, with the uniform density of a calibrated flow dashed.
The elementwise flow covers 54.4%, 79.0%, 88.3% and 93.4% of the held-out rows. At 80% it is within a point of nominal, so a check at that level alone would pass it; at the other levels it is off by 1.6 to 4.4 points, between two and a half and four standard errors, too high at 50% and too low at 90% and 95%. The Kolmogorov-Smirnov test rejects uniformity outright (). Its histogram of shows the shape of the failure: too many rows near and near . A correlated latent with unit marginals has the right mean of but a wider distribution, with too many rows near the centre and too many far out. A calibration check of should test the whole distribution of , not one or two levels.
fig, axes = plt.subplots(1, 3, figsize=(13, 4.4), sharex=True, sharey=True)
axes[0].scatter(
*np.asarray(draw_standardised(1500, 1.2)[0]).T, color=DATA_COLOR, **SCATTER_KW
)
axes[1].pcolormesh(
grid_axis,
grid_axis,
density_image(marginal_fit, 1.2),
cmap="viridis",
shading="auto",
)
axes[2].pcolormesh(
grid_axis,
grid_axis,
density_image(coupling_fit, 1.2),
cmap="viridis",
shading="auto",
)
for ax, title in zip(
axes, ("data, $y = 1.2$", "elementwise flow", "coupling flow"), strict=True
):
ax.set(
title=title, xlabel="$x_1$", xlim=(-3.5, 3.5), ylim=(-3.5, 3.5), aspect="equal"
)
style_ax(ax)
axes[0].set_ylabel("$x_2$")
plt.show()
Figure 6:At y = 1.2: rows of the family (left), the elementwise flow’s density (middle) and the coupling flow’s density (right).
At the coupling flow follows the S. The elementwise flow’s density is the product of its two marginals (5): it puts the mass of in horizontal bands that do not move with , so it is wide where the data are narrow and has mass in the two empty corners. The rule of thumb follows. When the context only moves, stretches or reshapes each coordinate, elementwise conditional maps are enough and cheap. As soon as it changes the dependence between coordinates, as it does here for every , the context has to reach a map that reads one coordinate to transform another: a conditional coupling.
Recap¶
| Piece | Equation | In code |
|---|---|---|
| the family and its exact conditional density | (1), (2) | draw_family, exact_log_density |
| the conditional change of variables | (3) | Transformed(StandardNormal((2,)), Scan(...)), log_prob(x, condition) |
| a coupling that reads the context | RQSplineCoupling(..., cond_dim=1) | |
| training on rows and their contexts | (1) | negative_log_likelihood(flow, x, condition=y) in ConditionalNLL |
| the conditional Gaussianizer | flow.bijection.inverse(x, y) | |
| the calibration test | (4) | radial_pit, stats.kstest |
| elementwise conditional maps | (5) | Conditioner(inner=RQSplineMarginal(...), cond_dim=1) |
A conditional flow with a standard-normal base learns a family of densities and a conditional Gaussianizer at once, and both can be checked: against the exact density when it is known, slice by slice through the moments of the latent, and over every row and context through the calibration of . Elementwise conditional maps Gaussianize each coordinate of every slice; only a coupling removes the dependence the context creates.
Next. Notebook 02 makes the context an observation, , and trains as a posterior that one pass of the flow samples for any observation.