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.

A conditional flow as an amortised posterior

Train one conditional flow on simulated pairs (x, y = Hx + ε), and it gives the posterior p(x | y) of every observation in one pass; we measure how far it is from the exact one

02 · A conditional flow as an amortised posterior

Open In Colab

Notebooks 00 and 01 trained flows pθ(x∣y)p_\theta(\vect{x} \mid \vect{y}) that read a context y\vect{y}. In an inverse problem the context is an observation: a measurement y\vect{y} of a hidden state x\vect{x}, through a forward model that loses information and adds noise, and the question is which states could have produced it. The answer is the posterior p(x∣y)p(\vect{x} \mid \vect{y}). A conditional flow trained on pairs (x,y)(\vect{x}, \vect{y}) simulated from the prior and the forward model learns that posterior for every observation at once Papamakarios et al., 2021Winkler et al., 2019: the cost of inference is paid once, in training, and each new observation costs one pass of the flow. This is an amortised posterior. What it costs in accuracy is the amortisation gap, and on a problem whose posterior we know exactly we can measure 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. An inverse problem and its posterior

A state x∈RDx\vect{x} \in \mathbb{R}^{D_x} is drawn from a prior p(x)p(\vect{x}) and observed through a linear observation operator H∈RDy×Dx\mat{H} \in \mathbb{R}^{D_y \times D_x} with noise ε∼N(0,σobs2I)\gvect{\varepsilon} \sim \mathcal{N}(\vect{0}, \sigma_{\mathrm{obs}}^2 \mat{I}):

y=Hx+ε\vect{y} = \mat{H} \vect{x} + \gvect{\varepsilon}

Here Dx=2D_x = 2 and Dy=1D_y = 1: the observation is the sum of the two coordinates, so it pins x\vect{x} to a band around the line x1+x2=yx_1 + x_2 = y and says nothing about where along the line. The posterior is Bayes’ rule,

p(x∣y)=p(y∣x)p(x)p(y)p(\vect{x} \mid \vect{y}) = \frac{p(\vect{y} \mid \vect{x}) p(\vect{x})}{p(\vect{y})}

A conditional flow qθ(x∣y)q_\theta(\vect{x} \mid \vect{y}) is trained on pairs simulated from the prior and (1) by the conditional negative log-likelihood, the loss (1) with y\vect{y} as the condition. Its expectation over the joint distribution of the pairs splits in two:

Ep(x,y)[−log⁡qθ(x∣y)]=H[x∣y]+Ep(y)KL[p(x∣y)∥qθ(x∣y)]\mathbb{E}_{p(\vect{x}, \vect{y})}[-\log q_\theta(\vect{x} \mid \vect{y})] = H[\vect{x} \mid \vect{y}] + \mathbb{E}_{p(\vect{y})} \mathrm{KL}[p(\vect{x} \mid \vect{y}) \Vert q_\theta(\vect{x} \mid \vect{y})]

The first term, the conditional entropy of the state given the observation, does not depend on θ\theta, so minimising the loss minimises the second: the KL divergence of the flow from the exact posterior, averaged over the observations the forward model produces. Neither the prior’s density nor the likelihood is ever evaluated; the flow needs only samples.

2. A linear-Gaussian problem, solved exactly

With a Gaussian prior N(μx,Σx)\mathcal{N}(\gvect{\mu}_x, \gmat{\Sigma}_x) the posterior is Gaussian too, with

Σx∣y=(Σx−1+σobs−2H⊤H)−1,μx∣y=Σx∣y(Σx−1μx+σobs−2H⊤y)\begin{aligned} \gmat{\Sigma}_{x \mid y} &= (\gmat{\Sigma}_x^{-1} + \sigma_{\mathrm{obs}}^{-2} \mat{H}^\top \mat{H})^{-1}, \\ \gvect{\mu}_{x \mid y} &= \gmat{\Sigma}_{x \mid y} (\gmat{\Sigma}_x^{-1} \gvect{\mu}_x + \sigma_{\mathrm{obs}}^{-2} \mat{H}^\top \vect{y}) \end{aligned}

The posterior covariance does not depend on y\vect{y}, so neither does the conditional entropy H[x∣y]H[\vect{x} \mid \vect{y}] of (3), the entropy (2) of Σx∣y\gmat{\Sigma}_{x \mid y}. We take a correlated prior, H=[1,1]\mat{H} = [1, 1] and σobs=0.1\sigma_{\mathrm{obs}} = 0.1, and simulate 10,000 pairs: 6,000 to train on and 4,000 held out.

