Neural ODEs: the solver is part of the calculation
神经常微分方程
Train a nonlinear continuous-depth model, compare numerical sensitivities with an exact solution and test failed reverse reconstruction.
neural-odesStart with the problem
A residual layer adds a learned increment to its input. Imagine specifying an instantaneous rate of change instead, then asking a differential-equation solver to carry the state to a final time. This is the central construction in Neural Ordinary Differential Equations.
Replacing layers with a differential equation does not remove numerical choices. Step size, solver order and the way gradients are computed affect the actual program. We use a one-unit nonlinear vector field with an exact solution, so errors in state and parameter sensitivity can be measured rather than hidden behind a training curve.
Definitions and derivation
A neural ODE defines a vector field fθ and an initial condition. Forward Euler approximates the continuous dynamics by residual steps:
This interpretation does not imply that every arbitrary residual network uses the same vector field at every layer. In a neural ODE, time may itself be an input. A sufficiently regular field is needed for a well-defined solution; here tanh is smooth and globally Lipschitz for fixed bounded θ.
Choose a scalar field fθ(h)=θ tanh h. Differentiate sinh h along its trajectory: cosh(h)·θ tanh(h)=θ sinh(h), a linear equation. Solving that equation and transforming back gives:
For h₀=0.4, θ=2 and t=1, the exact state is 1.829479230 and sensitivity is 0.949775103. This is a genuine nonlinear field, though only one scalar parameter is learned.
Instead of differentiating an unavailable closed-form solution in training, integrate the forward sensitivity s=∂h/∂θ jointly with h:
The code applies the same fourth-order Runge–Kutta stages to both components. For a fixed step sequence, this sensitivity update matches differentiating those RK4 operations with respect to θ. It still approximates the exact continuous sensitivity. Adaptive step-selection branches introduce additional issues not covered by this fixed-step example.
The original paper discusses a continuous adjoint: propagate a loss sensitivity backward using the transposed vector-field Jacobian, and integrate parameter contributions. With many parameters this can be cheaper than forward sensitivities. However, solving the state equation backward numerically is not the algebraic inverse of the forward solver. ANODE analyzes reconstruction instability and differences between differentiating a discretization and discretizing continuous gradients. Checkpointing and recomputation can trade memory for a gradient tied to the actual forward computation. Our program uses forward sensitivities, not an implementation of either adjoint framework.
Run the calculation
Complete Python 3.12 / NumPy 1.26.4 program:
import numpy as np
def solve(theta,steps,initial=.4,method='rk4'):
if type(steps) is not int or not 1 <= steps <= 256 or not np.isfinite([theta,initial]).all() or abs(theta)>5 or abs(initial)>5 or method not in ('rk4','euler'):
raise ValueError('Use bounded finite parameters and 1..256 fixed steps.')
value=np.array([initial,0.]);dt=1/steps
def field(z):
h,s=z;t=np.tanh(h)
return np.array([theta*t,t+theta*(1-t*t)*s])
for _ in range(steps):
k1=field(value)
if method=='euler':value+=dt*k1
else:
k2=field(value+dt*k1/2);k3=field(value+dt*k2/2);k4=field(value+dt*k3)
value+=dt*(k1+2*k2+2*k3+k4)/6
return value
def exact(theta,initial=.4):
v=np.exp(theta)*np.sinh(initial)
return np.array([np.arcsinh(v),v/np.sqrt(1+v*v)])
def reverse_euler(theta,steps,terminal):
h=float(terminal)
for _ in range(steps):h-=theta*np.tanh(h)/steps
return h
if __name__ == '__main__':
ref=exact(2.);print('exact state and sensitivity',ref.round(9).tolist())
for steps in (4,8,16):
value=solve(2.,steps);print('RK4 steps',steps,'state/sensitivity',value.round(9).tolist(),'max error',float(np.max(np.abs(value-ref))))
terminal=solve(2.,4,method='euler')[0];print('Euler reverse reconstruction',round(reverse_euler(2.,4,terminal),9),'true initial',.4)
theta=0.;loss0=.5*(solve(theta,16)[0]-2)**2
for _ in range(150):
state,s=solve(theta,16);theta-=.2*(state-2)*s
print('trained theta',round(theta,9),'loss',round(loss0,9),round(.5*(solve(theta,16)[0]-2)**2,12),'analytic target theta',round(float(np.log(np.sinh(2)/np.sinh(.4))),9))
Actual output:
exact state and sensitivity [1.82947923, 0.949775103]
RK4 steps 4 state/sensitivity [1.829241046, 0.949295441] max error 0.0004796626919549851
RK4 steps 8 state/sensitivity [1.829462253, 0.9497398] max error 3.53034610782732e-05
RK4 steps 16 state/sensitivity [1.829478099, 0.949772716] max error 2.3876800648858776e-06
Euler reverse reconstruction 0.227375176 true initial 0.4
trained theta 2.17813391 loss 1.28 0.0 analytic target theta 2.178132232
Increasing RK4 steps from 4 to 8 to 16 reduces the maximum state/sensitivity error from about 4.80×10⁻⁴ to 3.53×10⁻⁵ to 2.39×10⁻⁶. These are measured errors for this smooth problem, not a universal error bound. Four forward Euler steps followed by four backward steps reconstruct 0.227375176 instead of 0.4.
Training with sixteen-step RK4 gives θ≈2.178133910 for target state two. The exact continuous target parameter is about 2.178132232. The tiny mismatch is expected: the optimizer fits a numerical model. Each RK4 step makes four field evaluations; fixed-state streaming uses constant working storage here. Forward sensitivity cost grows with parameter count, so this scalar example does not establish scalable constant-memory training.
When the method fails
Stiff dynamics may require many explicit steps or another solver. Solver tolerances affect cost and can change predictions near decision boundaries. A model trained with one solver should be checked under the intended inference settings.
Continuous time does not automatically incorporate newly arriving observations: an observation update or controlled input must be specified. Under uniqueness conditions, trajectories of the same fixed ODE cannot cross at the same time in state space, which can restrict a model’s transformation capacity. State augmentation changes that setting. None of these limitations is resolved merely by calling depth continuous.
Exercises with answers
- How is the exact solution derived?
Answer 1: Let v=sinh h. Then v̇=θv, solve v(t)=exp(θt)sinh h₀ and apply arsinh.
- Why does θ fitted with RK4 differ from the exact target parameter?
Answer 2: Finite steps define an approximate terminal state, and training optimizes that numerical map.
- Is Euler stepping backward in time the inverse of forward Euler here?
Answer 3: No. Evaluating the reversed field at later states does not undo each forward update algebraically.
- What must change when the field has many parameters?
Answer 4: Forward sensitivity tracks one state sensitivity per parameter; adjoint methods and checkpointing offer other cost tradeoffs.
Sources and next steps
Neural ODE physical pages 2–3 discuss continuous-adjoint differentiation and computational tradeoffs. ANODE physical pages 1 and 3 state reconstruction and gradient-consistency concerns. Our tanh exact solution, RK4 sensitivity and Euler counterexample are independently derived teaching cases. Continue with differential equations and activation checkpointing.
Make a prediction, then check
What does fixed-step numerical training optimize?
Learning objectives
- Compare solver sensitivities against an analytic nonlinear ODE.
- Distinguish reverse integration from inverse discrete computation.
Prerequisites & connections
Explore related knowledge →References
- Neural Ordinary Differential Equations — arXiv v5
Ricky T. Q. Chen; Yulia Rubanova; Jesse Bettencourt; David Duvenaud · 2018 - ANODE: Unconditionally Accurate Memory-Efficient Gradients for Neural ODEs — arXiv v1
Amir Gholami; Kurt Keutzer; George Biros · 2019
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-06 · Codex single-AI-author technical check: primary-source scope, explicit assumptions, original calculations, independent mathematical references and bilingual tests; not independent human or second-agent review.
- Single-AI-author technical check: bounded primary-source reading, explicit assumptions, original calculations, runnable examples and matching bilingual equations, code and exercises. Not an independent human or second-agent review.
- Four focused CPython 3.12.4 tests passed per chapter, including independent finite differences, literal calculations, recurrence and convolution comparisons, permutation symmetry, closed-form limits and expressive counterexamples. All eight programs use NumPy 1.26.4. CPU teaching calculations, not framework or GPU benchmarks.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
Source locations checked:
- Neural Ordinary Differential Equations — arXiv v5 · Physical pages 2–3, Section 2 Equations 3–5: ODE loss and continuous adjoint sensitivity discussion.
- ANODE: Unconditionally Accurate Memory-Efficient Gradients for Neural ODEs — arXiv v1 · Physical pages 1 and 3: numerical reverse reconstruction and optimize-then-discretize versus discrete-gradient concerns.
Related topics