Foundations to Frontier
Tests
J. Scientific Machine Learning › J3 Neural Differential Equations

Neural ODEs and the adjoint method

A neural ordinary differential equation (neural ODE) uses a neural network as the right-hand side of dz/dt = f_θ(z, t) and computes predictions by integrating it with an ODE solver. It models the dynamics rather than the trajectory, so it handles irregularly spaced observations naturally, can be integrated forward from new starting states, and links deep learning to the large toolbox of numerical analysis. Training needs gradients through the solver. They can come from backpropagating through every solver step, which stores every intermediate state, or from the adjoint method, which solves a second ODE backward in time with memory that does not grow with the number of steps. This page derives the adjoint equations and builds both gradients from scratch for a small network with RK4. They agreed to within 4 × 10⁻⁸ with 10 steps, and the gap fell 16-fold when the step was halved, as expected for a fourth-order method. You then learn a damped pendulum from 40 noisy observations at irregular times. The neural ODE predicted the next 10 time units with RMS error 0.2, against 2 for a network fitted to the trajectory as a function of time, which cannot extrapolate.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Learning the rule of motion instead of the path

If you film a swinging pendulum, you could teach a network to draw the path it followed. A different idea is to teach the network the rule of motion: given where the pendulum is and how fast it moves, what happens next. Then we follow the rule step by step, as a physics simulator would. A learned rule can predict beyond the film and from new starting points, which a learned path cannot. To train it we need to know how a small change in the rule changes the end of the path; the adjoint method finds this by running a second calculation backwards in time. The demo shows a learned rule predicting past its training window.

Neural differential equation lab
Angle θ(t) of a damped pendulum, 0 ≤ t ≤ 20. Black: truth; green dashed: the learned vector field integrated from the same start. Shaded: training window. RMS error inside 0.203, after it 0.941. A model of the dynamics can extrapolate as long as the states it visits were seen in training.
Why engineers care

Neural ODEs and their relatives are used to model irregularly sampled patient records in hospitals and to learn the dynamics of chemical reactions and spacecraft attitude from telemetry.

📝 Quick check (Level 0)
0/3 answered
  1. 1. A neural ODE learns…
  2. 2. Predictions from a neural ODE come from…
  3. 3. The adjoint method runs…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

By hand

  • Model: dz/dt = f_θ(z, t), z(t₀) = z₀; prediction z(t₁) = ODESolve(f_θ, z₀, t₀, t₁). A residual network z_(k+1) = z_k + f(z_k) is one Euler step of such a model (Chen et al., 2018).
  • Strengths: continuous time (any query time, irregular sampling), reuse of adaptive and stiff solvers, invertibility (continuous normalising flows), and a natural place for physical structure (J3-3, J3-4).
  • Gradients, two routes:
    • Discretise-then-optimise: backpropagate through the solver’s operations; exact for the discrete solution; memory grows with the number of steps (O(N·stages)).
    • Optimise-then-discretise (adjoint): solve the adjoint ODE backward; memory O(1) in the number of steps; the gradient is exact only up to the solver’s error, and re-solving z backward can be unstable for dissipative or chaotic systems.
  • Adjoint equations: with a(t) = ∂L/∂z(t), da/dt = −a ᵀ ∂f/∂z, dL/dθ = ∫ aᵀ ∂f/∂θ dt, with a(t₁) = ∂L/∂z(t₁) and jumps added at every observation time.
  • Practical variants: checkpointing (store some states, recompute others), interpolated or quadrature adjoints, and multiple shooting (fit short segments started from data) to avoid long unstable rollouts.
📝 Quick check (Level 1)
0/3 answered
  1. 1. A ResNet block is one step of which ODE solver?
  2. 2. The adjoint method's memory in the number of steps is…
  3. 3. The adjoint state a(t) equals…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

Gradients through an ODE solver

Exercise 1.

  • A vector field f(z) = W₂ tanh(W₁z + b₁) + b₂ and its vector–Jacobian products aᵀ∂f/∂z and aᵀ∂f/∂θ.
  • RK4 integration with one step size per batch row (for irregular times).
  • The continuous adjoint (z, a, g integrated backward with RK4) and backpropagation through the RK4 stages; both checked against finite differences and each other.

Practice.

  • Start with backprop through the solver (torchdiffeq’s odeint, diffrax) for small problems; switch to the adjoint or checkpointing when memory runs out.
  • Normalise states and time so the field is of order 1; scale time so a typical interval is a few units.
  • Use multiple shooting for long or chaotic trajectories: integrate short segments from observed states and penalise mismatches.
  • Watch the number of function evaluations with adaptive solvers; it grows as the learned field stiffens. Regularising the field’s Jacobian or kinetic energy keeps it smooth.
  • Choose the solver like a numerical analyst: implicit methods for stiff dynamics, symplectic ones for Hamiltonian systems (J3-4).
  • Tools: torchdiffeq (odeint, odeint_adjoint), diffrax (JAX), DifferentialEquations.jl with SciMLSensitivity.
import torch
from torchdiffeq import odeint_adjoint as odeint

class Field(torch.nn.Module):
    def __init__(self):
        super().__init__()
        self.net = torch.nn.Sequential(torch.nn.Linear(2, 32), torch.nn.Tanh(), torch.nn.Linear(32, 2))
    def forward(self, t, z):
        return self.net(z)

f = Field(); opt = torch.optim.Adam(f.parameters(), lr=1e-2)
for it in range(1000):
    zp = odeint(f, y[0], t, method="rk4", options=dict(step_size=0.05))   # t: observation times
    loss = ((zp - y) ** 2).mean()
    opt.zero_grad(); loss.backward(); opt.step()                         # gradients by the adjoint ODE