Two numbers say how much one observation tells. The conditional entropy is the spread that remains, and the KL divergence of the posterior from the prior is the information the observation brings; we read it at y=0y = 0 with gaussian_kl_divergence. We also read the variance of Hx\mat{H} \vect{x} under the posterior, HΣx∣yH⊤\mat{H} \gmat{\Sigma}_{x \mid y} \mat{H}^\top, which we will check the flow’s samples against.

posterior covariance:
[[ 0.0922 -0.0865]
 [-0.0865  0.0908]]
H[x | y] = -0.6762 nats; KL[p(x | y = 0) || p(x)] = 2.3227 nats
variance of Hx under the posterior: 0.009965; sigma_obs^2 = 0.010000

The posterior is a thin ellipse along the line: its variance across the line is set by the noise, and along the line by the prior. The variance of Hx\mat{H} \vect{x} under it is slightly below σobs2\sigma_{\mathrm{obs}}^2, because the prior also says a little about x1+x2x_1 + x_2.

3. One flow for every observation

The flow is six blocks of a rational-quadratic spline coupling that reads the observation as its condition (cond_dim=1), each followed by a swap of the two coordinates so that both halves get transformed, on a standard-normal base. The 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 gauss_flows coupling is the identity, so before training the flow is N(0,I)\mathcal{N}(\vect{0}, \mat{I}) whatever the observation.

pipekit-train fits it with negative_log_likelihood, given the batch’s observations as the condition. Every run takes 3,000 Adam steps of 256 pairs 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.

trained in 36 s; held-out conditional NLL -0.6515 nats against H[x | y] = -0.6762

4. The amortisation gap

The held-out loss sits just above the conditional entropy, and by (3) the difference is the quantity training minimises. We call it the amortisation gap,

Δ=Ep(y)KL[p(x∣y)∥qθ(x∣y)]≈1Nv∑n=1Nv[log⁡p(xn∣yn)−log⁡qθ(xn∣yn)]\Delta = \mathbb{E}_{p(\vect{y})} \mathrm{KL}[p(\vect{x} \mid \vect{y}) \Vert q_\theta(\vect{x} \mid \vect{y})] \approx \frac{1}{N_v} \sum_{n=1}^{N_v} [\log p(\vect{x}_n \mid \vect{y}_n) - \log q_\theta(\vect{x}_n \mid \vect{y}_n)]

the KL divergence of the one trained network from the exact posterior, averaged over the observations the forward model produces. It is the whole price of answering every observation with one network trained on finite data. The estimate on the right uses the exact posterior density at each held-out pair, which removes the sampling noise of the held-out loss itself.

amortisation gap: 0.0256 +/- 0.0040 nats (one standard error); held-out NLL - H[x | y] = 0.0247

The gap is a few hundredths of a nat, against the 2.3 nats that one observation brings. The average hides where it comes from. For a single observation the KL divergence of the flow from the exact posterior can be estimated by sampling the exact posterior, and we sweep the observation from -6 to 6, far beyond the training pairs, whose observations have a standard deviation of about 1.7.

y = -6.0 (-3.6 sd): KL 0.5595 nats
y = -4.0 (-2.4 sd): KL 0.0941 nats
y = -2.0 (-1.2 sd): KL 0.0195 nats
y = +0.0 (+0.0 sd): KL 0.0114 nats
y = +2.0 (+1.2 sd): KL 0.0247 nats
y = +4.0 (+2.4 sd): KL 0.1496 nats
y = +6.0 (+3.6 sd): KL 2.6012 nats
fig, ax = plt.subplots(figsize=(7, 4))
twin = ax.twinx()
twin.hist(gauss_observations[:6000, 0], bins=60, color=DATA_COLOR, alpha=0.25)
ax.semilogy(sweep_observations, sweep_kl, marker="o", markersize=3, color=LATENT_COLOR)
ax.set_zorder(twin.get_zorder() + 1)
ax.patch.set_visible(False)
ax.set(
    xlabel="observation y",
    ylabel="KL[p(x | y) ‖ q_θ(x | y)] (nats)",
    title="the gap, observation by observation",
)
twin.set_ylabel("training observations")
style_ax(ax)
fig.tight_layout()
plt.show()
<Figure size 700x400 with 2 Axes>

Figure 1:The KL divergence of the trained flow from the exact posterior at each observation (left axis, log scale), over the histogram of the 6,000 training observations (right axis). The gap is smallest where training observations are dense and grows by more than an order of magnitude in the tails.

