Latent ODEs and the Gaussian they ask for
A neural ODE inside a variational autoencoder: the Gaussian moves from the data to a code, and the trained codes are far from it
03 · Latent ODEs and the Gaussian they ask for¶
The flows of notebooks 00 to 02 map one data point to one Gaussian point of the same dimension, and their log-determinant makes the likelihood exact. A latent ODE Rubanova et al., 2019 asks something else of the Gaussian. Its data are whole trajectories, observed at irregular times, and it summarises each one by a short code : an encoder reads the trajectory, a neural ODE integrates the code forward and a decoder turns the path back into observations. The Gaussian is now the prior on the code, the map from data to code is stochastic and loses information, and the exact likelihood gives way to a lower bound, the evidence lower bound of a variational autoencoder Kingma & Welling, 2014. The latent-ODE example trains this model on spirals and shows its reconstructions and extrapolations; here we ask the Gaussianization question of it: how close do the trained codes come to the prior they were pulled towards, and what does the gap cost?
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 diffrax
import equinox as eqx
import jax
import jax.nn as jnn
import jax.numpy as jnp
import jax.random as jr
import lineax as lx
import matplotlib.pyplot as plt
import numpy as np
import optax
from functax.geometry import Axis
from functax.interp import Linear, Policies
from flowjax.distributions import Transformed
from jax.scipy import stats as jstats
from jaxtyping import ArrayLike, Float, Int
from pipekit_train import ArrayDataset, History, TrainingLoop
from pipekit_train.backends.equinox import EquinoxModelOp
from scipy import stats
from sklearn.linear_model import LogisticRegression
from gauss_flows_docs.environment import watermark
from gauss_flows_docs.plotting import (
DATA_COLOR,
GAUSS_KW,
LATENT_COLOR,
SCATTER_KW,
style_ax,
use_compact_figures,
)
from gauss_flows_maps.conditioning import pack_time_control
from gauss_flows_models.flows import DiffeqMLP
from gauss_flows_models.inference import fit_rbig
from gauss_flows_models.info_theory import gaussian_kl_divergence
np.set_printoptions(precision=3, suppress=True)
# Figures are stored as palette PNGs to keep the notebook small.
use_compact_figures()
watermark("jax", "numpy", "diffrax", "functax", "pipekit_train", "gauss_flows_models")Python implementation: CPython
Python version : 3.13.12
IPython version : 9.12.0
jax : 0.12.1
numpy : 2.4.3
diffrax : 0.7.2
functax : 0.0.15
pipekit_train : 0.3.4
gauss_flows_models: 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
This notebook runs in float32, JAX’s default, unlike the others of this part: the two ODE solves per trajectory and step are the cost of training, and fit_rbig, which section 4 uses, fails when float64 is switched on (gauss_flows#247).
1. Spirals observed at irregular times¶
The data follow the toy problem of Rubanova et al. (2019), in the form the example uses. Each spiral has radius and angle , with a start angle drawn uniformly from and a direction drawn with equal odds, on . A spiral is observed at 30 of 100 evenly spaced times, chosen at random, with noise of standard deviation 0.05. Every spiral grows at the same rate and turns at the same speed; they differ only in where they start and which way they turn.
# Shapes: sample (N) = 300 spirals; time (N_q) = 100 dense times on [0, 5]
PerTime = Float[ArrayLike, " time"]
Scalar = Float[ArrayLike, ""]
# user
# x(t) = r(t) (cos α(t), sin α(t)), with r(t) = 0.4 t + 0.5 and α(t) = 1.5 s t + α₀
def spiral(
start_angle: Scalar, direction: Scalar, times: PerTime
) -> Float[ArrayLike, "time state"]:
"""The spiral that starts at ``start_angle`` and turns in ``direction`` (±1), at ``times``."""
# r(t) = 0.4 t + 0.5, (time)
radius: PerTime = 0.4 * times + 0.5
# α(t) = 1.5 s t + α₀, (time)
angle: PerTime = 1.5 * direction * times + start_angle
return jnp.stack([radius * jnp.cos(angle), radius * jnp.sin(angle)], axis=-1)# Shapes: state (D_x) = 2
PerSample = Float[ArrayLike, " sample"]
# tⱼ, 100 times evenly spaced on [0, 5], (time)
dense_times: PerTime = jnp.linspace(0.0, 5.0, 100)
# α₀ ~ 𝒰(0, 2π), (sample)
start_angles: PerSample = jr.uniform(jr.key(0), (300,), maxval=2 * jnp.pi)
# s = ±1 with equal odds, (sample)
directions: PerSample = jr.choice(jr.key(1), jnp.array([-1.0, 1.0]), (300,))
# user
# x(tⱼ) of every spiral, without noise, (sample, time, state)
clean_paths: Float[ArrayLike, "sample time state"] = jax.vmap(
spiral, in_axes=(0, 0, None)
)(start_angles, directions, dense_times)# Shapes: observation (N_o) = 30 observed times per spiral
SampleObservation = Float[ArrayLike, "sample observation"]
# 30 of the 100 time indices of each spiral, drawn without replacement and sorted, (sample, observation)
observed_index: Int[ArrayLike, "sample observation"] = jnp.sort(
jax.vmap(lambda key: jr.choice(key, 100, (30,), replace=False))(
jr.split(jr.key(2), 300)
),
axis=1,
)
# tᵢ, the observed times of each spiral, (sample, observation)
observed_times: SampleObservation = dense_times[observed_index]
# xᵢ = x(tᵢ) + 0.05 ε with ε ~ 𝒩(0, I), (sample, observation, state)
observed_points: Float[ArrayLike, "sample observation state"] = jnp.take_along_axis(
clean_paths, observed_index[..., None], axis=1
) + 0.05 * jr.normal(jr.key(3), (300, 30, 2))The first 250 spirals train the model and the last 50 are held out.
# Shapes: train (N_t) = 250 spirals; held_out (N_v) = 50 spirals
# the training spirals' observed times, (train, observation)
train_times: Float[ArrayLike, "train observation"] = observed_times[:250]
# their observations, (train, observation, state)
train_points: Float[ArrayLike, "train observation state"] = observed_points[:250]
# the held-out spirals' observed times, (held_out, observation)
held_times: Float[ArrayLike, "held_out observation"] = observed_times[250:]
# their observations, (held_out, observation, state)
held_points: Float[ArrayLike, "held_out observation state"] = observed_points[250:]2. The model and its lower bound¶
Write one spiral’s observations as . The generative model draws a code from the prior, integrates a neural ODE with vector field from it, and decodes each point of the path with a network , adding Gaussian noise of a fixed scale :
The encoder runs a second neural ODE over the observations, as the example does: the observations are joined into a piecewise-linear path , a hidden state follows from to , and a linear head turns into the mean and the log-variance of a diagonal Gaussian . Both vector fields are gauss_flows’ DiffeqMLP; the encoder’s takes as the control of its condition, packed with pack_time_control, the same contract FFJORD’s conditional fields use.
The code is not computed from the data by a bijection, so there is no change of variables and no exact likelihood. The model is trained instead by the evidence lower bound,
whose KL term between two Gaussians has a closed form:
The loss is the negative of (2) averaged over a batch, with one reparametrised draw per spiral. It replaces negative_log_likelihood, which needs an exact log-density. The sizes are the example’s: , , two hidden layers of 40 in each vector field, and .
# user
# the encoder field v_φ and its head, the latent field v_θ and the decoder dec_θ
class LatentODE(eqx.Module):
"""The four networks of a latent ODE."""
# today (gauss_flows)
# v_φ(t, h, x̂(t))
encoder_field: DiffeqMLP
# (μ_φ, log σ²_φ) = W h + b
encoder_head: eqx.nn.Linear
# today (gauss_flows)
# v_θ(t, z)
latent_field: DiffeqMLP
# dec_θ(z)
decoder: eqx.nn.MLP# Shapes: code (D_z) = 4; hidden (D_h) = 25
PerCode = Float[ArrayLike, " code"]
# today (gauss_flows)
# the encoder field v_φ(t, h, x̂(t)), with x̂(t) as its control
encoder_field: DiffeqMLP = DiffeqMLP(
jr.key(4), in_dim=25, control_dim=2, hidden=(40, 40), activation=jnn.tanh
)
# today (gauss_flows)
# the latent field v_θ(t, z), with no condition
latent_field: DiffeqMLP = DiffeqMLP(
jr.key(5), in_dim=4, control_dim=0, hidden=(40, 40), activation=jnn.tanh
)
# today (equinox)
# (μ_φ, log σ²_φ) = W h + b, and dec_θ, an MLP with two hidden layers of 20
model: LatentODE = LatentODE(
encoder_field,
eqx.nn.Linear(25, 8, key=jr.key(6)),
latent_field,
eqx.nn.MLP(4, 2, 20, 2, activation=jnn.tanh, key=jr.key(7)),
)Both solves use diffrax’s Tsit5 with an adaptive step, as the example does, and pass the networks to the vector field as the solve’s args.
# today (diffrax)
# Tsit5, first step 0.05, relative tolerance 10⁻³ and absolute 10⁻⁴
ode_settings: dict = {
"solver": diffrax.Tsit5(),
"dt0": 0.05,
"stepsize_controller": diffrax.PIDController(rtol=1e-3, atol=1e-4),
"max_steps": 4096,
}
# user
# y(t) of dy/dt = field(t, y, args) from y(t₀) = y₀, at the times `saveat` asks for
def solve(field, start, end, initial, saveat, args) -> Float[ArrayLike, "..."]:
"""The solution of an ODE, by Tsit5 with an adaptive step."""
# today (diffrax)
# the ODE's right-hand side
term: diffrax.ODETerm = diffrax.ODETerm(field)
# today (diffrax)
# the solution at the requested times
solution: diffrax.Solution = diffrax.diffeqsolve(
term, t0=start, t1=end, y0=initial, saveat=saveat, args=args, **ode_settings
)
return solution.ysThe encoder’s vector field reads the observed path at the current time and packs it as the control of its condition.
PerHidden = Float[ArrayLike, " hidden"]
# user
# dh/dt = v_φ(t, h, x̂(t)), with the model and the path x̂ as the solve's args
def encoder_dynamics(time, hidden: PerHidden, args) -> PerHidden:
"""The encoder's vector field at ``time``."""
# today (functax)
# the encoder and the observed path
model: LatentODE
path: Linear
model, path = args
# today (functax)
# x̂(t), (state)
control: Float[ArrayLike, " state"] = path(jnp.atleast_1d(time)[:, None])[:, 0]
# today (gauss_flows)
# v_φ(t, h, x̂(t)), (hidden)
return model.encoder_field(time, hidden, pack_time_control(time, control))The encoder fits the path through one spiral’s observations once, with functax’s linear interpolant (extrapolated past the ends), and integrates the hidden state along it.
# user
# (μ_φ, log σ²_φ) = head(h(t_{N_o})), with h(t₁) = 0
def encode(model: LatentODE, times, points) -> tuple[PerCode, PerCode]:
"""The mean and log-variance of q_φ(z₀ | X) for one spiral."""
# today (functax)
# x̂(t), the piecewise-linear path through the observations
path = Linear().fit(Axis(times), points.T, policies=Policies(outside="extrapolate"))
# user
# h(t_{N_o}), the hidden state at the last observation, (1, hidden)
final_hidden: Float[ArrayLike, "1 hidden"] = solve(
encoder_dynamics,
times[0],
times[-1],
jnp.zeros(25),
diffrax.SaveAt(t1=True),
(model, path),
)
# μ_φ and log σ²_φ, the two halves of the head's output, (code), (code)
mean: PerCode
log_variance: PerCode
mean, log_variance = jnp.split(model.encoder_head(final_hidden[-1]), 2)
return mean, jnp.clip(log_variance, -8.0, 4.0)The decoder starts every code at , so that means the same thing for every spiral whatever its first observed time.
# user
# dz/dt = v_θ(t, z), with the model as the solve's args
def latent_dynamics(time, state: PerCode, model: LatentODE) -> PerCode:
"""The latent vector field at ``time``."""
# today (gauss_flows)
# v_θ(t, z), (code)
return model.latent_field(time, state, None)
# user
# dec_θ(z(tᵢ)) at each requested time, from z(0) = z₀
def decode(
model: LatentODE, code: PerCode, times: PerTime
) -> Float[ArrayLike, "time state"]:
"""The decoded path of ``code`` at ``times``."""
# user
# z(tᵢ), (time, code)
latent_path: Float[ArrayLike, "time code"] = solve(
latent_dynamics, 0.0, times[-1], code, diffrax.SaveAt(ts=times), model
)
return jax.vmap(model.decoder)(latent_path)# user
# KL[𝒩(μ_φ, diag σ²_φ) ‖ 𝒩(0, I)] for one posterior
def prior_kl(mean: PerCode, log_variance: PerCode) -> Scalar:
"""The KL divergence of the diagonal posterior q_φ from the prior 𝒩(0, I)."""
# today (lineax)
# diag σ²_φ and I as covariance operators, (code, code)
posterior_cov = lx.DiagonalLinearOperator(jnp.exp(log_variance))
prior_cov = lx.IdentityLinearOperator(jax.eval_shape(lambda: mean))
# today (gauss_flows)
# ½ [tr(Σ_q) + μ_φᵀ μ_φ − D_z − log det Σ_q], the closed form for a diagonal Σ_q
return gaussian_kl_divergence(mean, posterior_cov, jnp.zeros_like(mean), prior_cov)# user
# the two terms of the bound for one spiral: ∑ᵢ log 𝒩(xᵢ; dec_θ(z(tᵢ)), σ²_obs I) at one draw z₀, and the KL
def bound_terms(model: LatentODE, key, times, points) -> tuple[Scalar, Scalar]:
"""The reconstruction log-likelihood at one draw of z₀, and the KL of q_φ from the prior."""
# user
# μ_φ and log σ²_φ, (code), (code)
mean: PerCode
log_variance: PerCode
mean, log_variance = encode(model, times, points)
# z₀ = μ_φ + σ_φ ⊙ ε with ε ~ 𝒩(0, I), (code)
code: PerCode = mean + jnp.exp(0.5 * log_variance) * jr.normal(key, mean.shape)
# user
# dec_θ(z(tᵢ)), (observation, state)
decoded: Float[ArrayLike, "observation state"] = decode(model, code, times)
# ∑ᵢ log 𝒩(xᵢ; dec_θ(z(tᵢ)), 0.1² I)
log_likelihood: Scalar = jnp.sum(jstats.norm.logpdf(points, decoded, 0.1))
# user
# KL[𝒩(μ_φ, diag σ²_φ) ‖ 𝒩(0, I)] = ½ ∑ₖ (σ²_k + μ²_k − 1 − log σ²_k)
kl: Scalar = prior_kl(mean, log_variance)
return log_likelihood, klpipekit-train’s task averages the negative bound over a batch and logs its two terms.
# user
# the two terms of the bound for every spiral of a batch, one key each
batch_bound_terms: Callable = jax.vmap(bound_terms, in_axes=(None, 0, 0, 0))# Shapes: batch (N_b) = 50 spirals
# user
# pipekit-train's task: the negative evidence lower bound of a batch
class NegativeELBO:
"""pipekit-train's task: minus the mean evidence lower bound of a batch of spirals."""
# user
# 𝓛 = −(1/N_b) ∑ₙ (reconstructionₙ − KLₙ), also logged with its two terms
def loss_fn(self, model, batch, key):
# the batch's times and observations, (batch, observation), (batch, observation, state)
batch_times: Float[ArrayLike, "batch observation"]
batch_points: Float[ArrayLike, "batch observation state"]
batch_times, batch_points = batch
# one key per spiral
keys: jax.Array = jr.split(key, len(batch_times))
# user
# the two terms of each spiral's bound, (batch), (batch)
log_likelihoods: Float[ArrayLike, " batch"]
kls: Float[ArrayLike, " batch"]
log_likelihoods, kls = batch_bound_terms(model, keys, batch_times, batch_points)
# minus the mean bound
loss: Scalar = -jnp.mean(log_likelihoods - kls)
return loss, {"loss": loss, "recon": log_likelihoods.mean(), "kl": kls.mean()}We train for 250 epochs of five steps of 50 spirals, 1,250 steps in all, with Adam on a one-cycle cosine rate that peaks at and the gradient clipped to a global norm of 5. That takes a couple of minutes on a CPU.
# Shapes: step = 1,250 training steps; epoch = 250 epochs of 5 steps
# 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=1250, peak_value=3e-3
)
# today (pipekit)
# the logged terms of every step
history = History()The spirals’ observed times are the dataset’s inputs and their observations its targets.
# today (pipekit)
# a loop over the training spirals, with their observed times as inputs and their observations as targets
loop: TrainingLoop = TrainingLoop(
EquinoxModelOp(model),
ArrayDataset(np.asarray(train_times), np.asarray(train_points)),
task=NegativeELBO(),
optimizer_config={"name": "adam", "lr": schedule, "clip_norm": 5.0},
max_steps=1250,
steps_per_epoch=5,
log_every_n_steps=5,
batch_size=50,
seed=1,
callbacks=(history,),
)# the clock before training
start: float = time.perf_counter()
# today (pipekit)
# the trained networks, held by the model op
trained_op: EquinoxModelOp
trained_op, _ = loop.run()
# the trained networks
trained: LatentODE = trained_op.module
print(f"training time: {time.perf_counter() - start:.0f} s")training time: 92 s
PerEpoch = Float[ArrayLike, " epoch"]
# the mean of each logged term over the steps of an epoch, (epoch)
epoch_terms: dict = {
name: np.array([metrics[name] for _, metrics in history.train])
.reshape(250, 5)
.mean(axis=1)
for name in ("loss", "recon", "kl")
}
for epoch in (0, 49, 99, 149, 199, 249):
print(
f"epoch {epoch + 1:>3}: -ELBO {epoch_terms['loss'][epoch]:8.1f}, reconstruction {epoch_terms['recon'][epoch]:8.1f}, KL {epoch_terms['kl'][epoch]:5.1f}"
)epoch 1: -ELBO 3851.7, reconstruction -3851.5, KL 0.1
epoch 50: -ELBO 3142.0, reconstruction -3114.0, KL 27.9
epoch 100: -ELBO 1432.6, reconstruction -1391.5, KL 41.1
epoch 150: -ELBO 151.7, reconstruction -113.6, KL 38.0
epoch 200: -ELBO 56.1, reconstruction -21.7, KL 34.4
epoch 250: -ELBO 34.9, reconstruction -1.9, KL 33.0
The loss falls by almost two orders of magnitude, nearly all of it in the reconstruction term, while the KL term rises from almost zero to about 41 nats per spiral by epoch 100 and settles near 33: to reconstruct, the encoder has to move each code away from the prior.
3. Reconstructions of held-out spirals¶
We encode each held-out spiral, decode its posterior mean on the 100 dense times, and compare the result with the spiral without noise.
HeldTimeState = Float[ArrayLike, "held_out time state"]
# user
# μ_φ of each held-out spiral, (held_out, code)
held_means: Float[ArrayLike, "held_out code"] = jax.vmap(
lambda times, points: encode(trained, times, points)[0]
)(held_times, held_points)
# user
# dec_θ(z(tⱼ)) from μ_φ at the dense times, (held_out, time, state)
held_paths: HeldTimeState = jax.vmap(decode, in_axes=(None, 0, None))(
trained, held_means, dense_times
)
# the root-mean-square distance to the spirals without noise
held_rmse: float = float(jnp.sqrt(jnp.mean((held_paths - clean_paths[250:]) ** 2)))
print(f"held-out RMSE to the clean spirals: {held_rmse:.3f}, for radii from 0.5 to 2.5")held-out RMSE to the clean spirals: 0.172, for radii from 0.5 to 2.5
fig, axes = plt.subplots(1, 3, figsize=(12, 4.2))
for spiral_index, ax in enumerate(axes):
ax.plot(*np.asarray(clean_paths[250 + spiral_index]).T, color="0.6", lw=1)
ax.plot(*np.asarray(held_paths[spiral_index]).T, color=LATENT_COLOR, lw=2)
ax.scatter(
*np.asarray(held_points[spiral_index]).T, color=DATA_COLOR, s=14, zorder=3
)
ax.set(title=f"held-out spiral {spiral_index + 1}", xlabel="x₁", ylabel="x₂")
ax.set_aspect("equal")
style_ax(ax)
fig.tight_layout()
plt.show()
Figure 1:Three held-out spirals: the noisy irregular observations (dots), the spiral without noise (grey) and the decoded posterior mean on the dense times (orange).
The decoded paths follow the spirals through and between the observations, with a root-mean-square error of 0.17 over the 50 held-out spirals, and miss most where the observations are sparse, as at the outer end of the first spiral. The example shows more of them and also extrapolates from the first half of each spiral; what it does not ask is what the codes themselves look like.
4. How far the codes are from the prior¶
The KL term of (2) pulls each posterior towards , one spiral at a time. The distribution a sampler would need to match is a different one, the aggregate posterior of the training spirals,
Adding and subtracting inside the average of the KL terms splits it in two:
where is the mutual information between the index of a training spiral, drawn uniformly, and its code. It is at most the entropy of the index, , so whatever the mean KL term exceeds by is a lower bound on the distance of the aggregate posterior from the prior:
We compute the KL term (3) of every training spiral at its posterior, with no sampling.
TrainCode = Float[ArrayLike, "train code"]
# μ_φ and log σ²_φ of each training spiral, (train, code), (train, code)
train_means: TrainCode
train_log_variances: TrainCode
# user
# the posterior of each training spiral
train_means, train_log_variances = jax.vmap(
lambda times, points: encode(trained, times, points)
)(train_times, train_points)
# user
# KL[q_φ(z₀ | 𝒳ₙ) ‖ 𝒩(0, I)] for each spiral, (train)
train_kls: Float[ArrayLike, " train"] = jax.vmap(prior_kl)(
train_means, train_log_variances
)
print(
f"mean KL term: {float(train_kls.mean()):.1f} nats; log N_t = {np.log(250):.2f} nats"
)
print(f"so KL[q̄ ‖ N(0, I)] ≥ {float(train_kls.mean()) - np.log(250):.1f} nats")mean KL term: 33.0 nats; log N_t = 5.52 nats
so KL[q̄ ‖ N(0, I)] ≥ 27.5 nats
Each posterior is narrow, with standard deviations of a few hundredths against the prior’s 1, so the aggregate posterior is close to the empirical distribution of the means . We read their moments, as in Part 0.
# the posterior standard deviations, as a mean over the spirals, and the mean, standard deviation and excess kurtosis of each coordinate of μ_φ, (code)
for name, statistic in [
("posterior std", jnp.exp(0.5 * train_log_variances).mean(axis=0)),
("mean", train_means.mean(axis=0)),
("standard deviation", train_means.std(axis=0)),
("excess kurtosis", stats.kurtosis(np.asarray(train_means), axis=0)),
]:
print(f"{name:>18}: {np.asarray(statistic)}")
# today (sklearn)
# a linear classifier of the direction s from μ_φ, trained on the training spirals
direction_classifier = LogisticRegression().fit(
np.asarray(train_means), np.asarray(directions[:250])
)
print(
f"direction predicted from μ_φ on held-out spirals: {direction_classifier.score(np.asarray(held_means), np.asarray(directions[250:])):.0%} correct"
) posterior std: [0.027 0.029 0.023 0.031]
mean: [ 1.032 -4.904 -2.129 0.936]
standard deviation: [1.957 1.371 1.858 0.964]
excess kurtosis: [-1.451 -0.609 -0.137 -0.776]
direction predicted from μ_φ on held-out spirals: 100% correct
centred: TrainCode = np.asarray(train_means - train_means.mean(axis=0))
principal_axes: Float[ArrayLike, "code code"] = np.linalg.svd(
centred, full_matrices=False
)[2]
projected: Float[ArrayLike, "train 2"] = np.asarray(train_means) @ principal_axes[:2].T
circle: Float[ArrayLike, "sample state"] = np.column_stack(
[np.cos(np.linspace(0, 2 * np.pi, 200)), np.sin(np.linspace(0, 2 * np.pi, 200))]
)
fig, ax = plt.subplots(figsize=(5.5, 5))
for sign, color, label in [
(-1.0, DATA_COLOR, "clockwise"),
(1.0, LATENT_COLOR, "anticlockwise"),
]:
ax.scatter(
*projected[np.asarray(directions[:250]) == sign].T,
color=color,
label=label,
**SCATTER_KW,
)
for radius in (1.0, 2.0):
ax.plot(*(radius * circle).T, **GAUSS_KW)
ax.set(
xlabel="leading principal coordinate of μ_φ",
ylabel="second principal coordinate",
title="codes of the training spirals",
)
ax.set_aspect("equal")
ax.legend()
style_ax(ax)
fig.tight_layout()
plt.show()
Figure 2:The posterior means of the training spirals in their two leading principal coordinates, coloured by the direction in which the spiral turns, against the circles of radius 1 and 2 of the prior. The codes sit off-centre, spread wider than the prior, and split by direction.
The codes are not standard normal in any sense: their mean is several units from zero in two coordinates, their spread is wider than 1 in three of the four, their excess kurtosis (2) is negative in all four (from -1.45 to -0.14), and a linear classifier reads the direction of every held-out spiral off its code. In the figure the codes of each direction lie along a curve, along which the start angle changes. Most of the KL term of the bound is not information about the spiral; by (6), at least 27 of its nats are the distance of the codes as a whole from the prior. A latent ODE gives up exactness to Gaussianize trajectories, and here it does not Gaussianize them.
5. What the gap costs, and a flow that closes it¶
The prior matters when we generate: a new spiral is a code drawn from the prior and decoded. Every spiral of the training family has radius and turns at an angular speed of 1.5 radians per unit time, so both can be checked on any decoded path. We decode 200 draws from .
# Shapes: sample (N) = 200 generated spirals
SampleTimeState = Float[ArrayLike, "sample time state"]
# user
# √((1/(N N_q)) ∑ₙ ∑ⱼ (‖xₙ(tⱼ)‖ − 0.4 tⱼ − 0.5)²), the radius error of decoded paths
def radius_rmse(paths: SampleTimeState) -> float:
"""The root-mean-square distance of the paths' radii from 0.4 t + 0.5."""
# ‖xₙ(tⱼ)‖ − 0.4 tⱼ − 0.5, (sample, time)
radius_error: Float[ArrayLike, "sample time"] = jnp.linalg.norm(paths, axis=-1) - (
0.4 * dense_times + 0.5
)
return float(jnp.sqrt(jnp.mean(radius_error**2)))
# user
# |α(5) − α(0)| / 5, the mean angular speed of each decoded path, (sample)
def angular_speeds(paths: SampleTimeState) -> PerSample:
"""The angle each path turns through over [0, 5], divided by 5."""
# α(tⱼ), unwrapped along time, (sample, time)
angles: Float[ArrayLike, "sample time"] = jnp.unwrap(
jnp.arctan2(paths[..., 1], paths[..., 0]), axis=1
)
return np.abs(np.asarray(angles[:, -1] - angles[:, 0])) / 5.0# z₀ ~ 𝒩(0, I), (sample, code)
prior_codes: Float[ArrayLike, "sample code"] = jr.normal(jr.key(8), (200, 4))
# user
# dec_θ(z(tⱼ)) of each prior code, (sample, time, state)
prior_paths: SampleTimeState = jax.vmap(decode, in_axes=(None, 0, None))(
trained, prior_codes, dense_times
)
# user
# the two checks of the prior draws
prior_rmse: float = radius_rmse(prior_paths)
# user
# the angular speed of each, (sample)
prior_speeds: PerSample = angular_speeds(prior_paths)
print(
f"prior draws: radius RMSE {prior_rmse:.2f}, angular speed quartiles {np.quantile(prior_speeds, [0.25, 0.5, 0.75])} (spirals: 1.5)"
)prior draws: radius RMSE 0.89, angular speed quartiles [0.087 0.204 0.758] (spirals: 1.5)
The prior’s draws decode to paths whose radius is wrong by 0.9 on average and that barely turn, at a median of 0.20 radians per unit time against the spirals’ 1.5: the decoder was only ever trained on codes from the aggregate posterior, and most of the prior’s mass lies where no training code was. The gap of section 4 is the reason.
The fix this library offers is a Gaussianizing flow on the codes. We fit RBIG fit_rbig of Part 3 to the 250 training means (the posteriors are narrow enough that the means stand in for ), with four blocks of four-component mixtures, a small flow for 250 points in four dimensions. Its draws are codes shaped like the training codes; we decode 200 and run the same checks.
# today (gauss_flows)
# an RBIG flow fitted to the training codes, with 4 blocks of 4-component mixtures
code_flow: Transformed = fit_rbig(train_means, n_layers=4, n_components=4)
# today (flowjax)
# z₀ ~ q̂, the fitted flow's draws, (sample, code)
flow_codes: Float[ArrayLike, "sample code"] = code_flow.sample(jr.key(9), (200,))
# user
# dec_θ(z(tⱼ)) of each flow code, (sample, time, state)
flow_paths: SampleTimeState = jax.vmap(decode, in_axes=(None, 0, None))(
trained, flow_codes, dense_times
)
# user
# the radius error of the flow draws
flow_rmse: float = radius_rmse(flow_paths)
# user
# the angular speed of each, (sample)
flow_speeds: PerSample = angular_speeds(flow_paths)
print(
f"flow draws: radius RMSE {flow_rmse:.2f}, angular speed quartiles {np.quantile(flow_speeds, [0.25, 0.5, 0.75])} (spirals: 1.5)"
)flow draws: radius RMSE 0.37, angular speed quartiles [1.082 1.433 1.513] (spirals: 1.5)
fig, axes = plt.subplots(1, 2, figsize=(10, 5), sharex=True, sharey=True)
for ax, paths, title in [
(axes[0], prior_paths, "codes drawn from N(0, I)"),
(axes[1], flow_paths, "codes drawn from the RBIG flow"),
]:
for path in paths[:12]:
ax.plot(*np.asarray(path).T, lw=1.2)
ax.set(title=title, xlabel="x₁", ylabel="x₂")
ax.set_aspect("equal")
style_ax(ax)
fig.tight_layout()
plt.show()
Figure 3:Twelve paths decoded from draws of the prior N(0, I) (left) and of an RBIG flow fitted to the training codes (right). The prior’s draws barely turn and do not grow like the training spirals; the flow’s draws grow outwards and turn like them, more roughly.
The flow’s draws decode to paths that grow outwards and turn at close to the right speed, a median of 1.43 radians per unit time, with less than half the radius error of the prior’s draws (0.37 against 0.89). They are rougher than the training spirals: 250 codes in four dimensions give only a coarse estimate of . The flow’s inverse is also a Gaussianization of the codes, and it can be checked like any other. We send the training codes and the 50 held-out codes through it and read the excess kurtosis.
# today (gauss_flows)
# the Gaussianized training codes, (train, code)
gaussianized_train: TrainCode = jax.vmap(code_flow.bijection.inverse)(train_means)
# today (gauss_flows)
# the Gaussianized held-out codes, (held_out, code)
gaussianized_held: Float[ArrayLike, "held_out code"] = jax.vmap(
code_flow.bijection.inverse
)(held_means)
print(
f"excess kurtosis, training codes: {stats.kurtosis(np.asarray(gaussianized_train), axis=0)}"
)
print(
f"excess kurtosis, held-out codes: {stats.kurtosis(np.asarray(gaussianized_held), axis=0)}"
)excess kurtosis, training codes: [0.033 0.21 0.03 0.111]
excess kurtosis, held-out codes: [ 0.73 0.352 3.735 -0.105]
The training codes come out with excess kurtosis within one standard error () of zero in every coordinate. The 50 held-out codes reach 3.74 in one coordinate: a flow fitted to 250 points generalises only as far as 250 points allow. Fitting a flow to the codes after training is the simplest way to close the gap between the codes and the prior; it leaves the model’s bound untouched, so the prior the model was trained with is still the wrong one.
Recap¶
| Piece | Equation | In code |
|---|---|---|
| the generative model: a code, a neural ODE, a decoder | (1) | DiffeqMLP for , decode |
| the encoder, an ODE driven by the observed path | DiffeqMLP with control_dim=2, pack_time_control(t, x̂(t)), functax.interp.Linear | |
| the loss, a lower bound rather than a likelihood | (2) | NegativeELBO, trained by pipekit-train |
| the KL term in closed form | (3) | prior_kl, through gaussian_kl_divergence |
| the aggregate posterior and the split of the KL term | (4), (5) | |
| the gap between the codes and the prior | (6) | train_kls.mean() - log(250) |
| a Gaussianizing flow on the codes | fit_rbig(train_means) |
Next. Part 6 ends here. The continuous flows of notebooks 00 to 02 keep the dimension and the exact likelihood; the latent ODE trades both for a code, and pays for it with a prior its codes do not follow. The stochastic encoder and its bound return in Part 8 as one kind of SurVAE layer, a code with a circle in it is the subject of Part 10, and Part 11 comes back to latent ODEs for irregular series.
- Rubanova, Y., Chen, R. T. Q., & Duvenaud, D. (2019). Latent Ordinary Differential Equations for Irregularly-Sampled Time Series. Advances in Neural Information Processing Systems (NeurIPS).
- Kingma, D. P., & Welling, M. (2014). Auto-Encoding Variational Bayes. International Conference on Learning Representations (ICLR).