Differentiable Planning

Michael BrenndoerferJuly 8, 202673 min read

Part of World Models Handbook

Explains how gradients flow through world-model rollouts, from adjoint backpropagation to action optimization, terminal values, and long-horizon stability.

Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.

Article links

Make inline references clickable

Differentiable Planning

In Sampling-Based Planning and Model Predictive Control, we planned by proposing action sequences, rolling each one through the world model, scoring the result, and keeping the best. Derivative-free population methods remain usable when model gradients are unavailable or unreliable, but their performance depends on the proposal, objective, and evaluation budget. Random shooting with a twenty-step horizon and six action dimensions searches a 120-dimensional space. If each added coordinate has conditional probability at most a fixed q<1q<1 of landing in its acceptable subset under the proposal, then one sample's success probability is at most qdq^d after dd such coordinates. Independent uniform coordinates with a fixed acceptable range fraction qq are one example. This is the relevant curse of dimensionality, not a guarantee that every high-dimensional planning problem is hard.

The derivative-free random-shooting planner used in the previous chapter does not compute or use an action-space derivative telling it which infinitesimal change lowers cost. Random shooting relies on sampled candidates, while CEM uses elite-sample statistics to concentrate its proposal on regions found promising. If the proposal assigns probability pp to near-good plans, NN independent candidates contain at least one with probability 1−(1−p)N1-(1-p)^N. When adding coordinates makes pp shrink exponentially, maintaining the same success probability requires exponentially more candidates. On smooth problems with reliable gradients, ignoring those derivatives can therefore require many more model evaluations to locate a useful update. The advantage is conditional: unstable, biased, or locally misleading gradients can erase it.

Differentiable planning asks a different question. Instead of "which of these candidates is best?", it asks "in which local direction should I change this candidate?" If the rollout and cost are differentiable along the executed trajectory, reverse-mode automatic differentiation gives the entire action-gradient vector at a small constant multiple of the cost of one objective evaluation, independent of the number of action coordinates. For cost minimization, whenever ∇aJ≠0\nabla_a J\neq0, the negative gradient is a local descent direction. With a suitable step size and constraint handling, any nonzero feasible negative-gradient or projected-gradient direction reduces cost locally and updates the action blocks with nonzero components. This direct sensitivity calculation can replace or complement population sampling.

The recipe is short enough to fit in a paragraph. Start with a guess for the action sequence. Roll the model forward from the current state, recording every intermediate state. Evaluate the cost of that trajectory. Backpropagate the cost through the rollout to obtain ∂J/∂at\partial J / \partial a_t for every time step tt. Take a gradient step on the action sequence. Repeat until a declared stopping rule or computation budget is met, such as a maximum iteration count paired with an objective-improvement tolerance and patience window. Then apply the first action and replan from the new state. Planning has become optimization.

This reframing has strict prerequisites and important failure modes:

  • The action-to-objective computation must provide a usable action derivative or derivative estimator. Ordinary reverse mode needs usable local pullbacks along the executed path. Many neural latent-dynamics models for continuous control use differentiable operations on this path, while stochastic objectives can instead use a valid derivative estimator. Hard contact and friction switches can introduce kinks or jumps. Discrete mode changes can also produce branch-dependent derivatives.
  • Decision-relevant objective terms on the differentiated action-to-objective path must contribute a usable action derivative or valid derivative estimator; separately handled terms need not. Quadratic tracking costs are differentiable, although their action signal can vanish or be poorly scaled. A hard indicator cost ("one if you miss the target") has a zero, and therefore uninformative, pathwise gradient away from its boundary; at the boundary it is generally nondifferentiable. A smooth surrogate can supply a pathwise gradient. For an expected cost under a suitable stochastic formulation, a score-function estimator can be valid under the regularity conditions developed later, though it often has high variance and may need variance reduction; if it is not usable, choose another valid sensitivity route. If differentiation through the hard term is bypassed, preserve its decision effect through a constraint, full-objective candidate evaluation, or an outer discrete or hybrid search.
  • The gradients must remain numerically usable across the planning horizon. A long rollout contains long Jacobian products. Those products can shrink, grow, remain bounded, oscillate, or show transient amplification; strong contraction, expansion, and ill-conditioning are the failure modes that concern us here.

Each condition requires its own tools. This chapter builds the derivative machinery, examines how costs and terminal values shape the objective, and then focuses on numerical gradient usability, a practical failure mode over long horizons.

We derive backpropagation through dynamics as an adjoint recursion, translate it into action optimization, examine what makes a cost or value function usable as a planning objective, and confront the numerical realities of long rollout derivatives. Along the way we build a complete differentiable planner for a double integrator and then isolate its gradient chain under contracting and expanding scalar dynamics.

Backpropagation Through Dynamics

The previous chapter used sts_t, ata_t, ff, HH, ℓ\ell, and ℓf\ell_f. Here we keep ata_t, ff, and HH, but write the state as ztz_t to emphasize that it may be latent, and write the stage and terminal costs as ctc_t and cHc_H. Thus ztz_t corresponds to the previous chapter's sts_t, while ctc_t and cHc_H correspond to ℓ\ell and ℓf\ell_f.

We work with a deterministic, differentiable dynamics model

zt+1=f(zt,at),zt∈Rn,  at∈Rm,z_{t+1} = f(z_t, a_t), \qquad z_t \in \mathbb{R}^n,\; a_t \in \mathbb{R}^m,

where ztz_t is the model state: it may be a fully observed physical configuration, a latent or belief state, or an observation when that observation is sufficient for the modeled transition. The action ata_t is continuous. The initial state z0z_0 is given and fixed. Over a horizon of HH transitions we accumulate the cost

J(a0,…,aH−1)=∑t=0H−1ct(zt,at)+cH(zH),J(a_0, \dots, a_{H-1}) = \sum_{t=0}^{H-1} c_t(z_t, a_t) + c_H(z_H),

where ctc_t is the stage cost at time tt and cHc_H is an optional terminal cost. The actions are the inputs to a recurrence, and JJ is a scalar function of those inputs. This is exactly the structure of a recurrent neural network unrolled over time, except that we are differentiating with respect to the inputs rather than the weights.

Differentiating with respect to actions, not parameters

In Recurrent State-Space Models we differentiated the loss with respect to model parameters θ\theta to train the model. Here the model is frozen and we differentiate with respect to the action sequence to use the model. Both calculations apply the same reverse-mode chain rule to an unrolled graph. Parameter gradients accumulate across repeated uses of shared weights, while each action has its own time-indexed gradient. Technically, this is BPTT through the unrolled model with the model parameters held fixed and the time-indexed actions treated as differentiation variables.

To make the chain rule concrete, trace the computational paths from one action ata_t. It has a direct path to the stage cost ctc_t and a path through the next state zt+1=f(zt,at)z_{t+1}=f(z_t,a_t) to later states and costs. The corresponding derivatives can still be zero: the cost may be locally flat, the action Jacobian may vanish, or later dynamics may erase the perturbation. The structural point is that a current action can contribute directly to the present cost and indirectly to future costs through the intervening transitions.

Define the state Jacobian and action Jacobian at time tt as

Ft=∂f∂z∣(zt,at)∈Rn×n,Gt=∂f∂a∣(zt,at)∈Rn×m.F_t = \frac{\partial f}{\partial z}\bigg|_{(z_t, a_t)} \in \mathbb{R}^{n \times n}, \qquad G_t = \frac{\partial f}{\partial a}\bigg|_{(z_t, a_t)} \in \mathbb{R}^{n \times m}.

The sensitivity of a future state to a past action is then a product of state Jacobians:

∂zk∂at=Fk−1Fk−2⋯Ft+1 Gt,k>t.\frac{\partial z_k}{\partial a_t} = F_{k-1} F_{k-2} \cdots F_{t+1} \, G_t, \qquad k > t.

Read this product from right to left: the action perturbs zt+1z_{t+1} through GtG_t, and each subsequent Jacobian transforms that perturbation. A subsequent Jacobian may mix or rotate directions and may shear a neighborhood of perturbations. Whether it amplifies or attenuates a particular perturbation depends on that direction and the chosen norm. If all relevant FjF_j have operator norm at most a common ρ<1\rho<1, the sensitivity decays at least geometrically with separation. Growth requires corresponding expansion along the propagated directions; an operator norm above one alone does not guarantee it.

The adjoint recursion

Computing every action gradient by expanding its Jacobian products separately would repeat shared factors. For example, the state sensitivities ∂zH/∂zH−1=FH−1\partial z_H/\partial z_{H-1}=F_{H-1} and ∂zH/∂zH−2=FH−1FH−2\partial z_H/\partial z_{H-2}=F_{H-1}F_{H-2} share the same suffix. A naive scalar implementation that forms each horizon-length product independently performs O(H2)O(H^2) transition multiplications; one backward sweep performs O(H)O(H). The adjoint (co-state) recursion is reverse-mode autodiff organized to reuse those suffixes.

Define the adjoint vector

λt=∂J∂zt∈Rn,\lambda_t = \frac{\partial J}{\partial z_t} \in \mathbb{R}^n,

interpreted as a column vector. The adjoint is a sensitivity of the objective to the state: it says how much the total cost would change if we could nudge ztz_t directly. Because ztz_t feeds into every later state and cost through the dynamics, this sensitivity already accumulates everything that happens downstream of time tt. At the end of the horizon the adjoint is just the terminal cost gradient:

λH=∂cH∂zH.\lambda_H = \frac{\partial c_H}{\partial z_H}.

Now walk backwards. The state ztz_t influences the objective in exactly two ways: through the stage cost ct(zt,at)c_t(z_t, a_t), and through the next state zt+1=f(zt,at)z_{t+1} = f(z_t, a_t), whose adjoint we already have. The chain rule gives

λt=∂ct∂zt+Ft⊤λt+1,t=H−1,H−2,…,0.\lambda_t = \frac{\partial c_t}{\partial z_t} + F_t^\top \lambda_{t+1}, \qquad t = H-1, H-2, \dots, 0.

The transpose appears because zt+1=f(zt,at)z_{t+1}=f(z_t,a_t) depends on ztz_t through FtF_t, and λ\lambda is a column vector. Under the local linearization, δzt+1=Ftδzt+o(∥δzt∥)\delta z_{t+1}=F_t\delta z_t+o(\lVert\delta z_t\rVert). Pulling a gradient back through the transition therefore multiplies by Ft⊤F_t^\top, converting next-state sensitivity into current-state sensitivity. For this discrete recurrence, the recursion is exactly the BPTT backward pass. It is the discrete-time analogue of the continuous ODE adjoint, which instead satisfies a backward differential equation; differentiating a chosen ODE discretization produces a discrete adjoint whose details depend on that discretization.

The action gradient then follows immediately. The action ata_t enters the objective only through ct(zt,at)c_t(z_t, a_t) and through zt+1=f(zt,at)z_{t+1} = f(z_t, a_t):

  ∂J∂at=∂ct∂at+Gt⊤λt+1.  \boxed{\;\frac{\partial J}{\partial a_t} = \frac{\partial c_t}{\partial a_t} + G_t^\top \lambda_{t+1}.\;}

where:

  • ∂ct/∂at\partial c_t / \partial a_t: the direct sensitivity of the stage cost at time tt to the action taken at time tt
  • Gt=∂f/∂a∣(zt,at)G_t = \partial f / \partial a \big|_{(z_t, a_t)}: the action Jacobian, mapping an action perturbation into a next-state perturbation
  • λt+1=∂J/∂zt+1\lambda_{t+1} = \partial J / \partial z_{t+1}: the adjoint of the next state, which aggregates the sensitivity of every future cost

One backward sweep computes λH,λH−1,…,λ1\lambda_H,\lambda_{H-1},\dots,\lambda_1 and every action gradient. Its arithmetic cost is a small constant multiple of the forward evaluation. A standard uncheckpointed implementation uses O(H)O(H) activation memory when per-step size is fixed; it retains the local information needed for the pullbacks, not necessarily explicit Jacobian matrices. Autodiff computes vector-Jacobian products such as Ft⊤λt+1F_t^\top\lambda_{t+1} and Gt⊤λt+1G_t^\top\lambda_{t+1} directly. Checkpointing or recomputation can reduce retained activations at additional compute cost.

