03 · Mixture CDF as a learnable bijection¶
Notebooks 01 and 02 fit a marginal from quantiles, EM or a plug-in rule. A normalizing flow asks for something else: every layer must be differentiable in its parameters, so that a deep stack can be trained jointly by gradient descent. This notebook treats the mixture CDF as that kind of layer and trains it end to end by maximum likelihood.
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 jax.scipy.stats as jstats
import matplotlib.pyplot as plt
import numpy as np
import paramax
from flowjax.bijections import Invert
from flowjax.distributions import StandardNormal, Transformed
from jaxtyping import ArrayLike, Float, Int, PRNGKeyArray
from pipekit_train import ArrayDataset, EarlyStopping, History, TrainingLoop
from pipekit_train.backends.equinox import EquinoxModelOp
from sklearn.mixture import GaussianMixture
from gauss_flows_docs.environment import watermark
from gauss_flows_docs.plotting import (
DATA_COLOR,
GAUSS_KW,
LATENT_COLOR,
standard_normal_pdf,
style_ax,
use_compact_figures,
)
from gauss_flows_maps.bijections import MixtureGaussianCDF
from gauss_flows_models.inference import negative_log_likelihood
# Log-determinants and losses get float64.
jax.config.update("jax_enable_x64", True)
rng = np.random.default_rng(13)
# Figures are stored as palette PNGs to keep the notebook small.
use_compact_figures()
watermark("jax", "numpy", "matplotlib", "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
matplotlib : 3.11.2
flowjax : 19.1.0
pipekit_train : 0.3.4
gauss_flows_maps: 0.3.0
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. The maximum-likelihood objective¶
Take one coordinate and a marginal map with parameters , which sends through a mixture CDF (2) and then the probit (3). With a standard-normal base, the change of variables (4) gives each point a log-density . Training maximises the mean log-density of samples , which is the same as minimising the negative log-likelihood
Both terms of (4) are closed form for a mixture CDF: is a sum of normal CDFs followed by , and its log-derivative is the marginal log-determinant (5). So is an ordinary differentiable function of , and jax.grad gives its gradient with no root find anywhere.
2. Unconstrained parameters¶
A mixture needs weights on the simplex and positive scales, but an optimiser like Adam moves parameters anywhere in . MixtureGaussianCDF stores unconstrained logits and raw scales , one per component, and maps them to valid values on every call:
The softmax keeps the weights positive and summing to one, and the softplus with a floor of 0.005 keeps every scale away from zero, where the mixture density would collapse onto a point. The means need no constraint. The parameters are then , and any gradient step on them leaves a valid mixture.
3. Training end to end¶
The data are 3000 draws from two well-separated Gaussians. We start from a deliberately rough fit: MixtureGaussianCDF.from_data places components at quantiles of every twentieth point, with equal weights. Wrapping the marginal as Transformed(StandardNormal((1,)), Invert(marginal)) makes it a FlowJax distribution whose log_prob runs the closed-form direction , so negative_log_likelihood from gauss_flows_models.inference evaluates (1) on a batch.
# Shapes: sample (N) = 3,000, 1,500 per mode; state (D_x) = 1
PerSample = Float[ArrayLike, " sample"]
# x ~ 𝒩(−2, 0.5²), the left mode, (sample)
left_mode: PerSample = rng.normal(-2.0, 0.5, 1500)
# x ~ 𝒩(1.5, 0.8²), the right mode, (sample)
right_mode: PerSample = rng.normal(1.5, 0.8, 1500)
SampleState = Float[ArrayLike, "sample state"]
# both modes as one column of samples, (sample, state)
samples: SampleState = np.concatenate([left_mode, right_mode])[:, None]
# the same samples as a JAX array, (sample, state)
samples_jax: SampleState = jnp.asarray(samples)The warm start is a mixture of components placed at quantiles of every twentieth point, wrapped as a flow whose log_prob runs .
# Shapes: component (M) = 6
# today (gauss_flows)
# F_θ with M = 6 components at quantiles of a 1-in-20 subsample
initial_marginal: MixtureGaussianCDF = MixtureGaussianCDF.from_data(
samples[::20], n_components=6
)
# today (flowjax)
# log p_x(x; θ) = log 𝒩(f_θ(x); 0, 1) + log |f_θ'(x)|, with log_prob running x → z
initial_flow: Transformed = Transformed(StandardNormal((1,)), Invert(initial_marginal))We evaluate at the warm start and check that its gradient in , which runs through the forward map only, is finite.
Scalar = Float[ArrayLike, ""]
# today (gauss_flows)
# 𝓛(θ) = −(1/N) ∑ₙ log p_x(xₙ; θ)
initial_nll: Scalar = negative_log_likelihood(initial_flow, samples_jax)
# today (gauss_flows)
# ∇_θ 𝓛(θ), a pytree shaped like the flow
nll_gradient: Transformed = eqx.filter_grad(negative_log_likelihood)(
initial_flow, samples_jax
)
# ∇_θ 𝓛 restricted to its array leaves
array_gradient: eqx.Module = eqx.filter(nll_gradient, eqx.is_inexact_array)
# one leaf per parameter group (α, μ, ρ)
gradient_leaves: list[Float[ArrayLike, "state component"]] = jax.tree.leaves(
array_gradient
)
# every entry of every leaf is finite
all_finite: bool = all(bool(jnp.all(jnp.isfinite(leaf))) for leaf in gradient_leaves)
print(f"initial NLL: {float(initial_nll):.4f}")
print(f"gradient leaves: {len(gradient_leaves)}, all finite: {all_finite}")initial NLL: 1.7146
gradient leaves: 3, all finite: True
pipekit-train runs the loop. Its task is the batch negative log-likelihood, a fifth of the points is held out, and training stops once the held-out loss has not improved for ten epochs, keeping the best epoch, whose parameters we call .
# Shapes: batch (N_b) = 256
# 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ₙ; θ) over a batch of N_b points, 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}The rows are split at random into training rows and held-out rows, and an epoch is steps of points.
# Shapes: train (N_t) = 2,400; held_out (N_v) = 600
# Adam's step size, the epoch budget, the early-stopping patience and N_b
learning_rate = 1e-2
max_epochs = 80
patience = 10
batch_size = 256
# the root key of the fit
root_key: PRNGKeyArray = jr.key(0)
# one key for the split, one for the loop's seed
split_key: PRNGKeyArray
loop_key: PRNGKeyArray
split_key, loop_key = jr.split(root_key)
# a random order of the N rows, (sample)
order: Int[ArrayLike, " sample"] = np.asarray(jr.permutation(split_key, len(samples)))
# N_t = N − round(0.2 N)
n_train: int = len(samples) - round(0.2 * len(samples))
# the first N_t rows of the order train, (train)
train_rows: Int[ArrayLike, " train"] = order[:n_train]
# the rest are held out, (held_out)
val_rows: Int[ArrayLike, " held_out"] = order[n_train:]
# ⌊N_t / N_b⌋ steps per epoch
steps_per_epoch: int = n_train // batch_sizeThe loop trains every array leaf of the flow except those wrapped in paramax.NonTrainable, keeps the per-step losses, and stops early on the held-out loss.
# True on each trainable leaf; paramax.NonTrainable leaves stay out of the optimiser
trainable: eqx.Module = jax.tree.map(
eqx.is_inexact_array,
initial_flow,
is_leaf=lambda leaf: isinstance(leaf, paramax.NonTrainable),
)
# today (pipekit)
# the flow as a trainable model with its mask
model_op = EquinoxModelOp(initial_flow, trainable=trainable)
# today (pipekit)
# the N_t training rows, with no targets
train_data = ArrayDataset(samples[train_rows], ())
# today (pipekit)
# the N_v held-out rows, with no targets
val_data = ArrayDataset(samples[val_rows], ())
# today (pipekit)
# the per-step training and evaluation losses
history = History()
# today (pipekit)
# stop after `patience` epochs with no better held-out loss, and keep the best epoch
early_stopping = EarlyStopping("loss", patience=patience, restore_best=True)
# a seed for the loop's own batching, drawn from the loop key
loop_seed: int = int(jr.randint(loop_key, (), 0, 2**31 - 1))# today (pipekit)
# Adam on 𝓛(θ), with one evaluation and one log line per epoch
loop = TrainingLoop(
model_op,
train_data,
val_dataset=val_data,
task=FlowNLL(),
optimizer_config={"name": "adam", "lr": learning_rate},
max_steps=max_epochs * steps_per_epoch,
steps_per_epoch=steps_per_epoch,
eval_every_n_steps=steps_per_epoch,
log_every_n_steps=steps_per_epoch,
batch_size=batch_size,
seed=loop_seed,
callbacks=(history, early_stopping),
)# today (pipekit)
# θ̂ = argmin_θ 𝓛(θ) on the training rows, restored to the best held-out epoch
trained_op: EquinoxModelOp
trained_op, _ = loop.run()
# today (pipekit)
# the trained flow, held by the model op
trained_flow: Transformed = trained_op.moduleThe history holds the loss of every step; we average it per epoch to compare with the held-out loss, which is evaluated once per epoch.
# Shapes: step = every training step run; epoch = 54 epochs run
PerStep = Float[ArrayLike, " step"]
# the training loss of every step, (step)
step_losses: PerStep = np.array([metrics["loss"] for _, metrics in history.train])
# E = ⌊S / K⌋, whole epochs run
n_epochs: int = len(step_losses) // steps_per_epoch
# the step losses of the whole epochs only, (step)
whole_epochs: PerStep = step_losses[: n_epochs * steps_per_epoch]
# one row of step losses per epoch, (epoch, step)
epoch_steps: Float[ArrayLike, "epoch step"] = whole_epochs.reshape(n_epochs, -1)
PerEpoch = Float[ArrayLike, " epoch"]
# the mean training loss of each epoch, (epoch)
train_losses: PerEpoch = epoch_steps.mean(axis=1)
# the held-out loss after each epoch, (epoch)
val_losses: PerEpoch = np.array([metrics["loss"] for _, metrics in history.eval])
print(f"epochs run: {len(train_losses)}")epochs run: 54
We compare four negative log-likelihoods on all 3000 points: the warm start, the trained flow, an EM fit of the same six components, and the true two-Gaussian density .
# an EM fit of the same M = 6 components, as a reference
em_fit = GaussianMixture(n_components=6, random_state=0).fit(samples)
# 𝒩(x; −2, 0.5²) at each sample, (sample)
left_density: PerSample = jstats.norm.pdf(samples[:, 0], -2.0, 0.5)
# 𝒩(x; 1.5, 0.8²) at each sample, (sample)
right_density: PerSample = jstats.norm.pdf(samples[:, 0], 1.5, 0.8)
# p(x) = ½ 𝒩(x; −2, 0.5²) + ½ 𝒩(x; 1.5, 0.8²), (sample)
true_density: PerSample = 0.5 * left_density + 0.5 * right_density# today (gauss_flows)
# 𝓛(θ̂) of the trained flow
trained_nll: Scalar = negative_log_likelihood(trained_flow, samples_jax)
# −(1/N) ∑ₙ log p_EM(xₙ)
em_nll: float = -em_fit.score(samples)
# −(1/N) ∑ₙ log p(xₙ)
true_nll: Scalar = -jnp.mean(jnp.log(true_density))
# the four negative log-likelihoods by name
nll = {
"initial": float(initial_nll),
"trained": float(trained_nll),
"EM": float(em_nll),
"true density": float(true_nll),
}
for name, value in nll.items():
print(f"NLL on all 3000 points, {name:>12}: {value:.4f}")NLL on all 3000 points, initial: 1.7146
NLL on all 3000 points, trained: 1.6372
NLL on all 3000 points, EM: 1.6397
NLL on all 3000 points, true density: 1.6379
Gradient descent closes the gap from the warm start (1.7146 nats) and lands on the EM fit with the same six components: 1.6372 against EM’s 1.6397. Both are within a few thousandths of a nat of the true density’s 1.6379. The trained mixture even dips slightly below it, because it was fitted to these very points; the true density is the floor only on average over fresh draws. The curves below show the descent, then the learned density and the latent it produces.
grid = jnp.linspace(-5.0, 5.0, 400)[:, None]
density = jnp.exp(jax.vmap(trained_flow.log_prob)(grid))
fig, axes = plt.subplots(1, 2, figsize=(12, 4.5))
epochs = np.arange(1, len(train_losses) + 1)
axes[0].plot(epochs, train_losses, color="C0", lw=2, label="train")
axes[0].plot(epochs, val_losses, color="C1", lw=2, label="held out")
axes[0].axhline(nll["EM"], color="C2", lw=1.5, label="EM")
axes[0].axhline(nll["true density"], **GAUSS_KW, label="true density")
axes[0].set(xlabel="epoch", ylabel=r"$\mathcal{L}(\theta)$", title="training")
axes[0].legend()
style_ax(axes[0])
axes[1].hist(
samples[:, 0], bins=60, density=True, color=DATA_COLOR, alpha=0.4, label="data"
)
axes[1].plot(grid[:, 0], density, color="C3", lw=2, label="trained marginal")
axes[1].set(xlabel="$x$", ylabel="density", title="learned density")
axes[1].legend()
style_ax(axes[1])
fig.tight_layout()
Figure 1:Left: the mean negative log-likelihood (1) per epoch, on the training points and on the held-out fifth, against the EM fit and the true density (dashed). Right: the density of the trained mixture-CDF marginal over a histogram of the data.
The density is not the only output. The same trained layer is a Gaussianizing map: pushing the data through gives a latent that should be standard normal, which is what a deeper flow relies on when it stacks this layer between rotations.
# today (flowjax)
# f_θ̂, the trained marginal inside the flow
trained_marginal: MixtureGaussianCDF = trained_flow.bijection.bijection
SampleLatent = Float[ArrayLike, "sample latent"]
# today (gauss_flows)
# z = f_θ̂(x), (sample, latent)
trained_latent_column: SampleLatent = jax.vmap(trained_marginal.transform)(samples_jax)
# the latent as a flat array, (sample)
latent_trained: PerSample = np.asarray(trained_latent_column)[:, 0]
# today (gauss_flows)
# z = f_θ(x) at the warm start, (sample, latent)
initial_latent_column: SampleLatent = jax.vmap(initial_marginal.transform)(samples_jax)
# the latent as a flat array, (sample)
latent_initial: PerSample = np.asarray(initial_latent_column)[:, 0]
latents = (("initial", latent_initial), ("trained", latent_trained))
for name, values in latents:
print(f"latent {name:>7}: mean {values.mean():+.3f}, std {values.std():.3f}")latent initial: mean +0.019, std 1.132
latent trained: mean -0.016, std 1.001
z_grid = np.linspace(-4.0, 4.0, 300)
fig, axes = plt.subplots(1, 2, figsize=(12, 4.5), sharey=True)
panels = ((axes[0], latent_initial, "initial"), (axes[1], latent_trained, "trained"))
for ax, values, title in panels:
ax.hist(values, bins=60, density=True, color=LATENT_COLOR, alpha=0.5)
ax.plot(z_grid, standard_normal_pdf(z_grid), **GAUSS_KW)
ax.set(xlabel="$z = f_\\theta(x)$", title=f"latent, {title} marginal")
style_ax(ax)
axes[0].set_ylabel("density")
fig.tight_layout()
Figure 2:The data pushed through the initial and the trained marginal, against the standard-normal density (dashed). Training moves the latent onto , which is what the layer is for inside a deep flow.
The latent standard deviation falls from 1.132 at the warm start to 1.001 after training. The fit itself is the EM fit, so the gain is not accuracy. It is that the layer is differentiable in : it drops into a deep flow and trains jointly with every rotation and coupling around it, instead of being fit on its own and frozen.
Every gradient here came from the closed-form forward map. The moment we train through the inverse instead, for example with a sampling or variational objective, the gradient has to pass through a root find, and notebook 04 answers how.
Recap¶
| Concept | Equation | In code |
|---|---|---|
| log-density of a point | (4), (5) | Transformed(StandardNormal, Invert(marginal)).log_prob |
| maximum-likelihood objective | (1) | negative_log_likelihood |
| unconstrained parameters | (2) | MixtureGaussianCDF leaves |
| end-to-end training | gradient descent in | pipekit_train.TrainingLoop |
| forward gradient | closed form, all maximum likelihood needs | eqx.filter_grad |
| inverse gradient | unrolling, one step or the adjoint | notebook 04 |
Next. Training leaned on the closed-form forward map. The inverse is a root find, and 04 · Inversion strategies covers it end to end: bisection against Newton, the safeguarded hybrid, how to differentiate the inverse and why unrolling can fail, and how to vectorise it across a batch.