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.

Three ways to condition a flow

A conditional Gaussianizer maps every slice p(x | y) to the same N(0, I); the context y can enter at the base, in the couplings, or through a modulation wrapped around any layer

00 · Three ways to condition a flow

Open In Colab

Every flow of Parts 4 to 6 learned one density p(x)p(\vect{x}). Here the flow’s parameters become functions of a context y\vect{y}, so one model holds a whole family of densities p(x∣y)p(\vect{x} \mid \vect{y}) Winkler et al., 2019, and its map sends every slice of that family to the same N(0,I)\mathcal{N}(\vect{0}, \mat{I}): a conditional Gaussianizer. Training, sampling and the log-determinant are unchanged; what changes is where the context enters. The conditional-flow example fits the same four variants (no context, the base, the couplings, both) on two moons and ranks them on the training rows; here we rank them on held-out rows, add the Conditioner wrapper as a fifth, ask how Gaussian each class’s latent is, test the rule of thumb on a pair of crescents that differ only by a shift, and look inside the conditioning layers.

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. Class-conditional two moons

The two moons of Parts 4 and 5, but this time we keep the label make_moons returns: y=0y = 0 for the upper crescent and y=1y = 1 for the lower one. The context is the one-hot label y∈{(1,0),(0,1)}\vect{y} \in \{(1, 0), (0, 1)\}, so Dy=2D_y = 2, and each slice p(x∣y)p(\vect{x} \mid \vect{y}) is one crescent. The two crescents differ in position and in shape, since the lower one is the upper one turned upside down.

A fixed shuffle holds out 600 rows; every flow trains on the other 2,400.

{'train': (2400, 2), 'held_out': (600, 2)}
<Figure size 500x450 with 1 Axes>

Figure 1:Two moons coloured by the crescent each point belongs to. The label is the context: each slice p(x | y) is one crescent.

2. Where the context can enter

Write f(⋅;y)f(\cdot; \vect{y}) for the flow’s map from data to latent at context y\vect{y}. For each fixed y\vect{y} it is a bijection, so the change of variables holds slice by slice:

log⁡p(x∣y)=log⁡pz(f(x;y)∣y)+log⁡∣det⁡Jf(x;y)∣\log p(\vect{x} \mid \vect{y}) = \log p_z(f(\vect{x}; \vect{y}) \mid \vect{y}) + \log \vert \det \mat{J}_f(\vect{x}; \vect{y}) \vert

where Jf(x;y)\mat{J}_f(\vect{x}; \vect{y}) is the Jacobian of ff in x\vect{x} alone. The context can enter in three places.

The base can depend on it. ConditionalDiagGaussian is a diagonal Gaussian whose mean β(y)\gvect{\beta}(\vect{y}) and standard deviations γ(y)\gvect{\gamma}(\vect{y}) come from a small network of the context:

pz(z∣y)=N(z;β(y),diag(γ(y))2)p_z(\vect{z} \mid \vect{y}) = \mathcal{N}(\vect{z}; \gvect{\beta}(\vect{y}), \mathrm{diag}(\gvect{\gamma}(\vect{y}))^2)

The couplings can read it. A coupling’s conditioner cϕc_\phi already reads the passive half xA\vect{x}_A (Part 5); RQSplineCoupling(cond_dim=D_y) also gives it the context, so the spline of the active half changes shape from one context to another:

zB=Tθ(xB),θ=cϕ(xA,y)\begin{aligned} \vect{z}_B &= T_\theta(\vect{x}_B), \\ \theta &= c_\phi(\vect{x}_A, \vect{y}) \end{aligned}

The Jacobian stays triangular, so the log-determinant is still a sum. Any other layer can be wrapped. Conditioner takes a bijection gg that cannot read a context (a rotation, a normalisation, or here the identity) and modulates its output feature by feature, which adds ∑ilog⁡γi(y)\sum_i \log \gamma_i(\vect{y}) to its log-determinant:

h′=γ(y)⊙g(h)+β(y)\vect{h}' = \gvect{\gamma}(\vect{y}) \odot g(\vect{h}) + \gvect{\beta}(\vect{y})