The next two cells compute and plot analytic scalar multiplication counts for two organizations of the same action-sensitivity calculation. They do not benchmark Python exponentiation. Independently forming ρH−1−t\rho^{H-1-t} by repeated multiplication uses ∑r=0H−1r=H(H−1)/2\sum_{r=0}^{H-1}r=H(H-1)/2 multiplications by ρ\rho. With the terminal seed λH\lambda_H available, the adjoint sweep needs H−1H-1 multiplications to produce λH−1,…,λ1\lambda_{H-1},\dots,\lambda_1; together, λ1,…,λH\lambda_1,\dots,\lambda_H are the adjoints required by all HH action gradients.

In[3]:
Code
import numpy as np
import torch

np.random.seed(0)
torch.manual_seed(0)

## Scalar linear system z_{t+1} = rho * z_t + a_t with a quadratic terminal cost,
## chosen so the exact adjoint recursion reduces to scalar multiplications with
## constant Jacobian F_t = rho and a simple terminal seed.
adjoint_rho = 0.93
adjoint_horizon = 200

## Forward rollout capturing intermediate states. The constant scalar Jacobian
## F_t = rho is stored separately in adjoint_rho and used by the backward sweep.
adjoint_a = torch.zeros(adjoint_horizon, requires_grad=True)
adjoint_states = [torch.tensor(0.0)]
for t in range(adjoint_horizon):
    adjoint_states.append(adjoint_rho * adjoint_states[-1] + adjoint_a[t])

## Terminal cost gradient d c_H / d z_H with c_H(z) = (z - 1)^2.
adjoint_terminal_grad = 2.0 * (adjoint_states[-1] - 1.0).item()

## Matched adjoint sweep: lambda_H fixed, then form lambda_{H-1}, ..., lambda_1.
adjoint_lambda = adjoint_terminal_grad
adjoint_lambdas = [adjoint_lambda]
for t in range(adjoint_horizon - 1, 0, -1):
    adjoint_lambda = adjoint_rho * adjoint_lambda
    adjoint_lambdas.append(adjoint_lambda)
adjoint_lambdas = adjoint_lambdas[::-1]  # lambda_1 ... lambda_H

## Direct per-action Jacobian products without reuse: sensitivities rho^{H-1-t}.
direct_products = np.array(
    [adjoint_rho ** (adjoint_horizon - 1 - t) for t in range(adjoint_horizon)]
)
## These magnitudes are unused by the count plot. At sufficiently long horizons,
## direct_products may underflow.

## Count the scalar multiplications required by each strategy for the same horizon.
adjoint_sweep_ops = adjoint_horizon - 1
direct_product_ops = adjoint_horizon * (adjoint_horizon - 1) // 2

## Analytic count of multiplications by rho for the two organizations.
print(f"Adjoint sweep multiply count : {adjoint_sweep_ops}")
print(f"Direct product multiply count: {direct_product_ops}")
print(
    f"Shared suffix factors reused : {direct_product_ops - adjoint_sweep_ops}"
)
Out[4]:
Visualization
Log-scale bar chart comparing adjoint sweep and direct product multiply counts.
Analytic scalar multiplication counts for a shared-suffix adjoint sweep and for independently forming every power of rho needed by the H action sensitivities. Both counts cover the H action-gradient blocks and include only multiplications by rho, not measured runtime.

This is the cheap gradient principle: reverse mode computes a full H×mH\times m action gradient at a small constant multiple of one scalar objective evaluation, whereas coordinate-wise finite differences require one or more extra evaluations per action coordinate. This evaluation-cost asymmetry is one important reason differentiable planning is attractive in high dimensions. Directional and simultaneous-perturbation estimators have different tradeoffs, so the comparison here is specifically with coordinate-wise finite differences.

Unrolling the recursion

Substituting the adjoint recursion into itself gives the explicit form

λt=∑k=tH−1(∏j=tk−1Fj⊤)∂ck∂zk  +  (∏j=tH−1Fj⊤)∂cH∂zH,\lambda_t = \sum_{k=t}^{H-1} \Big(\prod_{j=t}^{k-1} F_j^\top\Big) \frac{\partial c_k}{\partial z_k} \;+\; \Big(\prod_{j=t}^{H-1} F_j^\top\Big)\frac{\partial c_H}{\partial z_H},

and therefore

∂J∂at=∂ct∂at+Gt⊤[∑k=t+1H−1(∏j=t+1k−1Fj⊤)∂ck∂zk+(∏j=t+1H−1Fj⊤)∂cH∂zH].\frac{\partial J}{\partial a_t} = \frac{\partial c_t}{\partial a_t} + G_t^\top \Bigg[\sum_{k=t+1}^{H-1} \Big(\prod_{j=t+1}^{k-1} F_j^\top\Big)\frac{\partial c_k}{\partial z_k} + \Big(\prod_{j=t+1}^{H-1} F_j^\top\Big)\frac{\partial c_H}{\partial z_H}\Bigg].

Every indirect future-cost contribution contains an action Jacobian and a possibly empty product of state-Jacobian transposes applied to a cost gradient. This formula motivates the stability analysis below, and it explains a subtlety that is easy to miss: the gradient with respect to an early action is a sum of many terms, one for each future cost, each weighted by a generally different, time-indexed Jacobian product. Terms can reinforce or cancel. A vanishing product for one future step does not necessarily mean the total gradient vanishes. Conversely, a single large product term can dominate the sum even when the surrounding terms are small, which is one reason the gradient profile across actions can look erratic in practice.

What breaks differentiability

Ordinary reverse mode needs a valid local pullback for every operation on the executed path. At a switch, an autodiff implementation may select a branch or subgradient convention; a planner may instead install a surrogate or custom pullback; and some operations provide no useful derivative. Backpropagation-based planners therefore need a usable sensitivity route for the optimized path: ordinary pullbacks, event-aware or implicit sensitivities, a relaxation or surrogate, or an estimator. Otherwise they must bypass or search the hard component separately.

  • Contact and collision. Rigid-contact dynamics are often smooth within a fixed mode but hybrid across impacts. Classical derivatives can jump or fail to exist when contact timing or the active mode changes, while event-aware sensitivities can be valid away from grazing and other degenerate events. Compliant differentiable contact laws or relaxed complementarity conditions can smooth selected transitions, but they change the physical model and do not automatically smooth friction or contact activation. Another local approximation differentiates the active branch while holding the contact set fixed. This is locally exact only while perturbations preserve the full contact and friction mode; across a mode change it omits event sensitivity, although an optimizer may still use it heuristically.
  • Discrete actions and argmax operations. With a one-hot encoding, hard a=arg⁡max⁡iqia=\arg\max_i q_i has zero Jacobian away from ties and is nondifferentiable at ties, so it supplies no informative ordinary pathwise gradient for changing the selected category. A temperature-softmax relaxes a deterministic argmax; for categorical sampling, Gumbel-softmax relaxes the one-hot Gumbel-max sample. A straight-through estimator keeps the hard forward value but substitutes a surrogate backward derivative. These introduce approximation choices. For background on discrete and latent action representations, see Actions, Inverse Dynamics, and Latent Actions.
  • Stochastic dynamics. A sample zt+1∼pθ(zt+1∣zt,at)z_{t+1} \sim p_\theta(z_{t+1} \mid z_t, a_t) does not automatically provide a pathwise derivative with respect to the action. For a reparameterizable continuous distribution, write the sample as a deterministic function of the action and independent noise, for example zt+1=μθ(zt,at)+σθ(zt,at)⊙ϵz_{t+1} = \mu_\theta(z_t, a_t) + \sigma_\theta(z_t, a_t) \odot \epsilon with ϵ∼N(0,I)\epsilon\sim\mathcal N(0,I). Holding the sampled noise fixed then gives a pathwise gradient for a Monte Carlo objective. When reparameterization is unavailable, differentiating Ez∼pa[L(a,z)]\mathbb E_{z\sim p_a}[L(a,z)] yields the ordinary term E[∂aL]\mathbb E[\partial_a L] plus the likelihood-ratio term E[L ∂alog⁡pa(z)]\mathbb E[L\,\partial_a\log p_a(z)], provided differentiation can be interchanged with integration and the required terms are integrable. The likelihood-ratio term also requires action-independent support or vanishing boundary contributions; nonzero boundary terms from action-dependent support need a separate valid estimator. If the score itself is estimated, its conditional expectation given zz must equal the true score, or the weighted term must otherwise be jointly unbiased. Score-function estimators often have high variance. See Stochasticity and Uncertainty for the probabilistic background.
  • Rendering and perception. At fixed inputs and parameters, a differentiable deterministic image encoder defines a repeatable mathematical gradient, although it may be expensive or badly scaled. Implementation-level repeatability additionally requires deterministic forward and backward kernels in a fixed software and hardware environment. Stochastic rendering, noisy observations, and sampled layers can add gradient variance. Surrogate derivatives can add bias or mismatch; randomized surrogates can also add variance. Hard thresholding, such as a binarized mask or hard attention selection, needs a relaxation, estimator, or custom pullback.

Simulation systems such as DiffTaichi and the published Brax physics engine provide automatic differentiation for substantial parts of a physics computation. So do MJX-JAX and supported NVIDIA Warp kernels. Coverage is backend- and feature-dependent: current MJX-Warp is not differentiable, and contact smoothness depends on the chosen formulation and settings. Planning by backpropagation may instead use analytical dynamics, a learned model, event-aware sensitivities, or an implicitly differentiated solver.

Gradient-Based Action Optimization

Once we can compute ∇aJ∈RH×m\nabla_a J \in \mathbb{R}^{H \times m}, action-sequence planning is a constrained finite-dimensional optimization problem:

min⁡a0,…,aH−1  J(a)subject toat∈A    ∀t,\min_{a_0, \dots, a_{H-1}} \; J(a) \quad \text{subject to} \quad a_t \in \mathcal{A} \;\; \forall t,

where A\mathcal{A} is the admissible action set. Independent limits form a box: with shared scalar limits it is [amin⁡,amax⁡]m[a_{\min},a_{\max}]^m, and in general it is ∏i[amin⁡,i,amax⁡,i]\prod_i[a_{\min,i},a_{\max,i}]. Coupled actuator limits need non-box sets; rate constraints need sequence-coupled constraints or state augmentation; state-dependent limits need state-action or path constraints such as at∈A(zt)a_t\in\mathcal{A}(z_t). With continuous decision variables, the problem is a nonlinear program when its objective or explicit constraints are nonlinear. Discrete decisions instead lead to a discrete or mixed-integer formulation. The linear-quadratic example below is a convex quadratic program.

The simplest solver is gradient descent with a fixed scalar step: a←a−η∇aJa\leftarrow a-\eta\nabla_aJ. Adaptive methods such as Adam are convenient in implementations like the worked example below. Away from its numerical stabilizer and interventions such as clipping or weight decay, Adam's moment normalization makes updates less sensitive to a uniform positive rescaling of persistent gradients. It is not fully scale-free, and it does not remove poor conditioning. For a smooth positive-curvature local model, one global step size must be stable for the direction of largest curvature, which can force slow progress in flatter positive-curvature directions. Adaptive, accelerated, and preconditioned first-order methods may reduce that penalty but do not eliminate it in general.

Handling action bounds

Two simple approaches are especially easy to implement.

Projected gradient descent takes a step and then clips each coordinate back into the box:

a←clip(a−η∇aJ,  amin⁡,  amax⁡).a \leftarrow \mathrm{clip}\big(a - \eta \nabla_a J,\; a_{\min},\; a_{\max}\big).

This enforces the box constraint exactly. At a boundary, projection removes only the component of a proposed step that points outside the box; a later descent step that points inward can still move the coordinate. Repeated outward steps can pin a coordinate at the boundary, while changing or noisy directions can make iterates oscillate along active faces. The projection operator also introduces a kink that must be handled in convergence analysis near active constraints.

Reparameterization removes the constraint entirely. Write

