Learning Stability Certificates from Data
Nicholas M. Boffi, Stephen Tu, Nikolai Matni, Jean-Jacques E. Slotine, Vikas Sindhwani
Introduction
A fundamental barrier to widespread deployment of reinforcement learning policies on real robots is the lack of formal safety and stability guarantees. While much research has focused on how to train control policies for complex systems, considerably less emphasis has been placed on verifying stability for the resulting closed-loop system. Without any a-priori guarantees, practitioners will be hesitant to deploy learned solutions in the real world regardless of performance in simulation.
Many powerful tools have been developed in nonlinear control theory to address the safety and stability of systems with known dynamics. The most well-known technique is the construction of a Lyapunov function to demonstrate asymptotic stability of a system with respect to an equilibrium point. Similarly, barrier functions are used to show set-invariance, which has been widely used in safety-critical applications to prove that a system does not exit a desired safe set. Contraction analysis provides an alternative view of stability, applicable to many problems in nonlinear control and robotics, by considering the convergence of trajectories towards each other rather than to an equilibrium point. The unifying theme among these tools is the construction of a certificate function (the Lyapunov/barrier function or contraction metric) that proves a given desirable property for the system of interest. These certificates have strong converse results , which imply the existence of a certificate function if the desired property does hold, and can also be used for controller synthesis .
The main obstacle for producing certificate functions in modern robotics and reinforcement learning is that existing synthesis and verification tools such as sum-of-squares (SOS) optimization or SMT solvers typically assume the dynamics can be written down analytically in closed form. Furthermore, the functions of interest are often constrained to lie in restrictive classes such as polynomial basis functions of fixed degree. This presents a serious hurdle in modern robotics, where (a) sophisticated physics simulators are widely used to model complex environments and (b) control policies are often represented with complex deep neural networks. Finally, both SOS optimization and formal verification tools are computationally intensive, thus limiting their applicability.
To avoid these limitations, recent approaches have proposed to treat certificate synthesis as a machine learning problem, and train powerful function approximators such as deep neural networks and reproducing kernel Hilbert space (RKHS) predictors on trajectory data collected from a dynamical system . The general strategy is to enforce the desired certificate condition (e.g. the Lie derivative of a function should be negative) along collected samples. Empirically, this has been shown to be quite effective, and the learned certificate often generalizes well outside of the training data. However, a deeper theoretical understanding of when and why this approach works is missing.
Consider Figure 1, where a contraction metric, which certifies pairwise convergence of trajectories, is learned from rollouts of a damped Van der Pol oscillator. Regions of the state space for which the learned metric is not contracting are shown as a function of the number of trajectories . While the size of the violating regions appears to shrink as increases, Figure 1 raises many questions. How much data does one need to collect so that the violating regions cover at most a prescribed fraction of the relevant state space? Is the learning consistent, i.e. do the regions vanish as ?
Related Work
Prior research generally focuses on learning certificates for a fixed system from trajectories, or on using certificate conditions as regularizers when learning models for control.
Giesl et al. propose to learn a Lyapunov function from noisy trajectories using a specific reproducing kernel. Their algorithm first fits a dynamics model from data, and then uses interpolation to construct a Lyapunov function from the learned model. The authors prove convergence results on the Lie derivative of the constructed Lyapunov function compared to the ground truth, with rates depending on a dense cover of the state space.
Our work circumvents this two-step identification procedure by directly analyzing the generalization error of a Lyapunov function learned by enforcing derivative conditions along the training data. Many other authors have proposed similar approaches. Kenanian et al. show how to estimate the joint spectral radius of a switched linear system by learning a common quadratic Lyapunov function directly from data. Their analysis heavily exploits properties of linear systems. Chen et al. study how to learn a quadratic Lyapunov function for piecewise affine systems in feedback with a neural network controller. Richards et al. use a sum-of-squares neural network representation to learn the largest region of attraction of a nonlinear system. Manek and Kolter jointly train a neural network model and Lyapunov function. Neither Richards et al. nor Manek and Kolter provide formal guarantees that the learned Lyapunov function will generalize to new trajectories. Both Chang et al. and Ravanbakhsh and Sankaranarayanan propose to use ideas from formal verification to falsify the validity of a learned candidate Lyapunov function. A significant limitation is the requirement of access to the true dynamics.
In many of these works, the Lie derivative constraint that defines a Lyapunov function is relaxed to a soft constraint, so that first-order gradient methods can be used for optimization. We note that our generalization analysis can be modified to handle soft constraints in a straightforward manner.
Barrier functions are relaxations of Lyapunov functions that demonstrate invariance of a subset of the state space. Recently, many authors have proposed to use and learn barrier functions from data for safety-critical applications. Taylor et al. assume a control barrier function (CBF) is valid for both a nominal and unknown system model, and use the CBF to guide safe learning of the unknown system dynamics. More closely related to our work, Robey et al. learn a CBF for a known nonlinear dynamical system from expert demonstrations, and use Lipschitz arguments to extend the validity of the CBF beyond the training data. Jin et al. propose to jointly learn a Lyapunov, barrier, and a policy function from data. They also prove validity of the learned certificates using Lipschitz arguments.
The literature on learning contraction metrics from data is more sparse. In an imitation learning context, Sindhwani et al. propose to learn a vector field from demonstrations that satisfies contraction in the identity metric. The authors parameterize the vector field as a vector-valued reproducing kernel. Khadir et al. also learn a vector field from demonstrations by using sum-of-squares to enforce contraction. They argue by smoothness considerations that the learned vector field actually contracts in a tube around the demonstration trajectories. We note that in both these works, the metric is held fixed and is assumed to be known. Singh et al. jointly learn a model and a control contraction metric from data, and show empirically that using contraction as a regularizer in model learning can lead to better sample efficiency when learning to control. We leave studying the generalization properties of jointly learning an explicit model and a contraction metric to future work.
Our generalization bounds are similar in spirit to those provided for random convex programs (RCPs) . Random convex programming is concerned with approximating solutions to convex programs with an infinite number of constraints. Such infinitely-constrained problems are approximated by drawing i.i.d. samples from a distribution over the constraint parameters and enforcing constraints on samples. One can then show that the probability that a new sample from violates the constraint for the approximate solution scales as where is the number of decision variables. Our results can be viewed as generalizing these bounds beyond convex programs, though our constants are less sharp. In our experiments, we use the RCP bound for numerically computing generalization bounds when the problem is convex.
Learning Certificates Framework
As we describe below, through suitable choices of the function , equation (3.1) can be used to enforce various defining conditions for certificates such as Lyapunov functions and contraction metrics. We note that our framework can be modified to allow for more derivatives of , including higher order derivatives and also time derivatives for handling time-varying dynamics.
We study the following optimization problem for searching for a solution to (3.1):
Here, is a positive margin value which will allow us to generalize the behavior of on outside of the sampled data. In practice, we often solve (3.2) with a cost term on such as its norm. Let denote a solution to (3.2), assuming one exists. We quantify the generalization of by the probability of violation over trajectories starting from :
1.2 Contraction metrics
A system is said to be contracting in a region with rate if there exists a uniformly positive definite Riemannian metric such that for . Given knowledge of , this condition fits into our framework by taking .
We can enforce (3.4) by directly sampling trajectories on , by exploiting that the variational dynamics obeyed by is identical to the local linearization of around . Specifically, we sample pairs of initial conditions and for some small perturbation . Numerical differentiation of and provides access to and , which then allows us to evaluate (3.4) along system trajectories.
Generalization Error Results
We first define the notion of stability we will assume. Recall that is the set containing sample initial conditions, and is the interval over which our trajectories evolve.
Note that contraction implies Assumption 4.1, so that contracting systems are also covered in this setting. Next, we make some regularity assumptions on the function class .
We assume there exist finite constants , such that and .
Given Assumptions 4.1–4.2, we define (resp. ) to be an upper bound on (resp. the Lipschitz constant of ) over , and . Note that both and are guaranteed to be finite by our assumptions.
Fix a . Assume that Assumption 4.1 and Assumption 4.2 hold. Suppose that the optimization problem (3.2) is feasible and let denote a solution. The following statement holds with probability at least over the randomness of drawn i.i.d. from :
We consider the following parametric representation:
Under Assumption 4.1, if problem (3.2) over the parametric function class (4.1) is feasible, then any solution satisfies with probability at least over :
Here, and .
Often times (4.1) is more structured. For instance, in sum-of-squares (SOS) optimization, we have:
Under Assumption 4.1, if problem (3.2) over the parametric linear function class (4.3) is feasible, then any solution satisfies with probability at least over :
Here, and .
In general, using prior knowledge about the system to add more structure and reduce the number of parameters of the certificate function (e.g. diagonal contraction metrics for positive systems) yields better generalization bounds.
2 Reproducing kernel Hilbert space function classes
We now consider the following non-parametric function class:
Here, is a nonlinear function and is a probability distribution over . This function class is a subset of the reproducing kernel Hilbert space (RKHS) defined by the kernel , and is dense in the RKHS as . We further assume that is of the form with differentiable and . RKHSs of this type often arise naturally. For instance, Bochner’s theorem states that every translation invariant kernel can be expressed in this form.
Suppose that , is -Lipschitz, is differentiable, is -Lipschitz, and that is finite. Under Assumption 4.1, if problem (3.2) over the non-parametric class (4.5) is feasible, then any solution satisfies with probability at least over :
where .
Global Stability Results
In this section, we show how the bounds from Section 4 can be translated into global results for the learned certificate functions. To facilitate our analysis, we assume the dynamics is incrementally stable. Incremental stability is implied by contraction, but is stronger than Lyapunov stability. Before stating the assumption, we say that is a class function if for every the map is a class function and for every the map is continuous and non-increasing.
There exists a class function such that for all , for all .
Equation (5.3) yields bounds of the form , where depends on the specific form of . For example if for some , then . On the other hand, if we have the slower rate , then .
We note that Theorem 5.1 is conceptually similar to the results from Liu et al. , but incremental stability assumption dramatically simplifies the proof and enables us to make the constants explicit.
Theorem 5.2 is illustrated in Figure 1, which shows the structure of the violation set. Further details and exploration of the effect of can be found in Section A.5. In Section D we prove a result similar to Theorem 5.2 for metric learning with known dynamics.
Learning Certificates in Practice
We empirically study the generalization behavior of both learning Lyapunov functions and contraction metrics from trajectory data. We consider Lyapunov functions parameterized by , where is the (reshaped) value of a fully connected neural network with activations of size , where is the state-dimension of and is the hidden width. For metric learning, we study a convex formulation via SOS programming. Each matrix element is given by a polynomial where are the learned weights and is a feature map of monomials in the state vector. In our experiments, we numerically estimate the generalization error of a learned certificate using a test set. We compute an upper confidence bound (UCB) of the estimate using the Chernoff inequality with , as described by Langford . More experimental details are given in the appendix.
We learn a discrete-time Lyapunov function for a quadruped robot as it recovers from external forcing. We apply a random impulse force in the plane at time to the Minitaur quadruped environment in PyBullet , and use a hand-tuned PD controller to return the minitaur to a standing position. We train a discrete-time Lyapunov function in order to handle the discontinuities in the trajectories introduced by contact forces.
Figure 2 (LL) shows the result of this experiment. For the Lyapunov curve, the resulting model trained on trajectories is then validated using a trajectory test set. The generalization error is the ratio of trajectories which violate the desired decrease condition for any step . We run trials and plot the 10/50/90-th percentile of the generalization UCB. With , the median generalization UCB is . Since in practice a separate test set may not be available, we also compare to splitting the available training data into an actual training set of size and a validation set of size . The model is trained on the actual training set, and a generalization UCB is calculated from the validation set. We run trials of this setup and plot the 10/50/90-th percentile in the Holdout curve. After , the median generalization UCB is .
Conclusion
Our work shows that certificate functions can be efficiently learned from data, and raises many interesting questions for future work. Extending the results to handle both noisy state observations and process noise in the dynamics would allow for learning certificates in uncertain environments. Another interesting question is to establish bounds for joint learning of both the unknown dynamics and a certificate, which has shown to be effective in practice . Finally, lower bounds on the learning certificate problem would highlight the amount of conservatism introduced in our results.
Acknowledgements
The authors would like to thank Amir Ali Ahmadi, Brett Lopez, Alexander Robey, and Sumeet Singh for providing helpful feedback.
References
Appendix A Experiment Details
Here we give pseudocode for the metric learning algorithm used in the main text. Algorithm 1 is written for a parameterization that yields a convex optimization problem, and where uniform positive definiteness may be enforced globally, such as via SOS matrix constraints. It may be readily relaxed to nonconvex parameterizations such as neural networks by using soft constraints and minimizing the loss using a variant of stochastic gradient descent. Uniform positive definiteness can be imposed along trajectories rather than globally.
A.2 Pendulum
We repeat this experiment for trials. For each trial we use a test set of size to compute a UCB on the generalization error. The 10/50/90-th percentile of the UCBs are , , and .
We also uniformly grid the set with points and check numerically how often the condition is violated. The 10/50/90-th percentile of these violations over trials are , , and . We note that these numbers are higher than the generalization error because the set contains points that are outside the flow starting from .
For our adaptive control experiments, the dynamics combined with the added disturbance are
with continuously differentiable and locally bounded in uniformly in . Let be a twice continuously differentiable positive definite function such that for all for some continuously differentiable positive definite function . Let be a positive definite matrix. Let be defined by the differential equation
in feedback with (A.2) drives and .
Let and . Define the new candidate Lyapunov function
A.3 Minitaur
We collect random training trajectories and random test trajectories using the same distribution over the impulse force. For each trajectory, we step the simulator times at . The state dimension excluding the base orientation is .
We use a hidden width of and minimize the loss , setting . The loss is minimized for epochs with Adam using a step size with cosine decaySee https://www.tensorflow.org/api_docs/python/tf/compat/v1/train/cosine_decay. and a batch size of .
A.4 6-dimensional gradient system
We parametrize the metric via monomials up to degree two in the state variables. We enforce global positive definiteness via SOS matrix constraints and set . We use a tolerance of for the size of each perturbation . A pair of trajectories , with is considered to generate a trajectory if for all , so that a small overshoot is permitted. Pairs of trajectories not satisfying this requirement are discarded until the desired number of training samples is reached. The size of this overshoot parameter sets the maximum allowed where for any metric learned, as we impose . In general, the overshoot with respect to the Euclidean norm is given by for . In practice, we require the maximum bound on to be sufficiently small that the dynamics of well-approximates the variational system on the trajectory . To search for metrics with larger values of , we can vary , , and the maximum allowed while ensuring remains small throughout its entire trajectory.
Each trajectory is simulated until seconds with a timestep . Because we are interested in convergence of the variational dynamics, we use a small time horizon. This generates a dataset of size where is the number of trajectories and is the dimension of the tangent bundle. We subsequently downsample and impose differential Lyapunov constraints along each trajectory. We search for a metric with a rate . Initial conditions are drawn uniformly from the ball of radius .
The time derivatives and are computed numerically by fitting a cubic spline to the corresponding trajectories and analytically differentiating the spline. is found by minimizing where is a vector containing all parameters. The test set is of size and each data point in Figure 2 (LR) was computed by averaging over independent draws of the training set. The RCP bound is obtained with a confidence of .
Consider the following optimization problem:
Fix any . Define as:
With probability at least over , we have that:
We use Theorem A.2 as follows. We fix a failure probability . We then numerically solve for such that .
To understand the scaling of as a function of and , despite the lack of closed form expression, consider the following. If then by a Chernoff bound on the CDF of a Binomial random variable (c.f. Section 5 of Calafiore ), we can derive the upper bound
A.5 Van der Pol
The study of the Van der Pol (VDP) oscillator was foundational to the development of nonlinear dynamics , and its global contraction properties have been analyzed algoithmically via SOS programming . We study the damped VDP to visualize the violation set for the metric condition categorized in Theorem 5.2. The dynamics of the damped Van der Pol are given by
We parameterize the metric via monomials up to degree four in the state variables. Similar to the gradient system, we set and use a tolerance , for all . We use a timestep and simulate until a final time seconds. This generates a dateset of size where is the dimension of the tangent bundle and is the number of training trajectories.
We subsequently downsample and impose differential Lyapunov constraints along each trajectory with a rate . Initial conditions are drawn uniformly from a ball of radius . The same techniques are used for numerical differentiation as for the gradient system.
Theorem 5.2 predicts that the size of the violation set will decrease as the rate tested for the metric condition with decreases, or as the number of training samples increases. In both Figure 1 and Figure 3, we use a uniform grid with points over to test the metric condition for the learned metric and the true dynamics.
In Figure 1, we plot the violation set for fixed as a function of the number of training samples. As discussed in the main text, the size of the violation set decreases, and it is pushed to the boundary of the sampled region as increases.
In Figure 3, we plot the violation set as a function of . As decreases to zero, the size of the violation set decreases and is pushed to the boundary of the sampled region.
Appendix B Proofs for Section 4
Recall that Dudley’s inequality gives us the following estimate on :
B.2 Proof of Theorem 4.3
A simple calculation shows that . Hence by (B.1),
Here, is an absolute constant. By integrating this estimate we arrive at the bound:
B.3 Proof of Theorem 4.4
Define the function classes and as:
The following is a simple modification of Theorem 3.2 from Rahimi and Recht , which also accounts for uniform approximation of the derivatives.
Furthermore, now assume that is differentiable and is -Lipschitz. Then every is differentiable with
Finally, with probability at least , there exists a such that (B.5) holds and also:
Following the proof of Theorem 3.2 of Rahimi and Recht , we set , and we define . It is shown in that for all :
Next, we control the expected value of :
Above, the first inequality is a standard symmetrization argument where the Rademacher variables are introduced, and the second inequality is the triangle inequality. We first bound . Set . Clearly , and also is -Lipschitz. We bound . Therefore by the contraction inequality for Rademacher complexities (Theorem 4.12 of Ledoux and Talagrand ) followed by Jensen’s inequality:
Furthermore we can bound by similar arguments. The claim (B.5) now follows by invoking McDiarmid’s inequality.
We note that (B.6) follows from a basic application of the dominated convergence theorem, since we have that:
Finally, we focus on the derivative condition (B.7). Let . By symmetrization we have:
We can now apply Theorem 3 of Maurer to conclude that:
Next, we have for all :
The uniform bound on the derivatives (B.7) now follows from another application of McDiarmid’s inequality. ∎
We now turn to the proof of Theorem 4.4. Under the hypothesis of Lemma B.1, we have that for every :
We also have for any and any with ,
Hence for any , the function class satisfies Assumption 4.2 with and .
Let denote a feasible solution to (3.2).
At this point, it may be tempting to use the probabilistic method in conjunction with Lemma B.1 to conclude that there exists a set of weights such that there exists a such that closely approximates . This will not work however, since the function class then becomes a function of the training data , and hence we would not be able to apply Lemma 4.1 to it.
To work around this, we need to draw the weights independently of . In particular, we set such that
where is an absolute constant and let be drawn i.i.d. from .
By the definition of , these two inequalities imply that
The result is that with probability at least over :
Letting and , we have that . Hence by (B.1),
Appendix C Proofs for Section 5
Now if , then and hence .
where is the regularized incomplete beta function.
The solution to an LTV system is given by , where and is invertible for all . This means there exists a non-zero such that . The claim now follows by taking . ∎
We therefore have the following chain of inequalities:
C.2 Proof of Theorem 5.2
We begin with a simple lemma, which shows that if a system evolving on Euclidean space is contracting in the metric , then the corresponding prolongated system on the tangent bundle will be contracting in a block-diagonal metric.
Consider the differential dynamics . This system has Jacobian
Consideration of the differential Lyapunov function
shows that decreases exponentially by contraction of in the metric and hence that the virtual dynamics are contracting. Let be such that . The metric transformation
for leads to the generalized Jacobian
which shows that the prolongated system is contracting over any compact domain for sufficiently small. In particular, for contraction with rate for , we may set
Furthermore, note that the metric transformation corresponds to the block-diagonal metric
Now with this expression in hand, we choose such that
By -homogeneity of the inequality above, we may divide by on both sides to conclude:
Appendix D Known dynamics
In Section 5, we assume access only to trajectories. Here we prove a simple proposition under the assumption that the dynamics is known, so that the defining metric condition for contraction can be sampled directly.
with an identical bound for the transpose. Now let denote the tensor contraction . Then,
Furthermore, . Putting these bounds together, we find that