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 flavours of conditional flow: base, coupling, both (and none)

gauss_flows lets you make a flow conditional in three distinct places — the base distribution, the coupling layers, or both — with one consistent API: a single condition keyword that threads through SurVAEFlow.log_prob(...) and SurVAEFlow.sample(...). This notebook walks through the math of each variant, then shows the four resulting fits side by side on the two-moons dataset from notebook 01 (gaussianization_flow_2d).

We use the class label that notebook 01 discards (_, y = make_moons(...)) as the conditional context cc. make_moons returns y∈{0,1}y \in \{0, 1\} indicating which crescent each point belongs to, so p(x∣y=0)p(x \mid y=0) is the upper moon and p(x∣y=1)p(x \mid y=1) is the lower moon — two well-separated, single-crescent conditional densities, well within RQSplineCoupling capacity.

0. Math primer — conditional normalizing flows

A normalizing flow defines a density on x∈RDx \in \mathbb{R}^D via an invertible map fθ:RD→RDf_\theta : \mathbb{R}^D \to \mathbb{R}^D pulling samples back to a tractable base distribution pZp_Z:

pX(x)  =  pZ ⁣(fθ(x)) ∣det⁡∂fθ∂x(x)∣.p_X(x) \;=\; p_Z\!\big(f_\theta(x)\big) \,\left| \det \frac{\partial f_\theta}{\partial x}(x) \right|.

For a chain fθ=fK∘⋯∘f1f_\theta = f_K \circ \cdots \circ f_1 with intermediate states zk=fk(zk−1)z_k = f_k(z_{k-1}), z0=xz_0 = x:

log⁡pX(x)  =  log⁡pZ(zK)  +  ∑k=1Klog⁡ ⁣∣det⁡∂fk∂zk−1(zk−1)∣.\log p_X(x) \;=\; \log p_Z(z_K) \;+\; \sum_{k=1}^{K} \log\!\left| \det \frac{\partial f_k}{\partial z_{k-1}}(z_{k-1}) \right|.

To make this conditional on a context c∈RDcc \in \mathbb{R}^{D_c}, any of the three pieces — the base pZp_Z, the maps fkf_k, or both — can be made functions of cc. The general conditional flow density is

pX(x∣c)  =  pZ ⁣(fθ(x;c) ∣ c) ∣det⁡∂fθ(⋅ ;c)∂x(x)∣.p_X(x \mid c) \;=\; p_Z\!\big(f_\theta(x; c) \,\big|\, c\big) \,\left| \det \frac{\partial f_\theta(\cdot\,;c)}{\partial x}(x) \right|.

The four variants in this notebook correspond to which factors are functions of cc:

VariantDensity
None$p_X(x) = p_Z!\big(f_\theta(x)\big),\big
Base only$p_X(x \mid c) = p_Z!\big(f_\theta(x) ,\big
Coupling only$p_X(x \mid c) = p_Z!\big(f_\theta(x; c)\big),\big
Both$p_X(x \mid c) = p_Z!\big(f_\theta(x; c) ,\big

Conditional base — ConditionalDiagGaussian

A diagonal Gaussian whose location and log-scale are functions of cc:

pZ(z∣c)  =  ∏d=1DN ⁣(zd ∣ μd(c), σd(c)2),[μ(c), log⁡σ(c)]  =  gϕ(c),p_Z(z \mid c) \;=\; \prod_{d=1}^{D} \mathcal{N}\!\big(z_d \,\big|\, \mu_d(c),\, \sigma_d(c)^2\big), \qquad [\mu(c),\, \log \sigma(c)] \;=\; g_\phi(c),

where gϕg_\phi is a small MLP. Closed-form log-density:

log⁡pZ(z∣c)  =  −12∑d=1D[(zd−μd(c))2σd(c)2  +  log⁡ ⁣(2π σd(c)2)].\log p_Z(z \mid c) \;=\; -\frac{1}{2}\sum_{d=1}^{D}\left[ \frac{(z_d - \mu_d(c))^2}{\sigma_d(c)^2} \;+\; \log\!\big(2\pi\,\sigma_d(c)^2\big) \right].

This handles per-class shifts: if the only thing that varies with cc is the position of the mode, the conditional base alone is enough.

Conditional coupling — RQSplineCoupling(cond_dim=...)

A coupling layer splits x=(xa,xb)x = (x_a, x_b) on a binary mask. The “passthrough” half xax_a is left alone; the “active” half xbx_b goes through an elementwise transformer τ\tau whose parameters are produced by a conditioner MLP hψh_\psi that already takes xax_a as input. Adding cond_dim > 0 simply concatenates the external context cc to that input:

ya=xa,yb=τ ⁣(xb; θ),θ=hψ ⁣([xa,c]).\begin{aligned} y_a &= x_a, \\ y_b &= \tau\!\big(x_b;\, \theta\big), \qquad \theta = h_\psi\!\big([x_a, c]\big). \end{aligned}

For an RQSplineCoupling, τ(⋅;θ)\tau(\cdot;\theta) is a rational-quadratic spline whose knot positions and slopes come from θ\theta. The Jacobian is triangular by construction, so

log⁡ ⁣∣det⁡∂(ya,yb)∂(xa,xb)∣  =  ∑i∈activelog⁡τ′ ⁣(xb,i; θi).\log\!\left| \det \frac{\partial (y_a, y_b)}{\partial (x_a, x_b)} \right| \;=\; \sum_{i \in \text{active}} \log \tau'\!\big(x_{b,i};\, \theta_i\big).

This handles per-class shape warps: the spline knots can move with cc, producing genuinely class-specific maps.

How the package routes condition

Each layer (and the base) declares whether it is conditional via a static attribute cond_shape:

  • cond_shape is None → unconditional layer; the layer ignores any condition argument it receives.

  • cond_shape == (D_c,) → conditional layer; it expects a context of that shape.

SurVAEFlow.log_prob(x, key, condition=c) (and .sample(key, condition=c)) takes a single c and broadcasts it to every opted-in layer. There is no per-layer condition kwarg — you build the chain, decide for each layer whether it should look at cc via cond_dim=..., and the same cc flows through. flowjax’s _check_condition decorator raises if you forget to pass a context to a conditional layer.

For class-conditional density estimation specifically, ClassCondFlow(n_classes=..., event_shape=..., transforms=[...]) is sugar for “conditional base + unconditional transforms” with a label kwarg in place of condition. We don’t use it here because we want to expose all four variants explicitly.

For transforms that genuinely cannot take a context (rotations, normalizations, etc.), wrap them in Conditioner(key, inner=..., cond_dim=D_c) to add a FiLM-style affine modulation around the inner transform:

y=γ(c)⊙finner(x)+β(c),y = \gamma(c) \odot f_{\text{inner}}(x) + \beta(c),

where [β(c);rγ(c)]=gϕ(c)[\beta(c); r_\gamma(c)] = g_\phi(c) comes from the shared AffineModulation gϕg_\phi and γ(c)=σ(rγ(c))\gamma(c) = \sigma(r_\gamma(c)) for a positive scale map σ\sigma (scale_map, ere^{r} by default). Its readout starts at zero, so γ=1\gamma = 1 and β=0\beta = 0 and the wrapper starts as finnerf_{\text{inner}} itself for every cc.

1. Configurations under test

We compare four configurations under identical hyperparameters:

  1. None (baseline = notebook 01’s setup): a fixed N(0,I)\mathcal{N}(0, I) base + unconditional RQSplineCoupling chain. The flow ignores yy entirely and fits the marginal — the full two-moons. Useful as a sanity check; reproduces notebook 01’s fit quality.

  2. Base only: a ConditionalDiagGaussian base whose μ,log⁡σ\mu, \log \sigma come from the one-hot yy, paired with the same unconditional RQSplineCoupling chain. The base shifts per class but the chain learns one shared crescent shape.

  3. Coupling only: a fixed N(0,I)\mathcal{N}(0, I) base, paired with RQSplineCoupling(cond_dim=2) layers that read the one-hot yy. The couplings learn class-specific shapes; class-specific shift has to be absorbed through the spline parameters — awkward, but doable for two-moons.

  4. Both: conditional base and conditional couplings — the same one-hot label flows to both. Full capacity.

/home/azureuser/localfiles/geo_repos/geo_ml/gauss_flows-fit/.venv/lib/python3.13/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html
  from .autonotebook import tqdm as notebook_tqdm

2. Data

Same make_moons(...) call as notebook 01 — 5000 points standardised to zero mean and unit variance — but we keep the class label and one-hot encode it as the context c∈{(1,0)⊤,(0,1)⊤}c \in \{(1, 0)^\top, (0, 1)^\top\}. Each crescent has ≈2500\approx 2500 points.

X.shape=(5000, 2), C.shape=(5000, 2)
counts per class: y=0 -> 2500, y=1 -> 2500
/home/azureuser/localfiles/geo_repos/geo_ml/gauss_flows-fit/.venv/lib/python3.13/site-packages/seaborn/axisgrid.py:1766: UserWarning: The figure layout has changed to tight
  f.tight_layout()
<Figure size 715x715 with 3 Axes>

3. Four flow configurations

Each flow uses the same chain of four RQSplineCoupling layers separated by fixed permutations — splines for capacity, since fitting two-moons is not affine. The only difference between the four configurations is where conditioning happens.

FlowBase pZp_ZCouplings fθf_\thetaWhat can it model?
flow_noneN(0,I)\mathcal{N}(0, I)unconditionalonly the marginal p(x)p(x) — ignores yy
flow_baseN(μ(c),σ(c)2I)\mathcal{N}(\mu(c), \sigma(c)^2 I)unconditionalper-class shift only
flow_couplingN(0,I)\mathcal{N}(0, I)cond_dim=2per-class shape warps
flow_bothN(μ(c),σ(c)2I)\mathcal{N}(\mu(c), \sigma(c)^2 I)cond_dim=2both — full capacity

Architectural detail. A coupling layer leaves half the dims untouched, so we interleave fixed Permute layers between couplings to ensure every dim gets transformed. With D=2D=2 and a 1-vs-1 split, a single Permute([1, 0]) between couplings is enough. We use spline transformers (rational-quadratic, 8 bins, interval [−4,4][-4, 4]) because affine couplings cannot bend a Gaussian into a crescent.

          none  trainable params:  24448
     base only  trainable params:  29056
 coupling only  trainable params:  24960
          both  trainable params:  29568

4. Train each flow

All four flows minimize the same objective — negative log-likelihood under the model:

L(θ,ϕ)  =  − E(x,c)∼D[log⁡pX(x∣c)]  =  − E(x,c) ⁣[log⁡pZ(zK∣c)+∑k=1Klog⁡∣det⁡Jfk(zk−1;c)∣]\mathcal{L}(\theta, \phi) \;=\; -\,\mathbb{E}_{(x, c) \sim \mathcal{D}}\big[\log p_X(x \mid c)\big] \;=\; -\,\mathbb{E}_{(x, c)}\!\left[\log p_Z(z_K \mid c) + \sum_{k=1}^K \log \big| \det J_{f_k}(z_{k-1}; c) \big|\right]

with zK=fθ(x;c)z_K = f_\theta(x; c). For the “none” and “coupling only” variants the  ⋅ ∣c \,\cdot\, \mid c\, on the base drops out; for the “none” and “base only” variants the cc inside fkf_k drops out. Same code path for all four — only the layers’ cond_shapes differ.

fit_flow, the pipekit-train loop of notebook 01, trains each SurVAEFlow directly: gauss_flows’s negative_log_likelihood passes the step’s key and the context to SurVAEFlow.log_prob and averages over the batch, so no adapter to flowjax’s distribution API is needed. Hyperparameters match notebook 01 (learning_rate=5e-3, batch_size=256, max_epochs=600, max_patience=30).

training: none
training: base only
training: coupling only
training: both
WARNING:matplotlib.font_manager:findfont: Failed to find font weight semibold for DejaVu Sans, now using 700.
<Figure size 880x550 with 1 Axes>

5. Per-class sample comparison

To draw conditional samples we exploit invertibility:

z∼pZ(⋅∣c),x  =  fθ−1(z; c).z \sim p_Z(\cdot \mid c), \qquad x \;=\; f_\theta^{-1}(z;\, c).

For each variant we draw NN samples per class and overlay them on the true class samples. Two rows (one per class) × four columns (one per configuration). The “none” flow has no class information — its panel is the same in both rows by construction.

<Figure size 1760x880 with 8 Axes>

What to look for

  • None (column 1): the flow ignores yy — it samples from the full two-moons every time, so half the samples land in the wrong crescent. The blue (true class) and grey (flow) samples only partially overlap.

  • Base only (column 2): the per-class mean is correct, but the unconditional spline chain learned one shape that has to serve both classes — the per-class crescent shape is muddier than the truth.

  • Coupling only (column 3): the spline couplings can read the one-hot label and produce class-specific crescents. Position and shape both come out cleanly because the couplings have enough capacity to absorb the per-class shift through the spline parameters.

  • Both (column 4): same crisp per-class fit as coupling-only, with the conditional base providing a per-class warm-start. Its final NLL is within run-to-run noise of coupling-only’s (in this run it is slightly worse, and with another training key the order can flip), so once the couplings read the label the conditional base adds little on two-moons.

6. Quantitative comparison

Mean per-example conditional log-likelihood under each fitted model:

L ⁣ ⁣L^(θ,ϕ)  =  1N∑n=1Nlog⁡pX(xn∣cn).\widehat{\mathcal{L}\!\!L}(\theta, \phi) \;=\; \frac{1}{N} \sum_{n=1}^N \log p_X(x_n \mid c_n).

Computed on the training set — we have no held-out oracle, but the four configurations can still be ranked.

none          : -1.1645
base only     : -0.8162
coupling only : -0.4404
both          : -0.4470

7. Takeaways

Modelling guidance.

  • Pick what to condition based on what your data needs. If only the position of p(x∣c)p(x \mid c) varies with cc (location shift, isotropic scale), a conditional base alone is enough. If the shape varies — as it does here, since each class is a different crescent rather than a translated copy — conditional couplings are the natural fit. Real datasets usually benefit from both.

  • The conditioning capacity is multiplicative across layers. With KK conditional couplings, the per-class map composes KK class-dependent splines. A single conditional base contributes one Gaussian. Stacking helps mostly when the conditional density family is genuinely complex.

  • Keep DcD_c modest. The conditioner MLPs concatenate cc to xax_a, so DcD_c inflates the input layer. For categorical yy with many classes, prefer a learned embedding e(y)∈Rde(y) \in \mathbb{R}^d over one-hot encoding.

Implementation guidance for gauss_flows.

  • The same condition keyword threads everywhere. SurVAEFlow.log_prob(x, key, condition=c) and .sample(key, condition=c) broadcast cc to every layer that opted in (cond_shape is not None); other layers ignore it. There is no per-layer condition kwarg.

  • Inside a coupling there are two streams. The untransformed half of xx is always a conditioning input — that is how coupling layers work. Adding cond_dim > 0 also concatenates the external context onto the inner MLP. The two streams are merged inside flowjax and you never slice them apart from outside.

  • For class-conditional density estimation, prefer ClassCondFlow(n_classes=..., event_shape=..., transforms=[...]). It pairs a ClassCondDiagGaussian base (per-class learnable μ,log⁡σ\mu, \log \sigma) with an arbitrary chain of unconditional transforms, exposing a label keyword in place of condition. The construction validates that no transform in the chain is conditional, since the label flows only to the base.

  • For transforms that genuinely cannot take a context (rotations, normalizations, periodic shifts), wrap them in Conditioner(key, inner=..., cond_dim=D_c). The wrapper applies a FiLM-style affine modulation  y=γ(c)⊙finner(x)+β(c) \,y = \gamma(c) \odot f_{\text{inner}}(x) + \beta(c)\, from the shared AffineModulation around the inner transform — preserving invertibility, giving a closed-form log-determinant and starting as the inner transform itself for every cc — and rejects inner transforms that are already conditional.

  • Errors fail fast. Forgetting to pass condition to a flow with any conditional layer raises in flowjax’s _check_condition decorator; passing a wrong-shape context fails the same way.