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.

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

Open In Colab

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 z0\vect{z}_0: 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?

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 r(t)=0.4t+0.5r(t) = 0.4 t + 0.5 and angle α(t)=1.5st+α0\alpha(t) = 1.5 s t + \alpha_0, with a start angle α0\alpha_0 drawn uniformly from [0,2π)[0, 2\pi) and a direction s=±1s = \pm 1 drawn with equal odds, on t∈[0,5]t \in [0, 5]. 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.

The first 250 spirals train the model and the last 50 are held out.

2. The model and its lower bound

Write one spiral’s observations as X={(ti,xi)}i=1No\mathcal{X} = \{(t_i, \vect{x}_i)\}_{i=1}^{N_o}. The generative model draws a code z0∈RDz\vect{z}_0 \in \mathbb{R}^{D_z} from the prior, integrates a neural ODE with vector field vθ\vect{v}_\theta from it, and decodes each point of the path with a network decθ\mathrm{dec}_\theta, adding Gaussian noise of a fixed scale σobs\sigma_{\mathrm{obs}}:

z0∼N(0,I),dzdt=vθ(t,z),xi∼N(decθ(z(ti)),σobs2I)\begin{aligned} \vect{z}_0 &\sim \mathcal{N}(\vect{0}, \mat{I}), \\ \frac{d\vect{z}}{dt} &= \vect{v}_\theta(t, \vect{z}), \\ \vect{x}_i &\sim \mathcal{N}(\mathrm{dec}_\theta(\vect{z}(t_i)), \sigma_{\mathrm{obs}}^2 \mat{I}) \end{aligned}

The encoder runs a second neural ODE over the observations, as the example does: the observations are joined into a piecewise-linear path x^(t)\hat{\vect{x}}(t), a hidden state h∈RDh\vect{h} \in \mathbb{R}^{D_h} follows dh/dt=vϕ(t,h,x^(t))d\vect{h}/dt = \vect{v}_\phi(t, \vect{h}, \hat{\vect{x}}(t)) from h(t1)=0\vect{h}(t_1) = \vect{0} to tNot_{N_o}, and a linear head turns h(tNo)\vect{h}(t_{N_o}) into the mean μϕ\gvect{\mu}_\phi and the log-variance log⁡σϕ2\log \gvect{\sigma}_\phi^2 of a diagonal Gaussian qϕ(z0∣X)q_\phi(\vect{z}_0 \mid \mathcal{X}). Both vector fields are gauss_flows’ DiffeqMLP; the encoder’s takes x^(t)\hat{\vect{x}}(t) 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,

log⁡pθ(X)≥Eqϕ(z0∣X)[∑i=1Nolog⁡N(xi;decθ(z(ti)),σobs2I)]−KL[qϕ(z0∣X)∥N(0,I)]\log p_\theta(\mathcal{X}) \ge \mathbb{E}_{q_\phi(\vect{z}_0 \mid \mathcal{X})} \left[ \sum_{i=1}^{N_o} \log \mathcal{N}(\vect{x}_i; \mathrm{dec}_\theta(\vect{z}(t_i)), \sigma_{\mathrm{obs}}^2 \mat{I}) \right] - \mathrm{KL}[q_\phi(\vect{z}_0 \mid \mathcal{X}) \Vert \mathcal{N}(\vect{0}, \mat{I})]

whose KL term between two Gaussians has a closed form:

KL[qϕ(z0∣X)∥N(0,I)]=12∑k=1Dz(σϕ,k2+μϕ,k2−1−log⁡σϕ,k2)\mathrm{KL}[q_\phi(\vect{z}_0 \mid \mathcal{X}) \Vert \mathcal{N}(\vect{0}, \mat{I})] = \frac{1}{2} \sum_{k=1}^{D_z} (\sigma_{\phi,k}^2 + \mu_{\phi,k}^2 - 1 - \log \sigma_{\phi,k}^2)

The loss is the negative of (2) averaged over a batch, with one reparametrised draw z0=μϕ+σϕ⊙ε\vect{z}_0 = \gvect{\mu}_\phi + \gvect{\sigma}_\phi \odot \gvect{\varepsilon} per spiral. It replaces negative_log_likelihood, which needs an exact log-density. The sizes are the example’s: Dz=4D_z = 4, Dh=25D_h = 25, two hidden layers of 40 in each vector field, and σobs=0.1\sigma_{\mathrm{obs}} = 0.1.

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.

