Do Residual Neural Networks discretize Neural Ordinary Differential Equations?
Michael E. Sander, Pierre Ablin, Gabriel Peyré
Introduction
On the other hand, a Neural ODE (Chen et al., 2018) uses a neural network , that takes time into account, to parameterise a vector field (Kidger, 2022) in a differential equation, as follows,
Neural ODEs also provide a theoretical framework to study deep learning models from the continuous viewpoint, using the arsenal of ODE theory (Teh et al., 2019; Li et al., 2019; Teshima et al., 2020). Importantly, they can also be seen as the continuous analog of ResNets. Indeed, consider for an integer, the Euler scheme for solving Eq. (2) with time step starting from and iterating . Under mild assumptions on , this scheme is known to converge to the true solution of Eq. (2) as goes to . Also, if and , then the ResNet equation Eq. (1) corresponds to a Euler discretization with time step of Eq. (2). However, for a given ResNet with fixed depth and weights, the activations in Eq. (1) can be far from the solution of Eq. (2). This is illustrated in Figure 1 where we show that a deep ResNet can easily break the topology of the input space, which is impossible for a Neural ODE. In this paper, we study the link between ResNets and Neural ODEs. We make the following contributions:
In Section 3, we propose a framework to define a set of associated Neural ODEs for a given ResNet. We control the error between the discrete and the continuous trajectory. We show that without additional assumptions on the smoothness with depth of the residual functions, this error does not go to as (Prop. 1). However, we show that under some assumptions on the weight initialization, the trained parameters of a deep linear ResNet uniformly (with respect to both depth and training time) approach a Lipschitz function as the depth of the network goes to infinity, at speed (Prop. 2 and Th. 1). This result highlights an implicit regularization towards a limit Neural ODE.
In Section 4, we investigate a simple technique to train ResNets without storing activations. Inspired by the adjoint method, we propose to recover the approximated activations during the backward pass by using a reverse-time Euler scheme. We control the error for recovering the activations and gradients with this method. We show that if the residuals of the ResNet are bounded and Lipschitz continuous, with constants independent of , then this error scales in (Prop. 3). Hence, the adjoint method needs a large number of layers to lead to correct gradients (Prop. 4). We then consider a smoothness-dependent reconstruction with Heun’s method to bound the error between the true and approximated gradient by a term that depends on times the smoothness in depth of the residual functions, hence guaranteeing a better approximation when successive weights are close one to another (Prop. 5 and 6).
In Section 5, on the experimental side, we show that the adjoint method fails when training a ResNet 101 on ImageNet. Nevertheless, we empirically show that very deep ResNets pretrained with tied weights (constant weights: ) can be refined -using our adjoint method- on CIFAR-10 and ImageNet by untying their weights, leading to a better test accuracy. Last, but not least, we show using a ResNet architecture with heavy downsampling in the first layer that our adjoint method succeeds at large depth and that Heun’s method leads to a better behaved training, hence confirming our theoretical results.
Background and related work
Neural ODEs are a class of implicit deep learning models defined by an ODE where a neural network parameterises the vector field (Weinan, 2017; Chen et al., 2018; Teh et al., 2019; Sun et al., 2018; Weinan et al., 2019; Lu et al., 2018; Ruthotto and Haber, 2019; Kidger, 2022). Given an input , the output of the model is the solution of the ODE (2) at time . From a theoretical viewpoint, the expression capabilities of Neural ODEs have been investigated in (Cuchiero et al., 2020; Teshima et al., 2020; Li et al., 2019) and the Neural ODE framework has been used to better understand the dynamics of more general architectures that include residual connections such as Transformers (Sander et al., 2022; Lu et al., 2019). Experimentaly, Neural ODEs have been successful in a various range of applications, among which physical modelling (Greydanus et al., 2019; Cranmer et al., 2019) and generative modeling (Chen et al., 2018; Grathwohl et al., 2018). However, there are many areas where Neural ODEs have failed to replace ResNets, for instance for building computer vision classification models. Neural ODEs fail to compete with ResNets on ImageNet, and to the best of our knowledge, previous works using Neural ODEs on ImageNet consider weight-tied architectures and only achieves the same accuracy as a ResNet18 (Zhuang et al., 2021).
Implicit Regularization of ResNets towards ODEs.
Recent works have studied the link between ResNets and Neural ODEs. In (Cohen et al., 2021), the authors carry experiments to better understand the scaling behavior of weights in ResNets as a function of the depth. They show that under the assumption that there exists a scaling limit for the weights of the ResNets (with ) and if the scale of the ResNet is with and , then the hidden state of the ResNet converges to a solution of a linear ODE. In this paper, we are interested in the case where , which seems more natural since it is the scaling that appears in Euler’s method with step . In addition, we do not assume the existence of a scaling limit . In subsection 3.2, we demonstrate the existence of this scaling limit in the linear setting, under some assumptions. The recent work (Cont et al., 2022) shows results regarding linear convergence of gradient descent in ResNets and prove the existence of an -Hölder continuous scaling limit as with a scaling factor for the residuals in which is different from ours. In contrast, we show that our limit function is Lipschitz continuous, which is a stronger regularity. We also show that our convergence is uniform in depth and optimization time. More generally, recent works have proved the convergence of gradient descent training of ResNet when the initial loss is small enough. This include ResNet with finite width but arbitrary large depth (Du et al., 2019; Liu et al., 2020) and ResNet with both infinite width and depth (Lu et al., 2020; Barboni et al., 2021). These convergence proofs leverage an implicit bias toward weights with small amplitudes. They however leave open the question of convergence of individual weights as depth increases, which we tackle in this work in the linear case. This requires showing an extra bias toward weights with small variations across depth.
Memory bottleneck in ResNets.
Training deep learning models involve graphics processing units (GPUs) where memory is a practical bottleneck (Wang et al., 2018; Peng et al., 2017; Zhu et al., 2017). Indeed, backpropagation requires to store activations at each layer during the forward pass. Since samples are processed using mini batches, this storage can be important. For instance, with batches of size 128, the memory needed to compute gradients for a ResNet 152 on ImageNet is about 22 GiB. Note that the memory needed to store the parameters of the model is only 220 MiB, which is negligible compared to the memory needed to store the activations. Thus, designing deep invertible architectures where one can recover the activations on the fly during the backpropagation iterations has been an active field in recent years (Gomez et al., 2017; Sander et al., 2021a; Jacobsen et al., 2018). In this work, we propose to approximate activations using a reverse-time Euler scheme, as we detail in the next subsection.
Adjoint Method.
Consider a loss function for the ResNet (1). The backpropagation equations (Baydin et al., 2018) are
Now, consider a loss function for the Neural ODE (2). The adjoint state method (Pontryagin, 1987; Chen et al., 2018) gives
Note that if and , then Eq. (3) corresponds to a Euler discretization with time step of Eq. (4). The key advantage of using Eq. (4) is that one can recover on the fly by solving the Neural ODE (2) backward in time starting from . This strategy avoids storing the forward trajectory and leads to a memory footprint (Chen et al., 2018). In this work, we propose to use a discrete adjoint method by using a reverse-time Euler scheme for approximately recovering the activations in a ResNet (Section 4). Contrarily to other models such as RevNets (Gomez et al., 2017) (architecture change) or Momentum ResNets (Sander et al., 2021b) (forward rule modification) which rely on an exactly invertible forward rule, the proposed method requires no change at all in the network, but gives approximate gradients.
Notations.
ResNets as discretization of Neural ODEs
In this section we first show that without further assumptions, the distance between the discrete trajectory and the solution of associated ODEs can be constant with respect to the depth of the network if the residual functions lack smoothness with depth. We then present a positive result by studying the linear case where we show that, under some hypothesis (small loss initialization and initial smoothness with depth), the ResNet converges to a Neural ODE as the number of layers goes to infinity. We show that this convergence is uniform with depth and optimization time.
We first define associated Neural ODEs for a given ResNet.
Note that we omit the dependency of in to simplify notations. For example, for a given ResNet, there are two natural ways to interpolate it with a Neural ODE, either by interpolating the residuals, or by interpolating the weights. Indeed, one can interpolate the residuals with when , or interpolate the weights with for . If does not depend on , then both interpolations are identical and one can simply consider , .
We now consider any smooth interpolation for the ResNet (1) and a Euler scheme for the Neural ODE (2) with time step .
2 Linear Case
Gradient.
Two continuous variables involved.
Assumption 1 is the classical assumption in the literature (Zou et al., 2020; Barboni et al., 2021) to prove linear convergence of our loss and that the ’s stay bounded with . Note that this bounded norm assumption implies that . This is in contrast with classical initialization scales in the feedforward case where the initialization only depends on width (He et al., 2015). However this initialization scale is coherent with those of ResNets for which the scale has to depend on depth (Yang and Schoenholz, 2017). In addition, the experimental findings in Cohen et al. (2021) suggest that the weights in ResNets scale in with .
We now prove an implicit regularization result showing that if at initialization, in addition to assumption 1, the weights are close from one another (), they will stay at distance : the discrete derivative stay in , which is a central result to consider the infinite depth limit in our Th. 1.
Lemma 1 is proved in appendix A.3, and gives us the existence of a Lipschitz continuous accumulation point, but not the uniqueness nor the convergence speed. For the uniqueness, we show in appendix A.5 that, under the assumptions of Th. 1, one has that any accumulation point of satisfies the limit Neural ODE
and show that satisfies the hypothesis of the Picard–Lindelöf theorem, hence showing the uniqueness of . We finally show that, as intuitively expected, trajectories of the weights of our linear ResNets of depth and remain close one to each other. This gives the convergence speed in Th. 1. See appendix A.4 for a proof.
Adjoint Method in Residual Networks
The approximate recovery of the activations in Eq. (6) is implementable for any ResNet: there is no need for particular architecture or forward rule modification. The drawback is that the recovery is only approximate. We devote the remainder of the section to the study of the corresponding errors and to error reduction using second order Heun’s method. We first show that, if and its derivative are bounded by a constant independent of , then the error for reconstructing the activations in the backward scheme (6) is . Proofs of the theoretical results are in appendix A.
Then the error made by reconstructing the activations is in .
Prop. 3 shows a slow convergence of the error for recovering activations. This bound does not depend on the discrete derivative , contrarily to the errors between the ResNet activations and the trajectory of the interpolating Neural ODE in Prop 1. In summary, even though regularity in depth is necessary to imply closeness to a Neural ODE, it is not necessary to recover activations, and neither gradients, as we now show.
Error in gradients when using the adjoint method.
We use the result obtained in Prop. 3 to derive a bound in on the error made for computing gradients using formulas (7).
For a proof, see appendix A.7, where we give the dependency of our upper bound as a function of and .
Smoothness-dependent reconstruction with Heun’s method.
The bounds in Prop. 3 and 4 do not depend on the smoothness with respect to the weights of the . Only the magnitude of the residuals plays a role in the correct recovery of the activations and estimation of the gradient. Hence, there is no apparent benefit of having such a network behave like a Neural ODE. We now turn to Heun’s method, a second order integration scheme, and show that in this case smoothness in depth of the network improves activation recovery. A HeunNet (Maleki et al., 2021) of depth with parameters iterates for :
These forward iterations can once again be approximately reversed by doing for :
which also enables approximated backpropagation without storing activations. When discretizing an ODE, Heun’s method has a better error, hence we expect a better recovery than in Prop. 3. Indeed, we have:
Just like with activation, we see that Heun’s method allows for a better gradient estimation when the weights are smooth with depth. Equivalently, for a fixed depth, this proposition indicates that HeunNets have a better estimation of the gradient with the adjoint method than ResNets which ultimately leads to better training and overall better performances by such memory-free model.
Experiments
We now present experiments to investigate the applicability of the results presented in this paper. We use Pytorch (Paszke et al., 2017) and Nvidia Tesla V100 GPUs. Our code will be open-sourced. All the experimental details are given in appendix B, and we provide a recap on ResNet architectures in appendix C.
The ResNet model (1) is different from the classical ResNet because of the term. This makes the model depth aware, and we want to study the impact of this modification on the accuracy on CIFAR and ImageNet.
We first train a ResNet-101 (He et al., 2016a) on CIFAR-10 and ImageNet using the same hyper-parameters. Experimental details are in appendix B and results are summarized in table 1, showing that the explicit addition of the step size does not affect accuracy. In strike contrast, the classical ResNet rule without the scaling makes the network behave badly at large depth, while it still works well with our scaling , as shown in Figure 3 (a). On ImageNet, the scaling also leads to similar test accuracy in the weight tied setting: with blocks per layer, with blocks per layer and with blocks per layer (mean over runs).
2 Adjoint method
Our results in Prop. 3 and 4 assume uniform bounds in on our residual functions and their derivatives. We also formally proved in the linear setting that these assumptions hold during the whole learning process if the initial loss is small. A natural idea to start from a small loss is to consider a pretrained model.
In addition, we also want our pretrained model to verify assumption 2 so we consider the following setup. On CIFAR (resp. ImageNet) we train a ResNet with 4 (resp. 8) blocks in each layer, where weights are tied within each layer. A first observation is that one can transfer these weights to deeper ResNets without significantly affecting the test accuracy of the model: it remains above on CIFAR-10 and on ImageNet. We then untie the weights of our models and refine them. More precisely, for CIFAR, we then transfer the weights of our model to a ResNet with , , and blocks within each layer and fine-tune it only by refining the third layer, using our adjoint method. We display in table 2 the median of the new test accuracy, over runs for the initial pretraining of the model. For ImageNet, we transfer the weights to a ResNet with blocks per layer and fine-tune the whole model with our adjoint method for the residual layers. Results are summarized in table 2. To the best of our knowledge, this is the first time a Neural-ODE like ResNet achieves a test-accuracy of on ImageNet.
Failure in usual settings.
In Prop. 3 we showed under assumption 2, that is if the residuals are bounded and Lipschitz continuous with constant independent of the depth , then the error for computing the activations backward would scale in as well as the error for the gradients (Prop. 4). First, this results shows that the architecture needs to be deep enough, because it scales in : for instance, we fail to train a ResNet-101 (He et al., 2016a) on the ImageNet dataset using the adjoint method on its third layer (depth ), as shown in Figure 3 (b).
Success at large depth.
To further investigate the applicability of the adjoint method for training deeper ResNets, we train a simple ResNet model on the CIFAR data set. First, the input is processed by a convolution with out channels, and the image is down-sampled to a size .
We then apply a batch norm, a ReLU and iterate relation (1) where is a pre-activation basic block (He et al., 2016b). We consider the zero residual initialisation: the last batch norm of each basic block is initialized to zero. We consider different values for the depth and notice that in this setup, the deeper our model is, the better it performs in term of test accuracy. We then compare the performance of our model using a ResNet (forward rule (1)) or a HeunNet (forward rule (8)). We train our networks using either the classical backpropagation or our corresponding proxys using the adjoint method (formulas (6) and (9)). We display the final test accuracy (median over runs) for different values of the depth in Figure 4. The true backpropagation gives the same curves for the ResNet and the HeunNet. Approximated gradients, however, lead to a large test error at small depth, but give the same performance at large depth, hence confirming our results in Prop. 4 and 6. In addition, at fixed depth, the accuracy when training a HeunNet with the adjoint method is better (or similar at depths , and ) than for the ResNet with the adjoint method. This is to be linked with the two different bounds in Prop. 4 and 6: for the HeunNet, smoothness with depth, which is expected at large depth, according to the theoretical results for the linear case (Prop. 2), implies a faster convergence to the true gradients for the HeunNet than for the ResNet. We finally validate this convergence in Figure 3 (c): the deeper the architecture, the better the approximation on the gradients. In addition, the HeunNet approximates the true gradient better than the ResNet.
Conclusion, limitations and future works
We propose a methodology to analyze how well a ResNet discretizes a Neural ODE. The positive results predicted by our theory in the linear case are also observed in practice with real architectures: one can successfully use the adjoint method to train ResNets (or even more effectively HeunNets) using very deep architectures on CIFAR, or fine-tune them on ImageNet, without memory cost in the residual layers. However, we also show that for large scale problems such as ImageNet classification from scratch, the adjoint method fails at usual depths.
Our work provides a theoretical guarantee for the convergence to a Neural ODE in the linear setting under a small loss initialization. A natural extension would be to study the non-linear case. In addition, the adjoint method is time consuming, and an improvement would be to propose a cheaper method than a reverse mode traversal of the architecture for approximating the activations.
Acknowledgments
This work was granted access to the HPC resources of IDRIS under the allocation 2020-[AD011012073] made by GENCI. This work was supported in part by the French government under management of Agence Nationale de la Recherche as part of the “Investissements d’avenir” program, reference ANR19-P3IA-0001 (PRAIRIE 3IA Institute). This work was supported in part by the European Research Council (ERC project NORIA). M. S. thanks Mathieu Blondel and Zaccharie Ramzi for helpful discussions.
References
APPENDIX
In Section A we give the proofs of all the propositions, lemmas and the theorem presented in this work.
Section B gives details for the experiments in the paper.
We also give a recap on ResNet architectures in Section C.
Appendix A Proofs
Our proof is inspired by [Demailly, 2016].
We denote and . We define
We have that .
with . This implies that
The true error we are interested in is the global error . One has
Because is -Lipschitz, this gives and hence
this implies from the discrete Gronwall lemma, since that
Note that we have This gives the desired result. ∎
A.2 Proof of Prop. 2
Recall that we denote , and . We denote . One has
One has that , and which implies that
We now show our main result. Note that we have the relationship so that
Because if this gives . Integrating we get
A.3 Proof of lemma 1
We adapt a variant of the Ascoli–Arzelà theorem [Brezis and Brézis, 2011]. We showed in Prop. 2 that there exists that only depends on the initialization such that, ,
Its follows that and thus
These two properties are essential to prove our lemma. We proceed as follows.
(we denote the limit ).
and . There exists a finite set of such that
For our , there exists such that .
There also exists such that if ,
for big enough.
Finally,
for big enough, independently of and . This concludes the proof. ∎
A.4 Proof of lemma 2
Note also that since the Jacobian of is
for some constants , . Finally, we have
Our (PL) conditions precisely write for some . Let One has
Since we get
Let be such that . We have
A.5 Proof of Th. 1
We first prove the following lemma 3 before proving Th. 1.
and the Euler scheme with time step for its discretization
We know by Prop. 1, since has unit norm that
Since and has unit norm, there exists independent of such that, and , . Thus
as . We obtain the uniform convergence with .
Consider a sub-sequence of as in lemma 1 that converges to some .
1) We first prove the uniqueness of the limit.
We want to show that does not depend on . This will imply the uniqueness of any accumulation point of the relatively compact sequence and thus its convergence.
As , we have thanks to lemma 3 that the right hand term converges uniformly to
This uniform convergence makes it possible to consider the limit ODE as :
Let , with and and , the corresponding flows.
One has and . One has . Hence, since , , we have
for some . The same arguments go for and .
Since we only consider maps such that , this implies that the product is also Lipschitz and thus is Lipschitz. This guarantees the uniqueness of a solution to the Cauchy problem and we have that uniformly.
Letting finally gives
A.6 Proof of Prop. 3
and since , the discrete Gronwall lemma leads to In addition, one has so that
A.7 Proof of Prop. 4
1) We first control the error made in the gradient with respect to activations.
2) We can now control the gradients with respect to the parameters ’s.
Using our bound on and Prop. 3 we get
A.8 Proof of Prop. 5
In the following, we let for short , and we define
so that Heun’s forward and backward equations are
We have the following lemma that quantifies the reconstruction error over one iteration:
where is the Jacobian of .
As goes to infinity, we have the following expansions of (12):
Putting everything together, we find that the zero-th order in cancels, and that the first order simplifies to . ∎
We now turn the the proof of the main proposition:
Using the triangle inequality, and the Lispchitz continuity of , we get
The last term is controlled with the previous Lemma 4:
A.9 Proof of Prop. 6
1) We first control the error made in the gradient with respect to activations. We have the following recursions:
The last term is controled with the previous proposition, and we find
2) We can now control the gradients with respect to parameters. Since Heun’s method involves parameters both for the computation of and , the gradient formula is slightly more complicated than for the classical ResNet. It is the sum of two terms, the first one corresponding to iteration and the second one corresponding to iteration .
The gradient is finally
Overall, these equations map the activations and , and the gradients and to the gradient , which we rewrite as
where the function is explicitly defined by the above equations. With the memory-free backward pass, the gradient is rather estimated as
The function is Lispchitz-continuous since all functions involved in its composition are Lipschitz-continuous and the activations belong to a compact set, and its Lipschitz constant scales as . We write its Lipschitz constant as , and we get:
Appendix B Experimental details
In all our experiments, we use Nvidia Tesla V100 GPUs.
For our experiments on CIFAR-10 (training from scratch), we used a batch-size of and we employed SGD with a momentum of . The training was done over epochs. The initial learning rate was and we used a cosine learning rate scheduler. A constant weight decay was set to . Standard inputs preprocessing as proposed in Pytorch [Paszke et al., 2017] was performed.
For our finetuning experiment on CIFAR-10, we used a batch-size of and we employed SGD with a momentum of . The training was done over epochs. The learning rate was kept constant to . A constant weight decay was set to . Standard inputs preprocessing as proposed in Pytorch was also performed.
For our experiment with our simple ResNet model that processes the input by a convolution with out channels, we used a batch-size of and we employed SGD with a momentum of . The training was done over epochs. The learning rate was set to and was decayed by a factor every epochs. A constant weight decay was set to . Standard inputs preprocessing as proposed in Pytorch was also performed.
B.2 ImageNet
For our experiments on ImageNet (training from scratch), we used a batch-size of and we employed SGD with a momentum of . The training was done over epochs. The initial learning rate was and was decayed by a factor every epochs. A constant weight decay was set to . Standard inputs preprocessing as proposed in Pytorch was performed: normalization, random croping of size pixels, random horizontal flip.
For our finetuning experiment on ImageNet, we used a batch-size of and we employed SGD with a momentum of . The training was done over epochs. The learning rate was kept constant to . A constant weight decay was set to . Standard inputs preprocessing as proposed in Pytorch was performed: normalization, random croping of size pixels, random horizontal flip.
Appendix C Architecture details
In computer vision, the ResNet as presented in [He et al., 2016a] first applies non residual transformations to the input image: a feature extension convolution that goes to channels to 64, a batch norm, a non-linearity (ReLU) and optionally a maxpooling.
Finally, there is a classification module: average pooling followed by a fully connected layer.