Package: torchcde
torchcdeDifferentiable GPU-capable solvers for CDEsThis library provides differentiable GPU-capable solvers for controlled differential equations (CDEs). Backpropagation through the solver or via the adjoint method is supported; the latter allows for improved memory efficiency.In particular this allows for buildingNeural Controlled Differential Equationmodels, which are state-of-the-art models for (arbitrarily irregular!) time series. Neural CDEs can be thought of as a "continuous time RNN".InstallationpipinstalltorchcdeRequires PyTorch >=1.7.Exampleimporttorchimporttorchcde# Create some databatch,length,input_channels=1,10,2hidden_channels=3t=torch.linspace(0,1,length)t_=t.unsqueeze(0).unsqueeze(-1).expand(batch,length,1)x_=torch.rand(batch,length,input_channels-1)x=torch.cat([t_,x_],dim=2)# include time as a channel# Interpolate itcoeffs=torchcde.hermite_cubic_coefficients_with_backward_differences(x)X=torchcde.CubicSpline(coeffs)# Create the Neural CDE systemclassF(torch.nn.Module):def__init__(self):super(F,self).__init__()self.linear=torch.nn.Linear(hidden_channels,hidden_channels*input_channels)defforward(self,t,z):returnself.linear(z).view(batch,hidden_channels,input_channels)func=F()z0=torch.rand(batch,hidden_channels)# Integrate ittorchcde.cdeint(X=X,func=func,z0=z0,t=X.interval)Seetime_series_classification.py, which demonstrates how to use the library to train a Neural CDE model to predict the chirality of a spiral.Also seeirregular_data.py, for demonstrations on how to handle variable-length inputs, irregular sampling, or missing data, all of which can be handled easily, without changing the model.CitationIf you found use this library useful, please consider citing@article{kidger2020neuralcde,title={{N}eural {C}ontrolled {D}ifferential {E}quations for {I}rregular {T}ime {S}eries},author={Kidger, Patrick and Morrill, James and Foster, James and Lyons, Terry},journal={Advances in Neural Information Processing Systems},year={2020}}DocumentationThe library consists of two main components: (1) integrators for solving controlled differential equations, and (2) ways of constructing controls from data.IntegratorsThe library provides thecdeintfunction, which solves the system of controlled differential equations:dz(t) = f(t, z(t))dX(t)     z(t_0) = z0The goal is to find the responsezdriven by the controlX. This can be re-written as the following differential equation:dz/dt(t) = f(t, z)dX/dt(t)     z(t_0) = z0where the right hand side describes a matrix-vector product betweenf(t, z)anddX/dt(t).This is solved bycdeint(X,func,z0,t,adjoint,backend,**kwargs)where letting...denote an arbitrary number of batch dimensions:Xis atorch.nn.Modulewith methodderivative, such thatX.derivative(t)is a Tensor of shape(..., input_channels),funcis atorch.nn.Module, such thatfunc(t, z)returns a Tensor of shape(..., hidden_channels, input_channels),z0is a Tensor of shape(..., hidden_channels),tis a one-dimensional Tensor of times to outputzat.adjointis a boolean (defaulting toTrue).backendis a string (defaulting to"torchdiffeq").Adjoint backpropagation (which is slower but more memory efficient) can be toggled withadjoint=True/False.Thebackendshould be either"torchdiffeq"or"torchsde", corresponding to which underlying library to use for the solvers. If using torchsde then the stochastic term is zero -- so the CDE is still reduced to an ODE. This is useful if one library supports a feature that the other doesn't. (For example torchsde supports a reversible solver, thereversible Heun method; at time of writing torchdiffeq does not support any reversible solvers.)Any additional**kwargsare passed on totorchdiffeq.odeint[_adjoint]ortorchsde.sdeint[_adjoint], for example to specify the solver.Constructing controlsA very common scenario is to construct the continuous controlXfrom discrete data (which may be irregularly sampled with missing values). To support this, we provide three main interpolation schemes:Hermite cubic splines with backwards differencesLinear interpolationRectilinear interpolationNote that if for some reason you already have a continuous controlXthen you won't need an interpolation scheme at all!Hermite cubic splines are usually the best choice, if possible. Linear and rectilinear interpolations are particularly useful in causal settings -- when at inference time the data is arriving over time. We go into further details in theFurther Documentationbelow.Just demonstrating Hermite cubic splines for now:coeffs=hermite_cubic_coefficients_with_backward_differences(x)# coeffs is a torch.Tensor you can save, load,# pass through Datasets and DataLoaders etc.X=CubicSpline(coeffs)where:xis a Tensor of shape(..., length, input_channels), where...is some number of batch dimensions. Missing data should be represented as aNaN.The interface provided byCubicSplineis:.interval, which gives the time interval the spline is defined over. (Often used as thetargument incdeint.) This is determined implicitly from the length of the data, and so doesnotin general correspond to the time your data was actually observed at. (See theFurther Documentationnote on reparameterisation invariance.).grid_pointsis all of the knots in the spline, so that for exampleX.evaluate(X.grid_points)will recover the original data..evaluate(t), wheretis an any-dimensional Tensor, to evaluate the spline at any (collection of) time(s)..derivative(t), wheretis an any-dimensional Tensor, to evaluate the derivative of the spline at any (collection of) time(s).Usuallyhermite_cubic_coefficients_with_backward_differencesshould be computed as a preprocessing step, whilstCubicSplineshould be called inside the forward pass of your model. Seetime_series_classification.pyfor a worked example.Then call:cdeint(X=X,func=...z0=...,t=X.interval)Further documentationThe earlier documentation section should give everything you need to get up and running.Here we discuss a few more advanced bits of functionality:The reparameterisation invariance property of CDEs.Other interpolation methods, and the differences between them.The use of fixed solvers. (They just work.)Stacking CDEs (i.e. controlling one by the output of another).Computing logsignatures for the log-ODE method.Reparameterisation invarianceThis is a classical fact about CDEs.Letbe differentiable and increasing, withand. Let, let, let, and let. Then substitutinginto a CDE (and just using the standard change of variables formula):We see thatalsosatisfies the neural CDE equation, just withas input instead of. In other words, usingchanges the speed at which we traverse the input, and correspondingly changes the speed at which we traverse the output-- and that's it! In particular the CDE itself doesn't need any adjusting.This ends up being a really useful fact for writing neater software. We can handle things like messy data (e.g. variable length time series) just during data preprocessing, without it complicating the model code. Intime_series_classification.py, the region we integrate over is given byX.intervalas a standardised region to integrate over. In the exampleirregular_data.py, we use this to handle variable-length data.Different interpolation methodsFor a full breakdown into the interpolation schemes, seeNeural Controlled Differential Equations for Online Prediction Taskswhere each interpolation scheme is scrutinised, and best practices are presented.In brief:Will your data: (a) be arriving in an online fashion at inference time; and (b) be multivariate; and (c) potentially have missing values?Yes: rectilinear interpolation.No: Are you using an adaptive step size solver (e.g. the defaultdopri5)?Yes: Hermite cubic splines with backwards differences.No: linear interpolation.Not sure / both: Hermite cubic splines with backwards differences.In more detail:Linear interpolation: these are "kind-of" causal.During inference we can simply wait at each time point for the next data point to arrive, and then interpolate towards the next data point when it arrives, and solve the CDE over that interval.If there is missing data, however, then this isn't possible. (As some of the channels might not have observations you can interpolate to.) In this case use rectilinear interpolation, below.Example:coeffs=linear_interpolation_coeffs(x)X=LinearInterpolation(coeffs)cdeint(X=X,...)Linear interpolation has kinks. If using adaptive step size solvers then it should be told about the kinks. (Rather than expensively finding them for itself -- slowing down to resolve the kink, and then speeding up again afterwards.) This is done with thejump_toption when using thetorchdiffeqbackend:cdeint(...,backend='torchdiffeq',method='dopri5',options=dict(jump_t=X.grid_points))Although adaptive step size solvers will probably find it easier to resolve Hermite cubic splines with backward differences, below.Hermite cubic splines with backwards differences: these are "kind-of" causal in the same way as linear interpolation, but dont have kinks, which makes them faster with adaptive step size solvers. (But is simply an unnecessary overhead when working with fixed step size solvers, which is why we recommend linear interpolation is you know you're only going to be using fixed step size solvers.)Example:coeffs=hermite_cubic_coefficients_with_backward_differences(x)X=CubicSpline(coeffs)cdeint(X=X,...)Rectilinear interpolation: This is appropriate if there is multivariate missing data, and you need causality.What is done is to linearly interpolate forward in time (keeping the observations constant), and then linearly interpolate the values (keeping the time constant). This is possible because time is a channel (and doesn't need to line up with the "time" used in the differential equation solver, as per the reparameterisation invariance of the previous section).This can be a bit unintuitive at first. We suggest firing up matplotlib and plotting things to get a feel for what's going on. As a fun sidenote, using rectilinear interpolation makes neural CDEs generaliseODE-RNNs.Example:# standard setup for a neural CDE: include time as a channelt=torch.linspace(0,1,10)x=torch.rand(2,10,3)t_=t.unsqueeze(0).unsqueeze(-1).expand(2,10,1)x=torch.cat([t_,x],dim=-1)delt,t_# won't need these again!# The `rectilinear` argument is the channel index corresponding to timecoeffs=linear_interpolation_coeffs(x,rectilinear=0)X=LinearInterpolation(coeffs)cdeint(X=X,...)As before, if using an adaptive step size solver, it should be informed about the kinks.cdeint(...,backend='torchdiffeq',method='dopri5',options=dict(jump_t=X.grid_points))Fixed solversSolving CDEs (regardless of the choice of interpolation scheme in a Neural CDE) with fixed solvers likeeuler,midpoint,rk4etc. is pretty much exactly the same as solving an ODE with a fixed solver. Just make sure to set thestep_sizeoption to something sensible; for example the smallest gap between times:X=LinearInterpolation(coeffs)step_size=(X.grid_points[1:]-X.grid_points[:-1]).min()cdeint(X=X,t=X.interval,func=...,method='rk4',options=dict(step_size=step_size))Stacking CDEsYou may wish to use the output of one CDE to control another. That is, to solve the coupled CDEs:du(t) = g(t, u(t))dz(t)     u(t_0) = u0
dz(t) = f(t, z(t))dX(t)     z(t_0) = z0There are two ways to do this. The first way is to put everything inside a singlecdeintcall, by solving the systemv = [u, z]
v0 = [u0, z0]
h(t, v) = [g(t, u)f(t, z), f(t, z)]