at=amin⁡+amax⁡2+amax⁡−amin⁡2tanh⁡(ut)a_t = \frac{a_{\min} + a_{\max}}{2} + \frac{a_{\max} - a_{\min}}{2} \tanh(u_t)

and optimize the unconstrained variable uu. In exact real arithmetic, every finite uu maps into the strict interior of the box. In floating-point arithmetic, tanh⁡(u)\tanh(u) can round to ±1\pm1, and midpoint or half-width arithmetic can cancel, overflow, or underflow. The affine formula alone therefore does not universally guarantee even closed-box feasibility. With well-scaled bounds and overflow-free arithmetic, it typically lands in the closed box; apply a final clip when exact numerical box feasibility is required. The other cost is saturation: when ∣ut∣|u_t| is large, dat/dut\mathrm{d}a_t/\mathrm{d}u_t becomes exponentially small. The action lies very near a boundary and may become effectively stuck in finite precision, which is harmless only while the desired action remains there and harmful when an inward recovery is needed. A logistic parameterization has the same limitation.

Both methods are used in simple first-order planners. Reparameterization guarantees strict-interior feasibility in exact arithmetic but can compound vanishing gradients when it saturates. In finite precision, overflow-safe bound arithmetic followed by a final clamp, or another interval-preserving implementation, is needed to guarantee a result in the closed box. Projection can represent an exact boundary optimum directly, whereas real-arithmetic tanh⁡\tanh approaches a boundary only asymptotically. Overall convergence still depends on scaling, step size, curvature, and active constraints.

Single shooting, multiple shooting, and collocation

The trajectory transcription changes both sparsity and conditioning. A key distinction is which trajectory quantities become free variables and how the dynamics are enforced.

  • Single shooting optimizes only the actions and eliminates states by forward simulation. Each action-gradient block contains direct terms plus sums weighted by products of later transition Jacobians. This is the action-only formulation established above.
  • Multiple shooting also promotes segment-boundary states to decision variables and adds continuity constraints. This exposes sparse local continuity Jacobians to a constrained solver and often avoids the worst full-horizon sensitivity products, although the resulting KKT system can still be ill-conditioned. It is a standard option for difficult trajectory-optimization and nonlinear-MPC problems.
  • Direct collocation represents states and controls at mesh or collocation nodes and enforces integration defects. A-stable or L-stable implicit collocation schemes, such as appropriate Radau formulas, can be more stable for stiff modes than explicit integration at the same step size, although their nonlinear constraint Jacobians can still be poorly conditioned.

For sufficiently short, well-conditioned receding-horizon problems with modest path constraints, single shooting is a practical baseline with less transcription bookkeeping. As horizon-induced sensitivity products become problematic, multiple shooting can justify its additional variables and constraints; the crossover depends on dynamics, time step, dimensions, constraints, scaling, and solver. Its local continuity blocks shorten sensitivity chains but are not guaranteed to be well-conditioned.

Second-order methods: DDP and iLQR

Gradient descent uses only first-order information, and planning objectives can be badly conditioned when long-horizon sensitivities create strongly unequal curvature across action directions. Curvature-aware methods attack that local geometry directly.

Differential Dynamic Programming (DDP) and its Gauss-Newton variant iLQR compute a local quadratic approximation of the cost-to-go. Around a nominal pair (zˉt,aˉt)(\bar z_t,\bar a_t), define δz=z−zˉt\delta z=z-\bar z_t and δa=a−aˉt\delta a=a-\bar a_t; let qz,qaq_z,q_a denote the corresponding gradient blocks of the local action cost-to-go Qt\mathcal Q_t, and let Qzz,Qza,Qaz,QaaQ_{zz},Q_{za},Q_{az},Q_{aa} denote its Hessian blocks. When the unconstrained local control subproblem is well posed, typically after regularization makes QaaQ_{aa} positive definite, the backward algebra solves that local model exactly; it only approximates the original nonlinear problem. The backward pass augments the first-order adjoint, or value gradient, with a value Hessian:

Qt(z,a)≈const+12[δzδa]⊤[QzzQzaQazQaa][δzδa]+[qzqa]⊤[δzδa],\mathcal Q_t(z, a) \approx \text{const} + \tfrac{1}{2}\begin{bmatrix} \delta z \\ \delta a \end{bmatrix}^\top \begin{bmatrix} Q_{zz} & Q_{za} \\ Q_{az} & Q_{aa} \end{bmatrix} \begin{bmatrix} \delta z \\ \delta a \end{bmatrix} + \begin{bmatrix} q_z \\ q_a \end{bmatrix}^\top \begin{bmatrix} \delta z \\ \delta a \end{bmatrix},

and, when QaaQ_{aa} is positive definite, the local feedforward perturbation is δa⋆=−Qaa−1qa\delta a^\star=-Q_{aa}^{-1}q_a. At each time step the sweep forms QaaQ_{aa}, QazQ_{az}, and the local linear terms from the stage-cost derivatives, FtF_t, GtG_t, and the next value gradient and Hessian, then propagates the resulting value gradient and Hessian. Full DDP also retains contractions with second derivatives of the dynamics, while iLQR drops those dynamics terms but keeps the first and second cost derivatives. The resulting finite-horizon, generally time-varying Riccati recursion is related to, but not identical to, the discrete algebraic Riccati equation used for the infinite-horizon linear time-invariant example below.

On smooth problems with a useful local quadratic model, DDP or iLQR can converge in fewer iterations than first-order descent. The advantage is not guaranteed, especially when QaaQ_{aa} is indefinite or poorly stabilized rollouts make the local model inaccurate. DDP retains dynamics second derivatives, while iLQR drops them; both typically need regularization and a line search or trust region. With a descent-producing regularization, backtracking can reject an aggressive step until an acceptance condition is met. It can still stall or fail when no useful local direction exists.

Warm starting and the receding-horizon loop

In a smoothly evolving MPC loop, consecutive problems share structure and usually differ modestly unless disturbances, references, constraints, or modes change abruptly. Under those conditions, shifting the unused action suffix left, appending a terminal guess, and checking or restoring feasibility for the new state and constraints often gives a useful full-horizon initial sequence. The appended value can be the previous last action or zero only when it satisfies the new box, rate, coupled, and state-dependent constraints. This warm start alone does not guarantee recursive feasibility; that requires additional MPC assumptions. Warm starts can reduce the iterations needed per update, but whether this reaches a real-time deadline depends on the model, hardware, control rate, and accuracy target. The same shift-and-pad pattern is a common warm-starting discipline for CEM-based MPC, as introduced in Sampling-Based Planning and Model Predictive Control.

A useful hybrid is to evaluate a population of CEM candidates for a few distribution-update rounds to find a promising basin, then refine the best sequence with gradients. The sampling phase explores without requiring differentiability; the gradient phase performs local refinement. The outcome still depends on population size, initialization, and the objective's basin structure.

Differentiating through the planner

There is a second, distinct meaning of "differentiable planning" to separate from the first.

So far we have used gradients to perform the planning. We can also make the planning procedure a differentiable layer so gradients flow into upstream cost or dynamics parameters. One route solves the optimization problem in the forward pass and differentiates its KKT conditions implicitly. A standard sufficient regularity regime for classical implicit differentiation uses a differentiable local KKT residual, a strongly regular or locally unique solution branch, and a nonsingular linearized optimality system. A locally stable active set commonly permits a fixed-active-set derivative only when the problem data are differentiable and the corresponding reduced KKT system is nonsingular, conditions typically supported by constraint qualification and suitable second-order assumptions. Active-set changes may make the solution map nondifferentiable, but they do not do so in every problem. These conditions enable the classical inverse-system sensitivity formula; they are not universal necessities for every differentiable selected optimizer map. Unrolling a fixed number of solver iterations is a different route with different memory and approximation tradeoffs.

This distinction matters in learning-to-plan systems and differentiable optimization layers. It is separate from the next part of this chapter: using differentiable values inside a planning objective. The planned Policies Learned in Imagination chapter will instead examine policy learning from model-generated rollouts.

Differentiable Value and Cost Functions

The planning objective is a consequential design choice because it defines what the optimizer is asked to prefer. With accurate gradients and a suitable step-size or line-search rule, a gradient-based planner follows local descent directions in that objective, even if it has a convenient minimum in the wrong place.

Stage costs

A standard stage cost for smooth continuous control and trajectory tracking is

ct(zt,at)=(zt−z⋆)⊤Q(zt−z⋆)+at⊤Rat,c_t(z_t, a_t) = (z_t - z^\star)^\top Q (z_t - z^\star) + a_t^\top R a_t,

with z⋆z^\star the target state, Q⪰0Q\succeq0 weighting state error, and R≻0R\succ0 penalizing effort. For physical coordinates with documented units and suitably structured, calibrated QQ and RR, the terms can be interpreted as weighted state-error and action-effort contributions. For a learned latent state, the first term is a QQ-weighted squared discrepancy—a squared seminorm if QQ is singular—and need not align with task semantics. Without a bound on decoder sensitivity, numerically close latents can still decode to substantially different observations. For a decoder d(zt)d(z_t) and target x⋆x^\star in Rp\mathbb R^p, a decoded cost (d(zt)−x⋆)⊤Qx(d(zt)−x⋆)(d(z_t)-x^\star)^\top Q_x(d(z_t)-x^\star) with Qx⪰0Q_x\succeq0 in Rp×p\mathbb R^{p\times p} measures error in observation coordinates and costs a decoder evaluation per step. It is reliable as a task-semantic cost only if the observation metric is appropriate and decoder error over planned states does not materially distort task-relevant costs, rankings, or gradients. See Sufficient State and State Abstraction for the representation question.

Other common forms:

  • Smooth surrogates for sparse costs. Away from its boundary, a binary goal term has zero pathwise gradient and gives an action optimizer no local signal from that term. For β>0\beta>0, a smooth alternative is c(z)=β−1log⁡ ⁣(1+exp⁡(β(∥z−z⋆∥2−ϵ2)))c(z)=\beta^{-1}\log\!\left(1+\exp\left(\beta(\lVert z-z^\star\rVert^2-\epsilon^2)\right)\right), a softplus approximation to the hinge violation max⁡(0,∥z−z⋆∥2−ϵ2)\max(0,\lVert z-z^\star\rVert^2-\epsilon^2) rather than to a binary indicator. A Gaussian goal bonus, c(z)=−exp⁡(−∥z−z⋆∥2/2σ2)c(z)=-\exp(-\lVert z-z^\star\rVert^2/2\sigma^2), is another option. At fixed distance r=∥z−z⋆∥>0r=\lVert z-z^\star\rVert>0, its state-gradient magnitude is rσ−2exp⁡(−r2/2σ2)r\sigma^{-2}\exp(-r^2/2\sigma^2) and is largest at σ=r/2\sigma=r/\sqrt{2}. In the tail r>2σr>\sqrt{2}\sigma, shrinking σ\sigma further weakens the gradient; for σ>r/2\sigma>r/\sqrt{2}, shrinking it can strengthen the gradient. Tune σ\sigma to the candidate-distance distribution, and narrow it as candidates approach only while preserving a useful signal.
  • Logarithmic barriers. For a barrier weight κ>0\kappa>0, an inequality g(z)>0g(z)>0 on a strictly feasible trajectory can be represented by c(z)=−κlog⁡g(z)c(z)=-\kappa\log g(z). The term inherits gg's regularity in the strict interior: it is smooth there when gg is smooth, and merely differentiable there when gg is merely differentiable. It diverges to +∞+\infty as g(z)→0+g(z)\to0^+. At any finite positive κ\kappa it is an interior approximation, not an exact replacement for a general hard constraint, and it cannot be evaluated at an infeasible point.
  • Penalty terms. For a penalty weight ρ>0\rho>0, softer alternatives add ρmax⁡(0,−g(z))2\rho \max(0, -g(z))^2. Penalties allow small violations in exchange for lower cost elsewhere; barriers do not.
  • Learned costs. A neural cost can be learned from demonstrations through inverse optimal control or from explicit preferences through reward modeling. Smooth operations make it differentiable everywhere; standard ReLU networks provide gradients almost everywhere. Approximation and generalization errors, especially off distribution, can become exploitable when they make reachable plans look artificially attractive.
  • Energy-based and contrastive costs. If a model provides a differentiable energy whose low-energy configurations align with task success, that energy can serve as a planning cost. Predictive compatibility alone does not guarantee control utility; see the chapter on predictive embeddings and energy-based models.

