Foundations to Frontier
Tests
H. Generative Models › H5 Normalizing Flows

Neural Spline Flows: monotone rational-quadratic splines

Affine coupling and autoregressive layers transform each variable by a shift and a scale, so a single layer can only produce location-scale conditionals. Neural Spline Flows (Durkan, Bekasov, Murray and Papamakarios, 2019) replace the affine map with a monotone rational-quadratic spline: K bins whose widths, heights and knot derivatives are produced by the conditioner network. The spline is strictly increasing, smooth, has an analytic derivative for the log-determinant and an exact closed-form inverse (a quadratic equation per bin), and is the identity outside a bounding box with linear tails. Splines drop into coupling layers (fast both ways) or autoregressive layers, and became the default flow layer in tools such as nflows, Zuko and sbi. This page covers the spline construction, the parameterisation (softmax widths and heights, softplus derivatives, minimum bin sizes), inversion, tails, and earlier piecewise-linear and quadratic splines. In the exercises you implement the spline, its derivative and inverse, then fit a single 1-D spline layer to a three-mode density by maximum likelihood. A Gaussian (an affine flow) scored 2.027 nats, 2 bins 1.826, 4 bins 1.545 and 8 bins 1.534, within 0.01 nats of the true density (1.524); the inverse was exact to 1e-15.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

A flexible bend that never doubles back

A flow layer needs a one-dimensional bending rule that is always increasing, so it can be undone. A straight line with a slope (shift and stretch) is the simplest, but it can only move and widen a bump; it cannot turn one bump into three. A spline joins many small curved pieces end to end, each piece rising, so the whole curve rises but can be steep in some places and flat in others. Steep regions spread probability out, flat regions pile it up, so one spline can carve several peaks. The demo draws a spline with a few bins and lets you change one knot’s slope.

Flow lab
4 equal bins on [−3, 3] (dots are knots), identity outside. Solid: the spline, monotone for any positive slopes. Dashed: its derivative, whose log is the log-det. Setting the middle slope to 0.3 bends the curve locally without touching the other bins.
Why engineers care

Spline flows are the default in simulation-based inference toolkits, used for posteriors over physical parameters in gravitational-wave astronomy, cosmology and engineering model calibration.

📝 Quick check (Level 0)
0/3 answered
  1. 1. A flow's 1-D transform must be…
  2. 2. An affine 1-D flow can turn a Gaussian into…
  3. 3. A spline is built from…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

The rational-quadratic spline

  • Domain: [−B, B] split into K bins with knots (x_k, y_k); identity (linear tails) outside, so the map is defined on the whole real line.
  • Parameters per dimension: K unnormalised widths, K heights (softmax, scaled to 2B, with a minimum bin size) and K − 1 interior derivatives (softplus plus a minimum); boundary derivatives are 1 to match the tails: 3K − 1 outputs.
  • Within bin k: with s_k = h_k / w_k and ξ = (x − x_k)/w_k, y = y_k + h_k [s_k ξ² + d_k ξ(1 − ξ)] / [s_k + (d_(k+1) + d_k − 2 s_k) ξ(1 − ξ)] (Gregory and Delbourgo, 1982).
  • Monotone and smooth: positive slopes at the knots guarantee strict monotonicity; the curve is continuously differentiable across knots.
  • Derivative: dy/dx = s_k² [d_(k+1) ξ² + 2 s_k ξ(1 − ξ) + d_k (1 − ξ)²] / [denominator]²; the log-det is Σ log dy/dx.
  • Inverse: in the bin containing y, ξ solves a quadratic a ξ² + b ξ + c = 0; use the numerically stable root 2c / (−b − √(b² − 4ac)).
  • Placement: in coupling layers (RQ-NSF (C), fast both ways) or autoregressive layers (RQ-NSF (AR)), with K around 8.
  • Predecessors: piecewise-linear and piecewise-quadratic coupling (Müller et al., 2019, ‘Neural importance sampling’); cubic splines (Durkan et al., 2019a). Later: monotone rational-quadratic splines on circles and tori (Rezende et al., 2020).
📝 Quick check (Level 1)
0/3 answered
  1. 1. Raw outputs per dimension for K bins:
  2. 2. Outside [−B, B] the spline is…
  3. 3. The inverse is found by…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

Implementing spline layers

Exercise 1.

  • The rational-quadratic spline and its derivative.
  • Its closed-form inverse.

Practice.

  • Normalise widths and heights with softmax and enforce minimum bin sizes (about 1e-3) to avoid degenerate bins.
  • Use softplus plus a minimum for derivatives; fix the boundary derivatives to 1 for linear tails.
  • Standardise data so most of it lies inside [−B, B] (B = 3 to 5).
  • Use the stable quadratic root and clamp the discriminant at 0 in float32.
  • Prefer library implementations: nflows (PiecewiseRationalQuadraticCouplingTransform), Zuko (NSF), distrax (RationalQuadraticSpline).