The encoder’s vector field reads the observed path x^(t)\hat{\vect{x}}(t) at the current time and packs it as the control of its condition.

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.

The decoder starts every code at t=0t = 0, so that z0\vect{z}_0 means the same thing for every spiral whatever its first observed time.

pipekit-train’s task averages the negative bound over a batch and logs its two terms.

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 3×10−33 \times 10^{-3} and the gradient clipped to a global norm of 5. That takes a couple of minutes on a CPU.

The spirals’ observed times are the dataset’s inputs and their observations its targets.

training time: 92 s
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 μϕ\gvect{\mu}_\phi on the 100 dense times, and compare the result with the spiral without noise.

held-out RMSE to the clean spirals: 0.172, for radii from 0.5 to 2.5
<Figure size 1200x420 with 3 Axes>

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 qϕ(z0∣Xn)q_\phi(\vect{z}_0 \mid \mathcal{X}_n) towards N(0,I)\mathcal{N}(\vect{0}, \mat{I}), one spiral at a time. The distribution a sampler would need to match is a different one, the aggregate posterior of the NtN_t training spirals,

qˉ(z0)=1Nt∑n=1Ntqϕ(z0∣Xn)\bar{q}(\vect{z}_0) = \frac{1}{N_t} \sum_{n=1}^{N_t} q_\phi(\vect{z}_0 \mid \mathcal{X}_n)

Adding and subtracting log⁡qˉ\log \bar{q} inside the average of the KL terms splits it in two:

1Nt∑n=1NtKL[qϕ(z0∣Xn)∥N(0,I)]=Iq[n;z0]+KL[qˉ∥N(0,I)]\frac{1}{N_t} \sum_{n=1}^{N_t} \mathrm{KL}[q_\phi(\vect{z}_0 \mid \mathcal{X}_n) \Vert \mathcal{N}(\vect{0}, \mat{I})] = I_q[n; \vect{z}_0] + \mathrm{KL}[\bar{q} \Vert \mathcal{N}(\vect{0}, \mat{I})]

where Iq[n;z0]I_q[n; \vect{z}_0] is the mutual information between the index nn of a training spiral, drawn uniformly, and its code. It is at most the entropy of the index, log⁡Nt\log N_t, so whatever the mean KL term exceeds log⁡Nt\log N_t by is a lower bound on the distance of the aggregate posterior from the prior:

KL[qˉ∥N(0,I)]≥1Nt∑n=1NtKL[qϕ(z0∣Xn)∥N(0,I)]−log⁡Nt\mathrm{KL}[\bar{q} \Vert \mathcal{N}(\vect{0}, \mat{I})] \ge \frac{1}{N_t} \sum_{n=1}^{N_t} \mathrm{KL}[q_\phi(\vect{z}_0 \mid \mathcal{X}_n) \Vert \mathcal{N}(\vect{0}, \mat{I})] - \log N_t

We compute the KL term (3) of every training spiral at its posterior, with no sampling.

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 μϕ\gvect{\mu}_\phi. We read their moments, as in Part 0.

     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
<Figure size 550x500 with 1 Axes>

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 0.4t+0.50.4 t + 0.5 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 N(0,I)\mathcal{N}(\vect{0}, \mat{I}).

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 qˉ\bar{q}), 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.

flow draws: radius RMSE 0.37, angular speed quartiles [1.082 1.433 1.513] (spirals: 1.5)
<Figure size 1000x500 with 2 Axes>

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 qˉ\bar{q}. 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.

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 (24/250≈0.31\sqrt{24/250} \approx 0.31) 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

PieceEquationIn code
the generative model: a code, a neural ODE, a decoder(1)DiffeqMLP for vθ\vect{v}_\theta, decode
the encoder, an ODE driven by the observed pathDiffeqMLP 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 codesfit_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.

References
  1. 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).
  2. Kingma, D. P., & Welling, M. (2014). Auto-Encoding Variational Bayes. International Conference on Learning Representations (ICLR).