Cost shaping requires caution. A generic dense auxiliary term can change the optimal plan. For this finite-horizon, undiscounted cost convention, one invariant construction is

ct′=ct+Φt(zt)−Φt+1(zt+1),cH′=cH+ΦH(zH).c'_t=c_t+\Phi_t(z_t)-\Phi_{t+1}(z_{t+1}),\qquad c'_H=c_H+\Phi_H(z_H).

The added terms telescope to the fixed constant Φ0(z0)\Phi_0(z_0), so they do not change the ordering of feasible action sequences. Omitting the terminal correction leaves the residual −ΦH(zH)-\Phi_H(z_H), which is generally action-dependent and can change the optimum when ΦH(zH(a))\Phi_H(z_H(a)) varies across feasible plans. Discounted reward shaping uses a different sign and includes the discount factor; the reinforcement-learning result does not transfer verbatim without matching those conventions.

The terminal value function

When a finite horizon approximates a longer or infinite-horizon objective, it omits a tail whose value can vary across terminal states. A terminal cost can approximate that continuation:

JHV(a)=∑t=0H−1ct(zt,at)+V(zH),V(z)≈inf⁡π  Eπ[∑k=0∞c(zk,ak)  ∣  z0=z],J_H^V(a) = \sum_{t=0}^{H-1} c_t(z_t, a_t) + V(z_H), \qquad V(z) \approx \inf_{\pi} \; \mathbb{E}_{\pi}\Big[\sum_{k=0}^{\infty} c(z_k, a_k) \;\Big|\; z_0 = z\Big],

assuming the continuation cost is finite and uses the same dynamics, constraints, costs, and information pattern as the planner. If VV is the exact optimal continuation cost, the subproblems attain their minima, and H≥1H\geq1, dynamic programming makes every minimizing prefix begin with an action in the same infinite-horizon optimal first-action set. Without a unique optimum or consistent tie-breaking, different horizons may select different actions from that set. In MPC, suitable terminal costs—often together with terminal sets and other conditions—can support stability arguments. Structurally, the terminal value is the planning analogue of an nn-step temporal-difference bootstrap: both replace an omitted tail with a value estimate, but a planning terminal value guides action optimization only when it distinguishes reachable terminal states, while the bootstrap supplies a learning target.

For an equilibrium-centered, unconstrained infinite-horizon LTI linear-quadratic regulator, under the usual stabilizability and detectability assumptions, the value has the quadratic form

V(z)=(z−z⋆)⊤P(z−z⋆),V(z) = (z - z^\star)^\top P (z - z^\star),

where PP solves the discrete algebraic Riccati equation

P=Q+A⊤PA−A⊤PB(R+B⊤PB)−1B⊤PA.P = Q + A^\top P A - A^\top P B \big(R + B^\top P B\big)^{-1} B^\top P A.

The target and input must be shifted to a feasible equilibrium; general affine tracking can add linear and constant terms. We will solve this DARE numerically for the exactly specified LQ model and test the resulting terminal value in a short-horizon planner.

Outside special cases such as LQR, a nonlinear problem's value function need not have this quadratic form and may lack a tractable closed form. It can be approximated, for example by a learned VθV_\theta. When it preserves decision-relevant value differences or gradients over candidate terminal states, it can support a shorter explicit rollout. Shortening that rollout reduces the maximum transition-Jacobian chain length and may mitigate horizon-induced vanishing or exploding sensitivities, although the terminal value can introduce its own conditioning problems. The model and value become coupled when joint training links them through shared parameters, representations, losses, gradients, or targets. Coupling also arises when value targets depend on model rollouts. An optimizer can push candidate terminal states outside the value function's training support. Bellman-style training may impose consistency constraints, but it does not remove approximation error. A learned terminal value therefore trades part of the omitted-tail error for value-approximation error while the shorter action problem still has to be optimized.

Differentiable values as planning modules

Differentiable value functions support at least three planning patterns.

As a terminal cost. Backpropagation starts from ∇Vθ(zH)\nabla V_\theta(z_H). That terminal-state adjoint propagates through the rollout and contributes a gradient to every earlier action.

For direct action optimization. If Qθ(z,a)Q_\theta(z,a) denotes a reward or return to maximize and is differentiable in a continuous action, one ascent iteration is

a(k+1)=a(k)+η∇aQθ ⁣(z,a(k)),a^{(k+1)} = a^{(k)} + \eta \nabla_a Q_\theta\!\left(z,a^{(k)}\right),

with appropriate constraint handling for constrained actions, such as projection or reparameterization for simple action bounds. This QQ uses a reward convention, unlike the continuation cost VV above; for an action cost-to-go, the corresponding update uses the negative gradient. Each iteration differentiates one QQ evaluation rather than an explicit model rollout. Finding the global greedy action still requires solving a generally non-convex problem and may need restarts; differentiability alone guarantees neither a global maximizer nor even progress under an arbitrary step. For the displayed one-step update, only errors in the action gradient at the current iterate alter the step. Errors in action rankings can still affect candidate selection or the eventual greedy action.

As a tail estimate after finite lookahead. A terminal value can make short rollouts effective by estimating what lies beyond them. TD-MPC scores short latent rollouts with predicted rewards and a learned terminal value during sampling-based trajectory optimization, whereas MuZero backs up a value from a search-tree leaf. The planned chapters on MuZero and Value-Equivalent Models and TD-MPC and Control-Centric Representations will develop those distinct uses.

The exploitation hazard

An imperfect learned component can create an exploitation surface when its error varies across planner-reachable candidates and changes objective values or derivatives. A vanilla optimizer sees the supplied values and derivatives, not an independent test of whether the surrogate remains valid. When a reachable model error creates a smooth direction toward lower predicted cost, gradient optimization can exploit it rapidly. It is not guaranteed to find every error, nor is it uniformly faster than sampling: local basins, flat regions, constraints, and initialization still matter.

Concretely, this shows up as:

  • Plans that drive the latent state to a region where a learned cost is artificially low, decoding to something nonsensical.
  • Terminal cost-to-go estimates that are too low in unexplored regions, making unsupported terminal states look artificially attractive.
  • Reachable dynamics-model errors that make impossible trajectories look favorable. Directed gradients can refine such an exploit quickly once it lies in the current basin, although the comparison with sampling depends on the error landscape and budget. This is the model-exploitation failure introduced in Sampling-Based Planning and Model Predictive Control.

Several defenses against model exploitation have analogues for learned costs and values, but their uncertainty or support measures must be defined for the component they protect:

  • Uncertainty-aware objectives. An ensemble penalty can discourage plans in regions of high disagreement. When disagreement is a validated proxy for decision-relevant epistemic uncertainty, high-disagreement regions can also carry elevated exploitation risk. Agreement can still hide shared systematic bias. PETS uses probabilistic ensembles and particles to propagate uncertainty during trajectory evaluation rather than adding this exact penalty; the planned chapter on probabilistic and ensemble model-based RL will compare these mechanisms.
  • Smoothness constraints. Penalizing cost-gradient magnitude over a training distribution can discourage steep local variation there. It neither guarantees the removal of spurious minima nor, by itself, guarantees control of gradients at planner-reachable states outside that distribution.
  • Conservative objectives. Some conservative offline-RL objectives, such as COMBO-style value regularizers, penalize Q-values under distributions chosen to emphasize out-of-support model-rollout tuples, aiming for conservative estimates there. Other conservative methods act through reward penalties or policy constraints.
  • Trust regions in action space. A conventional trust region bounds each action-sequence update around the current optimizer iterate. To bound cumulative drift from an initially trusted plan, impose a constraint relative to that fixed reference or an equivalent episode-wide deviation budget.
  • Evaluation on the real system. No amount of surrogate engineering substitutes for checking whether the plan works on the real system.

A useful mental model is that ordinary optimization against a fixed learned surrogate can behave like an adversarial search for errors inside the optimizer's basin, even though it is not a formal min-max problem. With other factors controlled, gradients that align better with a locally valid descent direction and have usable scale and variance can make local surrogate optimization more effective. That can improve task performance or expose smooth model errors more aggressively. Optimization quality and real-system performance must therefore be evaluated separately.

Stability Under Long Rollout Gradients

We now turn to the central technical difficulty. Everything so far assumed that ∇aJ\nabla_aJ is usable. Over long horizons it can fail when accumulated sensitivities are strongly contractive, expansive, ill-conditioned, discontinuous, or noisy. A long horizon alone does not force failure.

The product of Jacobians

Return to the sensitivity formula

∂zk∂at=Fk−1Fk−2⋯Ft+1 Gt.\frac{\partial z_k}{\partial a_t} = F_{k-1} F_{k-2} \cdots F_{t+1} \, G_t.

If the state Jacobians were constant, Fj=FF_j = F for all jj, this product would be Fk−t−1GtF^{k-t-1} G_t. For a scalar F=ρF=\rho, or for a normal matrix whose relevant modes are excited, its asymptotic scale follows the eigenvalue magnitudes:

  • If ∣ρ∣<1|\rho|<1, the product decays geometrically. The influence of early actions on late states vanishes.
  • If ∣ρ∣>1|\rho|>1 and the action excites the scalar mode with a nonzero gain, the sensitivity magnitude grows geometrically. The influence of early actions on late states then becomes unbounded as the separation grows.
  • If ∣ρ∣≈1|\rho|\approx1, the modal magnitude changes little per transition. Over pp transitions it remains near one only when p∣log⁡∣ρ∣∣p|\log|\rho|| is small, and negative ρ\rho alternates sign.

For a general matrix, spectral radius alone is insufficient over a finite horizon: non-normal matrices can exhibit large transient growth even when every eigenvalue lies inside the unit disk. Time-varying nonlinear rollouts require the singular values and directions of the actual product Fk−1⋯Ft+1F_{k-1}\cdots F_{t+1}. The scalar spectral-radius example is therefore intuition, not a complete stability test. A real system's rates come from its physical dynamics. The implemented model's state and action Jacobians supply the planner's rollout-sensitivity factors and match the real rates only to the extent that the model is locally faithful. The full objective gradient also depends on cost or value derivatives and on the coordinates used to parameterize actions. Constraints separately determine feasible or projected directions unless they are encoded through a barrier, penalty, or reparameterization. For nonlinear dynamics, Jacobians depend on the evaluation point and can vary along a rollout.

What goes wrong

Numerical overflow and underflow. Float32's largest finite magnitude is about 3.4×10383.4\times10^{38}, its smallest positive normal value is about 1.2×10−381.2\times10^{-38}, and subnormal values extend to about 1.4×10−451.4\times10^{-45}. With ρ=1.2\rho = 1.2 and H=100H = 100, ρH≈8.3×107\rho^{H} \approx 8.3 \times 10^7; with ρ=1.5\rho = 1.5, the product is about 4.1×10174.1\times10^{17} at H=100H=100 and 1.7×10351.7\times10^{35} at H=200H=200, still finite, but it overflows near H=219H=219. In the other direction, 0.9400≈5.0×10−190.9^{400}\approx5.0\times10^{-19} is still normal; it reaches the normal/subnormal boundary only near H=829H=829. These scalar thresholds do not predict the conditioning of a matrix product, but they show when finite-precision range becomes an additional failure mode. Float64 postpones overflow and underflow without fixing vanishing or exploding sensitivity.

Ill-conditioning. Ill-conditioning can remain severe even when overflow and underflow are absent because it concerns relative directional scales rather than representable range. For a symmetric positive-definite quadratic Hessian whose smallest and largest eigenvalues are μ\mu and LL, respectively, κ2=L/μ\kappa_2=L/\mu; if [μ,L][\mu,L] is only an enclosing interval, then κ2≤L/μ\kappa_2\leq L/\mu. Gradient descent with step 1/L1/L contracts Euclidean iterate error by at most 1−1/κ21-1/\kappa_2 per step when LL is the largest eigenvalue; a constant-factor reduction can therefore take on the order of κ2\kappa_2 steps. In linear-quadratic problems the action Hessian is built from rollout Jacobians and cost curvature. Exact nonlinear Hessians also contain second derivatives of the dynamics and costs. This spread motivates regularized curvature-aware methods such as DDP, but they do not eliminate conditioning problems in general.