The divergence is a few hundredths of a nat wherever training observations are plentiful and rises steeply beyond about two standard deviations, where the network saw few pairs and has to extrapolate. An amortised posterior is as good as its training distribution is wide: an observation from the tail of p(y)p(\vect{y}), or from outside it, gets a worse answer, and nothing in the flow’s output says so. We look at the posterior itself at four observations, two in the bulk, one at the edge and one beyond it.

fig, axes = plt.subplots(1, 4, figsize=(15, 4), sharex=True, sharey=True)
for ax, observation in zip(axes, (-1.0, 1.0, 4.0, 6.0), strict=True):
    mean = posterior_mean(np.array([observation]))
    exact_draws = (
        mean + rng.standard_normal((1000, 2)) @ np.linalg.cholesky(posterior_cov).T
    )
    flow_draws = gauss_flow.sample(
        jr.key(3), (1000,), condition=jnp.array([observation])
    )
    ax.scatter(*np.asarray(exact_draws).T, color=DATA_COLOR, **SCATTER_KW)
    ax.scatter(*np.asarray(flow_draws).T, color=LATENT_COLOR, **SCATTER_KW)
    ax.plot([-4, 8], [observation + 4, observation - 8], color="0.3", ls="--", lw=1)
    ax.set(
        title=f"y = {observation:+.0f}", xlabel="x₁", xlim=(-2.5, 5.5), ylim=(-4.5, 3.5)
    )
    ax.set_aspect("equal")
    style_ax(ax)
axes[0].set_ylabel("x₂")
fig.tight_layout()
plt.show()
<Figure size 1500x400 with 4 Axes>

Figure 2:Draws from the trained flow (orange) and from the exact posterior (blue) at four observations, on the line Hx = y (dashed). In the bulk the two clouds coincide; at y = 6, beyond the training observations, the flow’s sits off-centre along the line.

5. A posterior with several modes

A linear-Gaussian problem needs no flow: its posterior is (4). A flow earns its place when the prior is not Gaussian. We keep H\mat{H} and σobs\sigma_{\mathrm{obs}} and take the two moons, standardised, as the prior. A line x1+x2=yx_1 + x_2 = y can cross a crescent twice and both crescents at once, and then the posterior has several modes.

There is no closed form now, but there is an exact sampler. Draw states from the prior and keep each with probability

a(x)=exp⁡(−∥y−Hx∥22σobs2)a(\vect{x}) = \exp \left( -\frac{\Vert \vect{y} - \mat{H} \vect{x} \Vert^2}{2 \sigma_{\mathrm{obs}}^2} \right)

the likelihood scaled to a maximum of 1. The states kept are exact draws from the posterior, and each keeps the moon it was drawn from, which we use to count the mass in each mode.

trained in 25 s; held-out conditional NLL -0.8842 nats

Flow draws carry no moon label, so we read their mode from a nearest-neighbour classifier fitted to 20,000 labelled prior draws, and check the classifier first on the rejection draws, whose labels we know.

21115 exact draws at y = 0; classifier agrees with the true moon on 100.0%
y = -1: upper moon 0.167 exact, 0.177 flow; flow draws off the moons 0.001
        Hx mean -1.010 exact, -1.014 flow; sd 0.0972 exact, 0.1034 flow
y = +0: upper moon 0.498 exact, 0.494 flow; flow draws off the moons 0.022
        Hx mean -0.001 exact, +0.004 flow; sd 0.1024 exact, 0.1107 flow
y = +1: upper moon 0.831 exact, 0.825 flow; flow draws off the moons 0.003
        Hx mean +1.011 exact, +1.013 flow; sd 0.0967 exact, 0.1030 flow
fig, axes = plt.subplots(1, 3, figsize=(14, 4.8), sharex=True, sharey=True)
for ax, seed, observation in zip(axes, (5, 6, 7), (-1.0, 0.0, 1.0), strict=True):
    exact_draws = reject_posterior(observation, seed)[0][:1500]
    flow_draws = moon_flow.sample(
        jr.key(seed), (1500,), condition=jnp.array([observation])
    )
    ax.scatter(*moon_states[:3000].T, color="0.75", s=4, alpha=0.3, edgecolors="none")
    ax.scatter(*np.asarray(exact_draws).T, color=DATA_COLOR, **SCATTER_KW)
    ax.scatter(*np.asarray(flow_draws).T, color=LATENT_COLOR, **SCATTER_KW)
    ax.plot([-3, 3], [observation + 3, observation - 3], color="0.3", ls="--", lw=1)
    ax.set(
        title=f"y = {observation:+.0f}", xlabel="x₁", xlim=(-2.3, 2.3), ylim=(-2.3, 2.3)
    )
    ax.set_aspect("equal")
    style_ax(ax)
