Trajectory Optimization: iLQR, DDP & Sampling Planners
Iterative linearization, differential dynamic programming, CEM and MPPI.
When the dynamics are nonlinear the Riccati recursion no longer applies, but it can be applied again and again around a guess. This lesson derives the backward pass of differential dynamic programming and of its Gauss–Newton cousin iLQR, explains the regularization and line search that make them reliable, then derives the two sampling planners that dominate learned-model RL, the cross-entropy method and MPPI, from first principles, and ends with when to use which.
What you’ll learn
- Contrast single shooting, multiple shooting and collocation, and derive the adjoint gradient of single shooting and its conditioning.
- Derive the DDP backward pass from a second-order expansion of the Q-function, obtain iLQR as its Gauss–Newton approximation, and prove that both solve linear–quadratic problems in one iteration.
- Explain Levenberg–Marquardt regularization and the line search on the feedforward term.
- Derive CEM's update as maximum likelihood on elite plans and MPPI's as the mean of a KL-regularized optimal distribution, and compare sampling and gradient planners on learned models.
Shooting, collocation and the gradient through time
Trajectory optimization solves the -step problem from one state: minimize subject to . The methods differ in what they treat as unknowns.
| Method | Unknowns | Dynamics enforced by | Strength | Weakness |
|---|---|---|---|---|
| Single shooting | Controls | Simulation | Few variables; every iterate is a feasible trajectory | Long products of Jacobians: ill-conditioned for long horizons or unstable dynamics |
| Multiple shooting | Controls, plus the state at the start of each segment | Simulation within segments, equality constraints between them | Breaks up the long products | A constrained problem |
| Direct collocation | All states and controls | Equality constraints at every step | Well conditioned; can start from infeasible guesses; sparse | A large nonlinear program, solved by SQP or interior-point methods |
| DDP, iLQR | Controls, through local feedback laws | Simulation in the forward pass | Riccati-like backward pass, cost linear in | Needs derivatives; local |
Define , the sensitivity of the remaining cost to the state at step . The chain rule gives a backward recursion, the discrete-time adjoint (or costate) equation:
A control affects the cost at its own step and, through , everything after it:
This is backpropagation through time: one forward simulation and one backward sweep. Unrolling it exposes the conditioning problem. The effect of on is the product of state Jacobians and one control Jacobian; for linear dynamics it is , which grows like when the system is unstable, so early controls receive huge gradients and late ones tiny gradients.
For and , by what factor does exceed ?
Show the answer
38.4
, while . A gradient step that suits the last control overshoots the first by a factor of 38, and at the factor is about . Collocation avoids these products by making every state a variable; DDP avoids them by propagating local feedback laws instead of raw sensitivities.
DDP and iLQR: Riccati around a trajectory
Differential dynamic programming (DDP; Mayne, 1966; Jacobson & Mayne, 1970) improves a nominal trajectory by doing dynamic programming on a local quadratic model of the problem around it. Write and for deviations from the nominal, subscripts for derivatives evaluated on it, and for the cost-to-go one step later.
Expand to second order. Its first derivatives are
and its second derivatives, where the dot contracts with a second-derivative tensor of :
Minimize the quadratic model over , assuming . The minimizer is affine in : a feedforward term plus a feedback gain.
Substitute back to obtain the quadratic model of the cost-to-go at step and the decrease it predicts. Start from and at the horizon and sweep backward:
Forward pass. Simulate the true dynamics with the new controls, using the feedback gains to stay near the nominal and a step size on the feedforward term only:
iLQR (Li & Todorov, 2004) drops the three tensor terms . That is a Gauss–Newton approximation: each iteration needs only the Jacobians of the dynamics, and stays positive definite whenever and . DDP keeps the tensor terms and converges like Newton's method near a nondegenerate minimum; iLQR converges fast when the dropped terms are small, as with nearly linear dynamics, and can be slower otherwise. With the forward pass reproduces the nominal trajectory exactly, so a small enough always gives a small change.
With linear dynamics every second derivative of vanishes, so the tensor terms are zero and DDP is iLQR. A quadratic equals its second-order expansion, so is the exact cost of the deviation problem, and minimizing it exactly over is exact dynamic programming in .
For the cost we have , and ; writing , the curvature update becomes twice the Riccati recursion, and is minus the LQR gain:
The forward pass with applies the exact optimal affine policy of the deviation problem to the true linear dynamics, so the resulting trajectory is optimal whatever the nominal was.
import numpy as np
def ilqr_backward(fx, fu, cx, cu, cxx, cuu, cux, Vx, Vxx, mu=0.0):
"""iLQR backward pass along a nominal trajectory of length H. fx[t], fu[t]: dynamics Jacobians;
c*: cost derivatives; Vx, Vxx: terminal-cost gradient and Hessian; mu: regularization."""
H = len(fx); k = [None] * H; K = [None] * H; dV = 0.0
for t in reversed(range(H)):
Qx = cx[t] + fx[t].T @ Vx
Qu = cu[t] + fu[t].T @ Vx
Qxx = cxx[t] + fx[t].T @ Vxx @ fx[t]
Quu = cuu[t] + fu[t].T @ Vxx @ fu[t]
Qux = cux[t] + fu[t].T @ Vxx @ fx[t]
Vreg = Vxx + mu * np.eye(Vxx.shape[0]) # penalize deviations of the next state
Quu_reg = cuu[t] + fu[t].T @ Vreg @ fu[t]
k[t] = -np.linalg.solve(Quu_reg, Qu)
K[t] = -np.linalg.solve(Quu_reg, cux[t] + fu[t].T @ Vreg @ fx[t])
Vx = Qx + K[t].T @ Quu @ k[t] + K[t].T @ Qu + Qux.T @ k[t]
Vxx = Qxx + K[t].T @ Quu @ K[t] + K[t].T @ Qux + Qux.T @ K[t]
Vxx = 0.5 * (Vxx + Vxx.T) # keep it symmetric
dV += k[t] @ Qu + 0.5 * k[t] @ Quu @ k[t] # predicted change for alpha = 1
return k, K, dVThe updates of and are written in a form that is exact for any and , so they can use the unregularized terms while the gains use the regularized ones, as in Tassa, Erez & Todorov (2012). A forward pass then tries and accepts the first step whose actual decrease is a reasonable fraction of the predicted .
Regularization and line search (Tassa, Erez & Todorov, 2012). Far from a minimum the quadratic model can be badly wrong, and in DDP can be indefinite. Adding to the next state's curvature penalizes deviations from the nominal states: a large gives small, cautious steps and the full step. As in Levenberg–Marquardt, is raised when a step fails and lowered when it succeeds. With these safeguards they ran iterative LQG online, as model predictive control, to synthesize behaviors such as a simulated humanoid getting up from the ground.
Sampling planners as stochastic optimization
Sampling planners treat the plan as a random variable and improve its distribution, using only simulated costs. The cross-entropy method began as a tool for estimating the probabilities of rare events (Rubinstein, 1997) and became a general optimizer (de Boer et al., 2005).
Sample plans from , simulate each, and keep the set of the cheapest. The refit maximizes the elites' likelihood:
For a diagonal Gaussian the maximizer is the elites' mean and their standard deviation in each coordinate. Equivalently it minimizes , where is the empirical distribution of the elites: the Gaussian moves to cover the best region found so far. Practical versions smooth the update, , and keep above a floor, because otherwise the spread can collapse before a good plan is found.
MPPI (model predictive path integral control; Williams et al., 2017) replaces CEM's hard cut by soft weights, and the weights come out of an optimization problem.
Let be the current sampling distribution of plans and a plan's simulated cost. Choose the distribution that trades low expected cost against staying close to , with a temperature :
Define with normalizer . For every the objective rewrites as follows, so is its unique minimizer (the free-energy, or Gibbs, variational principle):
is not Gaussian. Project it onto Gaussians with 's fixed covariance by minimizing over ; the minimizer matches the mean, .
Estimate that mean from samples of by self-normalized importance sampling, since . Subtracting the smallest cost leaves the weights unchanged and avoids numerical underflow:
The temperature interpolates between extremes: as the update jumps to the single best sample, like CEM with one elite; as it averages all samples and learns nothing. The same softmax over costs appears in maximum-entropy RL (Control as Inference).
import numpy as np
def mppi_update(mu, sigma, rollout_cost, lam=1.0, n=512, rng=None):
"""mu: (H, m) current plan; rollout_cost(U) -> total simulated cost of the plan U."""
rng = rng or np.random.default_rng()
eps = sigma * rng.standard_normal((n, *mu.shape)) # perturbations of the current plan
S = np.array([rollout_cost(mu + e) for e in eps]) # cost of each perturbed plan
w = np.exp(-(S - S.min()) / lam) # soft-min weights
w /= w.sum()
return mu + np.tensordot(w, eps, axes=1) # weighted average of the perturbed plansOne MPPI update. In MPC it is repeated a few times per real step, the first control of the result is applied, and the plan is shifted by one step to warm-start the next update.
Three sampled plans have simulated costs 1, 2 and 3, and . What weight does MPPI give the cheapest plan?
Show the answer
0.665
, and the other two get 0.245 and 0.090. With the cheapest plan would take almost all the weight; with the three weights would be nearly equal.
Improvements target the sample budget. iCEM (Pinneri et al., 2020) samples temporally correlated, "colored" action noise whose power spectrum falls off as , carries a fraction of the elites over to the next iteration and the next time step, and executes the best plan seen rather than the mean; it reported needing 2.7–22 times fewer samples than CEM while performing 1.2–10 times better on high-dimensional control problems. TD-MPC's planner is MPPI-like: it weights its top plans by exponentiated returns and mixes in plans proposed by a learned policy (Planning with Learned Values: TD-MPC).
Which planner, with which model?
Gradient-based optimizers (shooting with backpropagation, iLQR, DDP) use derivatives. They converge in few iterations and scale to long horizons and many controls, but they need a smooth, differentiable model, they find local minima, and with a learned model they follow its derivatives, which can be wrong even where its predictions are right.
Sampling optimizers (random shooting, CEM, MPPI) use only simulations. They parallelize on GPUs, cope with non-smooth costs and contacts, and treat the model as a black box, but the samples they need grow with the plan's dimension , and they too exploit errors in the model's predicted costs. Model-based RL with neural-network models has leaned on sampling: PlaNet planned with CEM in its latent space (horizon 12, 10 iterations, 1,000 candidates, refitting to the best 100), PETS with CEM through an ensemble, and TD-MPC with MPPI.
Guarantees, and open problems
What is known is mostly local. DDP converges like Newton's method near a nondegenerate local minimum and iLQR like Gauss–Newton; neither guarantees a global optimum on nonconvex problems. CEM has no general global guarantee, and with small populations its spread can collapse before it reaches a good plan, hence the floors on used in practice. MPPI's importance weights degenerate when is small or the sampling distribution is far from : the effective sample size falls toward 1, and the update becomes as noisy as a single sample. (For the three weights of the example above it is about 1.96 out of 3.)
Key takeaways
- Single shooting optimizes controls by simulation and backpropagation through time, whose sensitivities multiply Jacobians and become ill-conditioned for long or unstable horizons; collocation makes the states variables and enforces the dynamics as constraints.
- DDP's backward pass is the Riccati recursion applied to a second-order model of the Q-function around a nominal trajectory, with feedforward and gain ; iLQR drops the dynamics' second derivatives (Gauss–Newton), and both solve LQ problems in one iteration.
- Regularizing the next state's curvature and line-searching only the feedforward term make the methods reliable far from a minimum; reproduces the nominal trajectory.
- CEM refits a Gaussian to elite plans by maximum likelihood; MPPI computes the mean of the KL-regularized optimal distribution with importance weights, a soft version of the same idea.
- Gradient planners are efficient but local and follow a learned model's derivatives; sampling planners are robust and parallel but scale with the plan's dimension; neither can fix a wrong model.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
What does iLQR drop from DDP, and with what consequence?
- The second derivatives of the cost; it becomes a first-order method
- The feedback gains; it becomes open-loop
- The second derivatives of the dynamics; it becomes a Gauss–Newton method that needs only Jacobians of and coincides with DDP for linear dynamics
- The forward pass; it never simulates the dynamics
Show the answer
C. The second derivatives of the dynamics; it becomes a Gauss–Newton method that needs only Jacobians of and coincides with DDP for linear dynamics
iLQR keeps the cost's curvature and the gains, and drops only the terms . For linear dynamics those terms are zero anyway, so the two methods agree and solve LQ problems in one iteration.
In the forward pass , what trajectory does produce?
- Exactly the nominal trajectory: the states never deviate, so the feedback term stays zero
- The optimal trajectory
- A trajectory with zero control
- A trajectory that depends on the regularization
Show the answer
A. Exactly the nominal trajectory: the states never deviate, so the feedback term stays zero
With the first control is , so , and by induction every deviation is zero. The line search therefore moves continuously from the old trajectory toward the new one.
What does MPPI's update become as its temperature ?
- The average of all sampled plans
- The current mean, unchanged
- A gradient step on the expected cost
- The single cheapest sampled plan
Show the answer
D. The single cheapest sampled plan
The weights are , normalized: as every plan but the cheapest gets weight 0, like CEM with a single elite. As the weights become equal and the update is a plain average.
Why does CEM set its new mean and spread to those of the elite plans?
- It is the gradient of the expected cost
- It is the maximum-likelihood Gaussian for the elites, which moves the sampling distribution to cover the best region found so far
- It minimizes the worst-case cost
- It is required for the plans to be dynamically feasible
Show the answer
B. It is the maximum-likelihood Gaussian for the elites, which moves the sampling distribution to cover the best region found so far
Refitting maximizes the elites' likelihood, equivalently minimizes the KL divergence from their empirical distribution to the Gaussian. Repeating it concentrates the samples where cheap plans are.
Further reading
- D. H. Jacobson & D. Q. Mayne, Differential Dynamic Programming (American Elsevier, 1970).
- W. Li & E. Todorov, "Iterative linear quadratic regulator design for nonlinear biological movement systems," ICINCO (2004).
- Y. Tassa, T. Erez & E. Todorov, "Synthesis and stabilization of complex behaviors through online trajectory optimization," IROS (2012).
- P.-T. de Boer, D. P. Kroese, S. Mannor & R. Y. Rubinstein, "A tutorial on the cross-entropy method," Annals of Operations Research 134, 19–67 (2005).
- G. Williams, N. Wagener, B. Goldfain, P. Drews, J. M. Rehg, B. Boots & E. A. Theodorou, "Information theoretic MPC for model-based reinforcement learning," ICRA (2017).