Unequal update scales. Consider the terminal-only objective for zt+1=0.85zt+atz_{t+1}=0.85z_t+a_t with H=40H=40. The final-state sensitivities are ∂z40/∂a0=0.8539≈0.00177\partial z_{40}/\partial a_0=0.85^{39}\approx0.00177 and ∂z40/∂a39=1\partial z_{40}/\partial a_{39}=1. Away from a stationary terminal cost, the common terminal derivative cancels in their ratio, so the late-action gradient is about 0.85−39≈5660.85^{-39}\approx566 times larger. With plain gradient descent using one global learning rate, early-action updates are proportionally smaller. Global-norm clipping rescales the entire vector and preserves this ratio; it bounds magnitude but does not repair the imbalance. Per-coordinate moment normalization can make persistent nonzero components more similar in update magnitude, except where optimizer history or ϵ\epsilon dominates, and may over-amplify directions with little physical influence.

In a strongly contracting system, weak early-action influence on the terminal state can be physically correct. Early actions may still matter for stage costs. At a given candidate rollout, relative action-gradient weights depend on the initial state and visited state-action points through the dynamics, costs, horizon, discounting, and parameterization. Those weights may or may not suit the practical objective. If contraction is a model artifact, the sensitivity is misleading. If it is physical, weak terminal sensitivity is faithful, although its optimization consequences still depend on the rest of the formulation.

Gradient variance under stochastic dynamics. Under regularity conditions that permit differentiation under the expectation, reparameterization gives ∇aEϵ[L(a,ϵ)]=Eϵ[∇aL(a,ϵ)]\nabla_a\mathbb{E}_\epsilon[L(a,\epsilon)]=\mathbb{E}_\epsilon[\nabla_aL(a,\epsilon)]. In practice, we estimate it by averaging pathwise gradients from sampled noise realizations. Jacobian chains can amplify or attenuate each sample's influence, so variance may grow, shrink, or plateau with horizon. When measured Monte Carlo variance is large relative to the mean gradient, use more trajectories or validated control variates. For paired comparisons, common random numbers can help when the induced covariance is favorable.

Mitigations

The mitigations fall into five families.

(A) Shorten the effective horizon.

  • Receding-horizon MPC with a finite, task-appropriate planning horizon, the central deployment pattern in Sampling-Based Planning and Model Predictive Control.
  • A sufficiently decision-faithful terminal value, which estimates the omitted tail without another long transition chain.
  • Truncated backpropagation at selected recurrent-state boundaries. One scheme detaches the state KK transitions before the end and differentiates only the final window; this saves work but generally biases the full planning gradient unless the omitted chain-rule contributions are zero.
  • Discounting with 0≤γ<10\leq\gamma<1, which geometrically downweights late terms and shortens the effective horizon. It changes the objective and does not guarantee a better condition number.

(B) Control the gradient scale.

  • Global-norm clipping: rescale the whole vector when its norm exceeds a calibrated threshold. This preserves direction, unlike coordinate-wise clipping, and is preferable when direction preservation is the goal. It does not correct component imbalance.
  • Cost normalization: choose a practical scale from representative loss and gradient measurements, then tune the learning rate, optimizer ϵ\epsilon, and clipping threshold together. An order-one norm is a convention, not a requirement.
  • Higher precision when diagnostics show overflow, underflow, or harmful roundoff. Float64 extends numerical range without fixing true sensitivity decay or conditioning. FP16 mixed-precision optimization may need dynamic loss scaling when backward gradients would otherwise underflow, together with finite-value checks on overflow-prone paths. BF16 and inference-only mixed precision do not inherently require loss scaling; safeguards should match the format and measured numerical range. Sensitive reductions and optimizer state still need adequate precision.

(C) Improve conditioning.

  • Second-order and quasi-Newton methods (DDP, iLQR, Gauss-Newton, L-BFGS) can reduce sensitivity to eigenvalue spread when the local curvature model is accurate enough and suitably regularized or globalized. Approximate or indefinite curvature can produce an unhelpful step, while regularization choices and finite precision can leave the numerical problem ill-conditioned.
  • A compatible, well-chosen preconditioner, for example one based on a positive diagonal approximation to the Gauss-Newton Hessian, can reduce the transformed spectral spread. A poor, stale, or mismatched preconditioner can leave conditioning unchanged or worsen it.
  • Architecture choices inside the transition can help, but must be checked on planner-relevant rollout Jacobians. Layer normalization offers no conditioning guarantee. An upper spectral bound can limit expansion without preventing vanishing directions. A residual form f(z,a)=z+g(z,a)f(z,a)=z+g(z,a) stays near identity only when ∂g/∂z\partial g/\partial z is controlled, not merely when gg has small values.
  • For a linear component known to be asymptotically stable, Schur or diagonal parameterizations can constrain eigenvalues inside the unit disk. Orthogonal recurrences instead preserve norms with eigenvalues on the unit circle. Neither eigenvalue constraint controls finite-horizon transient growth in a non-normal system; monitor singular values or finite-horizon products separately.

(D) Break the chain.

  • Multiple shooting or direct collocation, which lifts state variables and exposes sparse local dynamics constraints instead of fully condensing every dependency into the action objective. The constrained system can still be ill-conditioned.
  • A square-root checkpoint schedule, which reduces activation memory from O(H)O(H) to O(H)O(\sqrt{H}) for a uniform chain at the cost of recomputation. Other schedules make different tradeoffs. Checkpointing addresses activation-memory pressure rather than Jacobian conditioning; it is worthwhile when the value of lower memory use outweighs its recomputation cost.
  • Explicit Jacobian or finite-horizon sensitivity regularizers over planner-relevant trajectories. Multi-step prediction losses expose rollout error but do not by themselves guarantee well-scaled derivative products.

(E) Avoid differentiating through hard components.

  • Straight-through estimators for quantization or discretization: use a hard value in the forward pass and substitute a surrogate backward derivative. In straight-through Gumbel-softmax, that surrogate is the soft relaxation's gradient.
  • Score-function estimators when pathwise reparameterization is unavailable. For Ez∼pa[L(a,z)]\mathbb E_{z\sim p_a}[L(a,z)], use the ordinary ∂aL\partial_a L term together with the likelihood-ratio term when differentiation and integration can be interchanged, the required terms are integrable, and the support is action-independent or its boundary contributions vanish. Nonzero boundary terms need a separate valid estimator. An estimated score must be conditionally unbiased given zz, or must otherwise make the weighted term jointly unbiased. Score-function estimators often have higher variance than a well-behaved pathwise estimator, so control variates are commonly useful.
  • Carefully chosen smooth surrogates: differentiable compliant contact for selected contact transitions, an interior barrier for a differentiable inequality whose initialization and every evaluated iterate remain strictly feasible, or a finite-temperature relaxation of a hard categorical choice. Each changes the original problem and must be validated.

Training models to be differentiable-friendly

Conventional supervised dynamics models are often fit with one-step prediction error, sometimes augmented with multi-step rollout losses. A standard value-only prediction objective does not explicitly control or guarantee the state-Jacobian spectrum. A model can therefore predict well on its training distribution and still be a poor substrate for gradient planning.

Two remedies target different aspects of the problem. Training with a multi-step prediction objective exposes the model to rollout errors caused by its repeated transitions, but it does not by itself guarantee well-conditioned Jacobians. An explicit regularizer can instead penalize selected Jacobian norms, singular values, or finite-horizon products; a guaranteed bound requires an enforced constraint or suitable parameterization. Suppressing physically real expansion may bias the dynamics. These choices connect to Predictive and Generative Objectives.

The deeper point is that one-step prediction quality and closed-loop decision usefulness are different properties. A model can score well on a one-step benchmark and still produce unusable plans. Part XI will revisit this distinction in evaluation. The architecture and learned parameters determine the realized derivatives; data, objective, regularization, initialization, and optimization influence which parameters are learned. Those derivatives are one major factor in how well a gradient planner works, alongside model accuracy, cost design, constraints, horizon, and optimizer.

A practical recipe

The numerical values in the worked example are not task-independent defaults. A measurement-driven starting procedure is:

  1. Nondimensionalize or rescale each state and action coordinate using documented characteristic scales so their numerical magnitudes are comparable, and transform costs and bounds consistently. Then measure representative objective and gradient scales; coordinate normalization alone does not make gradients order one.
  2. Choose a physical lookahead from the system's controllability and task timescales, sampling interval, terminal-value quality, and compute budget. Expressing the horizon only as a number of steps hides these dependencies.
  3. Tune the optimizer and learning rate from measured objective decrease. If you use clipping, set its threshold from the observed unclipped gradient distribution and log how often it activates.
  4. When consecutive receding-horizon problems evolve smoothly, shift the unused suffix, append a terminal action, and check or restore feasibility for the newly measured state and constraints before using the full-length sequence as a warm start. Reset or use additional starts after abrupt disturbances, reference changes, constraint changes, or mode switches.
  5. Log gradients by time step. A large span is a diagnostic trigger, not a verdict: inspect contraction or expansion, action gains, cost placement, cancellations, constraints, units, and horizon. For curvature, use matrix-free Hessian-vector products to estimate the most negative and largest algebraic eigenvalues of a symmetric action Hessian, or Jacobian-vector and vector-Jacobian products to estimate extreme singular values of a nonsymmetric rollout Jacobian or sensitivity product. Form the matrix directly only when the action problem is small enough.
  6. If progress stalls, first check gradient correctness, scale, saturation, active constraints, smoothness, and initialization. Consider regularized iLQR or DDP when curvature is the limiting factor and a useful local quadratic model exists.

Worked Example: A Double Integrator

We use a problem whose action gradient and optimum have closed matrix forms that we can verify numerically. The continuous dynamics are x˙=v\dot{x}=v and v˙=a\dot{v}=a, with acceleration held constant over each sampling interval. Their exact zero-order-hold discretization at time step Δt\Delta t is

zt=[xtvt],zt+1=[1Δt01]⏟Azt+[12Δt2Δt]⏟Bat.z_t = \begin{bmatrix} x_t \\ v_t \end{bmatrix}, \qquad z_{t+1} = \underbrace{\begin{bmatrix} 1 & \Delta t \\ 0 & 1 \end{bmatrix}}_{A} z_t + \underbrace{\begin{bmatrix} \tfrac{1}{2}\Delta t^2 \\ \Delta t \end{bmatrix}}_{B} a_t.

The cost is quadratic with target gg:

J(a)=∑t=0H(zt−g)⊤Q(zt−g)+∑t=0H−1Rat2.J(a) = \sum_{t=0}^{H} (z_t - g)^\top Q (z_t - g) + \sum_{t=0}^{H-1} R a_t^2.

This linear-quadratic structure makes the action gradient affine and the unconstrained optimum available from a linear solve. It is therefore a useful test case: we can compare autodiff with an independently assembled quadratic gradient at a declared action vector.

Deriving the closed-form gradient

Because the dynamics are linear, the state at time kk is an affine function of the whole action sequence:

zk=Akz0+∑j=0k−1Ak−1−jB aj=Akz0+Gka,z_k = A^k z_0 + \sum_{j=0}^{k-1} A^{k-1-j} B \, a_j = A^k z_0 + G_k a,

where a∈RHa \in \mathbb{R}^H collects the actions and Gk∈R2×HG_k \in \mathbb{R}^{2 \times H} has columns

