Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

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

Open In Colab

Every flow so far has learned one density px(x)p_x(\vect{x}). Many problems ask for a family of them, indexed by a context yy: a covariate, a sensor setting, a forcing. A conditional flow makes its map depend on the context, z=fθ(x;y)\vect{z} = f_\theta(\vect{x}; y), keeps the standard-normal base, and so learns the whole family px(x∣y)p_x(\vect{x} \mid y) 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 px(⋅∣y)p_x(\cdot \mid y) right, and is it Gaussianized? A family whose exact density we know answers both, and a calibration test answers the second without it.

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 w∼N(0,I)\vect{w} \sim \mathcal{N}(\vect{0}, \mat{I}) in two dimensions and a context yy uniformly on [−1.5,1.5][-1.5, 1.5], and set

x1=0.8w1,x2=0.6w2+1.5ytanh⁡(1.2w1)\begin{aligned} x_1 &= 0.8 w_1, \\ x_2 &= 0.6 w_2 + 1.5 y \tanh(1.2 w_1) \end{aligned}

At y=0y = 0 the two coordinates are independent Gaussians. As ∣y∣\lvert y \rvert grows, x2x_2 follows an S-shaped curve in x1x_1, rising for y>0y > 0 and falling for y<0y < 0, so the context changes the spread of x2x_2, its shape and its dependence on x1x_1 at once; the tanh⁡\tanh keeps the tails light. The map from w\vect{w} to x\vect{x} is triangular and invertible for every yy, so the exact conditional density follows from the change of variables of Part 0 (4):

log⁡px(x∣y)=log⁡N(w1;0,1)+log⁡N(w2;0,1)−log⁡0.8−log⁡0.6\log p_x(\vect{x} \mid y) = \log \mathcal{N}(w_1; 0, 1) + \log \mathcal{N}(w_2; 0, 1) - \log 0.8 - \log 0.6

with w1=x1/0.8w_1 = x_1 / 0.8 and w2=(x2−1.5ytanh⁡(1.2w1))/0.6w_2 = (x_2 - 1.5 y \tanh(1.2 w_1)) / 0.6. It is the reference every trained flow below is measured against.

The rows follow (1) at their contexts.

The 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.

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).

exact NLL: training rows 2.2674, held-out rows 2.2901 nats
<Figure size 560x500 with 2 Axes>

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 z=fθ(x;y)\vect{z} = f_\theta(\vect{x}; y) that is invertible in x\vect{x} for every context. The change of variables holds slice by slice:

log⁡px(x∣y)=log⁡N(fθ(x;y);0,I)+log⁡∣det⁡Jfθ(x;y)∣\log p_x(\vect{x} \mid y) = \log \mathcal{N}(f_\theta(\vect{x}; y); \vect{0}, \mat{I}) + \log \lvert \det \mat{J}_{f_\theta}(\vect{x}; y) \rvert

where the Jacobian is taken in x\vect{x} only; the context is an input, never transformed. Because the base is the same standard normal for every yy, a trained fθ(⋅;y)f_\theta(\cdot; y) is a conditional Gaussianizer: it should send every slice px(⋅∣y)p_x(\cdot \mid y) to the same N(0,I)\mathcal{N}(\vect{0}, \mat{I}).

The couplings of Part 5 take the context as an extra input to their conditioner: RQSplineCoupling with cond_dim=1 concatenates yy 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 fθ(x;y)=xf_\theta(\vect{x}; y) = \vect{x}.

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.

Every run takes 3,000 Adam steps of 256 rows on a one-cycle cosine rate that peaks at 3×10−33 \times 10^{-3}, with the gradient clipped to a global norm of 5, and evaluates the held-out rows every 100 steps.

trained in 18 s
coupling flow: training NLL 2.2568, held-out NLL 2.2992 nats
exact density: training NLL 2.2674, held-out NLL 2.2901 nats
<Figure size 700x350 with 1 Axes>

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 px(x∣y)p_x(\vect{x} \mid y) for any yy 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.

<Figure size 1600x660 with 10 Axes>

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 ∣y∣\lvert y \rvert grows, and leaves it round and unbent at y=0y = 0. Nothing in the architecture says the family is symmetric in yy; 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 fθ(⋅;y)f_\theta(\cdot; y) 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.

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, 24/1500≈0.13\sqrt{24/1500} \approx 0.13) and the correlation within 0.04 of zero (1.4 standard errors, 1/1500≈0.0261/\sqrt{1500} \approx 0.026). 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 fθ(⋅;y)f_\theta(\cdot; y) is exact, z∼N(0,I)\vect{z} \sim \mathcal{N}(\vect{0}, \mat{I}) for every yy, so ∥z∥2\lVert \vect{z} \rVert^2 follows a χ22\chi^2_2 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

