Monotone-spline CDFs
Monotone cubic CDFs, and the rational-quadratic spline with a closed-form inverse
02 · Monotone-spline CDFs¶
The mixture CDF of notebook 01 is smooth and compact, but its inverse is a root find, (4). Splines keep the smoothness and the compactness and buy something better: a parameterisation that is monotone by construction and, for the right spline, invertible in closed form. That is why splines are the marginal and coupling transform of choice in modern flows.
import warnings
warnings.filterwarnings("ignore", message=r".*IProgress.*")
from collections.abc import Iterator
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 paramax
import rbig
from flowjax.bijections import RationalQuadraticSpline
from functax.geometry import Axis, Points
from jaxtyping import ArrayLike, Bool, Float, Int, PRNGKeyArray
from functax.interp import CubicSpline, Pchip, Plan
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 RQSplineMarginal
# Round trips and log-determinants get float64.
jax.config.update("jax_enable_x64", True)
rng = np.random.default_rng(12)
# Figures are stored as palette PNGs to keep the notebook small.
use_compact_figures()
watermark("jax", "numpy", "matplotlib", "functax", "rbig", "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
functax : 0.0.15
rbig : 0.1.16
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. Monotonicity is the whole game¶
A CDF is non-decreasing, and its slope is the density, so a spline used as a CDF must be monotone. If it is not, is negative somewhere, is not a CDF, and the marginal map (3) is not invertible. A natural cubic spline, the smoothest interpolant, ignores this: between knots it can overshoot, rising past the next knot value and then falling back. The monotone cubic Hermite interpolant of Fritsch and Carlson Fritsch & Carlson, 1980, known as PCHIP, limits the slope at each knot so that every cubic piece stays between its two knot values. We interpolate the same monotone CDF knots, flat then steep then flat, with both, using functax’s CubicSpline and Pchip.
# Shapes: knot = 7 knots of the CDF; test = 601 points on [0, 6]
PerKnot = Float[ArrayLike, " knot"]
# knot positions, (knot)
knot_positions: PerKnot = jnp.array([0.0, 1, 2, 3, 4, 5, 6])
# F at the knots: flat, then a sharp central rise, then flat, (knot)
knot_cdf: PerKnot = jnp.array([0.0, 0.02, 0.05, 0.5, 0.95, 0.98, 1.0])
PerTestPoint = Float[ArrayLike, " test"]
# the fine grid the splines are evaluated on, (test)
fine_grid: PerTestPoint = jnp.linspace(0.0, 6.0, 601)
# today (functax)
# the fine grid as interpolation targets
targets = Points(fine_grid[:, None])
# today (functax)
# the knot positions as an interpolation axis
knot_axis = Axis(knot_positions)
# today (functax)
# natural cubic spline, the smoothest C² interpolant of the knots
cubic_plan: Plan = CubicSpline(bc="natural").plan(knot_axis, targets)
# today (functax)
# monotone cubic Hermite interpolant (PCHIP) of the knots
pchip_plan: Plan = Pchip().plan(knot_axis, targets)The interpolation plans map knot values to the fine grid, so applying them to the knot values gives each spline’s CDF, and its finite-difference slope gives the implied density.
# today (functax)
# F(x) of the natural cubic on the grid, (test)
cdf_cubic: PerTestPoint = cubic_plan(knot_cdf)
# today (functax)
# F(x) of PCHIP on the grid, (test)
cdf_pchip: PerTestPoint = pchip_plan(knot_cdf)
# p(x) = F'(x), the implied density, by finite differences, (test)
density_cubic: PerTestPoint = jnp.gradient(cdf_cubic, fine_grid)
# p(x) = F'(x) of PCHIP, (test)
density_pchip: PerTestPoint = jnp.gradient(cdf_pchip, fine_grid)We locate the most negative slope of the natural cubic and its lowest value between the second and third knots, and check that PCHIP never decreases.
# where the natural cubic's slope is smallest
worst: int = int(jnp.argmin(density_cubic))
TestMask = Bool[ArrayLike, " test"]
# the grid points strictly between the knots x = 1 and x = 2, (test)
between_knots: TestMask = (fine_grid > 1) & (fine_grid < 2)
# min F(x) of the natural cubic between those knots
dip: float = float(cdf_cubic[between_knots].min())
# F(x_{i+1}) − F(x_i) ≥ 0 at every grid step, up to rounding
pchip_monotone: bool = bool(jnp.all(jnp.diff(cdf_pchip) >= -1e-12))
# min p(x) of the natural cubic
smallest_slope: float = float(density_cubic.min())
print(
f"natural cubic: smallest slope {smallest_slope:.4f} at x = {fine_grid[worst]:.2f}"
)
print(f"natural cubic: falls to {dip:.4f}")
print(" between the knots F(1) = 0.02 and F(2) = 0.05")
print(f"PCHIP: smallest slope {float(density_pchip.min()):.4f}")
print(f"PCHIP: monotone = {pchip_monotone}")natural cubic: smallest slope -0.0447 at x = 4.81
natural cubic: falls to 0.0027
between the knots F(1) = 0.02 and F(2) = 0.05
PCHIP: smallest slope 0.0151
PCHIP: monotone = True
fig, axes = plt.subplots(1, 2, figsize=(12, 4.4))
axes[0].plot(fine_grid, cdf_cubic, color="C3", lw=1.8, label="natural cubic")
axes[0].plot(fine_grid, cdf_pchip, color="C2", lw=1.8, label="monotone cubic (PCHIP)")
axes[0].plot(knot_positions, knot_cdf, "ko", ms=6, label="CDF knots")
axes[0].set(title="Two splines through the same knots", xlabel="x", ylabel="F(x)")
axes[0].legend(fontsize=8)
style_ax(axes[0])
axes[1].axhspan(-0.1, 0.0, color="C3", alpha=0.08)
axes[1].plot(fine_grid, density_cubic, color="C3", lw=1.8, label="natural cubic")
axes[1].plot(fine_grid, density_pchip, color="C2", lw=1.8, label="PCHIP")
axes[1].axhline(0.0, color="k", lw=0.6)
axes[1].set(
title="Implied density F'(x)", xlabel="x", ylabel="F'(x)", ylim=(-0.1, 0.75)
)
axes[1].legend(fontsize=8)
style_ax(axes[1])
fig.tight_layout()
Figure 1:The same monotone CDF knots, interpolated two ways. Left: the natural cubic overshoots between knots, so it is not monotone; PCHIP stays between each pair of knot values. Right: the implied density of the natural cubic goes negative (shaded), which no density can do.
For these knots the natural cubic never leaves , so a range check would pass it. It still fails as a CDF: between and it falls from 0.02 to 0.0027, below its own left knot, and its slope reaches -0.045, a negative density. PCHIP honours the same knots with a non-negative slope everywhere. Monotonicity is a property of the slopes between knots, not of the values at them.
2. A spline on the knots of an estimated CDF¶
rbig’s SplineGaussianizer builds a marginal map from data with exactly this guarantee. It estimates the CDF and density of each coordinate with a kernel density estimate, places knots on the data, sets the latent knot values by (3), and sets the knot slopes to the derivative of the marginal map, , the exponential of (5). Those slopes are positive wherever the density estimate is (the library clips them at 10-3), and between knots it interpolates with the rational-quadratic spline of section 3, so the map is monotone and its inverse is closed form. We fit it to draws of a skewed gamma distribution.
# Shapes: sample (N) = 2,000; state (D_x) = 1
SampleState = Float[ArrayLike, "sample state"]
# x ~ Gamma(2, 1), (sample, state)
gamma_samples: SampleState = rng.gamma(2.0, 1.0, size=(2000, 1))
# today (rbig)
# fit T = Φ⁻¹ ∘ F̂, a rational-quadratic spline on KDE knots
gaussianizer = rbig.SplineGaussianizer().fit(gamma_samples)
SampleLatent = Float[ArrayLike, "sample latent"]
# today (rbig)
# z = T(x), (sample, latent)
latent_gamma: SampleLatent = gaussianizer.transform(gamma_samples)
# today (rbig)
# x̂ = T⁻¹(z), (sample, state)
recovered_gamma: SampleState = gaussianizer.inverse_transform(latent_gamma)
# today (rbig)
# the fitted spline of the one coordinate: knots x_l and knot slopes
fitted_spline: rbig.RQSpline = gaussianizer.splines_[0]
# max |x − x̂|
max_roundtrip: float = np.abs(gamma_samples - recovered_gamma).max()
# L + 1, the number of knots
n_knots: int = len(fitted_spline.x_knots_)
print(f"knots: {n_knots}, smallest knot slope: {fitted_spline.derivatives_.min()}")
print(
f"latent mean {latent_gamma.mean():.3f}, "
f"standard deviation {latent_gamma.std():.3f}"
)
print(f"round trip: max |x - T^-1(T(x))| = {max_roundtrip:.2e}")knots: 200, smallest knot slope: 0.001
latent mean 0.020, standard deviation 0.940
round trip: max |x - T^-1(T(x))| = 8.88e-16
fig, axes = plt.subplots(1, 2, figsize=(12, 4.2))
axes[0].hist(gamma_samples.ravel(), bins=60, density=True, color="C0", alpha=0.6)
axes[0].set(title="Input: gamma(2, 1)", xlabel="x", ylabel="density")
style_ax(axes[0])
latent_axis = np.linspace(-4, 4, 400)
axes[1].hist(latent_gamma.ravel(), bins=60, density=True, color="C1", alpha=0.6)
axes[1].plot(latent_axis, standard_normal_pdf(latent_axis), **GAUSS_KW, label="N(0, 1)")
axes[1].set(title="Latent: spline Gaussianizer", xlabel="z", ylabel="density")
axes[1].legend(fontsize=8)
style_ax(axes[1])
fig.tight_layout()
Figure 2:rbig’s spline Gaussianizer on gamma data. Left: the skewed input. Right: the latent, against the standard-normal density.
The latent is close to standard normal and the round trip is exact to machine precision. Its standard deviation is 0.94 rather than 1: the kernel density estimate smooths the CDF, which pulls the latent knots toward the centre. The map is fitted from the data in one pass, with no training; notebook 03 learns a marginal by maximum likelihood instead.
3. The rational-quadratic spline¶
A monotone cubic is invertible, but only by solving a cubic in each bin. The rational-quadratic spline of Durkan et al. Durkan et al., 2019 replaces each piece by a ratio of two quadratics chosen so that the inverse needs only the quadratic formula. On the interval it has bins, with increasing input knots , increasing output knots and positive knot slopes . On bin , the input becomes the fraction
and, with the bin slope and , the map is
It passes through and with slopes and , so neighbouring bins join with a continuous slope, and it is increasing whenever every . Outside the map is the identity. Inverting it means finding from an output . Clearing the denominator of (2) leaves a quadratic in ,
with , and . Its root in is
written in this form, rather than the textbook one, so that it does not lose precision when is small. Then , in one step and with no iteration, against the halvings of bisection (5).
This is gauss_flows’ RQSplineMarginal, one spline per coordinate, built on FlowJax’s RationalQuadraticSpline. Its n_bins argument is passed to FlowJax as the number of interior knots, so n_bins=8 gives bins. It starts at the identity, the right default for a flow layer, so to see a non-trivial spline we perturb its unconstrained parameters; the softmax and softplus reparameterisations keep any perturbation monotone. We then read its knots and compare (2) and (4), written out in a few lines of jax.numpy, against the library.
# today (gauss_flows)
# the spline layer, which starts at the identity
identity_spline = RQSplineMarginal(n_bins=8, shape=(1,), interval=4.0)
# its unconstrained array leaves θ, and the static rest
params: eqx.Module
static: eqx.Module
params, static = eqx.partition(identity_spline, eqx.is_inexact_array)
# one PRNG key per leaf
keys: Iterator[PRNGKeyArray] = iter(jr.split(jr.key(3), 8))
Leaf = Float[ArrayLike, " *leaf"]
# user
# θ + 0.8 ε, with ε ~ 𝒩(0, I) the shape of the leaf
def perturb(leaf: Leaf) -> Leaf:
"""Add Gaussian noise of scale 0.8 to one leaf, with the next key."""
# ε ~ 𝒩(0, I), (*leaf)
noise: Leaf = jr.normal(next(keys), leaf.shape)
return leaf + 0.8 * noise
# user
# every leaf of θ perturbed
params = jax.tree_util.tree_map(perturb, params)
# today (gauss_flows)
# the perturbed spline
rq_spline: RQSplineMarginal = eqx.combine(params, static)Reading the spline’s reparameterised knots gives the input knots , the output knots and the knot slopes of the one coordinate.
# Shapes: knot (L + 1) = 10 knots of the spline
# today (flowjax)
# the knots and slopes of the one coordinate, after the reparameterisation
knots: RationalQuadraticSpline = paramax.unwrap(rq_spline.spline.bijection)
# x_l, the input knots, (knot)
input_knots: PerKnot = jnp.asarray(knots.x_pos)[0]
# z_l, the output knots, (knot)
output_knots: PerKnot = jnp.asarray(knots.y_pos)[0]
# η_l, the knot slopes, (knot)
knot_slopes: PerKnot = jnp.asarray(knots.derivatives)[0]
slope_range = f"[{knot_slopes.min():.3f}, {knot_slopes.max():.3f}]"
print(f"bins L = {len(input_knots) - 1}, knot slopes in {slope_range}")bins L = 9, knot slopes in [0.271, 1.878]
Two helpers find the bin that holds a point and the per-bin quantities of (2): the width , the height , the bin slope and .
Scalar = Float[ArrayLike, ""]
Index = Int[ArrayLike, ""]
# user
# x_{l+1} − x_l, z_{l+1} − z_l, s_l and ω_l of bin l
def bin_terms(
bin_index: Index,
) -> tuple[Scalar, Scalar, Scalar, Scalar]:
"""Width, height, bin slope s_l and omega_l of bin ``bin_index``."""
# x_{l+1} − x_l
width: Scalar = input_knots[bin_index + 1] - input_knots[bin_index]
# z_{l+1} − z_l
height: Scalar = output_knots[bin_index + 1] - output_knots[bin_index]
# s_l = (z_{l+1} − z_l) / (x_{l+1} − x_l)
bin_slope: Scalar = height / width
# ω_l = η_{l+1} + η_l − 2 s_l
omega: Scalar = knot_slopes[bin_index + 1] + knot_slopes[bin_index] - 2 * bin_slope
return width, height, bin_slope, omegaThe bin that holds a point comes from a search over the knots.
# user
# l, the bin of the knots that holds a point
def bin_of(knot_values: PerKnot, point: Scalar) -> Index:
"""Index l of the bin of ``knot_values`` that holds ``point``."""
# the first knot above the point, minus one
position: Index = jnp.searchsorted(knot_values, point) - 1
return jnp.clip(position, 0, len(knot_values) - 2)# user
# T(x) = z_l + (z_{l+1} − z_l) (s_l ξ² + η_l ξ (1 − ξ)) / (s_l + ω_l ξ (1 − ξ))
def rqs_forward(point: Scalar) -> Scalar:
"""T(x) of the rational-quadratic spline, inside [-B, B]."""
# user
# l, the bin that holds x
bin_index: Index = bin_of(input_knots, point)
width: Scalar
height: Scalar
bin_slope: Scalar
omega: Scalar
# user
# x_{l+1} − x_l, z_{l+1} − z_l, s_l, ω_l
width, height, bin_slope, omega = bin_terms(bin_index)
# ξ = (x − x_l) / (x_{l+1} − x_l)
xi: Scalar = (point - input_knots[bin_index]) / width
# s_l ξ² + η_l ξ (1 − ξ)
numerator: Scalar = bin_slope * xi**2 + knot_slopes[bin_index] * xi * (1 - xi)
# s_l + ω_l ξ (1 − ξ)
denominator: Scalar = bin_slope + omega * xi * (1 - xi)
return output_knots[bin_index] + height * (numerator / denominator)The inverse finds the bin whose outputs hold , builds the coefficients of (3) and takes the stable root (4).
# user
# x = x_l + ξ (x_{l+1} − x_l), with ξ = 2 q₀ / (−q₁ − √(q₁² − 4 q₂ q₀))
def rqs_inverse(level: Scalar) -> Scalar:
"""x from the closed-form inverse, inside [-B, B]."""
# user
# l, the bin whose outputs hold z
bin_index: Index = bin_of(output_knots, level)
width: Scalar
height: Scalar
bin_slope: Scalar
omega: Scalar
# user
# x_{l+1} − x_l, z_{l+1} − z_l, s_l, ω_l
width, height, bin_slope, omega = bin_terms(bin_index)
# z − z_l
offset: Scalar = level - output_knots[bin_index]
# s_l − η_l
slope_gap: Scalar = bin_slope - knot_slopes[bin_index]
# q₂ = (z_{l+1} − z_l)(s_l − η_l) + (z − z_l) ω_l
q2: Scalar = height * slope_gap + offset * omega
# q₁ = (z_{l+1} − z_l) η_l − (z − z_l) ω_l
q1: Scalar = height * knot_slopes[bin_index] - offset * omega
# q₀ = −s_l (z − z_l)
q0: Scalar = -bin_slope * offset
# ξ = 2 q₀ / (−q₁ − √(q₁² − 4 q₂ q₀))
xi: Scalar = 2 * q0 / (-q1 - jnp.sqrt(q1**2 - 4 * q2 * q0))
return input_knots[bin_index] + xi * widthWe evaluate both formulas on a grid just inside and compare them with RQSplineMarginal.
# Shapes: test = 2,001 points inside [-4, 4]
# x on a grid just inside the interval, (test)
inputs_inside: PerTestPoint = jnp.linspace(-3.99, 3.99, 2001)
# today (gauss_flows)
# z = T(x) from the library, (test)
latent_lib: PerTestPoint = jax.vmap(rq_spline.transform)(inputs_inside[:, None])[:, 0]
# today (gauss_flows)
# x = T⁻¹(z) from the library, (test)
inputs_lib: PerTestPoint = jax.vmap(rq_spline.inverse)(latent_lib[:, None])[:, 0]The formulas, on the same points, against the library.
# user
# T(x) from the formula, (test)
latent_formula: PerTestPoint = jax.vmap(rqs_forward)(inputs_inside)
# user
# T⁻¹(z) from the formula, (test)
inputs_formula: PerTestPoint = jax.vmap(rqs_inverse)(latent_lib)
# max |T(x) − T_lib(x)|
err_forward: float = float(jnp.abs(latent_formula - latent_lib).max())
# max |T⁻¹(z) − T⁻¹_lib(z)|
err_inverse: float = float(jnp.abs(inputs_formula - inputs_lib).max())
print(
f"eq-spline-rqs vs RQSplineMarginal.transform: max |diff| = {err_forward:.1e}"
)
print(
f"eq-spline-inverse vs RQSplineMarginal.inverse: max |diff| = {err_inverse:.1e}"
)eq-spline-rqs vs RQSplineMarginal.transform: max |diff| = 4.4e-16
eq-spline-inverse vs RQSplineMarginal.inverse: max |diff| = 0.0e+00
The library’s round trip is checked on random points inside and outside the interval, and the forward map on a plot grid over .
# Shapes: sample = 3,000 random points; test = 600 plot points, both on [-5, 5]
# x ~ U(−5, 5), inside and outside the interval, (sample, state)
random_inputs: SampleState = jnp.asarray(rng.uniform(-5, 5, (3000, 1)))
# today (gauss_flows)
# z = T(x), (sample, latent)
random_latent: SampleLatent = jax.vmap(rq_spline.transform)(random_inputs)
# today (gauss_flows)
# x̂ = T⁻¹(z), (sample, state)
random_recovered: SampleState = jax.vmap(rq_spline.inverse)(random_latent)
# |x − x̂|
round_trip: SampleState = jnp.abs(random_inputs - random_recovered)
# x on a plot grid over [-5, 5], (test, state)
plot_grid: Float[ArrayLike, "test state"] = jnp.linspace(-5, 5, 600)[:, None]
# today (gauss_flows)
# T(x) on the plot grid, (test, latent)
plot_latent: Float[ArrayLike, "test latent"] = jax.vmap(rq_spline.transform)(plot_grid)
print(f"round trip: max |x - T^-1(T(x))| = {float(round_trip.max()):.1e}")
print(f"forward map increasing: {bool(jnp.all(jnp.diff(plot_latent.ravel()) > 0))}")round trip: max |x - T^-1(T(x))| = 1.3e-15
forward map increasing: True
fig, axes = plt.subplots(1, 2, figsize=(12, 4.2))
axes[0].plot(plot_grid.ravel(), plot_latent.ravel(), color="C4", lw=2, label="T(x)")
axes[0].plot(input_knots, output_knots, "ko", ms=5, label="knots")
axes[0].plot([-5, 5], [-5, 5], **GAUSS_KW, label="identity")
axes[0].set(title="Rational-quadratic spline, 9 bins", xlabel="x", ylabel="z = T(x)")
axes[0].legend(fontsize=8)
style_ax(axes[0])
axes[1].semilogy(
random_inputs.ravel(),
np.maximum(np.asarray(round_trip).ravel(), 1e-18),
".",
ms=3,
alpha=0.4,
color="C4",
)
axes[1].axhline(1e-15, color="k", ls="--", lw=1, label="1e-15")
axes[1].set(
title="Closed-form inverse: round-trip error",
xlabel="x",
ylabel="|x - T^-1(T(x))|",
ylim=(1e-18, 1e-3),
)
axes[1].legend(fontsize=8)
style_ax(axes[1])
fig.tight_layout()
Figure 3:Left: the perturbed rational-quadratic spline with its knots, and the identity outside . Right: the round-trip error of the closed-form inverse, at machine precision with no iteration.
Both formulas reproduce the library to rounding error, and the library round-trips at machine precision in one shot. The mixture CDF of notebook 01 reaches the same accuracy only after a bisection or Newton loop; notebook 04 compares those loops. The spline pays for its free inverse with a forward map that needs a bin search and more parameters per coordinate, which is a good trade whenever a flow must both score and sample.
4. The log-determinant in closed form¶
A flow also needs each layer’s log-determinant, (4). For a marginal map it is the sum over coordinates of , and the general form (5) asks for a density. The spline needs none: differentiating (2) gives
which is positive whenever every , because each term of the numerator is. We compare it with transform_and_log_det and with an autodiff derivative.
# user
# T'(x) = s_l² (η_{l+1} ξ² + 2 s_l ξ (1 − ξ) + η_l (1 − ξ)²) / (s_l + ω_l ξ (1 − ξ))²
def rqs_slope(point: Scalar) -> Scalar:
"""T'(x) of the rational-quadratic spline, inside [-B, B]."""
# user
# l, the bin that holds x
bin_index: Index = bin_of(input_knots, point)
width: Scalar
bin_slope: Scalar
omega: Scalar
# user
# x_{l+1} − x_l, s_l, ω_l
width, _, bin_slope, omega = bin_terms(bin_index)
# ξ = (x − x_l) / (x_{l+1} − x_l)
xi: Scalar = (point - input_knots[bin_index]) / width
# η_{l+1} ξ² + 2 s_l ξ (1 − ξ) + η_l (1 − ξ)²
top: Scalar = (
knot_slopes[bin_index + 1] * xi**2
+ 2 * bin_slope * xi * (1 - xi)
+ knot_slopes[bin_index] * (1 - xi) ** 2
)
return bin_slope**2 * top / (bin_slope + omega * xi * (1 - xi)) ** 2Autodiff gives an independent slope to check both the formula and the library’s log-determinant against.
# user
# T'(x) by forward-mode autodiff
def autodiff_slope(point: Float[ArrayLike, " state"]) -> Scalar:
"""T'(x) of the library spline by ``jax.jacfwd``, as a scalar."""
# today (gauss_flows)
# ∂T/∂x, (latent, state)
jacobian: Float[ArrayLike, "latent state"] = jax.jacfwd(rq_spline.transform)(point)
return jacobian.reshape(())On the plot grid we compare the library’s log-determinant with the log of the autodiff slope, and the formula with autodiff inside the interval, where of the plot points lie.
# Shapes: inside (N_in) = the test points inside (-4, 4)
# today (gauss_flows)
# log |T'(x)| from the library, (test)
log_det: PerTestPoint
_, log_det = jax.vmap(rq_spline.transform_and_log_det)(plot_grid)
# user
# T'(x) by autodiff, (test)
slope_autodiff: PerTestPoint = jax.vmap(autodiff_slope)(plot_grid)
# the plot points strictly inside (-4, 4), (test)
inside: TestMask = jnp.abs(plot_grid.ravel()) < 4.0
# user
# T'(x) from the formula, inside the interval, (inside)
slope_formula: Float[ArrayLike, " inside"] = jax.vmap(rqs_slope)(
plot_grid.ravel()[inside]
)
# max |log |T'(x)| − log T'_autodiff(x)|
err_logdet: float = float(jnp.max(jnp.abs(log_det - jnp.log(slope_autodiff))))
# max |T'_formula(x) − T'_autodiff(x)|
err_slope: float = float(jnp.max(jnp.abs(slope_formula - slope_autodiff[inside])))
print(f"transform_and_log_det vs log of autodiff slope: max |diff| = {err_logdet:.1e}")
print(f"eq-spline-deriv vs autodiff slope: max |diff| = {err_slope:.1e}")
print(f"slope at the left edge: inside {float(knot_slopes[0]):.3f}, outside 1.000")transform_and_log_det vs log of autodiff slope: max |diff| = 1.3e-15
eq-spline-deriv vs autodiff slope: max |diff| = 2.7e-15
slope at the left edge: inside 0.603, outside 1.000
fig, ax = plt.subplots(figsize=(12, 4.2))
ax.plot(plot_grid.ravel(), slope_autodiff.ravel(), color="C4", lw=2, label="T'(x)")
ax.plot(input_knots, knot_slopes, "ko", ms=5, label="knot slopes")
ax.axhline(1.0, **GAUSS_KW, label="slope 1 (identity tails)")
ax.set(title="The slope of the spline, in closed form", xlabel="x", ylabel="T'(x)")
ax.legend(fontsize=8)
style_ax(ax)
fig.tight_layout()
Figure 4:The slope of the rational-quadratic spline: continuous across the interior knots (dots), and 1 in the identity tails. Its end slopes are learned parameters, so it jumps at .
The formula, the library and autodiff agree to rounding error, so the log-determinant costs one evaluation of (5) per coordinate, with no autodiff and no quadrature. The slope is continuous across the interior knots, as section 3 promised. It is not continuous at the ends of the interval: FlowJax learns the end slopes and while the tails have slope 1, so here jumps from 0.60 to 1 at . Durkan et al. fix the end slopes at 1 to make the whole map ; with learned end slopes the density of the flow has a step at , which is harmless for training but visible in a plot of .
Recap¶
| Spline | Monotone | Inverse | Log-determinant | Tool |
|---|---|---|---|---|
| Natural cubic | no, overshoots | none | none | not a CDF |
| Monotone cubic (PCHIP) | yes | cubic root per bin | slope of the cubic | functax.interp.Pchip |
| Rational-quadratic | yes, by construction | closed form, (4) | closed form, (5) | RQSplineMarginal, rbig.SplineGaussianizer |
Next. So far every marginal has been fitted from quantiles or by EM. Notebook 03 trains the parameters of a mixture CDF end to end by maximum likelihood, as one layer of a flow.
- Fritsch, F. N., & Carlson, R. E. (1980). Monotone Piecewise Cubic Interpolation. SIAM Journal on Numerical Analysis, 17(2), 238–246. 10.1137/0717021
- Durkan, C., Bekasov, A., Murray, I., & Papamakarios, G. (2019). Neural Spline Flows. Advances in Neural Information Processing Systems (NeurIPS).