[Gk]:,j={Ak−1−jB,j≤k−1,0,j≥k.[G_k]_{:,j} = \begin{cases} A^{k-1-j} B, & j \le k-1, \\ 0, & j \ge k. \end{cases}

Substituting into the cost and collecting terms gives a quadratic function of aa:

J(a)=a⊤Ma+2a⊤b+const,M=∑k=0HGk⊤QkGk+RIH,b=∑k=0HGk⊤Qk(Akz0−g),J(a) = a^\top M a + 2 a^\top b + \text{const}, \qquad M = \sum_{k=0}^{H} G_k^\top Q_k G_k + R I_H, \qquad b = \sum_{k=0}^{H} G_k^\top Q_k \big(A^k z_0 - g\big),

with Qk=QQ_k=Q for all kk in this example. The gradient is affine in the actions:

∇aJ=2Ma+2b.\nabla_a J = 2 M a + 2 b.

Three consequences follow. The conditioning and nonlinear-gradient lessons extend beyond this toy problem, while strict convexity and the unique global optimum rely on this linear-quadratic structure with R>0R>0.

The objective is strictly convex. MM is a sum of positive semidefinite terms plus RIHRI_H, so M≻0M\succ0 when R>0R>0. The unique local minimum is the global minimum,

a⋆=−M−1b.a^\star=-M^{-1}b.

With exact gradients and a suitable step size, gradient descent converges to it; an excessive fixed step can still diverge.

For a suitably scaled fixed step, the convergence bound is governed by the condition number of MM. Near the optimum, equal displacements along eigenvectors with small eigenvalues raise the cost less than displacements along steep eigenvectors. A single stable scalar step then contracts slowly along the flat directions. For this double integrator, the eigenvalue spread grows over the horizons we test; that trend is not universal.

For nonlinear multi-step dynamics, the gradient is generally not affine in the actions. Pendulum, cart-pole, and neural-dynamics planning objectives are often non-convex, although special nonlinear cases can remain convex. If the objective is bounded below and has an LL-Lipschitz gradient, fixed-step gradient descent with 0<α<2/L0<\alpha<2/L drives the gradient norm toward zero. Any convergent iterate sequence therefore converges to a stationary point, which need not be a local minimum. The result can depend strongly on initialization, and warm starts can help retain a useful basin when consecutive problems change smoothly.

Code Implementation

We now build the planner. Each experiment isolates one point: autograd matches the analytic gradient at a tested action vector, Adam improves an open-loop plan, a Riccati terminal value improves a two-step MPC controller under a fixed optimization budget, and scalar dynamics expose contracting and expanding gradient chains.

The chapter-wide book setup runs before the first executable example so its plotting helpers are available throughout. Seeding controls the common random streams and improves repeatability within a fixed software and hardware environment; it does not by itself guarantee identical results across platforms or library versions.

Next we define the double integrator, the quadratic cost, and the horizon. Keeping the constants in one place makes it easy to vary the horizon later.

In[5]:
Code
import numpy as np
import torch

torch.manual_seed(0)

## Discrete-time double integrator: state z = [position, velocity]
dt = 0.25
A = torch.tensor([[1.0, dt], [0.0, 1.0]])
B = torch.tensor([[0.5 * dt**2], [dt]])

## Quadratic cost with target position 1.0 and target velocity 0.0
Q = torch.diag(torch.tensor([1.0, 0.1]))
R = torch.tensor([[0.01]])
goal = torch.tensor([1.0, 0.0])
z0 = torch.tensor([0.0, 0.0])

H = 12

The rollout and the cost are the two ingredients that autograd will differentiate. Notice that the rollout is an ordinary Python loop; the computation graph is built implicitly as the loop runs, exactly as it would be for an RNN. Autograd requires no planning-specific differentiation machinery or hand-derived adjoint, and the planner's autograd path does not assemble explicit Jacobians. The independent check below assembles GkG_k only for verification. The framework tracks the operations, and a single call to backward on the scalar cost computes and accumulates the full gradient in the action tensor's .grad field.

In[6]:
Code
def rollout(z_init, actions):
    """Roll the model forward. actions: (H,) tensor. Returns states (H+1, 2)."""
    b_col = B.squeeze(-1)
    states = [z_init]
    for t in range(actions.shape[0]):
        states.append(A @ states[-1] + b_col * actions[t])
    return torch.stack(states)


def trajectory_cost(states, actions, terminal_Q=Q):
    """Stage costs plus an optional quadratic terminal cost."""
    stage = sum((z - goal) @ Q @ (z - goal) for z in states[:-1])
    ctrl = sum(R.item() * a**2 for a in actions)
    terminal = (
        torch.tensor(0.0)
        if terminal_Q is None
        else (states[-1] - goal) @ terminal_Q @ (states[-1] - goal)
    )
    return stage + ctrl + terminal

Now we compute the gradient two ways. Autograd differentiates the rollout; the second calculation assembles the quadratic gradient independently. Agreement at the all-zero action vector is a focused numerical check of this implementation, consistent with the adjoint relation derived above.

In[7]:
Code
## --- Autograd gradient at the all-zero action sequence ---
a_flat = torch.zeros(H, requires_grad=True)
states0 = rollout(z0, a_flat)
J_val = trajectory_cost(states0, a_flat)
J_val.backward()
grad_autograd = a_flat.grad.detach().clone()


## --- Closed-form gradient from the quadratic structure ---
def control_to_state_matrix(k, horizon):
    """G_k such that z_k = A^k z_0 + G_k @ a for a of length `horizon`."""
    G = torch.zeros(2, horizon)
    for j in range(min(k, horizon)):
        G[:, j] = (torch.matrix_power(A, k - 1 - j) @ B).squeeze(-1)
    return G


M = torch.zeros(H, H)
b_lin = torch.zeros(H)
for k in range(H + 1):
    Gk = control_to_state_matrix(k, H)
    M += Gk.T @ Q @ Gk
    b_lin += Gk.T @ Q @ (torch.matrix_power(A, k) @ z0 - goal)
M += torch.eye(H) * R.item()

grad_closed_form = 2 * b_lin  # evaluated at a = 0, where grad J = 2 M a + 2 b
Out[8]:
Console
Objective J(a=0)             : 13.0000
Max |autograd - closed form| : 0.000e+00
Autograd gradient, first four: [-9.     -7.5625 -6.25   -5.0625]
Gradient norm                : 15.3996

The two gradients agree to numerical precision at this tested point. We check the gradient norm explicitly because agreement between two negligible vectors would be a weak test. Here the all-zero diagnostic vector has a substantial nonzero gradient.

Gradient-based optimization improves the trajectory

Now we hand the action sequence to Adam. The "parameters" are actions rather than model weights; the loop still zeroes gradients, computes the loss, backpropagates, and takes an update.

In[9]:
Code
actions = torch.linspace(-1.5, 1.5, H, requires_grad=True)
optimizer = torch.optim.Adam([actions], lr=0.02)

loss_history = []
for step in range(400):
    optimizer.zero_grad()
    states = rollout(z0, actions)
    loss = trajectory_cost(states, actions)
    loss.backward()
    optimizer.step()
    loss_history.append(loss.item())

with torch.no_grad():
    final_states = rollout(z0, actions).clone()
    final_actions = actions.clone()

We plot the loss curve and resulting phase trajectory. The loss trace shows optimization progress, not a convergence proof. For this Adam run, the optimizer starts from the declared linear ramp from −1.5-1.5 to 1.51.5; the all-zero vector used in the nearby gradient checks is separate from that run. We use R=0.01R=0.01. The deliberately high-loss ramp makes the reduction easy to see, but the 400-step budget does not reach the analytic optimum.

Before looking at the final plan, inspect the gradient by action index. The open-loop double integrator is not asymptotically stable and, because its unit eigenvalue has a nontrivial Jordan block, it is not Lyapunov stable: with nonzero initial velocity, its zero-input position grows linearly. With cumulative state costs, early actions affect more stage costs than late actions, so the all-zero profile is strongest at the start of the horizon. This is an example of the sum of future-cost contributions dominating the profile, not of a vanishing early-action gradient.

In[10]:
Code
## Recompute the gradient at the initial all-zero action sequence to inspect its profile.
probe_actions = torch.zeros(H, requires_grad=True)
probe_states = rollout(z0, probe_actions)
probe_loss = trajectory_cost(probe_states, probe_actions)
probe_loss.backward()
grad_profile_numpy = probe_actions.grad.detach().abs().numpy()

## Compare the earliest and latest action-gradient magnitudes.
grad_ratio_first_last = (
    float(grad_profile_numpy[0] / grad_profile_numpy[-1])
    if grad_profile_numpy[-1] != 0
    else float("nan")
)
grad_span_orders = (
    float(np.log10(grad_profile_numpy.max() / grad_profile_numpy.min()))
    if grad_profile_numpy.min() > 0
    else float("nan")
)

print(
    f"|dJ/da_0| / |dJ/da_{{H-1}}| : {grad_ratio_first_last:.4f}".replace(
        "_{{H-1}}", "[H-1]"
    )
)
print(f"Orders of magnitude spanned : {grad_span_orders:.3f}")
Out[11]:
Visualization
Log-scale bar chart of per-action gradient magnitudes across the plan horizon.
Per-action gradient magnitude at the all-zero diagnostic sequence for the twelve-step double integrator, on a logarithmic vertical axis. The first component is 144 times the last because it reaches more state-cost terms and its position influence grows with delay: at this zero profile, |dJ/da_j| = dt^2(H-j)^2. This noncontracting system can have linearly growing zero-input position and is not the contracting terminal-only example used later.
Out[12]:
Visualization
(<Figure size 900x750 with 1 Axes>, <Figure size 900x750 with 1 Axes>)
The planning objective over 400 Adam iterations, falling on a logarithmic vertical axis as the optimizer refines a linear action ramp from -1.5 to 1.5.
Line plot with a logarithmic vertical axis showing planning loss decreasing over Adam iterations from a nonzero linear-ramp initialization.
The improved open-loop trajectory in position-velocity space. It passes the target position and ends at approximately position 1.05 and velocity -0.28 after the fixed 400-step optimization budget.
Phase plot of a double-integrator trajectory approaching the marked goal state, overshooting the target position, and ending with negative velocity.

The objective decreases throughout the plotted run. Under this fixed budget, the trajectory approaches and overshoots the target position, ending near (x,v)=(1.05,−0.28)(x,v)=(1.05,-0.28) rather than settling exactly at (1,0)(1,0). In this run, the optimizer produces rising and then falling velocity while trading finite-horizon position and velocity tracking against action effort. No separately designed feedback law is used: given the model, cost, initialization, and optimizer, backpropagation through the known dynamics computes the action gradients, and Adam uses those gradients to produce the open-loop action sequence.

Ill-conditioning grows with the horizon in this example

We now assemble MM for increasing horizons in this fixed double-integrator problem. The true action Hessian is 2M2M, which has the same condition number as MM. Horizon growth need not worsen every system, but it does here.

In[13]:
Code
horizons = list(range(2, 41))
condition_numbers = []

for h in horizons:
    Mh = torch.zeros(h, h)
    for k in range(h + 1):
        Gk = control_to_state_matrix(k, h)
        Mh += Gk.T @ Q @ Gk
    Mh += torch.eye(h) * R.item()
    eigvals = torch.linalg.eigvalsh(Mh)
    # Curvature accumulates through the action-to-state sensitivity matrices G_k.
    condition_numbers.append(float(eigvals[-1] / eigvals[0]))

print(f"Condition number at H=2 : {condition_numbers[0]:.1f}")
print(f"Condition number at H=40: {condition_numbers[-1]:.1f}")
Out[14]:
Visualization
Line chart with a logarithmic vertical axis showing the condition number of M rising with horizon in the double-integrator example.
For this double-integrator single-shooting problem, the condition number of the action-space quadratic matrix M rises over horizons H=2 through H=40. The Hessian is 2M and has the same condition number. The vertical axis is logarithmic.

For this system, the condition number climbs by orders of magnitude over the tested range. This eigenvalue spread slows unpreconditioned fixed-step gradient descent. Curvature-aware or preconditioned methods can compensate for part of it, although approximate Hessians can remain inaccurate. Regularization choices and finite precision also matter.

For J(a)=a⊤Ma+2a⊤b+constJ(a)=a^\top Ma+2a^\top b+\text{const}, the Hessian has largest eigenvalue L=2λmax⁡(M)L=2\lambda_{\max}(M). Gradient descent with step α=1/L\alpha=1/L contracts Euclidean iterate error by at most q=1−1/κq=1-1/\kappa per step. For 0<τ<10<\tau<1 and κ>1\kappa>1, reaching ∥ak−a⋆∥≤τ∥a0−a⋆∥\lVert a_k-a^\star\rVert\leq\tau\lVert a_0-a^\star\rVert is therefore guaranteed once

k≥log⁡τlog⁡(1−1/κ).k \geq \frac{\log \tau}{\log(1-1/\kappa)}.

For an integer iteration count, take the ceiling of the right-hand side. When κ=1\kappa=1, the step α=1/L\alpha=1/L reaches the quadratic optimum in one update instead. This is a worst-case bound, not a prediction that every initialization will attain equality. We compare it with the realized iterate-error threshold for the H=12H=12 quadratic using the same learning rate.

In[15]:
Code
## Worst-case steps to reduce Euclidean iterate error to the declared tolerance
## with alpha = 1 / L, where L = 2 * lambda_max(M).
tolerance = 1e-2
condition_numbers_np = np.array(condition_numbers, dtype=float)
bound_steps = np.ceil(
    np.log(tolerance) / np.log(1.0 - 1.0 / condition_numbers_np)
)
## Handle the kappa=1 boundary or a value rounded to it.
bound_steps = np.maximum(bound_steps, 1.0)

## Realized iterate-error threshold for H=12 with the same alpha = 1 / L.
quadratic_eigvals = torch.linalg.eigvalsh(M)
quad_lr = 1.0 / (2.0 * float(quadratic_eigvals[-1]))
quad_optimum = torch.linalg.solve(M, -b_lin)
quad_actions = torch.zeros(H)
initial_iterate_error = torch.linalg.norm(quad_actions - quad_optimum)
h12_index = horizons.index(H)
actual_steps_h12 = None
for step in range(int(bound_steps[h12_index]) + 1):
    relative_error = (
        torch.linalg.norm(quad_actions - quad_optimum) / initial_iterate_error
    )
    if relative_error <= tolerance:
        actual_steps_h12 = step
        break
    quad_gradient = 2.0 * (M @ quad_actions + b_lin)
    quad_actions = quad_actions - quad_lr * quad_gradient

assert actual_steps_h12 is not None
assert actual_steps_h12 <= bound_steps[h12_index]

print(f"Worst-case bound at H=2  : {bound_steps[0]:.0f} steps")
print(f"Worst-case bound at H=12 : {bound_steps[h12_index]:.0f} steps")
print(f"Realized steps at H=12   : {actual_steps_h12} steps")
print(f"Worst-case bound at H=40 : {bound_steps[-1]:.0f} steps")
Out[16]:
Visualization
Log-log line chart of worst-case gradient descent steps versus condition number, with the realized H=12 step count marked below its bound.
Worst-case gradient-descent steps needed to reduce Euclidean iterate error to one percent with learning rate 1/L, where L is the largest Hessian eigenvalue. The marked H=12 run reaches the threshold within the bound. Both axes are logarithmic.

A Riccati terminal value improves a two-step horizon

We solve the discrete algebraic Riccati equation numerically, then compare three receding-horizon controllers under the same 100-iteration Adam budget per planning call: a declared two-step horizon without a terminal value, the same two-step horizon with the Riccati value, and a twelve-step reference without a terminal value. Finite optimizer budgets mean this is an empirical comparison of these implementations, not an exact Bellman-equivalence test.

In[17]:
Code
import scipy.linalg as sla

P_np = sla.solve_discrete_are(
    A.numpy().astype(float),
    B.numpy().astype(float),
    Q.numpy().astype(float),
    R.numpy().astype(float),
)
P = torch.tensor(P_np, dtype=torch.float32)

print(f"Riccati solution P:\n{P.numpy().round(4)}")
In[18]:
Code
def plan(z_init, horizon, terminal_Q, iters=100, lr=0.1):
    """Optimize an action sequence of length `horizon` from state z_init."""
    a = torch.zeros(horizon, requires_grad=True)
    opt = torch.optim.Adam([a], lr=lr)
    for _ in range(iters):
        opt.zero_grad()
        loss = trajectory_cost(rollout(z_init, a), a, terminal_Q=terminal_Q)
        loss.backward()
        opt.step()
    return a.detach()


def mpc_closed_loop(horizon, terminal_Q, steps=25):
    """Receding-horizon control: plan, apply the first action, replan."""
    z = z0.clone()
    trajectory = [z.clone()]
    total = 0.0
    for _ in range(steps):
        a_plan = plan(z, horizon, terminal_Q)
        with torch.no_grad():
            a0 = a_plan[0]
            total += float((z - goal) @ Q @ (z - goal) + R.item() * a0**2)
            z = A @ z + B.squeeze(-1) * a0
        trajectory.append(z.clone())
    return total, torch.stack(trajectory)


SHORT_HORIZON = 2
cost_short, traj_short = mpc_closed_loop(horizon=SHORT_HORIZON, terminal_Q=None)
cost_term, traj_term = mpc_closed_loop(horizon=SHORT_HORIZON, terminal_Q=P)
cost_long, traj_long = mpc_closed_loop(horizon=12, terminal_Q=None)

short_overshoot = float((traj_short[:, 0] - goal[0]).max())
term_overshoot = float((traj_term[:, 0] - goal[0]).max())
cost_reduction_percent = 100.0 * (cost_short - cost_term) / cost_short
Out[19]:
Console
Cumulative cost, H=2, no terminal value : 3.568
Cumulative cost, H=2 + Riccati value     : 2.824
Cumulative cost, H=12, no terminal value               : 3.113
Cost reduction from the terminal value                  : 20.9%
Peak overshoot, no terminal / Riccati                   : 0.0433 / 0.0052
Out[20]:
Visualization
Line chart comparing closed-loop position trajectories for short, short-plus-terminal-value, and long planning horizons.
Closed-loop position under three fixed-budget receding-horizon controllers: a two-step horizon without a terminal value, the same two-step horizon with the Riccati value, and a twelve-step reference without a terminal value. In this run, the Riccati term reduces the two-step controller's peak overshoot from about 0.043 to 0.005 and lowers its cumulative cost by about 21 percent.

The two-step controller without a terminal value overshoots the target by about 0.0430.043 in this deterministic run. Adding the Riccati value reduces peak overshoot to about 0.0050.005 and lowers the 25-step cumulative cost by about 21%21\% relative to the same two-step controller. The twelve-step curve is a reference, not a claimed trajectory match; with 100 Adam iterations per call its cumulative cost is about 10.3%10.3\% higher than the terminal-value controller's, an ordering influenced by finite optimization error. A terminal value is useful when it preserves decision-relevant values or gradients over candidate terminal states.

The gradient chain under stable and unstable dynamics

The final experiment isolates the spectral behavior of the Jacobian chain. For zt+1=ρzt+atz_{t+1}=\rho z_t+a_t and J=(zH−1)2J=(z_H-1)^2, the general derivative is

∂J∂at=2(zH−1)ρH−1−t.\frac{\partial J}{\partial a_t}=2(z_H-1)\rho^{H-1-t}.

At the code's evaluation point z0=0z_0=0 with all actions zero, zH=0z_H=0 and this reduces to −2ρH−1−t-2\rho^{H-1-t}. We sweep nonnegative ρ\rho and the horizon, recording the first-action gradient magnitude.

In[21]:
Code
def terminal_gradient_profile(rho, horizon):
    """|dJ/da_t| for J = (z_H - 1)^2 with z_{t+1} = rho * z_t + a_t."""
    a = torch.zeros(horizon, requires_grad=True)
    z = torch.tensor(0.0)
    for t in range(horizon):
        z = rho * z + a[t]
    ((z - 1.0) ** 2).backward()
    return a.grad.detach().abs().numpy()


rhos = [0.7, 0.9, 1.0, 1.1, 1.25]
sweep_horizons = list(range(1, 41))
first_action_grad = {
    rho: [float(terminal_gradient_profile(rho, h)[0]) for h in sweep_horizons]
    for rho in rhos
}

profile_stable = terminal_gradient_profile(0.9, 30)
profile_unstable = terminal_gradient_profile(1.1, 30)
Out[22]:
Visualization
(<Figure size 900x1050 with 1 Axes>, <Figure size 900x1050 with 1 Axes>)
The gradient with respect to the first action as the horizon grows, for scalar linear dynamics with nonnegative rho from 0.7 to 1.25. Values below one contract, values above one expand, and rho equal to one preserves this terminal-only sensitivity.
Log-scale line chart of gradient magnitude versus horizon for five spectral radii.
The gradient profile across action index at a fixed horizon of 30 steps. With rho=0.9 the early actions receive roughly twenty times less gradient than the final action, while with rho=1.1 the ordering reverses and the early actions dominate.
Log-scale line chart of gradient magnitude versus action index for two spectral radii.

The left panel shows the predicted exponential decay and growth for this terminal-only objective: for 0≤ρ<10\leq\rho<1 the first-action gradient tends toward zero, for ρ>1\rho>1 it grows, and at ρ=1\rho=1 it stays constant. More generally, contraction occurs when ∣ρ∣<1|\rho|<1. At fixed H=30H=30, the ρ=0.9\rho=0.9 first-action magnitude is 0.929≈0.0470.9^{29}\approx0.047 times the last-action magnitude; with ρ=1.1\rho=1.1 the ordering reverses. With plain gradient descent using one global learning rate, larger gradient components receive proportionally larger updates.

The update rule strongly affects relative step magnitudes. The next plot is an idealized first-step direction comparison, not a simulation of stateful Adam. It contrasts a normalized plain-gradient magnitude profile with elementwise normalization ∣gi∣/max⁡(∣gi∣,ϵ)|g_i|/\max(|g_i|,\epsilon). This sign-like normalization resembles Adam's first update only when moment state starts at zero, gradients dominate ϵ\epsilon, and clipping, weight decay, or other interventions do not materially alter the coordinatewise first update.

In[23]:
Code
## Gradient profile at a representative stable contraction factor and horizon.
imbalance_profile = terminal_gradient_profile(0.9, 30).astype(float)
plain_step_magnitudes = imbalance_profile / np.linalg.norm(imbalance_profile)

## Idealized first-step elementwise normalization, not stateful Adam.
normalized_coordinates = imbalance_profile / np.maximum(
    imbalance_profile, 1e-12
)
normalized_step_magnitudes = normalized_coordinates / np.linalg.norm(
    normalized_coordinates
)

print(
    "Plain-gradient magnitude ratio, late/early : "
    f"{plain_step_magnitudes[-1] / plain_step_magnitudes[0]:.3e}"
)
print(
    "Elementwise-normalized ratio, late/early  : "
    f"{normalized_step_magnitudes[-1] / normalized_step_magnitudes[0]:.3e}"
)
Out[24]:
Visualization
Log-scale line chart comparing a normalized plain-gradient magnitude profile with an idealized equalized first-step profile.
Idealized first-step magnitude directions for the rho=0.9, H=30 scalar gradient profile. Plain normalization preserves component ratios; elementwise sign-like normalization makes the nonzero magnitudes equal. This is not a simulation of Adam's stateful moments.

Limitations & Impact

Differentiable planning can be model-evaluation-efficient on smooth, well-conditioned problems because one forward/reverse evaluation supplies sensitivities for every action coordinate. The need for usable derivatives is structural, as is the local nature of derivative information for a pure local gradient planner. Hybrid or multistart methods can still explore multiple basins. Intrinsic conditioning depends on the model, objective, transcription, scaling, and parameterization; the solver determines how that conditioning is handled. Exploitation and memory cost depend on the broader implementation. Together with latency, safety, and accuracy requirements, these factors help determine where the method belongs.

The first limitation is locality. On a smooth objective and with a suitable step rule, gradient descent seeks a stationary point; it need not reach a local minimum or the global solution. A local derivative cannot certify which contact-mode basin is globally best, and a nearly flat maze objective may provide too little signal to discover a route around a corner. Sampling can explore more broadly when its proposal retains support over distant positive-measure regions, but finite budgets and proposal collapse prevent any automatic global guarantee. Hybrid planners can use sampling for basin discovery and gradients for local refinement. The next chapter, Search and Belief-Space Planning, turns to tree search and planning under state uncertainty.

The second limitation is differentiability itself. Hard contact-mode changes can produce discontinuous or invalid local sensitivities. Hard discrete choices provide no informative ordinary pathwise gradient for changing the selected outcome: the Jacobian of a typical continuous-logit-to-hard-choice map is zero almost everywhere and is undefined at switching boundaries. Raw symbolic states likewise need an encoding or another treatment before ordinary derivatives apply. Every decision-relevant hard component on the differentiated action-to-objective path needs a usable sensitivity route—ordinary, event-aware, implicit, surrogate, or stochastic—or it must be bypassed or optimized separately. Finite-temperature categorical relaxations and straight-through rules generally bias gradients for the original discrete problem, while score-function estimators can have high variance. Differentiable contact formulations provide useful local or surrogate gradients under their own assumptions, so contact is difficult rather than categorically impossible.

The third limitation is exploitation. At a nonstationary unconstrained point, the negative gradient supplies a local direction for reducing the model-based objective; constrained updates also need a feasible descent direction. When a reachable error makes a learned cost, terminal value, or dynamics rollout look artificially favorable, the optimizer can exploit it aggressively. There is no universal efficiency ordering against random search: gradient methods can also stall before a remote error. Defenses often add conservatism or computation, yet they may improve realized performance by preventing proxy exploitation.

The fourth limitation is conditioning and horizon. Longer horizons add sensitivity factors that can vanish, explode, or become ill-conditioned, although identity and isometric dynamics can preserve them. The behavior is shaped both by the physical system and by its learned or simulated representation. A common response is to shorten the rollout and append a terminal value, alongside preconditioning, curvature-aware methods, multiple shooting, or collocation. With a learned terminal value, that choice balances rollout-model error, terminal-value error, optimization conditioning, and computation.

Finally, there is the backward-pass cost and memory footprint. A conventional uncheckpointed reverse pass stores activation information at each step. For deterministic or equivalently replayed segments, with relevant random-number and mutable state preserved, gradient checkpointing reduces activation memory through recomputation while preserving the same gradient up to ordinary numerical reproducibility. Truncated backpropagation reduces memory and compute by cutting dependencies, but generally biases the full planning gradient unless the omitted contributions are zero. Holding per-step work, solver budget, replanning frequency, and checkpoint policy fixed, shorter horizons reduce per-call rollout work and the horizon-dependent activation-memory term; they generally lower rollout latency per planning call as well. They also reduce the number of transitions over which model error can compound, although realized error need not decrease monotonically and terminal-value error may replace it.

Differentiable models, simulators, and optimal-control layers have enabled particular model-based controllers to be optimized end to end with gradients. PILCO analytically differentiated an approximate multi-step probabilistic rollout of a Gaussian-process dynamics model with respect to policy parameters and demonstrated data-efficient robot learning. DiffTaichi-built simulators and the published Brax engine exposed gradients through supported simulation paths. MJX-JAX roughly supports gradients through its supported features, and supported differentiable Warp kernels can also provide them. These paths enable local optimization of controls and selected continuous parameters, not arbitrary structural design choices. With suitable smooth or contact-implicit formulations, such systems can optimize contact-rich trajectories. If the planner must choose an explicit contact-mode sequence, that choice needs hybrid search, enumeration, mixed-integer machinery, or an equivalent relaxation; a fixed supplied sequence can be optimized within its continuous modes. DDP and iLQR are established methods for smooth robot trajectory optimization and MPC. Current Brax guidance recommends MJX or MuJoCo Warp rather than the original Brax physics pipelines for simulation.

Modern model-based reinforcement learning uses related pieces in distinct ways. Original Dreamer used analytic pathwise gradients through imagined latent dynamics for behavior learning; later variants still learn from imagined rollouts but do not all use the same actor-gradient estimator. The planned Dreamer Family chapter will cover latent imagination and actor-critic learning across the variants. TD-MPC combines a learned latent model, reward and value predictions, and sampling-based trajectory optimization; its action search does not backpropagate the objective into sampled actions. MuZero uses a learned value at search-tree leaves rather than differentiating through tree-search decisions. A differentiable model can therefore support representation or value learning even when online action selection uses sampling or search.

The broader lesson is that differentiability is a design property of a world model. A model that predicts well but has badly scaled planner-relevant Jacobians can be a poor gradient-planning substrate. Architecture and training objectives influence that geometry, while the planning horizon changes the accumulated sensitivities. The solver, parameterization, preconditioning, and regularization determine how that geometry is handled and therefore affect its practical usefulness.

Summary

  • Differentiability makes action-sequence planning amenable to gradient optimization. If ff is differentiable in state and action and the stage and terminal costs are differentiable in their relevant arguments along the rollout, reverse mode returns the full action gradient at a small constant multiple of one objective evaluation. This removes the coordinate-wise finite-difference factor and can help in high-dimensional continuous action spaces. Naive random shooting suffers exponentially only when good plans occupy a shrinking fraction of its proposal distribution.

  • The backward pass is a discrete adjoint recursion. With λt=∂J/∂zt\lambda_t=\partial J/\partial z_t, the recursion is λH=∂cH/∂zH\lambda_H=\partial c_H/\partial z_H and λt=∂ct/∂zt+Ft⊤λt+1\lambda_t=\partial c_t/\partial z_t+F_t^\top\lambda_{t+1}; the action gradient is ∂J/∂at=∂ct/∂at+Gt⊤λt+1\partial J/\partial a_t=\partial c_t/\partial a_t+G_t^\top\lambda_{t+1}. This is BPTT for the discrete recurrence and the discrete-time analogue, not the identical equation, of a continuous ODE adjoint.

  • The gradient is a sum of Jacobian products. Unrolling the recursion shows terms containing ∏Fj⊤\prod F_j^\top. These products are a major source of poor conditioning in single shooting. Action Jacobians can improve or worsen conditioning depending on their rank, scale, and alignment. Cost curvature can worsen it when scales are highly unequal, while well-scaled positive control curvature can regularize the action Hessian. Active or poorly scaled condensed constraints can degrade the constrained Jacobian or KKT system. Cancellation among future-cost contributions is a separate problem that can weaken the net gradient signal. A poorly scaled or globally coupled trajectory parameterization can worsen conditioning, while a good one can act as preconditioning.

  • Bounds and conditioning require explicit choices. Projection represents exact box boundaries but can pin coordinates. In exact real arithmetic, finite uu in a tanh⁡\tanh parameterization gives strict-interior feasibility. Finite-precision tanh⁡\tanh may round to ±1\pm1; overflow-safe bound arithmetic with a final clamp, or another interval-preserving implementation, is needed to guarantee closed-box feasibility numerically. Adam reduces sensitivity to persistent coordinate-wise scaling without fixing poor conditioning. Regularized DDP or iLQR can mitigate curvature anisotropy; on nonlinear or non-convex problems, they typically also need a useful local model and globalization such as a line search or trust region. Warm starts often reduce MPC iterations; real-time sufficiency remains system- and hardware-dependent.

  • Decision-relevant objective terms on the differentiated path need a usable action derivative or derivative estimator. Separately handled terms need not. Smooth quadratic costs have analytic derivatives, but they provide a useful action-space signal only where the composite rollout derivative has usable direction and scale. Smooth sparse-cost surrogates built from autodiff-supported operations, such as the softplus and Gaussian examples above, are straightforward to differentiate. They provide a useful local planning signal only where their weighted gradients have usable direction and scale relative to other terms, estimator noise, numerical precision, and the optimizer. For differentiable inequalities and strictly feasible trajectories, log barriers are differentiable in the interior and grow without bound as the constraint boundary is approached. When learned costs or values are differentiated directly by ordinary pathwise reverse mode, their planner-relevant computations need suitable differentiable operations; otherwise they need another valid sensitivity estimator or must be handled separately. They also need decision fidelity on planner-relevant states, because reachable approximation errors can be exploited. Differentiability is not inherently an error source, although a smooth surrogate or restricted differentiable function class can introduce bias when the target is nonsmooth or discontinuous.

  • Long-rollout sensitivity depends on products of state Jacobians. For a constant scalar Jacobian F=ρF=\rho, an LL-factor sensitivity product has magnitude ∣ρ∣L|\rho|^L. For a constant normal Jacobian, each excited eigenmode scales as ∣λi∣L|\lambda_i|^L, and its Euclidean induced operator norm (spectral 22-norm) is ∥FL∥2=max⁡i∣λi∣L\lVert F^L\rVert_2=\max_i|\lambda_i|^L. General finite-horizon behavior depends on singular-value growth along propagated directions, including non-normal transient growth. Shortening the horizon and reformulating the trajectory problem can mitigate poor products. Loss scaling and higher precision can address some magnitude, range, and roundoff consequences without changing the exact physical sensitivity map. Consistent state and action rescaling can additionally improve the numerical representation and conditioning of that map, but it does not remove genuine physical contraction, expansion, rank loss, or mode discontinuities. Well-chosen preconditioning or suitably regularized curvature-aware methods can improve how the optimizer handles the resulting conditioning when their transformed or local model is accurate enough; poor choices need not help. Decision-relevant hard components that block a usable derivative require a valid fixed-branch or event-aware sensitivity, a relaxation or estimator, or a hybrid bypass or separate discrete search.

  • A short horizon plus a suitable terminal value can replace part of a long rollout. This reduces the transition-chain length but trades omitted-tail error for terminal approximation error. What matters is preserving decision-relevant values or gradients over candidate terminal states, not absolute value accuracy everywhere.

  • One-step prediction accuracy and closed-loop usefulness are different properties. A model can score well on prediction and still produce poor plans if its local sensitivities are inaccurate or badly scaled. Architecture, data, objectives, derivative regularization, and the planner together determine whether multi-step gradients are useful.

The next chapter, Search and Belief-Space Planning, turns from a single smooth action sequence to tree search and planning under uncertain state. That shift preserves the objective-design lessons here while changing how the planner represents alternatives and uncertainty.

Quiz

Ready to test your understanding? Take this quick quiz to reinforce what you've learned about differentiable planning.

Differentiable Planning

Question 1 of 80 of 8 completed
In the adjoint recursion for backpropagation through dynamics, how is the adjoint vector at time t defined and updated?

Comments

No comments yet. Be the first to share your thoughts!

Reference

Citation details

Cite or share this article.

BIBTEXAcademic
@misc{brenndoerfer2026differentiableplanning, author = {Michael Brenndoerfer}, title = {Differentiable Planning}, year = {2026}, url = {https://mbrenndoerfer.com/writing/differentiable-planning-world-models-gradients}, organization = {mbrenndoerfer.com}, note = {Accessed: 2026-10-15} }
APAAcademic
Michael Brenndoerfer (2026). Differentiable Planning. Retrieved from https://mbrenndoerfer.com/writing/differentiable-planning-world-models-gradients
MLAAcademic
Michael Brenndoerfer. "Differentiable Planning." 2026. Web. October 15, 2026. <https://mbrenndoerfer.com/writing/differentiable-planning-world-models-gradients>.
CHICAGOAcademic
Michael Brenndoerfer. "Differentiable Planning." Accessed October 15, 2026. https://mbrenndoerfer.com/writing/differentiable-planning-world-models-gradients.
HARVARDAcademic
Michael Brenndoerfer (2026) 'Differentiable Planning'. Available at: https://mbrenndoerfer.com/writing/differentiable-planning-world-models-gradients (Accessed: October 15, 2026).
SimpleBasic
Michael Brenndoerfer (2026). Differentiable Planning. https://mbrenndoerfer.com/writing/differentiable-planning-world-models-gradients

About the author

Continue with the full handbook

This chapter is part of World Models Handbook. Use the handbook page to browse the complete table of contents and continue reading in sequence.

Explore World Models Handbook
Newsletter

Stay up to date

Get articles, book updates, and news delivered to your inbox.

No spam, unsubscribe anytime.

or

Join the community

Sign in to remove popups, track your reading progress, and join the discussion.