Chapter 7: Dynamic Programming
In chapter 2, we spent some time thinking about the phase portrait of the simple pendulum, and concluded with a challenge: can we design a nonlinear controller to reshape the phase portrait, with a very modest amount of actuation, so that the upright fixed point becomes globally stable? With enough actuators and unbounded torque, feedback-cancellation solutions (e.g., invert gravity) can work well, but can also require an unnecessarily large amount of control effort. The energy-based swing-up control solutions presented for the Acrobot and cart-pole systems are considerably more appealing, but required some cleverness and might not scale to more complicated systems. Here we investigate another approach to the problem, using computational optimal control to synthesize a feedback controller directly.
Formulating control design as an optimization
In this chapter, we will introduce optimal control. Reinforcement learning is the machine learning name for optimal control; we'll discuss that machine learning perspective later in the notes. Optimal control is powerful for a number of reasons. First and foremost, it is very general - allowing us to specify the goal of control equally well for fully-actuated or underactuated, linear or nonlinear, deterministic or stochastic, and continuous or discrete systems. Second, it permits concise descriptions of potentially very complex desired behaviors, specifying the goal of control as a scalar objective (plus a list of constraints). Finally, and most importantly, optimal control is very amenable to numerical solutions. [1] is a fantastic reference on this material for those who want a somewhat rigorous treatment; [2] is an excellent (free) reference for those who want something more approachable.
The fundamental idea in optimal control is to formulate the goal of control as the long-term optimization of a scalar cost function. Let's introduce the basic concepts by considering a system that is even simpler than the simple pendulum.
Example: Optimal Control Formulations for the Double Integrator
Consider the "double integrator" system
If you would like a mechanical analog of the system (I always do), then you can think about this as a unit mass brick moving along the -axis on a frictionless surface, with a control input which provides a horizontal force, . The task is to design a control system, $u = \pi(\bx,t)$, to regulate this brick to $\bx = [0,0]^T$.![]()
The double integrator as a unit-mass brick on a frictionless surface
In order to formulate this control design problem using optimal control, we must define a scalar objective which scores the long-term performance of running each candidate control policy, , from each initial condition, , and a list of constraints that must be satisfied. For the task of driving the double integrator to the origin, one could imagine a number of optimal control formulations which would accomplish the task, e.g.:
- Minimum time: subject to
- Quadratic cost: $\min_\pi \int_{t_0}^{\infty} \left[ \bx^T(t) {\bf Q} \bx(t) \right] dt,$ .
The first is a constrained optimization formulation which optimizes time, and the second accrues a penalty at every instance according to the distance that the state is away from the origin (with weights defined by the matrix ), and therefore encourages trajectories that go more directly towards the goal, possibly at the expense of requiring a longer time to reach the goal. In fact the quadratic cost will result in an exponential approach to the goal, where as the minimum-time formulation will arrive at the goal in finite time. Note that there are some requirements for these optimization problems to have achieve a finite cost and have a well-defined optimal solution: for the minimum-time problem we must be able to drive the system to the origin in finite time, and for the quadratic cost, the (infinite) cost integral must converge to a finite value for all initial conditions. Fortunately both of these conditions are satisfied for the double integrator system, which is stabilizable and controllable, and therefore can be driven to the origin in finite time.
Note that the input limits, are also required to make this problem well-posed; otherwise both optimizations would result in the optimal policy using infinite control input to approach the goal infinitely fast. Besides input limits, another common approach to limiting the control effort is to add an additional quadratic cost on the input (or "effort"), e.g. $\int \left[ \bu^T(t) {\bf R} \bu(t) \right] dt,$ . This could be added to either formulation above. We will examine many of these formulations in some detail in the examples worked out at the end of this chapter.
Optimal control has a long history in robotics. It started out motivated by achieving peak performance in niche applications like programming minimum-time paths for a pick-and-place robot in a factory. But it is the generality of the approach (one can program almost any task using similar tools) that has made optimization-based and now machine-learning-based control dominate the way that state-of-the-art robot control systems are developed.
Example: The minimum time problem for the double integrator
For more intuition, let's do an informal derivation of the solution to the minimum time problem for the double integrator with input constraints: \begin{align*} \minimize_{\pi} \quad & t_f\ \subjto \quad & \bx(t_0) = \bx_0, \ & \bx(t_f) = {\bf 0}, \ & \ddot{q}(t) = u(t), \ & |u(t)| \le 1. \end{align*} What behavior would you expect an optimal controller to exhibit?
Your intuition might tell you that the best thing that the brick can do, to reach the goal in minimum time with limited control input, is to accelerate maximally towards the goal until reaching a critical point, then hitting the brakes in order to come to a stop exactly at the goal. This is called a bang-bang control policy; these are often optimal for systems with bounded input, and it is in fact optimal for the double integrator although we will not prove it until we have developed more tools.
Let's work out the details of this bang-bang policy. First, we can figure out the states from which, when the brakes are fully applied, the system comes to rest precisely at the origin. Let's start with the case where , and , and "hitting the brakes" implies that Integrating the equations, we have \begin{gather*} \ddot{q}(t) = u = -1, \\dot{q}(t) = \dot{q}(0) - t, \ q(t) = q(0) + \dot{q}(0) t - \frac{1}{2} t^2. \end{gather*} Substituting $t = \dot{q}(0) - \dot{q}$ into the solution reveals that the system trajectories are parabolic arcs:
with $c_{-} = q(0) + \frac{1}{2}\dot{q}^2(0)$.![]()
Two solutions for the system with
Similarly, the solutions for are $q = \frac{1}{2} \dot{q}^2 + c_{+}$, with . Perhaps the most important of these trajectories are the ones that pass directly through the origin (e.g., ). Following our initial logic, if the system is going slower than this for any , then the optimal thing to do is to slam on the accelerator (). If it's going faster than the that we've solved for, then still the best thing to do is to brake; but inevitably the system will overshoot the origin and have to come back. We can summarize this policy with:
Candidate optimal (bang-bang) policy for the minimum-time double integrator problem.
We can illustrate some of the optimal solution trajectories:
Solution trajectories of system using the optimal policy
And for completeness, we can compute the optimal time to the goal by solving for the amount of time required to reach the switching surface plus the amount of time spent moving along the switching surface to the goal. With a little algebra, you will find that the time to the goal, , is given by
which is plotted here:▶ Embedded content: https://underactuated.mit.edu/data/double_integrator_mintime_cost_to_go.html
Time to the origin using the bang-bang policy
Notice that the "time-to-the-origin function" is continuous over state (though not smooth), even though the policy is discontinuous.
Additive cost
As we begin to develop theoretical and algorithmic tools for optimal control, we will see that some formulations are much easier to deal with than others. One important example is the dramatic simplification that can come from formulating objective functions using additive cost, because they often yield recursive solutions. In the additive cost formulation, the long-term objective for a trajectory can be written as
The "quadratic cost" formulation we considered in the double integrator example above is clearly written as an additive cost. At first glance, our "minimum-time" formulation doesn't appear to be of this form, but we actually can write it as an additive cost problem using an infinite horizon and the instantaneous cost
We will examine a number of approaches to solving optimal control problems throughout the next few chapters. For the remainder of this chapter, we will focus on additive-cost problems and their solution via dynamic programming.
Optimal control as graph search
For systems with continuous states and continuous actions, dynamic programming is a set of theoretical ideas surrounding additive-cost optimal control problems. For systems with a finite, discrete set of states and a finite, discrete set of actions, dynamic programming also represents a set of very efficient numerical algorithms which can compute optimal feedback controllers. Many of you will have seen it introduced before as a tool for graph search.
Imagine you have a directed graph with states (or nodes) ${s_1,s_2,...} \in S$ and "actions" associated with edges labeled as ${a_1,a_2,...} \in A$, as in the following trivial example:
A simple directed graph.
Let us also assume that each edge has an associate weight or cost, using to denote the cost of being in state and taking action . Furthermore we will denote the transition "dynamics" using
There are many algorithms for finding (or approximating) the optimal path from a start to a goal on directed graphs. In dynamic programming, the key insight is that we can find the shortest path from every node by solving recursively for the optimal cost-to-go (the cost that will be accumulated when running the optimal controller), which we'll denote , from every node to the goal. One such algorithm starts by initializing an estimate for all , then proceeds with an iterative algorithm which sets \begin{equation} \forall i \quad \hat{J}^(s_i) \Leftarrow \min_{a \in A} \left[ \ell(s_i,a) + \hat{J}^\left({f(s_i,a)}\right) \right]. \label{eq:value_update} \end{equation} This notation assumes that the update and cost are defined for every state-action pair; we can add self transitions at each state for any missing actions which have zero cost for the goal state and sufficiently high cost anywhere else. In software, can be represented as a vector with dimension equal to the number of discrete states, and equation \eqref{eq:value_update} gives us an update for the entire vector. This algorithm, appropriately known as value iteration, is guaranteed to converge to the optimal cost-to-go up to a constant factor, [3], and in practice does so rapidly. Typically the update is done in batch -- e.g. the estimate is updated for all at once -- but the asynchronous version where states are updated one at a time is also known to converge, so long as every state is eventually updated infinitely often.
Value iteration is an amazingly simple algorithm, but it accomplishes something quite amazing: it efficiently computes the long-term cost of an optimal policy from every state by iteratively evaluating the one-step cost. If we know the optimal cost-to-go, then it's easy to extract the optimal policy, : \begin{equation} \pi^(s_i) = \argmin_a \left[ \ell(s_i,a) + J^\left( f(s_i,a) \right) \right]. \label{eq:policy_update} \end{equation} It's a simple algorithm, but playing with an example can help our intuition.
Example: Grid World
Imagine a robot living in a grid (finite state) world [4]. The robot wants to get to the goal location, but has to negotiate cells with obstacles (denoted by the red pit in the animation below). The robot's actions are to move up, down, left, right, or do nothing. Moving diagonally (e.g. both up and right) in a single step is allowed.
▶ Embedded content: https://underactuated.mit.edu/data/grid_world.html?height=350px
The grid-world minimum-time problem. The goal state has a cost of zero, the obstacles have a cost of 10, and every other state has a cost of 1. The first frame shows the one-step cost, and the next frames show repeated applications of the value iteration update \eqref{eq:value_update} -- until convergence.
As always, I encourage you to run the notebook and play with the code yourself:
Example: Dynamic Programming for the Double Integrator
You can run value iteration for the double integrator (using barycentric interpolation to discretize the continuous state space, as we'll describe below) in Drake using:
Please do take some time to try different cost functions by editing the code yourself.
Let's take a minute to appreciate how amazing this is. Our solution to finding the optimal controller for the double integrator wasn't all that hard, but it required some mechanical intuition and solutions to differential equations. The resulting policy was non-trivial -- bang-bang control with a parabolic switching surface. The value iteration algorithm doesn't use any of this directly -- it's a simple algorithm for graph search. But remarkably, it can generate effectively the same policy with just a few moments of computation.
It's important to note that there are some differences between the computed policy and the optimal policy that we derived, due to discretization errors. We will ask you to explore these in the exercises.
The real value of this numerical solution, however, is unlike our analytical solution for the double integrator, we can apply this same algorithm to any number of dynamical systems virtually without modification. Let's apply it now to the simple pendulum, which was intractable analytically.
Example: Dynamic Programming for the Simple Pendulum
You can run value iteration for the simple pendulum (again using barycentric interpolation) in Drake using:
Again, you can easily try different cost functions by editing the code yourself.
Continuous dynamic programming
I find the graph search algorithm extremely satisfying as a first step, but also become quickly frustrated by the limitations of the discretization required to use it. In many cases, we can do better; coming up with algorithms which work more natively on continuous dynamical systems. We'll explore those extensions in this section.
The Hamilton-Jacobi-Bellman Equation
It's important to understand that the value iteration equations, equations (\ref{eq:value_update}) and (\ref{eq:policy_update}), are more than just an algorithm. They are also sufficient conditions for optimality: if we can produce a and which satisfy these equations, then must be an optimal controller. There are an analogous set of conditions for the continuous systems. For a system and an infinite-horizon additive cost we have: \begin{gather} 0 = \min_\bu \left[ \ell(\bx,\bu) + \pd{J^}{\bx}f(\bx,\bu) \right], \label{eq:HJB} \ \pi^(\bx) = \argmin_\bu \left[ \ell(\bx,\bu) + \pd{J^*}{\bx}f(\bx,\bu) \right]. \end{gather} Equation \ref{eq:HJB} is known as the Hamilton-Jacobi-Bellman (HJB) equation.
Technically, a Hamilton-Jacobi equation is a PDE whose time derivative depends on the first-order partial derivatives over state, which we get in the finite-time deriviation; Eq \ref{eq:HJB} is the steady-state solution of the Hamilton-Jacobi equation.
[5] gives an informal derivation of these equations as the limit of a discrete-time approximation of the dynamics, and also gives the famous "sufficiency theorem". The treatment in [5] is for the finite-horizon case; I have modified it to one particular form of an infinite-horizon case here.
Theorem: HJB Sufficiency Theorem (stated informally)
Consider a system and an infinite-horizon additive cost , with and continuous functions, and a strictly-positive-definite function that obtains zero only at a unique state . Suppose is a solution to the HJB equation: is continuously differentiable in and satisfies
Further assume that is positive definite and that is the minimizer for all . Then, under some technical conditions on the existence and boundedness of solutions, we have that $J(\bx) - J(\bx^*)$ is the optimal cost-to-go and is an optimal policy. Here is a more formal version from a personal communication with Sasha Megretski.Given an open subset , with a selected element , a subset , continuous functions , , continuously differentiable function , and a function , such that
- is strictly positive definite, in the sense that for every sequence of vectors , () such that ;
- the function , defined by \begin{equation}\label{e0} g_V(x,u)=g(x,u)+\frac{dV(x)}{dx}f(x,u),\end{equation} is non-negative,
and achieves zero value whenever ; 3. for every , the system of equations \begin{equation}\label{e1} \dot x(t)=f(x(t),u(t)),
x(0)=x_0\left(\text{i.e.,}~ x(t)=x_0+\int_0^tf(x(\tau),u(\tau)d\tau\right)\end{equation} \begin{equation}\label{e2} u(t)=\mu(x(t)),\end{equation} has at least one piecewise continuous solution , .Then, for every , the functional
defined on the set of all piecewise continuous pairs satisfying (\ref{e1}), achieves its minimal value of at every piecewise continuous solution of (\ref{e1}), (\ref{e2}).Proof. First, observe that, for all piecewise continuous satisfying (\ref{e1}),
- due to (\ref{e0}), \begin{equation}\label{e3}
code\int_0^Tg(x(t),u(t))dt=V(x_0)-V(x(T))+\int_0^Tg_V(x(t),u(t))dt; \end{equation}
- whenever , there exists a sequece of positive numbers , , , such that , which, according to assumption (a), implies as .
In particular, for a piecewise continuous solution of (\ref{e1}), satisfying, in addition, equation (\ref{e2}), condition (I) means
Since the upper bound does not depend on , and is non-negative, we conclude thatTherefore observation (**) applies, and, for the corresponding , \begin{align*} J(x,u)&=\int_0^\infty g(x(t),u(t))dt=\lim_{k\to\infty}\int_0^{T_k}g(x(t),u(t))dt \&= \lim_{k\to\infty}V(x_0)-V(x(T_k))=V(x_0)-V(x^).\end{align} Moreover, since is non-negative, the inequality $V(x_0)\ge V(x^)$ must hold for every . To finish the proof, for an arbitrary piecewise continuous solution of (\ref{e1}), equation (\ref{e3}), together with non-negativity of , impliesWhen , applying this to , where are described in observation (II), and taking the limit as (and ) yields $J(x,u)\ge V(x_0)-V(x^)$.
It is possible to prove sufficiency under different assumptions, too. The particular assumptions here were chosen to ensure that $J(\bx(0)) < \infty$ implies that . As Sasha says, "without something like this, all sorts of counter-examples emerge."
As a tool for verifying optimality, the HJB equations are actually surprisingly easy to work with: we can verify optimality for an infinite-horizon objective without doing any integration; we simply have to check a derivative condition on the optimal cost-to-go function . Let's see this play out on the double integrator example.
Example: HJB for the Double Integrator
Consider the problem of regulating the double integrator (this time without input limits) to the origin using a quadratic cost:
I claim (without derivation) that the optimal controller for this objective isTo convince you that this is indeed optimal, I have produced the following cost-to-go function:Taking \begin{gather*} \pd{J}{q} = 2\sqrt{3} q + 2\dot{q}, \qquad \pd{J}{\dot{q}} = 2q + 2\sqrt{3}\dot{q}, \end{gather*} we can write \begin{align*} \ell(\bx,\bu) + \pd{J}{\bx}f(\bx,\bu) &= q^2 + \dot{q}^2 + u^2 + (2\sqrt{3} q + 2\dot{q}) \dot{q} + (2q + 2\sqrt{3}\dot{q}) u \end{align*} This is a convex quadratic function in , so we can find the minimum with respect to by finding where the gradient with respect to evaluates to zero.
Setting this equal to $0$ and solving for yields:thereby confirming that our policy is in fact the minimizer. Substituting back into the HJB reveals that the right side does in fact simplify to zero. I hope you are convinced!
Note that evaluating the HJB for the time-to-go of the minimum-time problem for the double integrator will also reveal that the HJB is satisfied wherever that gradient is well-defined. This is certainly mounting evidence in support of our bang-bang policy being optimal, but since is not defined everywhere, it does not actually satisfy the requirements of the sufficiency theorem as stated above. Since cusps are commonplace in optimal value functions, one could say that the assumption in the sufficiency theorem that is defined everywhere makes our current statement very weak.
Solving for the minimizing control
We still face a few barriers to actually using the HJB in an algorithm. The first barrier is the minimization over . When the action set was discrete, as in the graph search version, we could evaluate the one-step cost plus cost-to-go for every possible action, and then simply take the best. For continuous action spaces, in general we cannot rely on the strategy of evaluating a finite number of possible 's to find the minimizer.
All is not lost. In the quadratic cost double integrator example above, we were able to solve explicitly for the minimizing in terms of the cost-to-go. It turns out that this strategy will actually work for a number of the problems we're interested in, even when the system (which we are given) or cost function (which we are free to pick, but which should be expressive) gets more complicated.
Recall that I've already tried to convince you that a majority of the systems of interest are control affine, e.g. I can write
Exploiting the ability to solve for the optimal action in closed form is also nice for generating benchmark problems for numerical optimal control, as it can be used for "converse optimal control" [6].
Example: Converse optimal control for a cubic polynomial
Consider a one-dimensional system of the form $\dot{x} = f_1(x) + xu,$ and the running cost function The optimal policy is leading to the HJB
Choosing , we find that this is the cost-to-go when and
What happens in the case where our system is not control affine or if we really do need to specify an instantaneous cost function on that is not simply quadratic? If the goal is to produce an iterative algorithm, like value iteration, then one common approach is to make a (positive-definite) quadratic approximation in of the HJB, and updating that approximation on every iteration of the algorithm. This broad approach is often referred to as differential dynamic programming (c.f. [7]).
Numerical solutions for
The other major barrier to using the HJB in a value iteration algorithm is that the estimated optimal cost-to-go function, , must somehow be represented with a finite set of numbers, but we don't yet know anything about the potential form it must take. In fact, knowing the time-to-goal solution for minimum-time problem with the double integrator, we see that this function might need to be non-smooth for even very simple dynamics and objectives.
One natural way to parameterize -- a scalar valued-function defined over the state space -- is to define the values on a mesh. This approach then admits algorithms with close ties to the relatively very advanced numerical methods used to solve other partial differential equations (PDEs), such as the ones that appear in finite element modeling or fluid dynamics. One important difference, however, is that our PDE lives in the dimension of the state space, while many of the mesh representations from the other disciplines are optimized for two or three dimensional space. Also, our PDE may have discontinuities (or at least discontinuous gradients) at locations in the state space which are not known apriori.
These days, the other natural choice is to represent using a neural network, or some similarly richly parameterized function approximator. This is common practice in reinforcement learning, which we will discuss more later in the book.
Value iteration with function approximation
If we approximate with a finitely-parameterized function , with parameter vector , then this immediately raises many important questions. If the true cost-to-go function does not live in the prescribed function class -- e.g., there does not exist an which satisfies the sufficiency conditions for all -- then we might instead write a cost function to match the optimality conditions as closely as possible. But our choice of cost function is important. Are errors in all states equally important? If we are balancing an Acrobot, presumably having an accurate cost-to-go in the vicinity of the upright condition is more important that some rarely visited state? Even if we can define a cost function that we like, then can we say anything about the convergence of our algorithm in this more general case?
Let us start by considering a least-squares approximation of the value iteration update.
Using the least squares solution in a value iteration update is sometimes referred to as fitted value iteration, where are some number of samples taken from the continuous space and for discrete-time systems the iterative approximate solution to \begin{gather*} J^(\bx_0) = \min_{u[\cdot]} \sum_{n=0}^\infty \ell(\bx[n],\bu[n]), \ \text{ s.t. } \bx[n+1] = f(\bx[n], \bu[n]), \bx[0] = \bx_0\end{gather} becomes \begin{gather} J^d_k = \min_\bu \left[ \ell(\bx_k,\bu) + \hat{J}^\alpha\left({f(\bx_k,\bu)}\right) \right], \ \balpha \Leftarrow \argmin\balpha \sum_k \left(\hat{J}^_\balpha(\bx_k) - J^d_k \right)^2. \label{eq:fitted_value_iteration} \end{gather} Since the desired values are dependent on the current guess of the cost-to-go, we will apply this value iteration algorithm iteratively until (hopefully) we achieve some numerical convergence.
Note that the update in \eqref{eq:fitted_value_iteration} is not quite the same as doing least-squares optimization of
Linear function approximators
In general, the convergence and accuracy guarantees for value iteration with generic function approximators are quite weak. But we do have some results for the special case of linear function approximators. A linear function approximator takes the form:
In finite state and action settings, fitted value iteration with linear function approximators is known to converge to the globally optimal [8]. [9] extends these results and treats the continuous state-action case. [10] gives the important generalization to actor-critic algorithms, which we will discuss soon. There can be some subtleties required for achieving convergence in practice. In the next chapter, we'll see why exponentially-discounted cost functions are often used help the value iterations converge even for infinite-horizon formulations.
Value iteration on a mesh
Imagine that we use a mesh to approximate the cost-to-go function over that state space with mesh points . We would like to perform the value iteration update: \begin{equation} \forall k, \hat{J}^(\bx_k) \Leftarrow \min_\bu \left[ \ell(\bx_k,\bu) + \hat{J}^\left({f(\bx_k,\bu)}\right) \right], \label{eq:mesh_value_iteration} \end{equation} but must deal with the fact that might not result in a next state that is directly at a mesh point. Most interpolation schemes for a mesh can be written as some weighted combination of the values at nearby mesh points, e.g.
Neural fitted value iteration
Of course the most popular function approximators today are based on neural networks. In these much more general approximators, we cannot solve the least-squares update \eqref{eq:fitted_value_iteration} exactly, but instead attempt to minimize the loss function: with a few steps of (stochastic) gradient descent on each iteration. In practice, we can use any of the standard optimizers (the examples below uses Adam[12] as the default).
What sort of neural architectures work best for value iteration in robotics? AlphaGo famously used convolutional networks[13]; here they could represent the state of the board as an image and the some notion of translational equivariance makes sense. But in "deep" reinforcement learning for robotics, when the input to the network is a state vector, then the standard choice is to use a simple multi-layered perceptron like the one I've used in the examples below. For rotational coordinates, instead of passing in directly, we typically pass in both and
When it comes to neural network software, I'll mostly use PyTorch throughout these notes. But for
small problems (with small neural nets and modest batch sizes during
training) like the ones we'll consider here, the cost of going back and
forth to PyTorch and especially the GPU outweighs most of the benefits.
I've also implemented a simple CPU-based
MultilayerPerceptron in Drake, which can be used
directly in the Systems framework, and will use it when it
makes sense. My goal is to provide examples of both approaches so that
you can pick and choose.
Example: Neural Fitted Value Iteration
Let us try reproducing our double-integrator value iteration examples using neural networks:
Example: Continuous Neural Fitted Value Iteration
There is nice work on continuous neural fitted value iteration in [14]. [15] has some of the most complete and convincing HJB solutions with neural networks that I have seen recently, and recommends a number of architectural and optimization training tweaks which could make a significant difference.
Continuous-time systems
For solutions to systems with continuous-time dynamics, I have to uncover one of the details that I've so far been hiding to keep the notation simpler. Let us consider a problem with a finite-horizon: \begin{gather*} \min_{\bu[\cdot]} \sum_{n=0}^N \ell(\bx[n],\bu[n]), \ \text{ s.t. } \bx[n+1] = f(\bx[n], \bu[n]), \bx[0] = \bx_0\end{gather*} When the horizon is finite, the optimal cost-to-go and the optimal policy, in general, can depend on time (if the post office closes at 5pm, then your actions at 4:55pm might be very different than your actions at 4pm).
The way that we compute this is by solving the time-varying cost-to-go function backwards in time: \begin{gather*}J^(\bx,N) = \min_\bu \ell(\bx, \bu) \ J^(\bx,n-1) = \min_\bu \left[ \ell(\bx, \bu) + J^(f(\bx,\bu), n) \right]. \end{gather} Even in the infinite-horizon setting, one can actually understand the convergence of the value iteration update as solving this time-varying cost-to-go backwards in time until it reaches a steady-state solution (the infinite-horizon solution). This is one way to see why value iteration only converges if the optimal cost-to-go is bounded.
Now let's consider the continuous-time version. Again, we have a time-varying cost-to-go, Now
Probably most visible and consistent campaign using numerical HJB solutions in applied control (at least in robotics) has come from Claire Tomlin's group at Berkeley. Their work leverages Ian Mitchell's Level Set Toolbox, which solves the Hamilton-Jacobi PDEs on a Cartesian mesh using the technique cartooned above, and even includes the minimum-time problem for the double integrator as a tutorial example[17].
Extensions
There are many many nice extensions to the basic formulations that we've presented so far. I'll try to list a few of the most important ones here. I've also had a number of students in this course explore very interesting extensions; for example [18] looked at imposing a low-rank structure on the (discrete-state) value function using ideas from matrix completion to obtain good estimates despite updating only a small fraction of the states.
Discounted and average cost formulations
Throughout this chapter, we have focused primarily on minimizing an infinite-horizon sum of running costs. Whenever you write an infinite sum (or integral), one should immediately question whether that sum converges to a finite value. For many control problems, it does -- for instance, if we set the cost to be zero at the goal and the controller can drive the system to the goal in finite time, or exponentially at a rate that is faster than cost is accrued. However, once we enter the realm of approximate optimal control, we can run into problems. For instance, if we form a discrete state and action approximation of the dynamics, it may not be possible for the discretized system to arrive exactly at the zero-cost goal.
A common way to protect oneself from this is to add an exponential discount factor to the integral cost. This is a natural choice since it preserves the recursive structure of the Bellman equation. In discrete time, it takes the form
A word of warning: this discount factor does change the optimal policy; and it is not without its pitfalls. We'll work out a specific case of the discounted cost for the LQR problem, and see that the discounted controller is exactly a controller which assumes that the plant is more stable than it actually is. It is possible to find an optimal controller for the discounted cost that results in an unstable controller.
A more robust alternative is to consider an average-cost formulations... (details coming soon!)
Stochastic control for finite MDPs
One of the most amazing features of the dynamic programming, additive cost approach to optimal control is the relative ease with which it extends to optimizing stochastic systems.
For discrete systems, we can generalize our dynamics on a graph by adding action-dependent transition probabilities to the edges. This new dynamical system is known as a Markov Decision Process (MDP), and we write the dynamics completely in terms of the transition probabilities
We will continue to develop a much more general toolkit for for stochastic and robust control later in the notes.
Stochastic interpretation of deterministic, continuous-state value iteration
There is a particularly nice observation to be made here. Let's assume that we have discrete control inputs and discrete-time dynamics, but a continuous state space. Recall the fitted value iteration on a mesh algorithm described above. In fact, the resulting update is exactly the same as if we treated the system as a discrete state MDP with representing the probability of transitioning to state ! This sheds some light on the impact of discretization on the solutions -- discretization error here will cause a sort of diffusion corresponding to the probability of spreading across neighboring nodes.
Linear Programming Dynamic Programming
For discrete MDPs, value iteration is a magical algorithm because it is simple, but known to converge to the global optimal, . However, other important algorithms are known; one of the most important is a solution approach using linear programming. This formulation provides an alternative view, but may also be more generalizable and even more efficient for some instances of the problem.
Recall the optimality conditions from Eq. \eqref{eq:value_update}. If we describe the cost-to-go function as a vector, , then these optimality conditions can be rewritten in vector form as \begin{equation} \bJ = \min_a \left[ {\bf \ell}(a) + \bT(a) \bJ \right], \label{eq:vector_stochastic_dp} \end{equation} where is the cost vector, and $T_{i,j}(a) = \Pr(s_j|s_i,a)$ is the transition probability matrix. Let us take as the vector of decision variables, and replace Eq. (\ref{eq:vector_stochastic_dp}) with the constraints: \begin{equation} \forall a, \bJ \le {\bf \ell}(a) + \bT(a) \bJ.\end{equation} Clearly, for finite , this is finite list of linear constraints, and for any vector satisfying these constraints we have (elementwise). Now write the linear program: \begin{gather*} \maximize_\bJ \quad \bc^T \bJ, \ \subjto \quad \forall a, \bJ \le {\bf \ell}(a) + \bT(a) \bJ, \end{gather*} where is any positive vector. The solution to this problem is .
Perhaps even more interesting is that this approach can be generalized to linear function approximators. Taking a vector form of my notation above, now we have a matrix of features with $\bPsi_{i,j} = \psi^T_j(\bx_i)$ and we can write the LP \begin{gather} \maximize_\balpha \quad \bc^T \bPsi \balpha, \ \subjto \quad \forall a, \bPsi \balpha \le {\bf \ell}(a) + \bT(a) \bPsi \balpha. \end{gather} This time the solution is not necessarily optimal, because $\bPsi \balpha^*$ only approximates , and the relative values of the elements of (called the "state-relevance weights") can determine the relative tightness of the approximation for different features [20].
Sums-of-Squares Dynamic Programming
There are some cases where the linear programming approach to dynamic programming can be extended to continuous states and actions, with strong guarantees. This approach follows naturally from our study of Lyapunov functions in an upcoming chapter, and builds on the computational tools we develop there. Feel free to skip ahead.
Exercises
Exercise 1 (Discounting and the Convergence of Value Iteration)
Let's consider the discrete time, state, and action version of value iteration: \begin{equation} \hat{J}^(s_i) \Leftarrow \min_{a \in A} \left[ \ell(s_i,a) + \hat{J}^\left({f(s_i,a)}\right) \right],\end{equation} which finds the optimal policy for the infinite horizon cost function
- If is the true optimal cost-to-go, show that any solution , where is any constant scalar, is a fixed point of this value iteration update.
- Is the controller still optimal, even if the estimated cost-to-go function is off by a constant factor?
Surprisingly, adding a discount factor can help with this. Consider the infinite-horizon discounted cost: $\sum_{n=0}^\infty \gamma^n \ell(s[n],a[n])$, where $0 < \gamma \le 1$ is the discount factor. The corresponding value iteration update is \begin{equation} \hat{J}^(s_i) \Leftarrow \min_{a \in A} \left[ \ell(s_i,a) + \gamma\hat{J}^\left({f(s_i,a)}\right) \right].\end{equation} For simplicity, assume that there exists a state that is a zero-cost fixed point under the optimal policy; e.g. and .
- Is still a fixed point of the value iteration update when ? Show your work.
Exercise 2 (Choosing a Cost Function)
Autonomous car moving at velocity on a straight road.
The figure above shows an autonomous car moving at constant velocity on a straight road. Let be the (longitudinal) position of the car along the road, its (transversal) distance from the centerline, and the angle between the centerline and the direction of motion. The only control action is the steering velocity , which is constrained in the interval (where and ). We describe the car dynamics with the simple kinematic model \begin{align*}\dot x &= v \cos \theta, \ \dot y &= v \sin \theta, \ \dot \theta &= u.\end{align*} Let $\bx = [x, y, \theta]^T$ be the state vector. To optimize the car trajectory we consider a quadratic objective function
where is a constant positive-semidefinite (hence symmetric) matrix and is a constant nonnegative scalar (note that is allowed here).
- Suppose our only goal is to keep the distance between the car and the centerline as small as possible, as fast as possible, without worrying about anything else. What would be your choice for and ?
- How would the behavior of the car change if you were to multiply the weights and from the previous point by an arbitrary positive coefficient ?
- The cost function from point (a) might easily lead to excessively sharp turns. Which entry of or would you increase to mitigate this issue?
- Country roads are more slippery on the sides than in the center. Is this class of objective functions (quadratic objectives) rich enough to include a penalty on sharp turns that increases with the distance of the car from the centerline?
- With this dynamics model and this objective function, would you ever choose a weight matrix which is strictly positive definite (independent of the task you want the car to accomplish)? Why?
Exercise 3 (Ill-Posed Optimal Control Problem)
In this exercise we will see how seemingly simple cost functions can give surprising results. Consider the single-integrator system $\dot x = u$ with initial state . We would like to find the control signal that minimizes the seemingly innocuous cost function
with finite. To this end, we consider a square-wave control parameterized by :
- What are the states and the inputs for which the running cost
is equal to zero?- Consider now two control signals and , with . Which one of the two incurs the lower cost ? (Hint: start by sketching how the system state evolves under these two control signals.)
- What happens to the cost when gets smaller and smaller? What does the optimal control signal look like? Could you implement it with a finite-bandwidth controller?
Exercise 4 (A Linear System with Quadratic Cost)
Consider the scalar control differential equation
and the infinite horizon cost functionAs we will see in the chapter on linear-quadratic regulation, the optimal cost-to-go for a problem of this kind assumes the form . It is not hard to see that this, in turn, implies that the optimal controller has the form $u^* = - K x$.
- Imagine that you plugged the expression in the HJB equations for this problem, you solved them for , and you got $S \leq 0$. Would this result ring any alarm bells? Explain your
answer. 2. Use the HJB sufficiency theorem to derive the optimal values of and . 3. Working with digital controllers, we typically have to sample the dynamics of our systems, and approximate them with discrete-time models. Let us introduce a time step and discretize the dynamics as
and the objective asOne of the following expressions is the correct cost-to-go for this discretized problem. Can you identify it without solving the discrete-time HJB equation? Explain your answer.
- with .
- with $S_h = 1 + 2h + 2 \sqrt{h^2 + h +1}$.
- with $S_h = 3 + 2h^2 + \sqrt{h^2 + h + 2}$.
Exercise 5 (Value Iteration for Minimum-Time Problems)
In this exercise we analyze the performance of the value-iteration algorithm, considering its application to the minimum time problem for the double integrator. , you will find everything you need for this analysis. Take the time to go through the notebook and understand the code in it, then answer the following questions.
- At the end of the notebook section "Performance of the Value-Iteration Policy", we plot the state trajectory of the double integrator in closed loop with the value-iteration policy, as well as the resulting control signal.
- Does the state-space trajectory follow the theoretically-optimal quadratic arcs we have seen in the example?
- Is the control policy we get from value iteration a bang-bang policy? In other words, does the control signal take values in the set exclusively?
- Explain in a couple of sentences, what is the reason for this behavior.
- In the "Value Iteration Algorithm" section of the notebook, increase the number of knot points on the and the axes to refine the state-space mesh used in the value iteration. Does this fix the issues you have seen in point (a)?
- In the final section of the notebook, implement the theoretically-optimal control policy from the example, and use the plots to verify that the closed-loop system behaves as expected.
Exercise 6 (Linear Program for Dynamic Programming)
In this exercise we solve the dynamic programming using a linear program, considering its application to the grid world. , you will write a linear program for solving the optimal cost-to-go in the grid world.
Exercise 7 (Continuous Fitted Value Iteration for Pendulum Swingup)
In this excercise we will implement value iteration for a continuous time system with continuous actions and states. We will achieve by training a neural network to approximate our value function. You will work exclusively in to implement the algorithms described in the Continuous Dynamic Programming section.
Exercise 8 (Ordering of the Value Iteration Updates)
The batched Bellman update used in batched value iteration is as follows:
The batched Bellman update consists of individual Bellman updates on each iteration of the algorithm. Throughout this problem, we use the following goal reaching cost: \begin{align*} l(s_i, a) = \left{ \begin{array}{lr} 0 & \text{if } s_i = s_5\ 1 & \text{else} \end{array} \right} \end{align*}
Suppose we represent our dynamics with a graph where the vertices represent the states and edges represent the available actions/state transitions. Calculate the batched value iteration tables until convergence for the following directed acyclic graph (DAG), and calculate the total number of individual Bellman updates. Note: You do not need to include the updates required to check convergence.
Suppose we are performing asynchronous value iteration with a hand-specified update order. Produce the update order for the above graph that minimizes the number of individual Bellman updates till convergence, and calculate the total number of individual updates. Note: You do not need to include the updates required to check convergence.
Generalize the update order in part (b) to arbitrary DAGs with a single start node and single goal node by defining the set of states to be updated at iteration in terms of the set of states that were updated at iteration . Note: Describe the update sequence iteratively in terms of sets of states instead of individual states (as defined by asynchronous VI) because this simplifies the description of the update sequence.
Suppose we extend the class of dynamics graphs in part c) to allow cycles. Take an instance of this class of graphs and apply value iteration to get an optimal value function. Can an optimal policy associated with this value function contain a cycle? Explain your answer.
(Optional, ungraded) Suppose we are uniformly sampling states under asynchronous value iteration (updating each one at a time in a random order). What is the probability that asynchronous value iteration converges with less total Bellman updates than batched value iteration?
References
Dimitri P. Bertsekas, "Dynamic Programming and Optimal Control", Athena Scientific , 2000.
Richard S. Sutton and Andrew G. Barto, "Reinforcement Learning: An Introduction", MIT Press , 2018.
Dimitri P. Bertsekas and John N. Tsitsiklis, "Neuro-Dynamic Programming", Athena Scientific , October, 1996.
Richard S. Sutton and Andrew G. Barto, "Reinforcement Learning: An Introduction", MIT Press , 1998.
Dimitri P. Bertsekas, "Dynamic Programming & Optimal Control", Athena Scientific , vol. I and II, May 1, 2005.
John Doyle and James A Primbs and Benjamin Shapiro and Vesna Nevistic, "Nonlinear games: examples and counterexamples", Proceedings of 35th IEEE Conference on Decision and Control , vol. 4, pp. 3915--3920, 1996.
David H. Jacobson and David Q. Mayne, "Differential Dynamic Programming", American Elsevier Publishing Company, Inc. , 1970.
John Tsitsiklis and Ben Van Roy, "An Analysis of Temporal-Difference Learning with Function Approximation", IEEE Transactions on Automatic Control, vol. 42, no. 5, pp. 674-690, May, 1997.
Rémi Munos and Csaba Szepesvári, "Finite-Time Bounds for Fitted Value Iteration", J. Mach. Learn. Res., vol. 9, pp. 815--857, June, 2008.
V. R. Konda and J. N. Tsitsiklis, "Actor-Critic Algorithms", SIAM Journal on Control and Optimization, vol. 42, no. 4, pp. 1143-1166, 2003.
Remi Munos and Andrew Moore, "Barycentric Interpolators for Continuous Space and Time Reinforcement Learning", Advances in Neural Information Processing Systems , vol. 11, pp. 1024--1030, 1998.
Diederik P Kingma and Jimmy Ba, "Adam: A method for stochastic optimization", arXiv preprint arXiv:1412.6980, 2014.
David Silver and Aja Huang and Chris J Maddison and Arthur Guez and Laurent Sifre and George Van Den Driessche and Julian Schrittwieser and Ioannis Antonoglou and Veda Panneershelvam and Marc Lanctot and others, "Mastering the game of Go with deep neural networks and tree search", nature, vol. 529, no. 7587, pp. 484--489, 2016.
Michael Lutter and Shie Mannor and Jan Peters and Dieter Fox and Animesh Garg, "Value Iteration in Continuous Actions, States and Time", International Conference on Machine Learning , pp. 7224--7234, 2021.
Somil Bansal and Claire J Tomlin, "Deepreach: A deep learning approach to high-dimensional reachability", 2021 IEEE International Conference on Robotics and Automation (ICRA) , pp. 1817--1824, 2021.
Stanley Osher and Ronald Fedkiw, "Level Set Methods and Dynamic Implicit Surfaces", Springer , 2003.
Ian M. Mitchell and Jeremy A. Templeton, "A Toolbox of Hamilton-Jacobi Solvers for Analysis of Nondeterministic Continuous and Hybrid Systems", Proceedings of Hybrid Systems Computation and Control , March, 2005.
Yuzhe Yang and Guo Zhang and Zhi Xu and Dina Katabi, "Harnessing Structures for Value-Based Planning and Reinforcement Learning", International Conference on Learning Representations , 2020.
Doya and K., "Reinforcement Learning in Continuous Time and Space", Neural Computation, vol. 12, no. 1, pp. 219-245, January, 2000.
Daniela Pucci de Farias, "The Linear Programming Approach to Approximate Dynamic Programming: Theory and Application", PhD thesis, Stanford University, June, 2002.