import zuko, torch
flow = zuko.flows.NSF(features=2, context=3, transforms=4, bins=8, hidden_features=(64, 64))
x, c = torch.randn(256, 2), torch.randn(256, 3)        # data and conditioning variables
loss = -flow(c).log_prob(x).mean()                     # conditional density, e.g. a posterior
loss.backward()
theta = flow(c[:1]).sample((1000,))                    # 1000 posterior samples for one observation
🐍 Exercise 1: rational-quadratic spline
Write the monotone rational-quadratic spline with its derivative and its closed-form inverse.
📝 Quick check (Level 2)
0/3 answered
  1. 1. A typical number of bins is…
  2. 2. Degenerate bins are avoided with…
  3. 3. Before fitting, data should be…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

Monotonicity. Within a bin the RQ form is a ratio of quadratics whose derivative numerator is a positive combination of d_k, d_(k+1) and s_k when all are positive, so dy/dx is strictly positive; continuity of value and slope at knots follows from ξ = 0 giving (y_k, d_k) and ξ = 1 giving (y_(k+1), d_(k+1)).

Expressiveness per layer. In 1-D the ideal flow is F⁻¹_Z ∘ F_X, a monotone function. Any continuous monotone function can be approximated by a monotone spline with enough bins, so a single spline layer can represent multimodal 1-D densities that an affine layer cannot; in coupling form each conditional x_B given x_A gets this flexibility.

Cost. Bin search (searchsorted) is O(log K) per element and the rest is elementwise, so a spline layer costs little more than an affine one; the conditioner must output 3K − 1 numbers per transformed dimension instead of 2.

Exercise check. Fitting one spline layer to a three-mode mixture: with 2 bins the curve can only produce two density regions and stalled at 1.826 nats; with 4 bins it reached 1.545, and 8 bins 1.534 against 1.524 for the true density, closing 98% of the gap from the Gaussian.

📝 Quick check (Level 3)
0/3 answered
  1. 1. The ideal 1-D flow is…
  2. 2. A spline layer's extra cost over affine is mainly…
  3. 3. At ξ = 0 the spline passes through…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

How many spline bins does one layer need to fit a multimodal density?

History.

  • J. A. Gregory and R. Delbourgo, “Piecewise rational quadratic interpolation to monotonic data” (IMA J. Numer. Anal., 1982).
  • T. Müller, B. McWilliams, F. Rousselle, M. Gross and J. Novák, “Neural importance sampling” (ACM TOG, 2019): piecewise-linear and quadratic couplings.
  • C. Durkan, A. Bekasov, I. Murray and G. Papamakarios, “Neural spline flows” (NeurIPS 2019).

Exercise 2. 3000 training and 3000 test samples of 0.5 N(−2, 0.4²) + 0.3 N(0.5, 0.5²) + 0.2 N(2.5, 0.3²).

  • Model: one 1-D RQ spline on [−4, 4] with linear tails, K = 2, 4 or 8 bins (3K − 1 free parameters), base N(0, 1).
  • Training: Adam, learning rate 0.05, batch 512, 250 steps; exact gradients by the complex-step method (evaluate the loss at θ + iεI in one batched call).
  • Baselines: Gaussian fit (= the best affine 1-D flow); the true mixture NLL.
model seed 0 seed 1 seed 2
Gaussian (affine flow) 2.027 2.025 2.042
spline, 2 bins 1.826 1.831 1.832
spline, 4 bins 1.545 1.555 1.563
spline, 8 bins 1.534 1.542 1.537
true density 1.524 1.527 1.525
  • Bins matter up to the number of modes: 2 bins removed 40% of the gap, 4 bins about 95%, 8 bins 97–98%.
  • 8 bins were within 0.010–0.015 nats of the true density on every seed: one layer is enough in 1-D.
  • Exact inverse: round-trip error about 1e-15 (below 1e-12).
  • Caveat: 1-D only; in higher dimensions the conditioner network and depth matter, and gradients come from autodiff rather than complex steps.
🐍 Exercise 2 (research): how many spline bins does one layer need to fit a multimodal density?
Fit a 1-D rational-quadratic spline flow with 2, 4 and 8 bins to a three-mode density and compare with a Gaussian and the true density.

Spline flows in AI, robotics and aerospace

  • Simulation-based inference: NSF is a standard density estimator in sbi and Zuko for posteriors of simulator parameters (e.g. exoplanet atmospheres, gravitational waves, structural model calibration).
  • Neural importance sampling: piecewise-polynomial couplings learn sampling densities for Monte Carlo rendering and for integrals in particle physics.
  • Lattice field theory and molecules: spline flows on circles and tori model angles and periodic variables.

References

  1. C. Durkan, A. Bekasov, I. Murray and G. Papamakarios (2019). “Neural spline flows.” NeurIPS.
  2. J. A. Gregory and R. Delbourgo (1982). “Piecewise rational quadratic interpolation to monotonic data.” IMA Journal of Numerical Analysis.
  3. T. Müller et al. (2019). “Neural importance sampling.” ACM Transactions on Graphics.
  4. D. J. Rezende et al. (2020). “Normalizing flows on tori and spheres.” ICML.