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 for irregularly-sampled spirals

This notebook reproduces the toy spiral experiment from Rubanova, Chen & Duvenaud (NeurIPS 2019), “Latent ODEs for Irregularly-Sampled Time Series” — but with the ODE-RNN encoder replaced by a pure neural ODE, in the spirit of Kidger et al. (2020), “Neural CDEs”.

The model is a VAE on trajectories. For a single trajectory {(ti,xi)}i=1N\{(t_i, x_i)\}_{i=1}^N on [t0,tN][t_0, t_N]:

Encoder (neural ODE). Linearly interpolate the observations into a continuous path X^(t)\hat X(t). Integrate

dhdt=fenc(h(t), X^(t), t),h(t0)=0,\frac{dh}{dt} = f_\text{enc}\big(h(t),\, \hat X(t),\, t\big),\qquad h(t_0) = 0,

from t0t_0 to tNt_N with diffrax, then map h(tN)h(t_N) to (μ,log⁡σ2)(\mu, \log\sigma^2) of q(z0∣x1:N)q(z_0\mid x_{1:N}). No GRU, no RNN cells — the observations enter the encoder only through the interpolated path.

Latent dynamics (neural ODE). dz/dt=flat(z,t)dz/dt = f_\text{lat}(z, t), integrated forward from t0t_0 saving at every requested time.

Decoder. A small MLP z(ti)→x^iz(t_i) \to \hat x_i with fixed Gaussian observation noise σobs\sigma_\text{obs}.

Loss. Standard ELBO,

L=Eq(z0) ⁣[∑ilog⁡p(xi∣z(ti))]−KL(q(z0) ∥ N(0,I)).\mathcal{L} = \mathbb{E}_{q(z_0)}\!\Big[\sum_i \log p(x_i\mid z(t_i))\Big] - \mathrm{KL}\big(q(z_0)\,\|\,\mathcal{N}(0,I)\big).

We reuse gauss_flows.DiffeqMLP for both vector fields and the package’s existing pack_time_control plumbing for the encoder’s data-path conditioning.

1. Synthetic spiral dataset

We follow Rubanova et al. §4.1: 2-D spirals with a random rotation, random direction (clockwise vs counter-clockwise), and a small additive Gaussian noise. Each trajectory is sampled densely on a common grid for reference, then irregularly subsampled to mimic real-world sensors.

trajectories          : 300  (250 train / 50 eval)
dense grid points     : 100  on t in [0, 5.0]
observed per traj.    : 30  (irregular, sorted)
x_obs_train shape     : (250, 30, 2)
x_obs_eval shape      : (50, 30, 2)
findfont: Failed to find font weight semibold for DejaVu Sans, now using 700.
<Figure size 1320x550 with 2 Axes>

2. Model

The encoder, latent dynamics, and decoder are all small eqx.Modules. The two vector fields are gauss_flows’ DiffeqMLP. The encoder packages the interpolated observation X^(t)\hat X(t) as the control dimension of the time-control condition, so the same DiffeqMLP API used by FFJORD applies here unchanged.

Why forward, not reversed? The original Latent ODE encoder runs an ODE-RNN backward in time, a habit inherited from RNN seq2seq models that process tokens right-to-left. For a smooth ODE the path integral is symmetric in direction; running the encoder forward is the same model up to a reparametrization of fencf_\text{enc}, and one less thing to keep track of.

latent dim            : 4
encoder hidden        : 25
decoder hidden        : 20
obs noise sigma       : 0.1
trainable parameters  : 6679

3. Training

Per gradient step we

  1. encode each trajectory with one forward neural ODE solve;

  2. sample z0z_0 via the reparametrisation trick;

  3. decode by integrating the latent ODE forward, saving at every observed time;

  4. compute Gaussian log-likelihood + closed-form KL.

pipekit-train’s TrainingLoop runs the steps: the negative ELBO is its task, Adam its optimiser, and the gradient is clipped to a global norm of 5 (clip_norm).

Two ODE solves per trajectory per step makes this noticeably more expensive than the FFJORD-2D notebook. We keep the run short (250 epochs, batch 50) so it fits in a notebook; longer training tightens the reconstructions.

epoch    1  loss  3917.315  recon -3915.543  KL   1.773
epoch   25  loss  2462.764  recon -2431.598  KL  31.167
epoch   50  loss  1993.960  recon -1958.414  KL  35.546
epoch   75  loss  1427.120  recon -1397.331  KL  29.789
epoch  100  loss   763.492  recon  -732.846  KL  30.646
epoch  125  loss   441.578  recon  -414.423  KL  27.155
epoch  150  loss   355.303  recon  -327.906  KL  27.397
epoch  175  loss   376.346  recon  -345.447  KL  30.899
epoch  200  loss   233.756  recon  -204.976  KL  28.781
epoch  225  loss   308.273  recon  -280.824  KL  27.448
epoch  250  loss    68.290  recon   -44.572  KL  23.717
<Figure size 770x495 with 1 Axes>

4. Reconstruction on irregular observations

For each held-out trajectory we encode the irregular observations, then decode on the dense time grid. The smooth ODE-driven latent gives a clean spiral that passes through the noisy observations.

<Figure size 1650x1045 with 6 Axes>

5. Extrapolation

Latent ODEs extrapolate naturally: encode using only observations on [0,T/2][0, T/2], then integrate the latent ODE all the way to TT. The model has never seen the target times during this trajectory’s encoding, but the latent dynamics are time-translation-equivariant only insofar as the training data taught them — so this is a real generalisation test.

<Figure size 1650x1045 with 6 Axes>

6. Notes

  • Pure-ODE encoder cost. Two adaptive ODE solves per trajectory per step (encoder forward + decoder forward). On CPU each epoch in this notebook is a few seconds; with the original ODE-RNN encoder you avoid the encoder ODE entirely and replace it with cheap GRU updates. Pure ODE buys uniformity, not speed.

  • Path interpolation choice. We use linear interpolation for X^(t)\hat X(t). Kidger et al. argue for natural cubic splines because they give a smooth derivative for the controlled equation; for a 2-D toy with 30 obs the difference is small. To switch, replace Linear() with CubicSpline() (from functax.interp) in _interp_path (cost: a one-time spline fit per trajectory).

  • Forward vs. reversed encoder. The original paper runs the encoder backwards (t_N → t_0), inherited from RNN seq2seq habits. For an ODE the integral path is the same up to a sign of fencf_\text{enc}; we run forward for clarity.

  • Extrapolation regime. The latent dynamics are autonomous (unconditional on observations beyond z0z_0), so extrapolation is only as good as the prior over z0z_0 allows the dynamics to capture the spiral family. With more training and a richer dynamics MLP the extrapolated arms tighten visibly.