u~=Fχ22(∥z∥2)=1−e−∥z∥2/2\tilde{u} = F_{\chi^2_2}(\lVert \vect{z} \rVert^2) = 1 - e^{-\lVert \vect{z} \rVert^2 / 2}

which is uniform on [0,1][0, 1] for a calibrated flow. Its empirical distribution function at a level τ\tau is the coverage of the flow’s central region of probability τ\tau, the disk ∥z∥2≤Fχ22−1(τ)\lVert \vect{z} \rVert^2 \le F_{\chi^2_2}^{-1}(\tau) mapped back through fθ−1(⋅;y)f_\theta^{-1}(\cdot; y): a calibrated flow covers a fraction τ\tau of the rows at every level, and at every context. A Kolmogorov-Smirnov test of u~\tilde{u} against U(0,1)\mathcal{U}(0, 1) checks all levels at once.

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 ∣y∣\lvert y \rvert, where the standard error is up to 1.9 points. The Kolmogorov-Smirnov test does not reject uniformity (p=0.17p = 0.17). The flow is calibrated across the whole range of the context, where the spread of x2x_2 grows with ∣y∣\lvert y \rvert.

6. When elementwise maps are enough

A cheaper flow makes every map elementwise in x\vect{x}: each coordinate gets its own one-dimensional Gaussianization whose shape depends on yy, zd=fd(xd;y)z_d = f_d(x_d; y). Its density factorises,

px(x∣y)=∏d=1Dxpd(xd∣y)p_x(\vect{x} \mid y) = \prod_{d=1}^{D_x} p_d(x_d \mid y)

so it can fit the conditional marginal of each coordinate, its location, spread and shape at every yy, 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 yy-dependent scale and shift of each coordinate, γ(y)⊙g(x)+β(y)\gvect{\gamma}(y) \odot g(\vect{x}) + \gvect{\beta}(y), read by a small network from yy. Four such layers in turn make the shape of each marginal map depend on yy as well. Like the couplings, a fresh wrapper starts as the identity.

elementwise flow: held-out NLL 2.7178 nats
   coupling flow: held-out NLL 2.2992 nats
exact density: held-out NLL 2.2901 nats
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
<Figure size 1200x800 with 6 Axes>

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 y=−1y = -1 and +0.80 at y=+1y = +1: the dependence the context puts between x1x_1 and x2x_2 passes straight through, because no map of one coordinate can read the other. At y=0y = 0, where the family’s coordinates are independent, the correlation is 0.01 and the elementwise flow is as good as the coupling flow.

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
<Figure size 1000x360 with 2 Axes>

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 (p=1.5×10−10p = 1.5 \times 10^{-10}). Its histogram of u~\tilde{u} shows the shape of the failure: too many rows near u~=0\tilde{u} = 0 and near u~=1\tilde{u} = 1. A correlated latent with unit marginals has the right mean of ∥z∥2\lVert \vect{z} \rVert^2 but a wider distribution, with too many rows near the centre and too many far out. A calibration check of px(x∣y)p_x(\vect{x} \mid y) should test the whole distribution of u~\tilde{u}, not one or two levels.

<Figure size 1300x440 with 3 Axes>

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 y=1.2y = 1.2 the coupling flow follows the S. The elementwise flow’s density is the product of its two marginals (5): it puts the mass of x2x_2 in horizontal bands that do not move with x1x_1, 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 y≠0y \neq 0, the context has to reach a map that reads one coordinate to transform another: a conditional coupling.

Recap

PieceEquationIn 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 contextRQSplineCoupling(..., cond_dim=1)
training on rows and their contexts(1)negative_log_likelihood(flow, x, condition=y) in ConditionalNLL
the conditional Gaussianizer fθ(⋅;y)f_\theta(\cdot; y)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 ∥z∥2\lVert \vect{z} \rVert^2. 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, y=Hx+ε\vect{y} = \mat{H} \vect{x} + \gvect{\varepsilon}, and trains px(x∣y)p_x(\vect{x} \mid \vect{y}) as a posterior that one pass of the flow samples for any observation.