🐍 Exercise 1: adjoint and backprop gradients
Write a small vector field with its vector–Jacobian products, integrate it with RK4, and compute the gradient of a loss on the final state by the continuous adjoint and by backpropagation through the solver; compare them with finite differences and with each other as the step shrinks.
📝 Quick check (Level 2)
0/3 answered
  1. 1. torchdiffeq's memory-efficient solver is…
  2. 2. Multiple shooting integrates…
  3. 3. A field that stiffens during training shows up as…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

Deriving the adjoint. Let L depend on z(t₁). Add the constraint with a multiplier: L̃ = L − ∫ aᵀ(ż − f) dt. Integrating aᵀż by parts and asking that variations δz drop out gives ȧ = −(∂f/∂z)ᵀa with a(t₁) = ∂L/∂z(t₁); what remains is dL/dθ = ∫ from t₀ to t₁ of aᵀ ∂f/∂θ dt and dL/dz₀ = a(t₀). In practice z, a and the running integral g are integrated together backward from t₁, re-computing z(t) on the way.

Two gradients, one target. Backpropagation through RK4 differentiates the discrete map exactly. The adjoint discretises the continuous gradient instead, so it differs from the discrete gradient by the solver’s error. In Exercise 1 the difference was 4 × 10⁻⁸ with 10 steps and 3 × 10⁻⁹ with 20, a ratio of 16 = 2⁴, matching RK4’s fourth order. The adjoint stores only (z, a, g); backprop stored four states per step.

Why model dynamics. A function of time u(t) learned on [0, 10] has no information about t > 10; outside its data it returns whatever its activations do. A learned vector field is evaluated at states, and if the states visited later resemble those seen earlier, as for a decaying pendulum, the integrated model continues correctly. That is also its limit: in states never seen in training, a learned field is a guess.

Stability caveats. Integrating z backward reverses dissipation: for a damped system the backward problem amplifies errors. Checkpointing, storing z on the forward pass, or multiple shooting avoid this.

📝 Quick check (Level 3)
0/3 answered
  1. 1. The adjoint ODE is ȧ = …
  2. 2. Adjoint and backprop gradients for RK4 differ by…
  3. 3. Integrating a damped system backward…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

Can a neural ODE learned from irregular, noisy observations predict beyond its training window?

History.

  • The adjoint method dates to optimal control (L. Pontryagin et al., 1962) and was used for sensitivity analysis in meteorology and engineering long before deep learning.
  • R. T. Q. Chen, Y. Rubanova, J. Bettencourt and D. Duvenaud (2018), “Neural ordinary differential equations”, made ODE solvers a layer type with adjoint gradients and won a NeurIPS best-paper award.
  • Y. Rubanova, R. T. Q. Chen and D. Duvenaud (2019) introduced latent ODEs for irregularly sampled time series; P. Kidger (2021) unified neural differential equations and wrote diffrax.
  • C. Rackauckas et al. (2020) combined them with known physics in universal differential equations (J3-3).

Exercise 2. Damped pendulum θ″ = −sin θ − 0.1θ′ from (θ, ω) = (1.5, 0); 40 observations at random times in [0, 10] with noise 0.02. Neural ODE: width-16 tanh field, multiple shooting over the 39 segments between observations (4 RK4 steps each), Adam on adjoint gradients for 1500 iterations. Baseline: a tanh network of t fitted to the observations. RMS errors, rounded to one significant figure; the true signal’s RMS on [10, 20] is 0.48.

model RMS on [0, 10] RMS on [10, 20]
neural ODE 0.07 0.2
network of time 0.02 2

From a new start (−1, 0.5) the neural ODE’s RMS error over [0, 10] was 0.09.

  • The trajectory fit was better inside the window, useless outside. The time network interpolated the data well but extrapolated to errors four times larger than the signal itself.
  • The dynamics model extrapolated. Its error on [10, 20] was less than half the signal’s size, and it also predicted from a starting state it never saw.
  • Irregular sampling was no obstacle: each segment simply used its own step size.
  • Seeds 1 and 2: neural ODE 0.03 / 0.3 / 0.1 and 0.04 / 0.2 / 0.1 (fit / extrapolation / new start); time network 0.05 / 2 and 0.03 / 1.
🐍 Exercise 2 (research): can a neural ODE learned from irregular, noisy observations predict beyond its training window?
Learn the vector field of a damped pendulum from 40 noisy, irregularly timed observations with adjoint gradients, and compare its extrapolation with a network fitted to the trajectory.

Neural ODEs in science and engineering

  • Healthcare and sensor data: latent ODEs and ODE-RNNs handle irregular sampling in intensive-care records and in telemetry with gaps.
  • Physics and chemistry: learning reaction kinetics, pharmacokinetics and climate model closures inside differentiable solvers (J3-3).
  • Control and robotics: learned dynamics models for model-predictive control, trained on irregular robot or spacecraft logs.
  • Generative models: continuous normalising flows and flow matching use ODEs to transform noise into data (H2).

References

  1. R. T. Q. Chen, Y. Rubanova, J. Bettencourt and D. Duvenaud (2018). “Neural ordinary differential equations.” NeurIPS.
  2. Y. Rubanova, R. T. Q. Chen and D. Duvenaud (2019). “Latent ordinary differential equations for irregularly-sampled time series.” NeurIPS.
  3. P. Kidger (2021). “On neural differential equations.” PhD thesis, University of Oxford.
  4. L. S. Pontryagin, V. G. Boltyanskii, R. V. Gamkrelidze and E. F. Mishchenko (1962). The Mathematical Theory of Optimal Processes. Interscience.
  5. C. Rackauckas et al. (2020). “Universal differential equations for scientific machine learning.” arXiv:2001.04385.