This is FiLM, feature-wise linear modulation, and it is also how ConditionalDiagGaussian makes its mean and scale: both use AffineModulation, whose readout starts at zero so that γ=1\gvect{\gamma} = \vect{1} and β=0\gvect{\beta} = \vect{0} for every context. We compare five flows that differ only in where the context goes:

flowbasecouplingsdata sidewhat the context can change
noneN(0,I)\mathcal{N}(\vect{0}, \mat{I})unconditionalnothing: it fits the mixture of both crescents
base(2)unconditionalan affine map of the latent per context
couplingN(0,I)\mathcal{N}(\vect{0}, \mat{I})(3)the shape of every coupling’s spline
both(2)(3)both
wrapperN(0,I)\mathcal{N}(\vect{0}, \mat{I})unconditional(4) on the identityan affine map of the data per context

Every flow has four rational-quadratic spline couplings Durkan et al., 2019 with 8 bins on [−4,4][-4, 4] and a two-layer conditioner of width 64, with a flip after each so both coordinates are transformed. The four blocks share one type, so they are built at once with eqx.filter_vmap and applied in turn by FlowJax’s Scan.

conditional_flow assembles one of the five flows. FlowJax’s Transformed runs its bijection in the sampling direction, so the density-direction map is wrapped in Invert, as in Part 5.

Each of the three conditional pieces starts where it would be without the context: the couplings’ readouts start at zero (zero_readout, Part 5), and AffineModulation starts at γ=1\gvect{\gamma} = \vect{1}, β=0\gvect{\beta} = \vect{0}. With an even number of flips, every fresh flow is then the identity map with a standard-normal base, whatever the context. We check it on the training rows.

    none: 24,432 weights, max gap 1.3e-15
    base: 29,044 weights, max gap 3.1e-08
coupling: 24,944 weights, max gap 1.3e-15
    both: 29,556 weights, max gap 3.1e-08
 wrapper: 29,044 weights, max gap 1.3e-15

