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¶
Notebooks 00 and 01 trained flows that read a context . In an inverse problem the context is an observation: a measurement of a hidden state , 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 . A conditional flow trained on pairs 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.
import subprocess
import sys
try:
import google.colab # noqa: F401
IN_COLAB = True
except ImportError:
IN_COLAB = False
if IN_COLAB:
repo = "git+https://github.com/jejjohnson/gauss_flows@main"
subprocess.run(
[
sys.executable,
"-m",
"pip",
"install",
"-q",
f"gauss-flows-maps @ {repo}#subdirectory=packages/gauss-flows-maps",
f"gauss-flows-models @ {repo}#subdirectory=packages/gauss-flows-models",
f"gauss-flows-docs[notebooks] @ {repo}#subdirectory=docs",
],
check=True,
)import warnings
warnings.filterwarnings("ignore", message=r".*IProgress.*")
import time
from collections.abc import Callable
import equinox as eqx
import jax
import jax.numpy as jnp
import jax.random as jr
import matplotlib.pyplot as plt
import numpy as np
import optax
from flowjax.bijections import Chain, Permute, Scan
from flowjax.distributions import StandardNormal, Transformed
from jax.scipy.stats import multivariate_normal
from jaxtyping import ArrayLike, Float
from pipekit_train import ArrayDataset, TrainingLoop
from pipekit_train.backends.equinox import EquinoxModelOp
from sklearn.datasets import make_moons
from sklearn.neighbors import KNeighborsClassifier
from gauss_flows_docs.environment import watermark
from gauss_flows_docs.plotting import (
DATA_COLOR,
LATENT_COLOR,
SCATTER_KW,
style_ax,
use_compact_figures,
)
from gauss_flows_maps.bijections import RQSplineCoupling
from gauss_flows_models.inference import negative_log_likelihood
from gauss_flows_models.info_theory import gaussian_entropy, gaussian_kl_divergence
jax.config.update("jax_enable_x64", True)
np.set_printoptions(precision=4, suppress=True)
rng = np.random.default_rng(0)
# Figures are stored as palette PNGs to keep the notebook small.
use_compact_figures()
watermark("jax", "numpy", "optax", "flowjax", "pipekit_train", "gauss_flows_maps")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 is drawn from a prior and observed through a linear observation operator with noise :
Here and : the observation is the sum of the two coordinates, so it pins to a band around the line and says nothing about where along the line. The posterior is Bayes’ rule,
A conditional flow is trained on pairs simulated from the prior and (1) by the conditional negative log-likelihood, the loss (1) with as the condition. Its expectation over the joint distribution of the pairs splits in two:
The first term, the conditional entropy of the state given the observation, does not depend on , 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 the posterior is Gaussian too, with
The posterior covariance does not depend on , so neither does the conditional entropy of (3), the entropy (2) of . We take a correlated prior, and , and simulate 10,000 pairs: 6,000 to train on and 4,000 held out.
# Shapes: sample (N) = 10,000 pairs; train (N_t) = 6,000; held_out (N_v) = 4,000; observation (D_y) = 1
ObservationState = Float[ArrayLike, "observation state"]
StateMatrix = Float[ArrayLike, "state state"]
SampleState = Float[ArrayLike, "sample state"]
SampleObservation = Float[ArrayLike, "sample observation"]
# H = [1, 1], (observation, state)
observation_operator: ObservationState = np.array([[1.0, 1.0]])
# σ_obs, the noise of the observation
noise_scale: float = 0.1
# μ_x, the prior mean, (state)
prior_mean: Float[ArrayLike, " state"] = np.array([0.5, -0.5])
# L_x, the Cholesky factor of the prior covariance Σ_x = L_x L_xᵀ, (state, state)
prior_factor: StateMatrix = np.array([[1.0, 0.0], [0.6, 0.5]])
# x = μ_x + L_x w with w ~ 𝒩(0, I), (sample, state)
gauss_states: SampleState = (
prior_mean + rng.standard_normal((10000, 2)) @ prior_factor.T
)
# y = H x + ε with ε ~ 𝒩(0, σ²_obs), (sample, observation)
gauss_observations: SampleObservation = (
gauss_states @ observation_operator.T
+ noise_scale * rng.standard_normal((10000, 1))
)# Σ_x = L_x L_xᵀ, (state, state)
prior_cov: StateMatrix = prior_factor @ prior_factor.T
# Σ_{x|y} = (Σ_x⁻¹ + σ⁻²_obs Hᵀ H)⁻¹, the same for every y, (state, state)
posterior_cov: StateMatrix = np.linalg.inv(
np.linalg.inv(prior_cov)
+ observation_operator.T @ observation_operator / noise_scale**2
)
# user
# μ_{x|y} = Σ_{x|y} (Σ_x⁻¹ μ_x + σ⁻²_obs Hᵀ y), (state)
def posterior_mean(
observation: Float[ArrayLike, " observation"],
) -> Float[ArrayLike, " state"]:
"""The mean of the exact posterior given one observation."""
# Σ_x⁻¹ μ_x + σ⁻²_obs Hᵀ y, (state)
information: Float[ArrayLike, " state"] = (
np.linalg.solve(prior_cov, prior_mean)
+ observation_operator.T @ observation / noise_scale**2
)
return posterior_cov @ informationTwo 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 with gaussian_kl_divergence. We also read the variance of under the posterior, , which we will check the flow’s samples against.
# today (gauss_flows)
# H[x | y] = ½ log det(2πe Σ_{x|y}), the same for every y
conditional_entropy: float = float(gaussian_entropy(posterior_cov))
# today (gauss_flows)
# KL[p(x | y = 0) ‖ p(x)], the information one observation brings
information_gain: float = float(
gaussian_kl_divergence(
posterior_mean(np.zeros(1)), posterior_cov, prior_mean, prior_cov
)
)
print(f"posterior covariance:\n{posterior_cov}")
print(
f"H[x | y] = {conditional_entropy:.4f} nats; KL[p(x | y = 0) || p(x)] = {information_gain:.4f} nats"
)
print(
f"variance of Hx under the posterior: {(observation_operator @ posterior_cov @ observation_operator.T).item():.6f}; sigma_obs^2 = {noise_scale**2:.6f}"
)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 under it is slightly below , because the prior also says a little about .
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 whatever the observation.
# user
# q_θ(x | y) = (T₆ ∘ … ∘ T₁)_# 𝒩(0, I), each Tₖ a spline coupling that reads y, then a swap
def make_flow(key) -> Transformed:
"""A fresh conditional flow of six coupling blocks on a standard-normal base."""
# user
# one block: a coupling conditioned on y, then a swap of the two coordinates
def make_block(block_key) -> Chain:
"""A conditional spline coupling followed by a swap."""
# today (gauss_flows)
# the spline coupling, whose conditioner reads the copied half and y
coupling = RQSplineCoupling(block_key, shape=(2,), interval=5.0, cond_dim=1)
# today (flowjax)
# the coupling, then the swap
return Chain([coupling, Permute(jnp.array([1, 0]))])
# today (flowjax)
# six blocks stacked on a leading axis, applied in turn on a standard-normal base
blocks: Chain = eqx.filter_vmap(make_block)(jr.split(key, 6))
return Transformed(StandardNormal((2,)), Scan(blocks))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 , with the gradient clipped to a global norm of 5.
# Shapes: batch (N_b) = 256 pairs; step = 3,000 training steps
Scalar = Float[ArrayLike, ""]
# user
# pipekit-train's task: the conditional 𝓛(θ) of one batch
class ConditionalNLL:
"""pipekit-train's task: the conditional negative log-likelihood of a batch."""
# user
# 𝓛(θ) = −(1/N_b) ∑ₙ log q_θ(xₙ | yₙ), also logged
def loss_fn(self, flow, batch, key):
# the states and observations of the batch, (batch, state), (batch, observation)
batch_states: Float[ArrayLike, "batch state"]
batch_observations: Float[ArrayLike, "batch observation"]
batch_states, batch_observations = batch
# today (gauss_flows)
# −(1/N_b) ∑ₙ log q_θ(xₙ | yₙ)
loss: Scalar = negative_log_likelihood(
flow, batch_states, condition=batch_observations
)
return loss, {"loss": loss}# today (optax)
# the learning rate of each step: up to 3·10⁻³, then down to almost zero
schedule: optax.Schedule = optax.cosine_onecycle_schedule(
transition_steps=3000, peak_value=3e-3
)
# the settings every run shares
loop_settings: dict = {
"task": ConditionalNLL(),
"optimizer_config": {"name": "adam", "lr": schedule, "clip_norm": 5.0},
"max_steps": 3000,
"steps_per_epoch": 100,
"log_every_n_steps": 100,
"batch_size": 256,
"seed": 1,
}# user
# θ after 3,000 steps on the training pairs, and the training time in seconds
def fit_posterior(
states: SampleState, observations: SampleObservation
) -> tuple[Transformed, float]:
"""Train a fresh conditional flow on the pairs ``(states, observations)``."""
# the clock before training
start: float = time.perf_counter()
# today (pipekit)
# θ after 3,000 steps, held by the model op
trained_op: EquinoxModelOp
trained_op, _ = TrainingLoop(
EquinoxModelOp(make_flow(jr.key(2))),
ArrayDataset(states, observations),
**loop_settings,
).run()
return trained_op.module, time.perf_counter() - start# user
# the flow trained on the first 6,000 linear-Gaussian pairs
gauss_flow: Transformed
gauss_seconds: float
gauss_flow, gauss_seconds = fit_posterior(
gauss_states[:6000], gauss_observations[:6000]
)
# today (gauss_flows)
# −(1/N_v) ∑ₙ log q_θ(xₙ | yₙ) on the held-out pairs
gauss_held_nll: float = float(
negative_log_likelihood(
gauss_flow, gauss_states[6000:], condition=gauss_observations[6000:]
)
)
print(
f"trained in {gauss_seconds:.0f} s; held-out conditional NLL {gauss_held_nll:.4f} nats against H[x | y] = {conditional_entropy:.4f}"
)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,
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.
# Shapes: held_out (N_v) = 4,000 pairs
PerHeldOut = Float[ArrayLike, " held_out"]
# user
# μ_{x|yₙ} for each held-out observation, (held_out, state)
held_means: Float[ArrayLike, "held_out state"] = np.stack(
[posterior_mean(observation) for observation in gauss_observations[6000:]]
)
# today (jax)
# log p(xₙ | yₙ) = log 𝒩(xₙ; μ_{x|yₙ}, Σ_{x|y}), (held_out)
exact_log_density: PerHeldOut = jax.vmap(
multivariate_normal.logpdf, in_axes=(0, 0, None)
)(gauss_states[6000:], held_means, posterior_cov)
# today (flowjax)
# log q_θ(xₙ | yₙ), (held_out)
flow_log_density: PerHeldOut = gauss_flow.log_prob(
gauss_states[6000:], gauss_observations[6000:]
)
# log p(xₙ | yₙ) − log q_θ(xₙ | yₙ), the terms of Δ, (held_out)
gap_terms: PerHeldOut = np.asarray(exact_log_density - flow_log_density)
print(
f"amortisation gap: {gap_terms.mean():.4f} +/- {gap_terms.std() / np.sqrt(len(gap_terms)):.4f} nats (one standard error); held-out NLL - H[x | y] = {gauss_held_nll - conditional_entropy:.4f}"
)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.
# Shapes: test (N_q) = 25 observations; sample (N) = 4,000 posterior draws
# user
# KL[p(x | y) ‖ q_θ(x | y)] ≈ (1/N) ∑ᵢ [log p(xᵢ | y) − log q_θ(xᵢ | y)] with xᵢ ~ p(x | y)
def kl_at(flow: Transformed, observation: float) -> float:
"""The KL divergence of the flow from the exact posterior at one observation."""
# user
# μ_{x|y} at this observation, (state)
mean: Float[ArrayLike, " state"] = posterior_mean(np.array([observation]))
# xᵢ = μ_{x|y} + chol(Σ_{x|y}) wᵢ with wᵢ ~ 𝒩(0, I), the same draws for every y, (sample, state)
draws: SampleState = (
mean
+ np.random.default_rng(1).standard_normal((4000, 2))
@ np.linalg.cholesky(posterior_cov).T
)
# today (jax)
# log p(xᵢ | y), (sample)
exact: Float[ArrayLike, " sample"] = multivariate_normal.logpdf(
draws, mean, posterior_cov
)
# today (flowjax)
# log q_θ(xᵢ | y), (sample)
flow_density: Float[ArrayLike, " sample"] = flow.log_prob(
draws, jnp.array([observation])
)
return float(jnp.mean(exact - flow_density))# y₁, …, y₂₅ evenly spread over [−6, 6], (test)
sweep_observations: Float[ArrayLike, " test"] = np.linspace(-6.0, 6.0, 25)
# user
# KL[p(x | y) ‖ q_θ(x | y)] at each yᵢ, (test)
sweep_kl: Float[ArrayLike, " test"] = np.array(
[kl_at(gauss_flow, float(observation)) for observation in sweep_observations]
)
# the standard deviation of the training observations
observation_spread: float = float(gauss_observations[:6000].std())
for observation, kl in zip(sweep_observations[::4], sweep_kl[::4], strict=True):
print(
f"y = {observation:+.1f} ({observation / observation_spread:+.1f} sd): KL {kl:.4f} nats"
)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 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 , 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 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 and and take the two moons, standardised, as the prior. A line 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
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.
# Shapes: sample (N) = 10,000 pairs; train (N_t) = 6,000; held_out (N_v) = 4,000
# today (sklearn)
# 200,000 draws of the raw two moons, (sample, state)
moon_pilot: SampleState = make_moons(200000, noise=0.06, random_state=1)[0]
# the mean of each coordinate, (state)
moon_center: Float[ArrayLike, " state"] = moon_pilot.mean(axis=0)
# the standard deviation of each coordinate, (state)
moon_scale: Float[ArrayLike, " state"] = moon_pilot.std(axis=0)
# user
# x ~ p(x), the standardised two moons, with the moon of each draw (0 is the upper one)
def moon_prior(
count: int, seed: int
) -> tuple[SampleState, Float[ArrayLike, " sample"]]:
"""``count`` standardised two-moons draws and their moon labels."""
# today (sklearn)
# the raw draws and their labels, (sample, state), (sample)
raw: SampleState
labels: Float[ArrayLike, " sample"]
raw, labels = make_moons(count, noise=0.06, random_state=seed)
return (raw - moon_center) / moon_scale, labels# user
# x ~ p(x), the states of the pairs, (sample, state)
moon_states: SampleState = moon_prior(10000, 0)[0]
# y = H x + ε with ε ~ 𝒩(0, σ²_obs), (sample, observation)
moon_observations: SampleObservation = (
moon_states @ observation_operator.T + noise_scale * rng.standard_normal((10000, 1))
)
# user
# the flow trained on the first 6,000 two-moons pairs
moon_flow: Transformed
moon_seconds: float
moon_flow, moon_seconds = fit_posterior(moon_states[:6000], moon_observations[:6000])
# today (gauss_flows)
# −(1/N_v) ∑ₙ log q_θ(xₙ | yₙ) on the held-out pairs
moon_held_nll: float = float(
negative_log_likelihood(
moon_flow, moon_states[6000:], condition=moon_observations[6000:]
)
)
print(
f"trained in {moon_seconds:.0f} s; held-out conditional NLL {moon_held_nll:.4f} nats"
)trained in 25 s; held-out conditional NLL -0.8842 nats
# Shapes: sample (N) = 400,000 prior draws
PerSample = Float[ArrayLike, " sample"]
# user
# exact posterior draws at y: prior draws kept with probability a(x), and their moons
def reject_posterior(observation: float, seed: int) -> tuple[SampleState, PerSample]:
"""Exact draws from the two-moons posterior at one observation, by rejection."""
# user
# 400,000 prior draws and their moons, (sample, state), (sample)
candidates: SampleState
labels: PerSample
candidates, labels = moon_prior(400000, seed)
# Hx of each draw, (sample)
projection: PerSample = (candidates @ observation_operator.T)[:, 0]
# a(x) = exp(−(y − H x)² / (2σ²_obs)), (sample)
accept: PerSample = np.exp(-0.5 * (projection - observation) ** 2 / noise_scale**2)
# u ~ 𝒰(0, 1) for each draw; a draw is kept where u < a(x), (sample)
uniform: PerSample = np.random.default_rng(seed).uniform(size=len(accept))
return candidates[uniform < accept], labels[uniform < accept]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.
# today (sklearn)
# the moon of a point, from its 15 nearest labelled prior draws
moon_classifier = KNeighborsClassifier(15).fit(*moon_prior(20000, 3))
# user
# exact posterior draws at y = 0 and their moons, (sample, state), (sample)
check_draws: SampleState
check_labels: Float[ArrayLike, " sample"]
check_draws, check_labels = reject_posterior(0.0, 4)
print(
f"{len(check_draws)} exact draws at y = 0; classifier agrees with the true moon on {np.mean(moon_classifier.predict(check_draws) == check_labels):.1%}"
)21115 exact draws at y = 0; classifier agrees with the true moon on 100.0%
# user
# the exact draws, their moons, and as many draws of the flow, at one observation
def posterior_draws(
observation: float, seed: int
) -> tuple[SampleState, PerSample, SampleState]:
"""Exact draws by rejection, their moons, and the same number of flow draws."""
# user
# exact draws by rejection and their moons, (sample, state), (sample)
exact_draws: SampleState
exact_labels: PerSample
exact_draws, exact_labels = reject_posterior(observation, seed)
# today (flowjax)
# as many draws of q_θ(x | y), (sample, state)
flow_draws: SampleState = moon_flow.sample(
jr.key(seed), (len(exact_draws),), condition=jnp.array([observation])
)
return exact_draws, exact_labels, np.asarray(flow_draws)# the exact draws, their moons and the flow draws at each observation, (sample, state), (sample), (sample, state)
exact_draws: SampleState
exact_labels: PerSample
flow_draws: SampleState
for seed, observation in enumerate((-1.0, 0.0, 1.0), start=5):
# user
# the exact and the flow draws at this observation, (sample, state), (sample), (sample, state)
exact_draws, exact_labels, flow_draws = posterior_draws(observation, seed)
# today (sklearn)
# the upper moon's share of the flow draws, by the classifier
flow_upper: float = 1 - moon_classifier.predict(flow_draws).mean()
# today (sklearn)
# the distance of each flow draw to its nearest labelled prior draw, (sample)
flow_distance: PerSample = moon_classifier.kneighbors(flow_draws, 1)[0][:, 0]
# Hx of each exact draw, (sample, observation)
exact_projection: SampleObservation = exact_draws @ observation_operator.T
# Hx of each flow draw, (sample, observation)
flow_projection: SampleObservation = flow_draws @ observation_operator.T
print(
f"y = {observation:+.0f}: upper moon {1 - exact_labels.mean():.3f} exact, {flow_upper:.3f} flow; flow draws off the moons {np.mean(flow_distance > 0.15):.3f}\n Hx mean {exact_projection.mean():+.3f} exact, {flow_projection.mean():+.3f} flow; sd {exact_projection.std():.4f} exact, {flow_projection.std():.4f} flow"
)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 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 the line crosses each crescent twice, the posterior has four modes, and the mass splits evenly between the crescents; at one draw in six sits on the far crescent, and the flow’s share is within one percentage point of the exact one. Its is centred on the observation with a spread 6 to 8 per cent wider than the exact one, which is about : 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 , 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 below a fixed window samples a different distribution, the posterior of a noise-free observation smeared by the window.
# user
# 400,000 prior draws, (sample, state)
window_draws: SampleState = moon_prior(400000, 6)[0]
# Hx of each draw, (sample)
window_projection: Float[ArrayLike, " sample"] = (
window_draws @ observation_operator.T
)[:, 0]
# the spread of Hx over the draws with |Hx − 0| < 0.06, a hard window in place of a(x)
print(
f"sd of Hx in a window of half-width 0.06: {window_projection[np.abs(window_projection) < 0.06].std():.4f}; sigma_obs = {noise_scale}"
)sd of Hx in a window of half-width 0.06: 0.0348; sigma_obs = 0.1
The window gives a spread of about a third of the true one, so it is the wrong reference for this flow, which was trained with noise .
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.
# user
# 4,000 draws of q_θ(x | y), (sample, state)
def draw_posterior(flow: Transformed, observation, key) -> SampleState:
"""4,000 draws of the flow posterior at ``observation``."""
# today (flowjax)
# xᵢ ~ q_θ(x | y), (sample, state)
return flow.sample(key, (4000,), condition=observation)
# today (equinox)
# the same function compiled once, for any flow and any y
compiled_draws: Callable = eqx.filter_jit(draw_posterior)
# user
# one call to compile, before the clock starts
compiled_draws(moon_flow, jnp.array([0.0]), jr.key(0)).block_until_ready()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)# the clock before the flow's draws at a new observation
start: float = time.perf_counter()
# user
# 4,000 draws at y = 0.37
compiled_draws(moon_flow, jnp.array([0.37]), jr.key(1)).block_until_ready()
# the seconds the flow took
flow_seconds: float = time.perf_counter() - start
# the clock before the rejection run at the same observation
start = time.perf_counter()
# user
# exact draws at y = 0.37 by rejection, (sample, state)
rejection_draws: SampleState = reject_posterior(0.37, 9)[0]
# the seconds the rejection run took
rejection_seconds: float = time.perf_counter() - start
print(
f"flow: 4,000 draws in {1000 * flow_seconds:.1f} ms; rejection: {len(rejection_draws)} draws in {1000 * rejection_seconds:.0f} ms from 400,000 prior draws"
)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 over the prior, and with independent measurements 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¶
| Piece | Equation | In 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 flow | RQSplineCoupling(..., 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.
- 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.
- Winkler, C., Worrall, D. E., Hoogeboom, E., & Welling, M. (2019). Learning Likelihoods with Conditional Normalizing Flows. arXiv Preprint arXiv:1912.00042.