dv(t) = h(t, v(t))dX(t)      v(t_0) = v0and usingcdeintas normal. This is usually the best way to do it! It's simpler and usually faster. (But forces you to use the same solver for the whole system, for example.)The second way is to havecdeintoutputz(t)at multiple timest, interpolate the discrete output into a continuous path, and then callcdeintagain. This is probably less memory efficient, but allows for different choices of solver for each call tocdeint.For example, this could be used to create multi-layer Neural CDEs, just like multi-layer RNNs. Although as of writing this, no-one seems to have tried this yet!The log-ODE methodThis is a way of reducing the length of data by using extra channels. (For example, this may help train Neural CDE models faster, as the extra channels can be parallelised, but extra length cannot.)This is done by splitting the controlXup into windows, and computing thelogsignatureof the control over each window. The logsignature is a transform known to extract the information that is most important to describing howXcontrols a CDE.This is supported by thelogsig_windowsfunction, which takes in data, and produces a transformed path, that now exists in logsignature space:batch,length,channels=1,100,2x=torch.rand(batch,length,channels)depth,window=3,10.0x=torchcde.logsig_windows(x,depth,window)# use x as you would normally: interpolate, etc.See the paperNeural Rough Differential Equations for Long Time Seriesfor more information. Seelogsignature_example.pyfor a worked example.Note that this requires installing theSignatorypackage.