axes[0].set_ylabel("x₂")
fig.tight_layout()
plt.show()
<Figure size 1400x480 with 3 Axes>

Figure 3:The two-moons prior (grey), exact posterior draws by rejection (blue) and draws from the trained flow (orange) at three observations, on the line Hx = y (dashed). At y = 0 the line crosses each crescent twice, and both posteriors have four modes with half the mass on each crescent; the flow leaves a thin trail of draws between neighbouring modes.

The flow puts its modes where the exact posterior has them, with close to the same mass. At y=0y = 0 the line crosses each crescent twice, the posterior has four modes, and the mass splits evenly between the crescents; at y=±1y = \pm 1 one draw in six sits on the far crescent, and the flow’s share is within one percentage point of the exact one. Its Hx\mat{H} \vect{x} is centred on the observation with a spread 6 to 8 per cent wider than the exact one, which is about σobs\sigma_{\mathrm{obs}}: it has learned the likelihood, not only where the prior puts its mass. What it cannot do exactly is separate the modes. A flow is a continuous bijection of a Gaussian, so it joins neighbouring modes with thin trails of mass, and at y=0y = 0, 2.2 per cent of its draws lie more than 0.15 from every one of the 20,000 labelled prior draws, where the exact posterior has almost no mass. A Gaussian or Laplace approximation would do far worse, with one mode between the crescents.

The acceptance step (6) matters for the reference. Keeping only the prior draws with ∣y−Hx∣|y - \mat{H} \vect{x}| below a fixed window samples a different distribution, the posterior of a noise-free observation smeared by the window.

sd of Hx in a window of half-width 0.06: 0.0348; sigma_obs = 0.1

The window gives a spread of Hx\mat{H} \vect{x} about a third of the true one, so it is the wrong reference for this flow, which was trained with noise σobs=0.1\sigma_{\mathrm{obs}} = 0.1.

6. What one observation costs

The point of amortising is the cost of the next observation. We time 4,000 posterior draws from the compiled flow and one run of the rejection sampler, at an observation neither has seen.

Array([[ 1.2923, -1.2756], [-1.2793, 1.3024], [-1.0706, 1.1561], ..., [ 1.1342, -1.1129], [ 1.1518, -1.1527], [-1.2261, 1.1994]], dtype=float64)
flow: 4,000 draws in 14.0 ms; rejection: 24928 draws in 138 ms from 400,000 prior draws

The flow is several times faster here, and this toy flatters rejection: its prior is cheap to draw from, and with two dimensions and one observation about 6 per cent of the prior draws are kept. The acceptance rate is the average of a(x)a(\vect{x}) over the prior, and with independent measurements a(x)a(\vect{x}) is a product of one factor below 1 per measurement, so the rate falls with every measurement added, while the flow’s cost per observation stays one pass. The flow’s cost is paid up front, in the two training runs above, and it buys the gap of section 4.

Recap

PieceEquationIn code
the forward model(1)observation_operator, noise_scale
the posterior(2)
the conditional NLL trains the posterior(3)negative_log_likelihood(flow, x, condition=y)
the linear-Gaussian posterior in closed form(4)posterior_mean, posterior_cov, gaussian_entropy
the amortisation gap(5)gap_terms.mean(), kl_at
the conditional flowRQSplineCoupling(..., cond_dim=1), eqx.filter_vmap, Scan
exact posterior draws by rejection(6)reject_posterior

Next. Part 7 ends here: notebook 00 placed the context, 01 estimated conditional densities, and this notebook made the context an observation. When the prior is a Gaussianizing flow that we cannot simulate pairs from cheaply, or the forward model changes from one problem to the next, amortising does not pay; Part 16 solves the same inverse problems one observation at a time, with a flow as the prior in a plug-and-play scheme.

References
  1. Papamakarios, G., Nalisnick, E., Rezende, D. J., Mohamed, S., & Lakshminarayanan, B. (2021). Normalizing Flows for Probabilistic Modeling and Inference. Journal of Machine Learning Research, 22(57), 1–64.
  2. Winkler, C., Worrall, D. E., Hoogeboom, E., & Welling, M. (2019). Learning Likelihoods with Conditional Normalizing Flows. arXiv Preprint arXiv:1912.00042.