Every fresh flow is the identity with a standard-normal base. Three agree with log⁡N(x;0,I)\log \mathcal{N}(\vect{x}; \vect{0}, \mat{I}) to 10-15; the two with a conditional base differ by 3.1×10−83.1 \times 10^{-8}, because ConditionalDiagGaussian keeps log⁡2π\log 2\pi in float32 when float64 is switched on after the import, as it is here (gauss_flows#272). The context costs few weights: the conditional base and the wrapper each add 4,612 to the 24,432 of the couplings, and the conditional couplings add 512, one more input to each conditioner’s first layer per context coordinate.

3. Training all five

Every flow minimises the same loss, the mean negative conditional log-likelihood of a batch, −1Nb∑nlog⁡p(xn∣yn)-\frac{1}{N_b} \sum_n \log p(\vect{x}_n \mid \vect{y}_n) by (1). negative_log_likelihood takes the batch’s contexts as its condition, so the task is the one of Part 4 with the context passed through.

Each run takes 2,000 Adam steps of 256 rows on a one-cycle cosine rate that peaks at 5×10−35 \times 10^{-3}, with the gradient clipped to a global norm of 1.

    none: held-out NLL 1.374 nats
    base: held-out NLL 0.659 nats
coupling: held-out NLL 0.663 nats
    both: held-out NLL 0.666 nats
 wrapper: held-out NLL 1.234 nats

The held-out rows are the same for every flow, so the standard error of a difference between two flows comes from the row-by-row differences of their log-densities, which is much smaller than the spread of either.

Here is how much better the base-conditioned flow does than each of the others on the moons.

base against coupling: +0.003 ± 0.008 nats per row
base against     both: +0.007 ± 0.007 nats per row
base against  wrapper: +0.575 ± 0.017 nats per row

The flow with no context is far behind, at 1.374 nats against 0.659 to 0.666 for the three that read the context through the base or the couplings. The gap of 0.715 nats is close to log⁡2=0.693\log 2 = 0.693, which is what the label is worth here: the two crescents do not overlap and are equally likely, so where one has density the marginal p(x)p(\vect{x}) is half of p(x∣y)p(\vect{x} \mid \vect{y}). The wrapper recovers only part of it, at 1.234 nats.

The base, the couplings and both tie: the base is ahead of the couplings by 0.003 ± 0.008 nats per row and of both by 0.007 ± 0.007, within one standard error, and ahead of the wrapper by 0.575 ± 0.017. The conditional-flow example trains differently (5,000 rows with less noise, a constant rate and early stopping, in float32), and its run puts the base-only flow well behind the coupling flow on its training rows (-0.816 against -0.440 nats; its training keys change from one execution to the next, gauss_flows#274). On these rows and with this schedule the base keeps up.

Sampling runs each flow the other way: draw z∼pz(⋅∣y)\vect{z} \sim p_z(\cdot \mid \vect{y}), then x=f−1(z;y)\vect{x} = f^{-1}(\vect{z}; \vect{y}). We draw 1,000 points for each label from each flow.

<Figure size 1500x640 with 10 Axes>

Figure 2:Draws of each trained flow for each label (colour) over the training rows of that label (grey). The flow with no context draws both crescents for both labels; base, coupling and both put the draws of each label on its crescent; the wrapper adds a branch across the other crescent.

The draws tell the same story. With no context, each label gets both crescents. The base, the couplings and both put each label’s draws on its own crescent and nowhere else. The wrapper can only move and stretch the data before one shared map, and it cannot turn the upper crescent into the lower one, so each label gets its crescent plus a branch across the other.

4. How Gaussian is each slice?

A conditional Gaussianizer should send each slice to N(0,I)\mathcal{N}(\vect{0}, \mat{I}), not only the mixture of all of them. For the flows with a conditional base, the latent f(x;y)f(\vect{x}; \vect{y}) follows (2), so we standardise it first; for the others the latent is already the standardised one:

z~=(f(x;y)−β(y))⊘γ(y)\tilde{\vect{z}} = (f(\vect{x}; \vect{y}) - \gvect{\beta}(\vect{y})) \oslash \gvect{\gamma}(\vect{y})

For each label we send its held-out rows through, fit a Gaussian to the z~\tilde{\vect{z}} by their sample mean and covariance, and measure that Gaussian’s KL divergence from N(0,I)\mathcal{N}(\vect{0}, \mat{I}) with gaussian_kl_divergence. It is zero when the first two moments match and says nothing about higher ones, so it is a floor on how far each slice is from the target.

The KL of a slice is then a closed form in the sample moments of its standardised latent.

    none: KL of the y = 0 slice 0.487, of the y = 1 slice 0.486 nats
    base: KL of the y = 0 slice 0.006, of the y = 1 slice 0.005 nats
coupling: KL of the y = 0 slice 0.008, of the y = 1 slice 0.007 nats
    both: KL of the y = 0 slice 0.007, of the y = 1 slice 0.005 nats
 wrapper: KL of the y = 0 slice 0.159, of the y = 1 slice 0.169 nats

The flow with no context leaves each slice 0.49 nats from N(0,I)\mathcal{N}(\vect{0}, \mat{I}): it Gaussianizes the mixture of the two crescents, so each one lands on its own part of the target. Reading the context through the base, the couplings or both brings both slices within 0.008 nats of N(0,I)\mathcal{N}(\vect{0}, \mat{I}) in their first two moments, and the wrapper leaves 0.16 and 0.17 nats. The latents show why conditioning only the base is enough here: the unconditional map is free to send the two crescents to two separate blobs, and β(y)\gvect{\beta}(\vect{y}) and γ(y)\gvect{\gamma}(\vect{y}) centre and scale each one. A base that reads the context acts after a nonlinear map, so it does not force one shape on both labels.

<Figure size 1300x440 with 3 Axes>

Figure 3:Held-out rows of each label sent through the flow with no context and through the base-conditioned flow, before (left two) and after (right) the standardisation by β(y) and γ(y), with the circles of radius 1 and 2 of N(0, I).

On the left, the flow with no context shares N(0,I)\mathcal{N}(\vect{0}, \mat{I}) between the labels: the upper crescent fills the upper half of the disc and the lower crescent the lower half, so neither slice is centred, and that is the 0.49 nats of each. In the middle, the base-conditioned map sends the two crescents to two compact blobs far apart, one near (−1,1.6)(-1, 1.6) and one near (1,−0.9)(1, -0.9), each narrower than the unit circle. On the right, the standardisation by β(y)\gvect{\beta}(\vect{y}) and γ(y)\gvect{\gamma}(\vect{y}) moves both blobs onto the same disc, where the two labels overlap.

5. A context that only shifts

The usual rule of thumb is to condition the base when the context moves the density and the couplings when it changes its shape. We test it on two crescents of the same shape: the label-1 crescent is the label-0 crescent moved by (1,−0.5)(1, -0.5) in the raw coordinates, standardised with the moons’ own mean and scale so that both datasets share one frame.

    none: held-out NLL 1.360 nats, slice KLs 0.126 and 0.228
    base: held-out NLL 0.722 nats, slice KLs 0.010 and 0.021
coupling: held-out NLL 0.700 nats, slice KLs 0.005 and 0.013
    both: held-out NLL 0.689 nats, slice KLs 0.007 and 0.017
 wrapper: held-out NLL 0.682 nats, slice KLs 0.007 and 0.008
wrapper against     base: +0.040 ± 0.016 nats per row
wrapper against coupling: +0.018 ± 0.017 nats per row
wrapper against     both: +0.007 ± 0.015 nats per row

The wrapper beats the base by 0.040 ± 0.016 nats per row, two and a half standard errors; against the couplings (0.018 ± 0.017) and both (0.007 ± 0.015) it is within about one.

These standard errors cover the choice of held-out rows, not the training run. To see whether the order survives a different start, we train the base and coupling flows on the moons, and the base and wrapped flows on the shifted pair, a second time from a second key.

moons: base against coupling +0.005 ± 0.007 nats per row
shifted pair: wrapper against base +0.055 ± 0.016 nats per row

Here the order changes. The wrapper, which can move the data by a shift that depends on the label before the shared map, does best at 0.682 nats, and the base does worst of the four that read the context, at 0.722 nats; the couplings and both sit in between. The paired differences say which gaps are real.

<Figure size 900x420 with 2 Axes>

Figure 4:Draws of the base-conditioned flow (left) and of the wrapped flow (right) for each label of the shifted pair, over the training rows (grey).

Both flows put each label on its own crescent; they differ at the ends, where the base-conditioned flow bends the right end of the upper crescent inwards and runs the left end of the lower one further down than the data. A second start repeats both comparisons: on the moons the base and the couplings tie again (0.005 ± 0.007 nats per row), and on the shifted pair the wrapper beats the base again (0.055 ± 0.016). So the rule “condition the base for shifts” holds for shifts of the latent, not of the data. A shift of the data is a shift of the latent only when the map commutes with translations, which a spline flow does not; the layer that models a shift of the data is a modulation on the data side, the wrapper.

6. The conditioning layers

Three layers (h,y)↦h′(\vect{h}, \vect{y}) \mapsto \vect{h}' in gauss_flows.conditioning turn an activation h∈RDh\vect{h} \in \mathbb{R}^{D_h} and a context y∈RDy\vect{y} \in \mathbb{R}^{D_y} into a conditioned activation, the pieces from which the conditional layers above are built. ConcatConditioner appends the context and applies one linear layer; AffineModulation is the FiLM of (4) Perez et al., 2018; HyperLinear is a hypernetwork that generates the weights and bias of a whole linear layer from the context:

concatenation:h′=W[h;y]+b,FiLM:h′=γ(y)⊙h+β(y),hypernetwork:h′=W(y)h+b(y)\begin{aligned} \text{concatenation:} & \vect{h}' = \mat{W} [\vect{h}; \vect{y}] + \vect{b}, \\ \text{FiLM:} & \vect{h}' = \gvect{\gamma}(\vect{y}) \odot \vect{h} + \gvect{\beta}(\vect{y}), \\ \text{hypernetwork:} & \vect{h}' = \mat{W}(\vect{y}) \vect{h} + \vect{b}(\vect{y}) \end{aligned}

They differ in what the context may change: concatenation only shifts the pre-activation by Wyy\mat{W}_y \vect{y}, FiLM rescales and shifts each feature, and the hypernetwork changes the whole matrix. We build each for Dh=64D_h = 64 features with a context of Dy=2D_y = 2 (the label here) and of Dy=64D_y = 64 (an embedding), count its parameters, and measure how far it starts from the identity on 100 random activations.

D_y =  2, concatenation:   4,288 weights, max |h' - h| = 0.00
D_y =  2,          FiLM:     384 weights, max |h' - h| = 0.00
D_y =  2,  hypernetwork:  12,480 weights, max |h' - h| = 4.74
D_y = 64, concatenation:   8,256 weights, max |h' - h| = 0.00
D_y = 64,          FiLM:   8,320 weights, max |h' - h| = 0.00
D_y = 64,  hypernetwork: 270,400 weights, max |h' - h| = 4.35

At the start, concatenation and FiLM return their input exactly for every context: concatenation starts at W=[I∣0]\mat{W} = [\mat{I} \mid \mat{0}], and FiLM at γ=1\gvect{\gamma} = \vect{1}, β=0\gvect{\beta} = \vect{0}. The hypernetwork does not start at the identity: it starts its generated layer at the variance of a fresh linear layer, so it moves every activation, here by up to 4.7. Their sizes grow differently with the context. Concatenation costs DhD_h weights per context coordinate on top of a Dh×DhD_h \times D_h layer (4,288 at Dy=2D_y = 2, 8,256 at Dy=64D_y = 64), FiLM 2Dh2 D_h per context coordinate and nothing else but a bias (384 and 8,320), and the hypernetwork Dh2+DhD_h^2 + D_h per context coordinate (12,480 and 270,400), the price of letting the context change the whole matrix.

The conditional pieces of the flows above use two of the three. A conditional coupling concatenates: RQSplineCoupling(cond_dim=2) appends the context to the passive half before its conditioner’s first layer, which we can read off the layer’s input size.

input size of c_φ: 3 = D_A + D_y = 1 + 2

The base and the wrapper modulate: ConditionalDiagGaussian and Conditioner both hold an AffineModulation, and so do GINCoupling and ContinuousAffineCoupling. Every one starts as the identity because its readout starts at zero weight, which is what zero_readout does to any eqx.nn.Linear or eqx.nn.MLP: the readout returns its bias for every input, and the weight still gets a gradient from the first step.

fresh network, spread of the outputs over contexts: 0.079
after zero_readout: every output is [1.]

A context need not be a label. A continuous context, a time with an optional control vector, is packed into one condition by pack_time_control, which is how MatrixExponential in Part 6 takes its time; any of the layers above then reads it as y\vect{y}.

y = [ 0.5  1.  -1. ]; fresh wrapper at x = (1, 2): [1. 2.]

Recap

PieceEquationIn code
the conditional change of variables(1)negative_log_likelihood(flow, x, condition=y)
a conditional base, a Gaussian per context(2)ConditionalDiagGaussian(key, event_shape, cond_dim)
a conditional coupling, a spline per context(3)RQSplineCoupling(key, shape, cond_dim=D_y)
a modulation around any unconditional layer(4)Conditioner(key, inner=g, cond_dim)
how Gaussian each slice is(5)gaussian_kl_divergence of the moment-matched Gaussian
concatenation, FiLM and a hypernetwork(6)ConcatConditioner, AffineModulation, HyperLinear
a start at the identityzero_readout
a continuous contextpack_time_control(t, u)

On these two datasets the rule of thumb needs restating. A context that changes the shape of the density can be read by the base as well as by the couplings, because the base acts after a nonlinear map. A context that shifts the data is modelled best by a modulation on the data side, and worst, of the conditional flows, by the base.

Next. Notebook 01 moves to a continuous context, makes the marginal CDFs depend on it, and checks that the conditional density it learns is calibrated.

References
  1. Winkler, C., Worrall, D. E., Hoogeboom, E., & Welling, M. (2019). Learning Likelihoods with Conditional Normalizing Flows. arXiv Preprint arXiv:1912.00042.
  2. Durkan, C., Bekasov, A., Murray, I., & Papamakarios, G. (2019). Neural Spline Flows. Advances in Neural Information Processing Systems (NeurIPS).
  3. Perez, E., Strub, F., de Vries, H., Dumoulin, V., & Courville, A. (2018). FiLM: Visual Reasoning with a General Conditioning Layer. Proceedings of the AAAI Conference on Artificial Intelligence.